Completed
Push — master ( 81c425...a2bf82 )
by Joschi
02:41
created

FileAdapterStrategy::__construct()   C

Complexity

Conditions 7
Paths 5

Size

Total Lines 36
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 7

Importance

Changes 5
Bugs 0 Features 1
Metric Value
c 5
b 0
f 1
dl 0
loc 36
ccs 22
cts 22
cp 1
rs 6.7272
cc 7
eloc 18
nc 5
nop 1
crap 7
1
<?php
2
3
/**
4
 * apparat-object
5
 *
6
 * @category    Apparat
7
 * @package     Apparat\Object
8
 * @subpackage  Apparat\Object\Infrastructure
9
 * @author      Joschi Kuphal <[email protected]> / @jkphl
10
 * @copyright   Copyright © 2016 Joschi Kuphal <[email protected]> / @jkphl
11
 * @license     http://opensource.org/licenses/MIT The MIT License (MIT)
12
 */
13
14
/***********************************************************************************
15
 *  The MIT License (MIT)
16
 *
17
 *  Copyright © 2016 Joschi Kuphal <[email protected]> / @jkphl
18
 *
19
 *  Permission is hereby granted, free of charge, to any person obtaining a copy of
20
 *  this software and associated documentation files (the "Software"), to deal in
21
 *  the Software without restriction, including without limitation the rights to
22
 *  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
23
 *  the Software, and to permit persons to whom the Software is furnished to do so,
24
 *  subject to the following conditions:
25
 *
26
 *  The above copyright notice and this permission notice shall be included in all
27
 *  copies or substantial portions of the Software.
28
 *
29
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
31
 *  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
32
 *  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
33
 *  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
34
 *  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35
 ***********************************************************************************/
36
37
namespace Apparat\Object\Infrastructure\Repository;
38
39
use Apparat\Kernel\Ports\Kernel;
40
use Apparat\Object\Application\Repository\AbstractAdapterStrategy;
41
use Apparat\Object\Domain\Model\Object\Id;
42
use Apparat\Object\Domain\Model\Object\ObjectInterface;
43
use Apparat\Object\Domain\Model\Object\ResourceInterface;
44
use Apparat\Object\Domain\Model\Path\PathInterface;
45
use Apparat\Object\Domain\Model\Path\RepositoryPath;
46
use Apparat\Object\Domain\Repository\RepositoryInterface;
47
use Apparat\Object\Domain\Repository\RuntimeException;
48
use Apparat\Object\Domain\Repository\Selector;
49
use Apparat\Object\Domain\Repository\SelectorInterface;
50
use Apparat\Object\Infrastructure\Factory\ResourceFactory;
51
use Apparat\Resource\Infrastructure\Io\File\AbstractFileReaderWriter;
52
use Apparat\Resource\Infrastructure\Io\File\Writer;
53
54
/**
55
 * File adapter strategy
56
 *
57
 * @package Apparat\Object
58
 * @subpackage Apparat\Object\Infrastructure
59
 */
