Completed
Push — master ( ef4825...fadc20 )
by Joschi
02:55
created

FileAdapterStrategy::__construct()   C

Complexity

Conditions 7
Paths 5

Size

Total Lines 37
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 7

Importance

Changes 4
Bugs 0 Features 1
Metric Value
c 4
b 0
f 1
dl 0
loc 37
ccs 18
cts 18
cp 1
rs 6.7272
cc 7
eloc 19
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\ResourceInterface;
42
use Apparat\Object\Domain\Model\Path\RepositoryPath;
43
use Apparat\Object\Domain\Repository\RepositoryInterface;
44
use Apparat\Object\Domain\Repository\RuntimeException;
45
use Apparat\Object\Domain\Repository\Selector;
46
use Apparat\Object\Domain\Repository\SelectorInterface;
47
use Apparat\Object\Infrastructure\Factory\ResourceFactory;
48
use Apparat\Resource\Infrastructure\Io\File\AbstractFileReaderWriter;
49
50
/**
51
 * File adapter strategy
52
 *
53
 * @package Apparat\Object
54
 * @subpackage Apparat\Object\Infrastructure
55
 */
56
class FileAdapterStrategy extends AbstractAdapterStrategy
57
{
58
    /**
59
     * Adapter strategy type
60
     *
61
     * @var string
62
     */
63
    const TYPE = 'file';
64
    /**
65
     * Configuration
66
     *
67
     * Example
68
     *
69
     * @var array
70
     */
71
    protected $config = null;
72
    /**
73
     * Root directory (without trailing directory separator)
74
     *
75
     * @var string
76
     */
77
    protected $root = null;
78
    /**
79
     * Configuration directory (including trailing directory separator)
80
     *
81
     * @var string
82
     */
83
    protected $configDir = null;
84
85
    /**
86
     * Adapter strategy constructor
87
     *
88
     * @param array $config Adapter strategy configuration
89
     * @throws InvalidArgumentException If the root directory configuration is empty
90
     * @throws InvalidArgumentException If the root directory configuration is invalid
91
     */
92 13
    public function __construct(array $config)
93
    {
94 13
        parent::__construct($config, ['root']);
95
96
        // If the root directory configuration is empty
97 12
        if (empty($this->config['root'])) {
98 1
            throw new InvalidArgumentException(
99 1
                'Empty file adapter strategy root',
100 1
                InvalidArgumentException::EMTPY_FILE_STRATEGY_ROOT
101
            );
102
        }
103
104
        // Get the real path of the root directory
105 11
        $this->root = realpath($this->config['root']);
106
107
        // If the repository should be initialized
108
        if (
109 11
            !empty($this->config['init'])
110 11
            && (boolean)$this->config['init']
111 11
            && $this->initializeRepository()
112
        ) {
113 1
            $this->root = realpath($this->config['root']);
114
        }
115
116
        // If the root directory configuration is still invalid
117 11
        if (empty($this->root) || !@is_dir($this->root)) {
118 1
            throw new InvalidArgumentException(
119
                sprintf(
120 1
                    'Invalid file adapter strategy root "%s"',
121 1
                    $this->config['root']
122
                ),
123 1
                InvalidArgumentException::INVALID_FILE_STRATEGY_ROOT
124
            );
125
        }
126
127 10
        $this->configDir = $this->root.DIRECTORY_SEPARATOR.'.repo'.DIRECTORY_SEPARATOR;
128 10
    }
129
130
    /**
131
     * Initialize the repository
132
     *
133
     * @return boolean Success
134
     * @throws RuntimeException If the repository cannot be initialized
135
     * @throws RuntimeException If the repository size descriptor can not be created
136
     */
137 1
    public function initializeRepository()
138
    {
139 1
        $configDir = $this->config['root'].DIRECTORY_SEPARATOR.'.repo'.DIRECTORY_SEPARATOR;
140
141
        // If the repository cannot be initialized
142 1
        if (!is_dir($configDir) && !mkdir($configDir, 0777, true)) {
143
            throw new RuntimeException('Could not initialize repository', RuntimeException::REPO_NOT_INITIALIZED);
144
        }
145
146
        // If the repository size descriptor can not be created
147 1
        if (!@is_file($configDir.'size.txt') && !file_put_contents($configDir.'size.txt', '0')) {
148
            throw new RuntimeException(
149
                'Could not create repository size descriptor',
150
                RuntimeException::REPO_SIZE_DESCRIPTOR_NOT_CREATED
151
            );
152
        }
153
154 1
        return true;
155
    }
156
157
    /**
158
     * Find objects by selector
159
     *
160
     * @param Selector|SelectorInterface $selector Object selector
161
     * @param RepositoryInterface $repository Object repository
162
     * @return array[PathInterface] Object paths
0 ignored issues
show
Documentation introduced by
The doc-type array[PathInterface] could not be parsed: Expected "]" at position 2, but found "PathInterface". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
163
     */
164 7
    public function findObjectPaths(SelectorInterface $selector, RepositoryInterface $repository)
165
    {
166 7
        chdir($this->root);
167
168
        // Build a glob string from the selector
169 7
        $glob = '';
170 7
        $globFlags = GLOB_ONLYDIR | GLOB_NOSORT;
171
172 7
        $year = $selector->getYear();
173 7
        if ($year !== null) {
174 7
            $glob .= '/'.$year;
175
        }
176
177 7
        $month = $selector->getMonth();
178 7
        if ($month !== null) {
179 7
            $glob .= '/'.$month;
180
        }
181
182 7
        $day = $selector->getDay();
183 7
        if ($day !== null) {
184 7
            $glob .= '/'.$day;
185
        }
186
187 7
        $hour = $selector->getHour();
188 7
        if ($hour !== null) {
189 2
            $glob .= '/'.$hour;
190
        }
191
192 7
        $minute = $selector->getMinute();
193 7
        if ($minute !== null) {
194 2
            $glob .= '/'.$minute;
195
        }
196
197 7
        $second = $selector->getSecond();
198 7
        if ($second !== null) {
199 2
            $glob .= '/'.$second;
200
        }
201
202 7
        $uid = $selector->getId();
203 7
        $type = $selector->getType();
204 7
        if (($uid !== null) || ($type !== null)) {
205 7
            $glob .= '/'.($uid ?: Selector::WILDCARD).'.'.($type ?: Selector::WILDCARD);
206
207 7
            $revision = $selector->getRevision();
208 7
            if ($revision !== null) {
209 1
                $glob .= '/'.($uid ?: Selector::WILDCARD).'-'.$revision;
210 1
                $globFlags &= ~GLOB_ONLYDIR;
211
            }
212
        }
213
214 7
        return array_map(
215 7
            function ($objectPath) use ($repository) {
216 7
                return Kernel::create(RepositoryPath::class, [$repository, '/'.$objectPath]);
217 7
            },
218 7
            glob(ltrim($glob, '/'), $globFlags)
219
        );
220
    }
221
222
    /**
223
     * Find and return an object resource
224
     *
225
     * @param string $resourcePath Repository relative resource path
226
     * @return ResourceInterface Object resource
227
     */
228 6
    public function getObjectResource($resourcePath)
229
    {
230 6
        return ResourceFactory::create(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\Domain\Re...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...
231
    }
232
233
    /**
234
     * Return the repository size (number of objects in the repository)
235
     *
236
     * @return int Repository size
237
     */
238
    public function getRepositorySize()
239
    {
240
        $sizeDescriptorFile = $this->configDir.'size.txt';
241
        $repositorySize = 0;
242
        if (is_file($sizeDescriptorFile) && is_readable($sizeDescriptorFile)) {
243
            $repositorySize = intval(file_get_contents($this->configDir.'size.txt'));
244
        }
245
        return $repositorySize;
246
    }
247
}
248