Completed
Push — master ( ca81b9...863650 )
by Joschi
03:44
created

AbstractObject::persist()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.5

Importance

Changes 2
Bugs 0 Features 2
Metric Value
cc 2
eloc 11
nc 2
nop 0
dl 0
loc 22
rs 9.2
c 2
b 0
f 2
ccs 5
cts 10
cp 0.5
crap 2.5
1
<?php
2
3
/**
4
 * apparat-object
5
 *
6
 * @category    Apparat
7
 * @package     Apparat\Object
8
 * @subpackage  Apparat\Object\Domain
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\Domain\Model\Object;
38
39
use Apparat\Kernel\Ports\Kernel;
40
use Apparat\Object\Domain\Model\Object\Traits\DomainPropertiesTrait;
41
use Apparat\Object\Domain\Model\Object\Traits\MetaPropertiesTrait;
42
use Apparat\Object\Domain\Model\Object\Traits\PayloadTrait;
43
use Apparat\Object\Domain\Model\Object\Traits\ProcessingInstructionsTrait;
44
use Apparat\Object\Domain\Model\Object\Traits\RelationsTrait;
45
use Apparat\Object\Domain\Model\Object\Traits\SystemPropertiesTrait;
46
use Apparat\Object\Domain\Model\Path\RepositoryPath;
47
use Apparat\Object\Domain\Model\Path\RepositoryPathInterface;
48
use Apparat\Object\Domain\Model\Properties\AbstractDomainProperties;
49
use Apparat\Object\Domain\Model\Properties\InvalidArgumentException as PropertyInvalidArgumentException;
50
use Apparat\Object\Domain\Model\Properties\MetaProperties;
51
use Apparat\Object\Domain\Model\Properties\ProcessingInstructions;
52
use Apparat\Object\Domain\Model\Properties\Relations;
53
use Apparat\Object\Domain\Model\Properties\SystemProperties;
54
use Apparat\Object\Domain\Repository\Service;
55
56
/**
57
 * Abstract object
58
 *
59
 * @package Apparat\Object
60
 * @subpackage Apparat\Object\Domain
61
 */
