1: <?php
2: 3: 4: 5: 6: 7:
8: namespace Chippyash\Authentication\Manager\Digest;
9:
10: use Chippyash\Authentication\Manager\Digest\AbstractDigestCollection;
11: use Chippyash\Authentication\Manager\Encoder\DigestEncoderInterface;
12: use Chippyash\Authentication\Manager\Traits\RealmHandler;
13: use Chippyash\Authentication\Manager\Exceptions\AuthManagerException;
14: use Chippyash\Type\String\StringType;
15: use Chippyash\Type\Number\IntType;
16: use Chippyash\Type\BoolType;
17:
18: 19: 20:
21: class BasicDigestCollection extends AbstractDigestCollection
22: {
23: use RealmHandler;
24:
25: const SEP_DIGEST = ':';
26: const ERR_NO_DIGEST_TPL = 'Digest entry (%d) does not exist';
27:
28: 29: 30: 31:
32: protected $encoder;
33:
34: 35: 36: 37: 38: 39: 40:
41: public function __construct(DigestEncoderInterface $encoder, StringType $fileName, array $digests = [])
42: {
43: $this->setEncoder($encoder);
44: parent::__construct($fileName, $digests);
45: }
46:
47: 48: 49: 50: 51: 52: 53: 54:
55: public function findByUid(StringType $uid)
56: {
57: $index = false;
58: foreach($this->collection as $key => $digest) {
59: if ($digest[0] == $uid() && $digest[1] == $this->realm()) {
60: $index = $key;
61: break;
62: }
63: }
64:
65: if ($index === false) {
66: return New BoolType(false);
67: } else {
68: return new IntType($index);
69: }
70: }
71:
72: 73: 74: 75: 76:
77: public function read()
78: {
79: try {
80: $fh = fopen($this->fileName->get(), 'r');
81: $ret = [];
82: while (!feof($fh)) {
83: $csv = fgetcsv($fh, 0, self::SEP_DIGEST);
84: if ($csv !== false) {
85: $ret[] = $csv;
86: }
87: }
88: fclose($fh);
89: $this->collection = $ret;
90:
91: return new BoolType(true);
92: } catch (\Exception $e) {
93: return new BoolType(false);
94: }
95: }
96:
97: 98: 99: 100: 101:
102: public function write()
103: {
104: $output = '';
105: foreach($this->collection as $digest) {
106: $output .= $this->raw($digest) . PHP_EOL;
107: }
108: $ret = file_put_contents($this->fileName->get(), $output, $this->writeOptions);
109: if ($ret === false) {
110: return new BoolType(false);
111: }
112:
113: return new BoolType(strlen($output) == $ret);
114: }
115:
116: 117: 118: 119: 120: 121: 122: 123:
124: public function add(StringType $uid, StringType $pwd)
125: {
126: try {
127: $digest = $this->encoder->encode($uid, $pwd);
128: $this->collection[] = explode(self::SEP_DIGEST, $digest());
129:
130: return new BoolType(true);
131:
132: } catch (\Exception $e) {
133:
134: return new BoolType(false);
135: }
136: }
137:
138: 139: 140: 141: 142: 143: 144: 145: 146:
147: public function asString(IntType $index)
148: {
149: if (!isset($this->collection[$index()])) {
150: throw new AuthManagerException(sprintf(self::ERR_NO_DIGEST_TPL, $index()));
151: }
152: return new StringType($this->raw($this->collection[$index()]));
153: }
154:
155: 156: 157: 158: 159:
160: protected function raw(array $digest)
161: {
162: return implode(self::SEP_DIGEST, $digest);
163: }
164: }
165: