Completed
Push — master ( acf07d...e75790 )
by Joschi
02:54
created

FileAdapterStrategy::absoluteResourcePath()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
rs 9.4285
c 1
b 0
f 1
ccs 3
cts 3
cp 1
crap 1
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\Object\Revision;
45
use Apparat\Object\Domain\Model\Path\PathInterface;
46
use Apparat\Object\Domain\Model\Path\RepositoryPath;
47
use Apparat\Object\Domain\Model\Path\RepositoryPathInterface;
48
use Apparat\Object\Domain\Repository\AdapterStrategyInterface;
49
use Apparat\Object\Domain\Repository\RepositoryInterface;
50
use Apparat\Object\Domain\Repository\RuntimeException;
51
use Apparat\Object\Domain\Repository\Selector;
52
use Apparat\Object\Domain\Repository\SelectorInterface;
53
use Apparat\Object\Infrastructure\Factory\ResourceFactory;
54
use Apparat\Resource\Infrastructure\Io\File\AbstractFileReaderWriter;
55
use Apparat\Resource\Infrastructure\Io\File\Writer;
56
57
/**
58
 * File adapter strategy
59
 *
60
 * @package Apparat\Object
61
 * @subpackage Apparat\Object\Infrastructure
62
 */
63
class FileAdapterStrategy extends AbstractAdapterStrategy
64
{
65
    /**
66
     * Adapter strategy type
67
     *
68
     * @var string
69
     */
70
    const TYPE = 'file';
71
    /**
72
     * Configuration
73
     *
74
     * @var array
75
     */
76
    protected $config = null;
77
    /**
78
     * Root directory (without trailing directory separator)
79
     *
80
     * @var string
81
     */
82
    protected $root = null;
83
    /**
84
     * Configuration directory (including trailing directory separator)
85
     *
86
     * @var string
87
     */
88
    protected $configDir = null;
89
90
    /**
91
     * Adapter strategy constructor
92
     *
93
     * @param array $config Adapter strategy configuration
94
     * @throws InvalidArgumentException If the root directory configuration is empty
95
     * @throws InvalidArgumentException If the root directory configuration is invalid
96
     */
97 17
    public function __construct(array $config)
98
    {
99 17
        parent::__construct($config, ['root']);
100
101
        // If the root directory configuration is empty
102 16
        if (empty($this->config['root'])) {
103 1
            throw new InvalidArgumentException(
104 1
                'Empty file adapter strategy root',
105 1
                InvalidArgumentException::EMTPY_FILE_STRATEGY_ROOT
106
            );
107
        }
108
109
        // Get the real path of the root directory
110 15
        $this->root = realpath($this->config['root']);
111
112
        // If the repository should be initialized
113 15
        if (!empty($this->config['init'])
114 15
            && (boolean)$this->config['init']
115 15
            && $this->initializeRepository()
116
        ) {
117 3
            $this->root = realpath($this->config['root']);
118
        }
119
120
        // If the root directory configuration is still invalid
121 13
        if (empty($this->root) || !@is_dir($this->root)) {
122 1
            throw new InvalidArgumentException(
123
                sprintf(
124 1
                    'Invalid file adapter strategy root "%s"',
125 1
                    $this->config['root']
126
                ),
127 1
                InvalidArgumentException::INVALID_FILE_STRATEGY_ROOT
128
            );
129
        }
130
131 12
        $this->configDir = $this->root.DIRECTORY_SEPARATOR.'.repo'.DIRECTORY_SEPARATOR;
132 12
    }
133
134
    /**
135
     * Initialize the repository
136
     *
137
     * @return boolean Success
138
     * @throws RuntimeException If the repository cannot be initialized
139
     * @throws RuntimeException If the repository size descriptor can not be created
140
     */
141 5
    public function initializeRepository()
142
    {
143
        // Successively create the repository directories
144 5
        $repoDirectories = [$this->config['root'], $this->config['root'].DIRECTORY_SEPARATOR.'.repo'];
145 5
        foreach ($repoDirectories as $repoDirectory) {
146
            // If the repository cannot be initialized
147 5
            if (file_exists($repoDirectory) ? !is_dir($repoDirectory) : !mkdir($repoDirectory, 0777, true)) {
148 5
                throw new RuntimeException('Could not initialize repository', RuntimeException::REPO_NOT_INITIALIZED);
149
            }
150
        }
151
152
        // If the repository size descriptor can not be created
153 4
        $configDir = $this->config['root'].DIRECTORY_SEPARATOR.'.repo'.DIRECTORY_SEPARATOR;
154
        if (
155 4
            (file_exists($configDir.'size.txt') && !is_file($configDir.'size.txt'))
156 4
            || !file_put_contents($configDir.'size.txt', '0')
157
        ) {
158 1
            throw new RuntimeException(
159 1
                'Could not create repository size descriptor',
160 1
                RuntimeException::REPO_SIZE_DESCRIPTOR_NOT_CREATED
161
            );
162
        }
163
164 3
        return true;
165
    }
166
167
    /**
168
     * Find objects by selector
169
     *
170
     * @param Selector|SelectorInterface $selector Object selector
171
     * @param RepositoryInterface $repository Object repository
172
     * @return PathInterface[] Object paths
173
     */
174 7
    public function findObjectPaths(SelectorInterface $selector, RepositoryInterface $repository)
175
    {
176 7
        chdir($this->root);
177
178
        // Build a glob string from the selector
179 7
        $glob = '';
180 7
        $globFlags = GLOB_ONLYDIR | GLOB_NOSORT;
181
182 7
        $year = $selector->getYear();
183 7
        if ($year !== null) {
184 7
            $glob .= '/'.$year;
185
        }
186
187 7
        $month = $selector->getMonth();
188 7
        if ($month !== null) {
189 7
            $glob .= '/'.$month;
190
        }
191
192 7
        $day = $selector->getDay();
193 7
        if ($day !== null) {
194 7
            $glob .= '/'.$day;
195
        }
196
197 7
        $hour = $selector->getHour();
198 7
        if ($hour !== null) {
199 2
            $glob .= '/'.$hour;
200
        }
201
202 7
        $minute = $selector->getMinute();
203 7
        if ($minute !== null) {
204 2
            $glob .= '/'.$minute;
205
        }
206
207 7
        $second = $selector->getSecond();
208 7
        if ($second !== null) {
209 2
            $glob .= '/'.$second;
210
        }
211
212 7
        $uid = $selector->getId();
213 7
        $type = $selector->getType();
214 7
        if (($uid !== null) || ($type !== null)) {
215 7
            $glob .= '/'.($uid ?: Selector::WILDCARD).'.'.($type ?: Selector::WILDCARD);
216
217 7
            $revision = $selector->getRevision();
218 7
            if ($revision !== null) {
219 1
                $glob .= '/'.($uid ?: Selector::WILDCARD).'-'.$revision;
220 1
                $globFlags &= ~GLOB_ONLYDIR;
221
            }
222
        }
223
224 7
        return array_map(
225 7
            function ($objectPath) use ($repository) {
226 7
                return Kernel::create(RepositoryPath::class, [$repository, '/'.$objectPath]);
227 7
            },
228 7
            glob(ltrim($glob, '/'), $globFlags)
229
        );
230
    }
231
232
    /**
233
     * Find and return an object resource
234
     *
235
     * @param string $resourcePath Repository relative resource path
236
     * @return ResourceInterface Object resource
237
     */
238 19
    public function getObjectResource($resourcePath)
239
    {
240 19
        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...
241
    }
242
243
    /**
244
     * Allocate an object ID and create an object resource
245
     *
246
     * @param \Closure $creator Object creation closure
247
     * @return ObjectInterface Object
248
     * @throws RuntimeException If no object could be created
249
     * @throws \Exception If another error occurs
250
     */
251 2
    public function createObjectResource(\Closure $creator)
252
    {
253 2
        $sizeDescriptor = null;
254
255
        try {
256
            // Open the size descriptor
257 2
            $sizeDescriptor = fopen($this->configDir.'size.txt', 'r+');
258
259
            // If a lock of the size descriptor can be acquired
260 2
            if (flock($sizeDescriptor, LOCK_EX)) {
261
                // Determine the current repository size
262 1
                $repositorySize = '';
263 1
                while (!feof($sizeDescriptor)) {
264 1
                    $repositorySize .= fread($sizeDescriptor, 8);
265
                }
266 1
                $repositorySize = intval(trim($repositorySize));
267
268
                // Instantiate the next consecutive object ID
269 1
                $nextObjectId = Kernel::create(Id::class, [++$repositorySize]);
270
271
                // Create & persist the object (bypassing the repository)
272 1
                $object = $creator($nextObjectId);
273 1
                $this->persistObject($object);
274
275
                // Dump the new repository size, unlock the size descriptor
276 1
                ftruncate($sizeDescriptor, 0);
277 1
                fwrite($sizeDescriptor, $repositorySize);
278 1
                fflush($sizeDescriptor);
279 1
                flock($sizeDescriptor, LOCK_UN);
280
281
                // Return the newly created object
282 1
                return $object;
283
            }
284
285
            // If no object could be created
286 1
            throw new RuntimeException(
287 1
                'The repository size descriptor is unlockable',
288 1
                RuntimeException::REPO_SIZE_DESCRIPTOR_UNLOCKABLE
289
            );
290
291
            // If any exception is thrown
292 1
        } catch (\Exception $e) {
293
            // Release the size descriptor lock
294 1
            if (is_resource($sizeDescriptor)) {
295 1
                flock($sizeDescriptor, LOCK_UN);
296
            }
297
298
            // Forward the thrown exception
299 1
            throw $e;
300
        }
301
    }
302
303
    /**
304
     * Persist an object in the repository
305
     *
306
     * @param ObjectInterface $object Object
307
     * @return AdapterStrategyInterface Self reference
308
     */
309 1
    public function persistObject(ObjectInterface $object)
310
    {
311
        // If the object has just been published
312 1
        if ($object->isPublished()) {
313 1
            $this->publishObject($object);
314
        }
315
316
        /** @var \Apparat\Object\Infrastructure\Model\Object\Resource $objectResource */
317 1
        $objectResource = ResourceFactory::createFromObject($object);
318
319
        // Create the absolute object resource path
320 1
        $objectResourcePath = $this->absoluteResourcePath($object->getRepositoryPath());
321
322
        /** @var Writer $fileWriter */
323 1
        $fileWriter = Kernel::create(
324 1
            Writer::class,
325 1
            [$objectResourcePath, Writer::FILE_CREATE | Writer::FILE_CREATE_DIRS | Writer::FILE_OVERWRITE]
326
        );
327 1
        $objectResource->dump($fileWriter);
328
329 1
        return $this;
330
    }
331
332
    /**
333
     * Publish an object in the repository
334
     *
335
     * @param ObjectInterface $object
336
     */
337 1
    protected function publishObject(ObjectInterface $object)
338
    {
339 1
        $objectRepositoryPath = $object->getRepositoryPath();
340
341
        // If the object had been persisted as a draft: Remove the draft resource
342 1
        $objectDraftResourcePath = $this->absoluteResourcePath($objectRepositoryPath->setDraft(true));
343 1
        if (@file_exists($objectDraftResourcePath)) {
344 1
            unlink($objectDraftResourcePath);
345
        }
346
347
        // If it's not the first object revision: Rotate the previous revision resource
348 1
        $objectRevisionNumber = $object->getRevision()->getRevision();
349 1
        if ($objectRevisionNumber > 1) {
350
            // Build the "current" object repository path
351 1
            $currentRevision = Revision::current();
352
            $currentObjectResourcePath =
353 1
                $this->absoluteResourcePath($objectRepositoryPath->setRevision($currentRevision));
354
355
            // Build the previous object repository path
356
            /** @var Revision $previousRevision */
357 1
            $previousRevision = Kernel::create(Revision::class, [$objectRevisionNumber - 1]);
358
            $previousObjectResourcePath
359 1
                = $this->absoluteResourcePath($objectRepositoryPath->setRevision($previousRevision));
360
361
            // Rotate the previous revision's resource path
362 1
            if (file_exists($currentObjectResourcePath)) {
363 1
                rename($currentObjectResourcePath, $previousObjectResourcePath);
364
            }
365
        }
366 1
    }
367
368
    /**
369
     * Build an absolute repository resource path
370
     *
371
     * @param RepositoryPathInterface $repositoryPath Repository path
372
     * @return string Absolute repository resource path
373
     */
374 1
    protected function absoluteResourcePath(RepositoryPathInterface $repositoryPath)
375
    {
376 1
        return $this->root.str_replace('/', DIRECTORY_SEPARATOR,
377 1
            $repositoryPath->withExtension(getenv('OBJECT_RESOURCE_EXTENSION')));
378
    }
379
380
    /**
381
     * Return the repository size (number of objects in the repository)
382
     *
383
     * @return int Repository size
384
     */
385 2
    public function getRepositorySize()
386
    {
387 2
        $sizeDescriptorFile = $this->configDir.'size.txt';
388 2
        $repositorySize = 0;
389 2
        if (is_file($sizeDescriptorFile) && is_readable($sizeDescriptorFile)) {
390 2
            $repositorySize = intval(file_get_contents($this->configDir.'size.txt'));
391
        }
392 2
        return $repositorySize;
393
    }
394
}
395