62
abstract class AbstractObject implements ObjectInterface
63
{
64
    /**
65
     * Use traits
66
     */
67
    use SystemPropertiesTrait, MetaPropertiesTrait, DomainPropertiesTrait, RelationsTrait,
68
        ProcessingInstructionsTrait, PayloadTrait;
69
    /**
70
     * Clean state
71
     *
72
     * @var int
73
     */
74
    const STATE_CLEAN = 0;
75
    /**
76
     * Dirty state
77
     *
78
     * @var int
79
     */
80
    const STATE_DIRTY = 1;
81
    /**
82
     * Mutated state
83
     *
84
     * @var int
85
     */
86
    const STATE_MUTATED = 2;
87
    /**
88
     * Published state
89
     *
90
     * @var int
91
     */
92
    const STATE_PUBLISHED = 4;
93
    /**
94
     * Repository path
95
     *
96
     * @var RepositoryPathInterface
97
     */
98
    protected $path;
99
    /**
100
     * Latest revision index
101
     *
102
     * @var Revision
103
     */
104
    protected $latestRevision;
105
    /**
106
     * Object state
107
     *
108
     * @var int
109
     */
110
    protected $state = self::STATE_CLEAN;
111
    /**
112
     * Property collection states
113
     *
114
     * @var array
115
     */
116
    protected $collectionStates = [];
117
118
    /**
119
     * Object constructor
120
     *
121
     * @param string $payload Object payload
122
     * @param array $propertyData Property data
123
     * @param RepositoryPathInterface $path Object repository path
124
     */
125 21
    public function __construct($payload = '', array $propertyData = [], RepositoryPathInterface $path = null)
126
    {
127
        // If the domain property collection class is invalid
128 21
        if (!$this->domainPropertyCClass
129 21
            || !class_exists($this->domainPropertyCClass)
130 21
            || !(new \ReflectionClass($this->domainPropertyCClass))->isSubclassOf(AbstractDomainProperties::class)
131
        ) {
132 1
            throw new PropertyInvalidArgumentException(
133
                sprintf(
134 1
                    'Invalid domain property collection class "%s"',
135 1
                    $this->domainPropertyCClass
136
                ),
137 1
                PropertyInvalidArgumentException::INVALID_DOMAIN_PROPERTY_COLLECTION_CLASS
138
            );
139
        }
140
141
        // Right after instantiation it's always the current revision
142 20
        $this->path = $path->setRevision(Revision::current());
0 ignored issues
show
Bug introduced by
It seems like $path is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
143
144
        // Load the current revision data
145 20
        $this->loadRevisionData($payload, $propertyData);
146
147
        // Save the latest revision index
148 19
        $this->latestRevision = $this->getRevision();
149 19
    }
150
151
    /**
152
     * Load object revision data
153
     *
154
     * @param string $payload Object payload
155
     * @param array $propertyData Property data
156
     */
157 20
    protected function loadRevisionData($payload = '', array $propertyData = [])
158
    {
159 20
        $this->payload = $payload;
160
161
        // Instantiate the system properties
162 20
        $systemPropertyData = (empty($propertyData[SystemProperties::COLLECTION]) ||
163 20
            !is_array(
164 20
                $propertyData[SystemProperties::COLLECTION]
165 20
            )) ? [] : $propertyData[SystemProperties::COLLECTION];
166 20
        $this->systemProperties = Kernel::create(SystemProperties::class, [$systemPropertyData, $this]);
167
168
        // Instantiate the meta properties
169 19
        $metaPropertyData = (empty($propertyData[MetaProperties::COLLECTION]) ||
170 18
            !is_array(
171 19
                $propertyData[MetaProperties::COLLECTION]
172 19
            )) ? [] : $propertyData[MetaProperties::COLLECTION];
173
        /** @var MetaProperties $metaPropertyCollection */
174 19
        $metaPropertyCollection = Kernel::create(MetaProperties::class, [$metaPropertyData, $this]);
175 19
        $this->setMetaProperties($metaPropertyCollection, true);
176
177
        // Instantiate the domain properties
178 19
        $domainPropertyData = (empty($propertyData[AbstractDomainProperties::COLLECTION]) ||
179 18
            !is_array(
180 19
                $propertyData[AbstractDomainProperties::COLLECTION]
181 19
            )) ? [] : $propertyData[AbstractDomainProperties::COLLECTION];
182
        /** @var AbstractDomainProperties $domainPropertyCollection */
183 19
        $domainPropertyCollection = Kernel::create($this->domainPropertyCClass, [$domainPropertyData, $this]);
184 19
        $this->setDomainProperties($domainPropertyCollection, true);
185
186
        // Instantiate the processing instructions
187 19
        $procInstData = (empty($propertyData[ProcessingInstructions::COLLECTION]) ||
188 15
            !is_array(
189 19
                $propertyData[ProcessingInstructions::COLLECTION]
190 19
            )) ? [] : $propertyData[ProcessingInstructions::COLLECTION];
191
        /** @var ProcessingInstructions $procInstCollection */
192 19
        $procInstCollection = Kernel::create(ProcessingInstructions::class, [$procInstData, $this]);
193 19
        $this->setProcessingInstructions($procInstCollection, true);
194
195
        // Instantiate the object relations
196 19
        $relationData = (empty($propertyData[Relations::COLLECTION]) ||
197 18
            !is_array(
198 19
                $propertyData[Relations::COLLECTION]
199 19
            )) ? [] : $propertyData[Relations::COLLECTION];
200
        /** @var Relations $relationCollection */
201 19
        $relationCollection = Kernel::create(Relations::class, [$relationData, $this]);
202 19
        $this->setRelations($relationCollection, true);
203
204
        // Reset the object state to clean
205 19
        $this->state = self::STATE_CLEAN;
206 19
    }
207
208
    /**
209
     * Return whether the object is in mutated state
210
     *
211
     * @return boolean Mutated state
212
     */
213 3
    public function isMutated()
214
    {
215 3
        return !!($this->state & self::STATE_MUTATED);
216
    }
217
218
    /**
219
     * Use a specific object revision
220
     *
221
     * @param Revision $revision Revision to be used
222
     * @return ObjectInterface Object
223
     * @throws OutOfBoundsException If the requested revision is invalid
224
     */
225 18
    public function useRevision(Revision $revision)
226
    {
227 18
        $isCurrentRevision = false;
228
229
        // If the requested revision is invalid
230 18
        if (!$revision->isCurrent() &&
231 18
            (($revision->getRevision() < 1) || ($revision->getRevision() > $this->latestRevision->getRevision()))
232
        ) {
233
            throw new OutOfBoundsException(sprintf('Invalid object revision "%s"', $revision->getRevision()),
234
                OutOfBoundsException::INVALID_OBJECT_REVISION);
235
        }
236
237
        // If the current revision got requested
238 18
        if ($revision->isCurrent()) {
239 18
            $isCurrentRevision = true;
240 18
            $revision = $this->latestRevision;
241
        }
242
243
        // If the requested revision is not already used
244 18
        if ($revision != $this->getRevision()) {
245
            /** @var ManagerInterface $objectManager */
246
            $objectManager = Kernel::create(Service::class)->getObjectManager();
247
248
            // Load the requested object revision resource
249
            /** @var Revision $newRevision */
250
            $newRevision = $isCurrentRevision ? Revision::current() : $revision;
251
            /** @var RepositoryPath $newRevisionPath */
252
            $newRevisionPath = $this->path->setRevision($newRevision);
253
            $revisionResource = $objectManager->loadObject($newRevisionPath);
254
255
            // Load the revision resource data
256
            $this->loadRevisionData($revisionResource->getPayload(), $revisionResource->getPropertyData());
257
258
            // Set the current revision path
259
            $this->path = $newRevisionPath;
260
        }
261
262 18
        return $this;
263
    }
264
265
    /**
266
     * Return the object repository path
267
     *
268
     * @return RepositoryPathInterface Object repository path
269
     */
270 19
    public function getRepositoryPath()
271
    {
272 19
        return $this->path;
273
    }
274
275
    /**
276
     * Return the object property data
277
     *
278
     * @return array Object property data
279
     */
280 5
    public function getPropertyData()
281
    {
282 5
        $propertyData = array_filter([
283 5
            SystemProperties::COLLECTION => $this->systemProperties->toArray(),
284 5
            MetaProperties::COLLECTION => $this->metaProperties->toArray(),
285 5
            AbstractDomainProperties::COLLECTION => $this->domainProperties->toArray(),
286 5
            ProcessingInstructions::COLLECTION => $this->processingInstructions->toArray(),
287 5
            Relations::COLLECTION => $this->relations->toArray(),
288 5
        ], function (array $collection) {
289 5
            return (boolean)count($collection);
290 5
        });
291
292 5
        return $propertyData;
293
    }
294
295
    /**
296
     * Set the object state to mutated
297
     */
298 3
    protected function setMutatedState()
299
    {
300
        // If this object is not in mutated state yet
301 3
        if (!($this->state & self::STATE_MUTATED) && !$this->isDraft()) {
302
            // TODO: Send signal
303 3
            $this->convertToDraft();
304
        }
305
306
        // Enable the mutated (and dirty) state
307 3
        $this->state |= (self::STATE_DIRTY | self::STATE_MUTATED);
308 3
    }
309
310
    /**
311
     * Return the object draft mode
312
     *
313
     * @return boolean Object draft mode
314
     */
315 4
    public function isDraft()
316
    {
317 4
        return $this->systemProperties->isDraft() || $this->isPublished();
318
    }
319
320
    /**
321
     * Return whether the object is in published state
322
     *
323
     * @return boolean Published state
324
     */
325 4
    public function isPublished()
326
    {
327 4
        return !!($this->state & self::STATE_PUBLISHED);
328
    }
329
330
    /**
331
     * Convert this object revision into a draft
332
     */
333 3
    protected function convertToDraft()
334
    {
335
        // Increment the latest revision number
336 3
        $this->latestRevision = $this->latestRevision->increment();
337
338
        // Create draft system properties
339 3
        $this->systemProperties = $this->systemProperties->createDraft($this->latestRevision);
340
341
        // Adapt the system properties collection state
342 3
        $this->collectionStates[SystemProperties::COLLECTION] = spl_object_hash($this->systemProperties);
343
344
        // Set the draft flag on the repository path
345 3
        $this->path = $this->path->setDraft(true)->setRevision(Revision::current());
346
347
        // If this is not already a draft ...
348
        // Recreate the system properties
349
        // Copy the object ID
350
        // Copy the object type
351
        // Set the revision number to latest revision + 1
352
        // Set the creation date to now
353
        // Set no publication date
354
        // Set the draft flag on the repository path
355
        // Increase the latest revision by 1
356
357
        // Else if this is a draft
358
        // No action needed
359 3
    }
360
361
    /**
362
     * Return the absolute object URL
363
     *
364
     * @return string
365
     */
366 4
    public function getAbsoluteUrl()
367
    {
368 4
        return getenv('APPARAT_BASE_URL').ltrim($this->path->getRepository()->getUrl(), '/').strval($this->path);
369
    }
370
371
    /**
372
     * Persist the current object revision
373
     *
374
     * @return ObjectInterface Object
375
     */
376 1
    public function persist()
377
    {
378
        // If this is not the latest revision
379 1
        if ($this->getRevision() != $this->latestRevision) {
380
            throw new RuntimeException(
381
                sprintf(
382
                    'Cannot persist revision %s/%s',
383
                    $this->getRevision()->getRevision(),
384
                    $this->latestRevision->getRevision()
385
                ),
386
                RuntimeException::CANNOT_PERSIST_EARLIER_REVISION
387
            );
388
        }
389
390
        // Update the object repository
391 1
        $this->path->getRepository()->updateObject($this);
392
393
        // Reset state
394 1
        $this->state = self::STATE_CLEAN;
395
396 1
        return $this;
397
    }
398
399
    /**
400
     * Publish the current object revision
401
     *
402
     * @return ObjectInterface Object
403
     */
404 1
    public function publish()
405
    {
406
        // If this is a draft
407 1
        if ($this->isDraft()) {
408
            // TODO: Send signal
409
410
            // Create draft system properties
411 1
            $this->systemProperties = $this->systemProperties->publish();
412
413
            // Adapt the system properties collection state
414 1
            $this->collectionStates[SystemProperties::COLLECTION] = spl_object_hash($this->systemProperties);
415
416
            // Set the draft flag on the repository path
417 1
            $this->path = $this->path->setDraft(false);
418
419
            // Flag this object as dirty
420 1
            $this->setPublishedState();
421
        }
422
423 1
        return $this;
424
    }
425
426
    /**
427
     * Set the object state to published
428
     */
429 1
    protected function setPublishedState()
430
    {
431
        // If this object is not in dirty state yet
432 1
        if (!($this->state & self::STATE_PUBLISHED)) {
433
            // TODO: Send signal
434
        }
435
436
        // Enable the dirty state
437 1
        $this->state |= (self::STATE_DIRTY | self::STATE_PUBLISHED);
438 1
    }
439
440
    /**
441
     * Return whether the object is in dirty state
442
     *
443
     * @return boolean Dirty state
444
     */
445 3
    public function isDirty()
446
    {
447 3
        return !!($this->state & self::STATE_DIRTY);
448
    }
449
450
    /**
451
     * Set the object state to dirty
452
     */
453 2
    protected function setDirtyState()
454
    {
455
        // If this object is not in dirty state yet
456 2
        if (!($this->state & self::STATE_DIRTY)) {
457
            // TODO: Send signal
458
        }
459
460
        // Enable the dirty state
461 2
        $this->state |= self::STATE_DIRTY;
462 2
    }
463
}
464