Completed
Push — master ( 2d80b2...8a71ed )
by Joschi
03:21
created

Manager::loadObjectResource()   C

Complexity

Conditions 8
Paths 5

Size

Total Lines 44
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 8.2964

Importance

Changes 9
Bugs 0 Features 1
Metric Value
cc 8
eloc 21
c 9
b 0
f 1
nc 5
nop 2
dl 0
loc 44
ccs 15
cts 18
cp 0.8333
crap 8.2964
rs 5.3846
1
<?php
2
3
/**
4
 * apparat-object
5
 *
6
 * @category    Apparat
7
 * @package     Apparat\Object
8
 * @subpackage  Apparat\Object\Application
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\Application\Model\Object;
38
39
use Apparat\Kernel\Ports\Kernel;
40
use Apparat\Object\Application\Factory\ObjectFactory;
41
use Apparat\Object\Domain\Model\Object\Id;
42
use Apparat\Object\Domain\Model\Object\ManagerInterface;
43
use Apparat\Object\Domain\Model\Object\ObjectInterface;
44
use Apparat\Object\Domain\Model\Object\ResourceInterface;
45
use Apparat\Object\Domain\Model\Object\Revision;
46
use Apparat\Object\Domain\Model\Object\Type;
47
use Apparat\Object\Domain\Model\Uri\RepositoryLocator;
48
use Apparat\Object\Domain\Model\Uri\RepositoryLocatorInterface;
49
use Apparat\Object\Domain\Repository\InvalidArgumentException as RepositoryInvalidArgumentException;
50
use Apparat\Object\Domain\Repository\RepositoryInterface;
51
use Apparat\Object\Domain\Repository\Selector;
52
use Apparat\Object\Domain\Repository\SelectorInterface;
53
use Apparat\Resource\Ports\InvalidReaderArgumentException;
54
55
/**
56
 * Object manager
57
 *
58
 * @package Apparat\Object
59
 * @subpackage Apparat\Object\Infrastructure
60
 */