60
class FileAdapterStrategy extends AbstractAdapterStrategy
61
{
62
    /**
63
     * Adapter strategy type
64
     *
65
     * @var string
66
     */
67
    const TYPE = 'file';
68
    /**
69
     * Configuration
70
     *
71
     * @var array
72
     */
73
    protected $config = null;
74
    /**
75
     * Root directory (without trailing directory separator)
76
     *
77
     * @var string
78
     */
79
    protected $root = null;
80
    /**
81
     * Configuration directory (including trailing directory separator)
82
     *
83
     * @var string
84
     */
85
    protected $configDir = null;
86
87
    /**
88
     * Adapter strategy constructor
89
     *
90
     * @param array $config Adapter strategy configuration
91
     * @throws InvalidArgumentException If the root directory configuration is empty
92
     * @throws InvalidArgumentException If the root directory configuration is invalid
93
     */
94 14
    public function __construct(array $config)
95
    {
96 14
        parent::__construct($config, ['root']);
97
98
        // If the root directory configuration is empty
99 13
        if (empty($this->config['root'])) {
100 1
            throw new InvalidArgumentException(
101 1
                'Empty file adapter strategy root',
102
                InvalidArgumentException::EMTPY_FILE_STRATEGY_ROOT
103 1
            );
104
        }
105
106
        // Get the real path of the root directory
107 12
        $this->root = realpath($this->config['root']);
108
109
        // If the repository should be initialized
110 12
        if (!empty($this->config['init'])
111 12
            && (boolean)$this->config['init']
112 12
            && $this->initializeRepository()
113 12
        ) {
114 2
            $this->root = realpath($this->config['root']);
115 2
        }
116
117
        // If the root directory configuration is still invalid
118 12
        if (empty($this->root) || !@is_dir($this->root)) {
119 1
            throw new InvalidArgumentException(
120 1
                sprintf(
121 1
                    'Invalid file adapter strategy root "%s"',
122 1
                    $this->config['root']
123 1
                ),
124
                InvalidArgumentException::INVALID_FILE_STRATEGY_ROOT
125 1
            );
126
        }
127
128 11
        $this->configDir = $this->root.DIRECTORY_SEPARATOR.'.repo'.DIRECTORY_SEPARATOR;
129 11
    }
130
131
    /**
132
     * Initialize the repository
133
     *
134
     * @return boolean Success
135
     * @throws RuntimeException If the repository cannot be initialized
136
     * @throws RuntimeException If the repository size descriptor can not be created
137
     */
138 2
    public function initializeRepository()
139
    {
140 2
        $configDir = $this->config['root'].DIRECTORY_SEPARATOR.'.repo'.DIRECTORY_SEPARATOR;
141
142
        // If the repository cannot be initialized
143 2
        if (!is_dir($configDir) && !mkdir($configDir, 0777, true)) {
144
            throw new RuntimeException('Could not initialize repository', RuntimeException::REPO_NOT_INITIALIZED);
145
        }
146
147
        // If the repository size descriptor can not be created
148 2
        if (!@is_file($configDir.'size.txt') && !file_put_contents($configDir.'size.txt', '0')) {
149
            throw new RuntimeException(
150
                'Could not create repository size descriptor',
151
                RuntimeException::REPO_SIZE_DESCRIPTOR_NOT_CREATED
152
            );
153
        }
154
155 2
        return true;
156
    }
157
158
    /**
159
     * Find objects by selector
160
     *
161
     * @param Selector|SelectorInterface $selector Object selector
162
     * @param RepositoryInterface $repository Object repository
163
     * @return PathInterface[] Object paths
164
     */
165 7
    public function findObjectPaths(SelectorInterface $selector, RepositoryInterface $repository)
166
    {
167 7
        chdir($this->root);
168
169
        // Build a glob string from the selector
170 7
        $glob = '';
171 7
        $globFlags = GLOB_ONLYDIR | GLOB_NOSORT;
172
173 7
        $year = $selector->getYear();
174 7
        if ($year !== null) {
175 7
            $glob .= '/'.$year;
176 7
        }
177
178 7
        $month = $selector->getMonth();
179 7
        if ($month !== null) {
180 7
            $glob .= '/'.$month;
181 7
        }
182
183 7
        $day = $selector->getDay();
184 7
        if ($day !== null) {
185 7
            $glob .= '/'.$day;
186 7
        }
187
188 7
        $hour = $selector->getHour();
189 7
        if ($hour !== null) {
190 2
            $glob .= '/'.$hour;
191 2
        }
192
193 7
        $minute = $selector->getMinute();
194 7
        if ($minute !== null) {
195 2
            $glob .= '/'.$minute;
196 2
        }
197
198 7
        $second = $selector->getSecond();
199 7
        if ($second !== null) {
200 2
            $glob .= '/'.$second;
201 2
        }
202
203 7
        $uid = $selector->getId();
204 7
        $type = $selector->getType();
205 7
        if (($uid !== null) || ($type !== null)) {
206 7
            $glob .= '/'.($uid ?: Selector::WILDCARD).'.'.($type ?: Selector::WILDCARD);
207
208 7
            $revision = $selector->getRevision();
209 7
            if ($revision !== null) {
210 1
                $glob .= '/'.($uid ?: Selector::WILDCARD).'-'.$revision;
211 1
                $globFlags &= ~GLOB_ONLYDIR;
212 1
            }
213 7
        }
214
215 7
        return array_map(
216 7
            function ($objectPath) use ($repository) {
217 7
                return Kernel::create(RepositoryPath::class, [$repository, '/'.$objectPath]);
218 7
            },
219 7
            glob(ltrim($glob, '/'), $globFlags)
220 7
        );
221
    }
222
223
    /**
224
     * Find and return an object resource
225
     *
226
     * @param string $resourcePath Repository relative resource path
227
     * @return ResourceInterface Object resource
228
     */
229 16
    public function getObjectResource($resourcePath)
230
    {
231 16
        return ResourceFactory::createFromSource(AbstractFileReaderWriter::WRAPPER.$this->root.$resourcePath);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return \Apparat\Object\I...>root . $resourcePath); (Apparat\Resource\Domain\...source\AbstractResource) is incompatible with the return type declared by the interface Apparat\Object\Applicati...face::getObjectResource of type Apparat\Object\Domain\Mo...bject\ResourceInterface.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
232
    }
