Completed
Push — master ( f077fb...76bf7f )
by Joschi
05:21
created

Locator::toUrl()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 24
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 5
eloc 11
c 1
b 1
f 0
nc 8
nop 1
dl 0
loc 24
ccs 13
cts 13
cp 1
crap 5
rs 8.5125
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\Uri;
38
39
use Apparat\Kernel\Ports\Kernel;
40
use Apparat\Object\Domain\Model\Object\Id;
41
use Apparat\Object\Domain\Model\Object\Revision;
42
use Apparat\Object\Domain\Model\Object\Type;
43
44
/**
45
 * Object locator
46
 *
47
 * @package Apparat\Object
48
 * @subpackage Apparat\Object\Domain
49
 */
50
class Locator implements LocatorInterface
51
{
52
    /**
53
     * Date PCRE pattern
54
     *
55
     * @var array
56
     */
57
    protected static $datePattern = [
58
        'Y' => '(?P<year>\d{4})',
59
        'm' => '(?P<month>\d{2})',
60
        'd' => '(?P<day>\d{2})',
61
        'H' => '(?P<hour>\d{2})',
62
        'i' => '(?P<minute>\d{2})',
63
        's' => '(?P<second>\d{2})',
64
    ];
65
    /**
66
     * Creation date
67
     *
68
     * @var \DateTimeInterface
69
     */
70
    protected $creationDate = null;
71
    /**
72
     * Object ID
73
     *
74
     * @var Id
75
     */
76
    protected $uid = null;
77
    /**
78
     * Object type
79
     *
80
     * @var Type
81
     */
82
    protected $type = null;
83
    /**
84
     * Object revision
85
     *
86
     * @var Revision
87
     */
88
    protected $revision = null;
89
    /**
90
     * Hidden object
91
     *
92
     * @var boolean
93
     */
94
    protected $hidden = false;
95
96
    /*******************************************************************************
97
     * PUBLIC METHODS
98
     *******************************************************************************/
99
100
    /**
101
     * Object URL constructor
102
     *
103
     * @param null|string $locator Object locator
104
     * @param null|boolean|int $datePrecision Date precision [NULL = local default, TRUE = any precision (remote object
105
     *     URLs)]
106
     * @param string $leader Leading base locator
107
     * @throws InvalidArgumentException If the object URL locator is invalid
108
     */
109 78
    public function __construct($locator = null, $datePrecision = null, &$leader = '')
110
    {
111 78
        if (!empty($locator)) {
112
            // If the local default date precision should be used
113 72
            if ($datePrecision === null) {
114 38
                $datePrecision = intval(getenv('OBJECT_DATE_PRECISION'));
115 38
            }
116
117
            // Build the regular expression for matching a local locator
118 72
            $locatorPattern = $this->buildLocatorRegex($datePrecision);
119
120
            // Match the local locator
121 71
            if (!preg_match($locatorPattern, $locator, $locatorParts)) {
122 38
                throw new InvalidArgumentException(
123 38
                    sprintf('Invalid object URL locator "%s"', $locator),
124
                    InvalidArgumentException::INVALID_OBJECT_URL_LOCATOR
125 38
                );
126
            }
127
128
            // If date components are used
129 71
            if ($datePrecision) {
130 71
                $year = $locatorParts['year'];
131 71
                $month = isset($locatorParts['month']) ? $locatorParts['month'] ?: '01' : '01';
132 71
                $day = isset($locatorParts['day']) ? $locatorParts['day'] ?: '01' : '01';
133 71
                $hour = isset($locatorParts['hour']) ? $locatorParts['hour'] ?: '00' : '00';
134 71
                $minute = isset($locatorParts['minute']) ? $locatorParts['minute'] ?: '00' : '00';
135 71
                $second = isset($locatorParts['second']) ? $locatorParts['second'] ?: '00' : '00';
136 71
                $this->creationDate = new \DateTimeImmutable("$year-$month-$day".'T'."$hour:$minute:$second+00:00");
137 71
            }
138
139
            // Determine the leader
140 71
            $leader = ($datePrecision === true) ? substr(
141 48
                $locator,
142 48
                0,
143 48
                strlen($locator) - strlen($locatorParts[0])
144 71
            ) : $locatorParts['leader'];
145
146
            // Set the hidden state
147 71
            $this->hidden = !empty($locatorParts['hidden']);
148
149
            // Set the ID
150 71
            $this->uid = Kernel::create(Id::class, [intval($locatorParts['id'])]);
151
152
            // Set the type
153 71
            $this->type = Kernel::create(Type::class, [$locatorParts['type']]);
154
155
            // Set the revision
156 71
            $this->revision = Kernel::create(
157 71
                Revision::class,
158
                [
159 71
                    empty($locatorParts['revision']) ? Revision::CURRENT : intval($locatorParts['revision']),
160 71
                    !empty($locatorParts['draft'])
161 71
                ]
162 71
            );
163 71
        }
164 77
    }
165
166
    /**
167
     * Build the regular expression for matching a local object locator
168
     *
169
     * @param null|boolean|int $datePrecision Date precision [NULL = local default, TRUE = any precision (remote object
170
     *     URLs)]
171
     * @return string Regular expression for matching a local object locator
172
     * @throws InvalidArgumentException If the date precision is invalid
173
     */
174 72
    protected function buildLocatorRegex($datePrecision)
175
    {
176 72
        $locatorPattern = null;
177
178
        // If a valid integer date precision is given
179 72
        if (is_int($datePrecision) && ($datePrecision >= 0) && ($datePrecision < 7)) {
180
            $locatorPattern = '%^(?P<leader>(/[^/]+)*)?/'.
181 38
                implode(
182 38
                    '/',
183 38
                    array_slice(self::$datePattern, 0, $datePrecision)
184 38
                ).($datePrecision ? '/' : '');
185
186
            // Else if the date precision may be arbitrary
187 72
        } elseif ($datePrecision === true) {
188 51
            $locatorPattern = '%(?:/'.implode('(?:/', self::$datePattern);
189 51
            $locatorPattern .= str_repeat(')?', count(self::$datePattern));
190 51
            $locatorPattern .= '/';
191 51
        }
192
193
        // If the date precision is invalid
194 72
        if ($locatorPattern === null) {
195 1
            throw new InvalidArgumentException(
196 1
                sprintf(
197 1
                    'Invalid date precision "%s" (%s)',
198 1
                    strval($datePrecision),
199 1
                    gettype($datePrecision)
200 1
                ),
201
                InvalidArgumentException::INVALID_DATE_PRECISION
202 1
            );
203
        }
204
205 71
        $locatorPattern .= '(?P<hidden>\.)?(?P<id>\d+)\-(?P<type>[a-z]+)(?:/(?P<draft>\.)?(.*\.)?';
206 71
        $locatorPattern .= '\\k<id>(?:-(?P<revision>\d+))?(?P<extension>\.[a-z0-9]+)?)?$%';
207
208 71
        return $locatorPattern;
209
    }
210
211
    /**
212
     * Serialize the object locator
213
     *
214
     * @return string Object locator
215
     */
216 48
    public function __toString()
217
    {
218 48
        return $this->toUrl(false);
219
    }
220
221
    /**
222
     * Serialize as relative URL
223
     *
224
     * @param bool $canonical Canonical URL
225
     * @return string Relative URL
226
     */
227 49
    public function toUrl($canonical = false)
228
    {
229 49
        $locator = [];
230 49
        $datePrecision = intval(getenv('OBJECT_DATE_PRECISION'));
231
232
        // Add the creation date
233 49
        foreach (array_slice(array_keys(self::$datePattern), 0, $datePrecision) as $dateFormat) {
234 49
            $locator[] = $this->creationDate->format($dateFormat);
235 49
        }
236
237
        // Add the object ID and type
238 49
        $uid = $this->uid->getId();
239 49
        $locator[] = ($this->hidden ? '.' : '').$uid;
240
241
        // If not only the canonical URL should be returned
242 49
        if (!$canonical) {
243 49
            $locator[count($locator) - 1] .= '-'.$this->type->getType();
244
245
            // Add the ID, draft mode and revision
246 49
            $locator[] = rtrim(($this->revision->isDraft() ? '.' : '').$uid.'-'.$this->revision->getRevision(), '-');
247 49
        }
248
249 49
        return '/'.implode('/', $locator);
250
    }
251
252
    /**
253
     * Return the object's creation date
254
     *
255
     * @return \DateTimeInterface Object creation date
256
     */
257 51
    public function getCreationDate()
258
    {
259 51
        return $this->creationDate;
260
    }
261
262
    /**
263
     * Set the object's creation date
264
     *
265
     * @param \DateTimeInterface $creationDate
266
     * @return LocatorInterface|Locator New object locator
267
     */
268 8
    public function setCreationDate(\DateTimeInterface $creationDate)
269
    {
270 8
        $locator = clone $this;
271 8
        $locator->creationDate = $creationDate;
272 8
        return $locator;
273
    }
274
275
    /**
276
     * Return the object type
277
     *
278
     * @return Type Object type
279
     */
280 55
    public function getObjectType()
281
    {
282 55
        return $this->type;
283
    }
284
285
    /**
286
     * Set the object type
287
     *
288
     * @param Type $type Object type
289
     * @return LocatorInterface|Locator New object locator
290
     */
291 8
    public function setObjectType(Type $type)
292
    {
293 8
        $locator = clone $this;
294 8
        $locator->type = $type;
295 8
        return $locator;
296
    }
297
298
    /**
299
     * Return the object ID
300
     *
301
     * @return Id Object ID
302
     */
303 54
    public function getId()
304
    {
305 54
        return $this->uid;
306
    }
307
308
    /**
309
     * Set the object ID
310
     *
311
     * @param Id $uid Object ID
312
     * @return LocatorInterface|Locator New object locator
313
     */
314 8
    public function setId(Id $uid)
315
    {
316 8
        $locator = clone $this;
317 8
        $locator->uid = $uid;
318 8
        return $locator;
319
    }
320
321
    /**
322
     * Return the object revision
323
     *
324
     * @return Revision Object revision
325
     */
326 53
    public function getRevision()
327
    {
328 53
        return $this->revision;
329
    }
330
331
    /**
332
     * Set the object revision
333
     *
334
     * @param Revision $revision Object revision
335
     * @return LocatorInterface|Locator New object locator
336
     */
337 50
    public function setRevision(Revision $revision)
338
    {
339 50
        $locator = clone $this;
340 50
        $locator->revision = $revision;
341 50
        return $locator;
342
    }
343
344
    /**
345
     * Return the object hidden state
346
     *
347
     * @return boolean Object hidden state
348
     */
349 3
    public function isHidden()
350
    {
351 3
        return $this->hidden;
352
    }
353
354
    /**
355
     * Set the object hidden state
356
     *
357
     * @param boolean $hidden Object hidden state
358
     * @return LocatorInterface|Locator New object locator
359
     */
360 48
    public function setHidden($hidden)
361
    {
362 48
        $locator = clone $this;
363 48
        $locator->hidden = !!$hidden;
364 48
        return $locator;
365
    }
366
}
367