61
class Manager implements ManagerInterface
62
{
63
    /**
64
     * Create and return a new object
65
     *
66
     * @param RepositoryInterface $repository Repository to create the object in
67
     * @param Type $type Object type
68
     * @param string $payload Object payload
69
     * @param array $propertyData Object property data
70
     * @param \DateTimeInterface $creationDate Object creation date
71
     * @return ObjectInterface Object
72
     */
73 7
    public function createObject(
74
        RepositoryInterface $repository,
75
        Type $type,
76
        $payload = '',
77
        array $propertyData = [],
78
        \DateTimeInterface $creationDate = null
79
    ) {
80
        // Set the creation date to now if empty
81 7
        if ($creationDate === null) {
82 5
            $creationDate = new \DateTimeImmutable('now');
83
        }
84
85
        // Construct a creation closure
86 7
        $creationClosure = function (Id $uid) use ($repository, $type, $payload, $propertyData, $creationDate) {
87
            /** @var Revision $revision */
88 6
            $revision = Kernel::create(Revision::class, [1, true]);
89
90
            /** @var RepositoryLocator $repositoryLocator */
91 6
            $repositoryLocator = Kernel::create(RepositoryLocator::class, [$repository]);
92 6
            $repositoryLocator = $repositoryLocator->setId($uid);
93 6
            $repositoryLocator = $repositoryLocator->setRevision($revision);
94 6
            $repositoryLocator = $repositoryLocator->setType($type);
95 6
            $repositoryLocator = $repositoryLocator->setCreationDate($creationDate);
96
97 6
            return ObjectFactory::createFromParams($repositoryLocator, $payload, $propertyData);
98 7
        };
99
100
        // Wrap the object creation in an ID allocation transaction
101 7
        return $repository->getAdapterStrategy()->createObjectResource($creationClosure);
102
    }
103
104
    /**
105
     * Load an object from a repository
106
     *
107
     * @param RepositoryLocatorInterface $locator Repository object locator
108
     * @param int $visibility Object visibility
109
     * @return ObjectInterface Object
110
     */
111 34
    public function loadObject(RepositoryLocatorInterface $locator, $visibility = SelectorInterface::ALL)
112
    {
113
        // Create the current revision locator
114
        /** @var RepositoryLocatorInterface $currentLocator */
115 34
        $currentLocator = $locator->setRevision(Revision::current());
116
117
        // Load the object resource respecting visibility constraints
118 34
        $objectResource = $this->loadObjectResource($currentLocator, $visibility);
119
120
        // Instantiate the object
121 32
        $object = ObjectFactory::createFromResource($currentLocator, $objectResource);
122
123
        // Use and return the requested object revision
124 32
        return $object->useRevision($locator->getRevision());
125
    }
126
127
    /**
128
     * Load and return an object resource respecting visibility constraints
129
     *
130
     * @param RepositoryLocatorInterface $currentLocator
131
     * @param int $visibility Object visibility
132
     * @return ResourceInterface Object resource
133
     * @throws InvalidArgumentException If the resource could not be loaded
134
     */
135 35
    public function loadObjectResource(
136
        RepositoryLocatorInterface &$currentLocator,
137
        $visibility = SelectorInterface::ALL
138
    ) {
139
        // Validate the object visibility
140 35
        $this->validateVisibility($visibility);
141
142 34
        $objectResource = null;
143
144
        // Create the current revision locators (visible and hidden)
145
        /** @var RepositoryLocatorInterface[] $currentLocators */
146 34
        $currentLocators = array_filter([
147 34
            ($visibility & SelectorInterface::VISIBLE) ? $currentLocator->setHidden(false) : null,
148 34
            ($visibility & SelectorInterface::HIDDEN) ? $currentLocator->setHidden(true) : null,
149
        ]);
150
151
        // Run through the possible revision locators
152 34
        foreach ($currentLocators as $currentLocatorIndex => $currentLocator) {
153
            try {
154
                // Load the current object resource
155 34
                $objectResource = $this->getObjectResource($currentLocator);
156 33
                break;
157
158
                // In case of an error
159 3
            } catch (InvalidReaderArgumentException $e) {
160
                // If it's not an error about the resource not existing or if it's the last possible option
161 3
                if (($e->getCode() != InvalidReaderArgumentException::RESOURCE_DOES_NOT_EXIST)
162 3
                    || ($currentLocatorIndex >= (count($currentLocators) - 1))
163
                ) {
164 3
                    throw $e;
165
                }
166
            }
167
        }
168
169
        // If the resource could not be loaded
170 33
        if (!($objectResource instanceof ResourceInterface)) {
171
            throw new InvalidArgumentException(
172
                'Resource does not exist',
173
                InvalidArgumentException::RESOURCE_DOES_NOT_EXIST
174
            );
175
        }
176
177 33
        return $objectResource;
178
    }
179
180
    /**
181
     * Validate a given object visibility
182
     *
183
     * @param int $visibility Object visibility
184
     * @throw RepositoryInvalidArgumentException If the visibility requirement is invalid
185
     */
186 35
    protected function validateVisibility($visibility)
187
    {
188
        // If the visibility requirement is invalid
189 35
        if (!Selector::isValidVisibility($visibility)) {
190 1
            throw new RepositoryInvalidArgumentException(
191
                sprintf(
192 1
                    'Invalid repository selector visibility "%s"',
193
                    $visibility
194
                ),
195 1
                RepositoryInvalidArgumentException::INVALID_REPOSITORY_SELECTOR_COMPONENT,
196 1
                null,
197 1
                'visibility'
198
            );
199
        }
200 34
    }
201
202
    /**
203
     * Instantiate object resource
204
     *
205
     * @param RepositoryLocatorInterface $locator
206
     * @return ResourceInterface Object resource
207
     */
208 34
    public function getObjectResource(RepositoryLocatorInterface $locator)
209
    {
210 34
        return $locator->getRepository()->getAdapterStrategy()->getObjectResource(
211 34
            $locator->withExtension(getenv('OBJECT_RESOURCE_EXTENSION'))
212
        );
213
    }
214
215
    /**
216
     * Test whether an object resource exists
217
     *
218
     * @param RepositoryLocatorInterface $locator
219
     * @return boolean Object resource exists
220
     */
221 38
    public function objectResourceExists(RepositoryLocatorInterface $locator)
222
    {
223 38
        return $locator->getRepository()->getAdapterStrategy()->hasResource(
224 38
            $locator->withExtension(getenv('OBJECT_RESOURCE_EXTENSION'))
225
        );
226
    }
227
}
228