233
234
    /**
235
     * Allocate an object ID and create an object resource
236
     *
237
     * @param \Closure $creator Object creation closure
238
     * @return ObjectInterface Object
239
     */
240 1
    public function createObjectResource(\Closure $creator)
241
    {
242 1
        $sizeDescriptor = null;
243
244
        try {
245
            // Open the size descriptor
246 1
            $sizeDescriptor = fopen($this->configDir.'size.txt', 'r+');
247
248
            // If a lock of the size descriptor can be acquired
249 1
            if (flock($sizeDescriptor, LOCK_EX)) {
250
                // Determine the current repository size
251 1
                $repositorySize = '';
252 1
                while (!feof($sizeDescriptor)) {
253 1
                    $repositorySize .= fread($sizeDescriptor, 8);
254 1
                }
255 1
                $repositorySize = intval(trim($repositorySize));
256
257
                // Instantiate the next consecutive object ID
258 1
                $nextObjectId = Kernel::create(Id::class, [++$repositorySize]);
259
260
                // Create & persist the object
261 1
                $object = $this->persistObject($creator($nextObjectId));
262
263
                // Dump the new repository size, unlock the size descriptor
264 1
                ftruncate($sizeDescriptor, 0);
265 1
                fwrite($sizeDescriptor, $repositorySize);
266 1
                fflush($sizeDescriptor);
267 1
                flock($sizeDescriptor, LOCK_UN);
268
269
                // Return the newly created object
270 1
                return $object;
271
            }
272
273
            // Throw an error if no object could be created
274
            throw new RuntimeException(
275
                'The repository size descriptor is unlockable',
276
                RuntimeException::REPO_SIZE_DESCRIPTOR_UNLOCKABLE
277
            );
278
279
            // If any exception is thrown
280
        } catch (\Exception $e) {
281
            // Release the size descriptor lock
282
            if (is_resource($sizeDescriptor)) {
283
                flock($sizeDescriptor, LOCK_UN);
284
            }
285
286
            // Forward the thrown exception
287
            throw $e;
288
        }
289
    }
290
291
    /**
292
     * Persist an object in the repository
293
     *
294
     * @param ObjectInterface $object Object
295
     * @return ObjectInterface Persisted object
296
     */
297 1
    public function persistObject(ObjectInterface $object)
298
    {
299
        /** @var \Apparat\Object\Infrastructure\Model\Object\Resource $objectResource */
300 1
        $objectResource = ResourceFactory::createFromObject($object);
301
302
        // Create the absolute object resource path
303 1
        $objectResourcePath = $this->root.str_replace('/', DIRECTORY_SEPARATOR,
304 1
                $object->getRepositoryPath()->withExtension(getenv('OBJECT_RESOURCE_EXTENSION')));
305
306
        /** @var Writer $fileWriter */
307 1
        $fileWriter = Kernel::create(
308 1
            Writer::class,
309 1
            [$objectResourcePath, Writer::FILE_CREATE | Writer::FILE_CREATE_DIRS | Writer::FILE_OVERWRITE]
310 1
        );
311 1
        $objectResource->dump($fileWriter);
312
313
        // TODO: Set object clean
314
315 1
        return $object;
316
    }
317
318
    /**
319
     * Return the repository size (number of objects in the repository)
320
     *
321
     * @return int Repository size
322
     */
323
    public function getRepositorySize()
324
    {
325
        $sizeDescriptorFile = $this->configDir.'size.txt';
326
        $repositorySize = 0;
327
        if (is_file($sizeDescriptorFile) && is_readable($sizeDescriptorFile)) {
328
            $repositorySize = intval(file_get_contents($this->configDir.'size.txt'));
329
        }
330
        return $repositorySize;
331
    }
332
}
333