Passed
Push — master ( 67ee52...70965b )
by Mathieu
02:28
created

RoutableTrait::getLatestObjectRoute()   B

Complexity

Conditions 8
Paths 9

Size

Total Lines 53
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 53
rs 7.1199
c 0
b 0
f 0
cc 8
eloc 32
nc 9
nop 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Charcoal\Object;
4
5
use Exception;
6
use InvalidArgumentException;
7
use UnexpectedValueException;
8
9
// From 'charcoal-core'
10
use Charcoal\Loader\CollectionLoader;
11
12
// From 'charcoal-translation'
13
use Charcoal\Translator\Translation;
14
15
// From 'charcoal-view'
16
use Charcoal\View\ViewableInterface;
17
18
// From 'charcoal-object'
19
use Charcoal\Object\ObjectRoute;
20
use Charcoal\Object\ObjectRouteInterface;
21
22
/**
23
 * Full implementation, as Trait, of the {@see \Charcoal\Object\RoutableInterface}.
24
 *
25
 * This implementation uses a secondary model, {@see \Charcoal\Object\ObjectRoute},
26
 * to collect all routes of routable models under a single source.
27
 */
28
trait RoutableTrait
29
{
30
    /**
31
     * The object's route.
32
     *
33
     * @var \Charcoal\Translator\Translation|null
34
     */
35
    protected $slug;
36
37
    /**
38
     * Whether the slug is editable.
39
     *
40
     * If FALSE, the slug is always auto-generated from its pattern.
41
     * If TRUE, the slug is auto-generated only if the slug is empty.
42
     *
43
     * @var boolean|null
44
     */
45
    private $isSlugEditable;
46
47
    /**
48
     * The object's route pattern.
49
     *
50
     * @var \Charcoal\Translator\Translation|null
51
     */
52
    private $slugPattern = '';
53
54
    /**
55
     * A prefix for the object's route.
56
     *
57
     * @var \Charcoal\Translator\Translation|null
58
     */
59
    private $slugPrefix = '';
60
61
    /**
62
     * A suffix for the object's route.
63
     *
64
     * @var \Charcoal\Translator\Translation|null
65
     */
66
    private $slugSuffix = '';
67
68
    /**
69
     * Latest ObjectRoute object concerning the current object.
70
     *
71
     * @var ObjectRouteInterface
72
     */
73
    private $latestObjectRoute;
74
75
    /**
76
     * The class name of the object route model.
77
     *
78
     * Must be a fully-qualified PHP namespace and an implementation of
79
     * {@see \Charcoal\Object\ObjectRouteInterface}. Used by the model factory.
80
     *
81
     * @var string
82
     */
83
    private $objectRouteClass = ObjectRoute::class;
84
85
    /**
86
     * The object's route options.
87
     *
88
     * @var array|null
89
     */
90
    protected $routeOptions;
91
92
    /**
93
     * Retrieve the foreign object's routes options ident.
94
     *
95
     * @var string
96
     */
97
    protected $routeOptionsIdent;
98
99
    /**
100
     * Set the object's URL slug pattern.
101
     *
102
     * @param  mixed $pattern The slug pattern.
103
     * @return RoutableInterface Chainable
104
     */
105
    public function setSlugPattern($pattern)
106
    {
107
        $this->slugPattern = $this->translator()->translation($pattern);
108
109
        return $this;
110
    }
111
112
    /**
113
     * Retrieve the object's URL slug pattern.
114
     *
115
     * @throws Exception If a slug pattern is not defined.
116
     * @return \Charcoal\Translator\Translation|null
117
     */
118
    public function slugPattern()
119
    {
120
        if (!$this->slugPattern) {
121
            $metadata = $this->metadata();
0 ignored issues
show
Bug introduced by
It seems like metadata() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
122
123
            if (isset($metadata['routable']['pattern'])) {
124
                $this->setSlugPattern($metadata['routable']['pattern']);
125
            } elseif (isset($metadata['slug_pattern'])) {
126
                $this->setSlugPattern($metadata['slug_pattern']);
127
            } else {
128
                throw new Exception(sprintf(
129
                    'Undefined route pattern (slug) for %s',
130
                    get_called_class()
131
                ));
132
            }
133
        }
134
135
        return $this->slugPattern;
136
    }
137
138
    /**
139
     * Retrieve route prefix for the object's URL slug pattern.
140
     *
141
     * @return \Charcoal\Translator\Translation|null
142
     */
143 View Code Duplication
    public function slugPrefix()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
144
    {
145
        if (!$this->slugPrefix) {
146
            $metadata = $this->metadata();
0 ignored issues
show
Bug introduced by
It seems like metadata() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
147
148
            if (isset($metadata['routable']['prefix'])) {
149
                $this->slugPrefix = $this->translator()->translation($metadata['routable']['prefix']);
150
            }
151
        }
152
153
        return $this->slugPrefix;
154
    }
155
156
    /**
157
     * Retrieve route suffix for the object's URL slug pattern.
158
     *
159
     * @return \Charcoal\Translator\Translation|null
160
     */
161 View Code Duplication
    public function slugSuffix()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
162
    {
163
        if (!$this->slugSuffix) {
164
            $metadata = $this->metadata();
0 ignored issues
show
Bug introduced by
It seems like metadata() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
165
166
            if (isset($metadata['routable']['suffix'])) {
167
                $this->slugSuffix = $this->translator()->translation($metadata['routable']['suffix']);
168
            }
169
        }
170
171
        return $this->slugSuffix;
172
    }
173
174
    /**
175
     * Determine if the slug is editable.
176
     *
177
     * @return boolean
178
     */
179
    public function isSlugEditable()
180
    {
181
        if ($this->isSlugEditable === null) {
182
            $metadata = $this->metadata();
0 ignored issues
show
Bug introduced by
It seems like metadata() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
183
184
            if (isset($metadata['routable']['editable'])) {
185
                $this->isSlugEditable = !!$metadata['routable']['editable'];
186
            } else {
187
                $this->isSlugEditable = false;
188
            }
189
        }
190
191
        return $this->isSlugEditable;
192
    }
193
194
    /**
195
     * Set the object's URL slug.
196
     *
197
     * @param  mixed $slug The slug.
198
     * @return RoutableInterface Chainable
199
     */
200
    public function setSlug($slug)
0 ignored issues
show
Coding Style introduced by
setSlug uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
201
    {
202
        $slug = $this->translator()->translation($slug);
203
        if ($slug !== null) {
204
            $this->slug = $slug;
205
206
            $values = $this->slug->data();
207
            foreach ($values as $lang => $val) {
208
                $this->slug[$lang] = $this->slugify($val);
209
            }
210
        } else {
211
            /** @todo Hack used for regenerating route */
212
            if (isset($_POST['slug'])) {
213
                $this->slug = [];
0 ignored issues
show
Documentation Bug introduced by
It seems like array() of type array is incompatible with the declared type object<Charcoal\Translator\Translation>|null of property $slug.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
214
            } else {
215
                $this->slug = null;
216
            }
217
        }
218
219
        return $this;
220
    }
221
222
    /**
223
     * Retrieve the object's URL slug.
224
     *
225
     * @return \Charcoal\Translator\Translation|null
226
     */
227
    public function slug()
228
    {
229
        return $this->slug;
230
    }
231
232
    /**
233
     * Generate a URL slug from the object's URL slug pattern.
234
     *
235
     * @throws UnexpectedValueException If the slug is empty.
236
     * @return \Charcoal\Translator\Translation
237
     */
238
    public function generateSlug()
239
    {
240
        $languages = $this->translator()->availableLocales();
241
        $patterns = $this->slugPattern();
242
        $curSlug = $this->slug();
243
        $newSlug = [];
244
245
        $origLang = $this->translator()->getLocale();
246
        foreach ($languages as $lang) {
247
            $pattern = $patterns[$lang];
248
249
            $this->translator()->setLocale($lang);
250
            if ($this->isSlugEditable() && isset($curSlug[$lang]) && strlen($curSlug[$lang])) {
251
                $newSlug[$lang] = $curSlug[$lang];
252
            } else {
253
                $newSlug[$lang] = $this->generateRoutePattern($pattern);
254
                if (!strlen($newSlug[$lang])) {
255
                    throw new UnexpectedValueException(sprintf(
256
                        'The slug is empty. The pattern is "%s"',
257
                        $pattern
258
                    ));
259
                }
260
            }
261
            $newSlug[$lang] = $this->finalizeSlug($newSlug[$lang]);
262
263
            $objectRoute = $this->createRouteObject();
264
            $objectRoute->setData([
265
                'lang'           => $lang,
266
                'slug'           => $newSlug[$lang],
267
                'route_obj_type' => $this->objType(),
0 ignored issues
show
Bug introduced by
It seems like objType() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
268
                'route_obj_id'   => $this->id()
0 ignored issues
show
Bug introduced by
It seems like id() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
269
            ]);
270
271
            if (!$objectRoute->isSlugUnique()) {
272
                $objectRoute->generateUniqueSlug();
273
                $newSlug[$lang] = $objectRoute->slug();
274
            }
275
        }
276
        $this->translator()->setLocale($origLang);
277
278
        return $this->translator()->translation($newSlug);
279
    }
280
281
    /**
282
     * Generate a route from the given pattern.
283
     *
284
     * @uses   self::parseRouteToken() If a view renderer is unavailable.
285
     * @param  string $pattern The slug pattern.
286
     * @return string Returns the generated route.
287
     */
288
    protected function generateRoutePattern($pattern)
289
    {
290
        if ($this instanceof ViewableInterface && $this->view() !== null) {
291
            $route = $this->view()->render($pattern, $this->viewController());
292
        } else {
293
            $route = preg_replace_callback('~\{\{\s*(.*?)\s*\}\}~i', [ $this, 'parseRouteToken' ], $pattern);
294
        }
295
296
        return $this->slugify($route);
297
    }
298
299
    /**
300
     * Parse the given slug (URI token) for the current object.
301
     *
302
     * @used-by self::generateRoutePattern() If a view renderer is unavailable.
303
     * @uses    self::filterRouteToken() For customize the route value filtering,
304
     * @param   string|array $token The token to parse relative to the model entry.
305
     * @throws  InvalidArgumentException If a route token is not a string.
306
     * @return  string
307
     */
308
    protected function parseRouteToken($token)
309
    {
310
        // Processes matches from a regular expression operation
311
        if (is_array($token) && isset($token[1])) {
312
            $token = $token[1];
313
        }
314
315
        $token = trim($token);
316
        $method = [ $this, $token ];
317
318
        if (is_callable($method)) {
319
            $value = call_user_func($method);
320
            /** @see \Charcoal\Config\AbstractEntity::offsetGet() */
321
        } elseif (isset($this[$token])) {
322
            $value = $this[$token];
323
        } else {
324
            return '';
325
        }
326
327
        $value = $this->filterRouteToken($value, $token);
328
        if (!is_string($value) && !is_numeric($value)) {
329
            throw new InvalidArgumentException(sprintf(
330
                'Route token "%1$s" must be a string with %2$s; received %3$s',
331
                $token,
332
                get_called_class(),
333
                (is_object($value) ? get_class($value) : gettype($value))
334
            ));
335
        }
336
337
        return $value;
338
    }
339
340
    /**
341
     * Filter the given value for a URI.
342
     *
343
     * @used-by self::parseRouteToken() To resolve the token's value.
344
     * @param   mixed  $value A value to filter.
345
     * @param   string $token The parsed token.
346
     * @return  string The filtered $value.
347
     */
348
    protected function filterRouteToken($value, $token = null)
349
    {
350
        unset($token);
351
352
        if ($value instanceof \Closure) {
353
            $value = $value();
354
        }
355
356
        if ($value instanceof \DateTime) {
357
            $value = $value->format('Y-m-d-H:i');
358
        }
359
360
        if (method_exists($value, '__toString')) {
361
            $value = strval($value);
362
        }
363
364
        return $value;
365
    }
366
367
    /**
368
     * Route generation.
369
     *
370
     * Saves all routes to {@see \Charcoal\Object\ObjectRoute}.
371
     *
372
     * @param  mixed $slug Slug by langs.
373
     * @param  array $data Object route custom data.
374
     * @throws InvalidArgumentException If the slug is invalid.
375
     * @return void
376
     */
377
    protected function generateObjectRoute($slug = null, array $data = [])
378
    {
379
        if (!$slug) {
380
            $slug = $this->generateSlug();
381
        }
382
383
        if ($slug instanceof Translation) {
384
            $slugs = $slug->data();
385
        } else {
386
            throw new InvalidArgumentException(sprintf(
387
                '[%s] slug parameter must be an instance of %s, received %s',
388
                get_called_class().'::'.__FUNCTION__,
389
                Translation::class,
390
                is_object($slug) ? get_class($slug) : gettype($slug)
391
            ));
392
        }
393
394
        if (!is_array($data)) {
395
            $data = [];
396
        }
397
398
        $origLang = $this->translator()->getLocale();
399
        foreach ($slugs as $lang => $slug) {
400
            if (!in_array($lang, $this->translator()->availableLocales())) {
401
                continue;
402
            }
403
            $this->translator()->setLocale($lang);
404
405
            $objectRoute = $this->createRouteObject();
406
407
            $oldRoute = $this->getLatestObjectRoute();
408
409
            $defaultData = [
410
                'lang'                => $lang,
411
                'route_obj_type'      => $this->objType(),
0 ignored issues
show
Bug introduced by
It seems like objType() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
412
                'route_obj_id'        => $this->id(),
0 ignored issues
show
Bug introduced by
It seems like id() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
413
                // Not used, might be too much.
414
                'route_template'      => $this->templateIdent(),
415
                'route_options'       => $this->routeOptions(),
416
                'route_options_ident' => $this->routeOptionsIdent(),
417
                'active'              => true
418
            ];
419
420
            $data = array_merge($defaultData, $data);
421
422
            // Unchanged but sync extra properties
423
            if ($slug === $oldRoute->slug()) {
424
                $oldRoute->setData([
425
                    'route_template'      => $data['route_template'],
426
                    'route_options'       => $data['route_options'],
427
                    'route_options_ident' => $data['route_options_ident']
428
                ]);
429
                $oldRoute->update([ 'route_template', 'route_options' ]);
430
                continue;
431
            }
432
433
            $objectRoute->setData($data);
434
            $objectRoute->setSlug($slug);
435
            $objectRoute->setLang($lang);
436
437
            if (!$objectRoute->isSlugUnique()) {
438
                $objectRoute->generateUniqueSlug();
439
            }
440
441
            if ($objectRoute->id()) {
442
                $objectRoute->update();
443
            } else {
444
                $objectRoute->save();
445
            }
446
        }
447
448
        $this->translator()->setLocale($origLang);
449
    }
450
451
    /**
452
     * Retrieve the latest object route.
453
     *
454
     * @param  string|null $lang If object is multilingual, return the object route for the specified locale.
455
     * @throws InvalidArgumentException If the given language is invalid.
456
     * @return ObjectRouteInterface Latest object route.
457
     */
458
    protected function getLatestObjectRoute($lang = null)
459
    {
460
461
        if ($lang === null) {
462
            $lang = $this->translator()->getLocale();
463
        } elseif (!in_array($lang, $this->translator()->availableLocales())) {
464
            throw new InvalidArgumentException(sprintf(
465
                'Invalid language, received %s',
466
                (is_object($lang) ? get_class($lang) : gettype($lang))
467
            ));
468
        }
469
470
        if (isset($this->latestObjectRoute[$lang])) {
471
            return $this->latestObjectRoute[$lang];
472
        }
473
474
        $model = $this->createRouteObject();
475
476
        if (!$this->objType() || !$this->id()) {
0 ignored issues
show
Bug introduced by
It seems like objType() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
Bug introduced by
It seems like id() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
477
            $this->latestObjectRoute[$lang] = $model;
478
479
            return $this->latestObjectRoute[$lang];
480
        }
481
482
        // For URL.
483
        $loader = new CollectionLoader([
484
            'logger'  => $this->logger,
0 ignored issues
show
Bug introduced by
The property logger does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
485
            'factory' => $this->modelFactory()
486
        ]);
487
488
        $loader
489
            ->setModel($model)
0 ignored issues
show
Documentation introduced by
$model is of type object<Charcoal\Object\ObjectRouteInterface>, but the function expects a string|object<Charcoal\Model\ModelInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
490
            ->addFilter('route_obj_type', $this->objType())
0 ignored issues
show
Bug introduced by
It seems like objType() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
491
            ->addFilter('route_obj_id', $this->id())
0 ignored issues
show
Bug introduced by
It seems like id() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
492
            ->addFilter('route_options_ident', '', ['operator' => 'IS NULL'])
493
            ->addFilter('lang', $lang)
494
            ->addFilter('active', true)
495
            ->addOrder('creation_date', 'desc')
496
            ->setPage(1)
497
            ->setNumPerPage(1);
498
499
        $collection = $loader->load()->objects();
500
501
        if (!count($collection)) {
502
            $this->latestObjectRoute[$lang] = $model;
503
504
            return $this->latestObjectRoute[$lang];
505
        }
506
507
        $this->latestObjectRoute[$lang] = $collection[0];
508
509
        return $this->latestObjectRoute[$lang];
510
    }
511
512
    /**
513
     * Retrieve the object's URI.
514
     *
515
     * @param  string|null $lang If object is multilingual, return the object route for the specified locale.
516
     * @return string
517
     */
518
    public function url($lang = null)
519
    {
520
        $slug = $this->slug();
521
522
        if ($slug instanceof Translation && $lang) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $lang of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
523
            return $slug[$lang];
524
        }
525
526
        if ($slug) {
527
            return $slug;
528
        }
529
530
        $url = (string)$this->getLatestObjectRoute($lang)->slug();
531
        return $url;
532
    }
533
534
    /**
535
     * Convert a string into a slug.
536
     *
537
     * @param  string $str The string to slugify.
538
     * @return string The slugified string.
539
     */
540
    public function slugify($str)
541
    {
542
        static $sluggedArray;
543
544
        if (isset($sluggedArray[$str])) {
545
            return $sluggedArray[$str];
546
        }
547
548
        $metadata = $this->metadata();
0 ignored issues
show
Bug introduced by
It seems like metadata() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
549
        $separator = isset($metadata['routable']['separator']) ? $metadata['routable']['separator'] : '-';
550
        $delimiters = '-_|';
551
        $pregDelim = preg_quote($delimiters);
552
        $directories = '\\/';
553
        $pregDir = preg_quote($directories);
554
555
        // Do NOT remove forward slashes.
556
        $slug = preg_replace('![^(\p{L}|\p{N})(\s|\/)]!u', $separator, $str);
557
558
        if (!isset($metadata['routable']['lowercase']) || $metadata['routable']['lowercase'] === false) {
559
            $slug = mb_strtolower($slug, 'UTF-8');
560
        }
561
562
        // Strip HTML
563
        $slug = strip_tags($slug);
564
565
        // Remove diacritics
566
        $slug = htmlentities($slug, ENT_COMPAT, 'UTF-8');
567
        $slug = preg_replace('!&([a-zA-Z])(uml|acute|grave|circ|tilde|cedil|ring);!', '$1', $slug);
568
569
        // Simplify ligatures
570
        $slug = preg_replace('!&([a-zA-Z]{2})(lig);!', '$1', $slug);
571
572
        // Remove unescaped HTML characters
573
        $unescaped = '!&(raquo|laquo|rsaquo|lsaquo|rdquo|ldquo|rsquo|lsquo|hellip|amp|nbsp|quot|ordf|ordm);!';
574
        $slug = preg_replace($unescaped, '', $slug);
575
576
        // Unify all dashes/underscores as one separator character
577
        $flip = ($separator === '-') ? '_' : '-';
578
        $slug = preg_replace('!['.preg_quote($flip).']+!u', $separator, $slug);
579
580
        // Remove all whitespace and normalize delimiters
581
        $slug = preg_replace('![_\|\s]+!', $separator, $slug);
582
583
        // Squeeze multiple delimiters and whitespace with a single separator
584
        $slug = preg_replace('!['.$pregDelim.'\s]{2,}!', $separator, $slug);
585
586
        // Squeeze multiple URI path delimiters
587
        $slug = preg_replace('!['.$pregDir.']{2,}!', $separator, $slug);
588
589
        // Remove delimiters surrouding URI path delimiters
590
        $slug = preg_replace('!(?<=['.$pregDir.'])['.$pregDelim.']|['.$pregDelim.'](?=['.$pregDir.'])!', '', $slug);
591
592
        // Strip leading and trailing dashes or underscores
593
        $slug = trim($slug, $delimiters);
594
595
        // Cache the slugified string
596
        $sluggedArray[$str] = $slug;
597
598
        return $slug;
599
    }
600
601
    /**
602
     * Finalize slug.
603
     *
604
     * Adds any prefix and suffix defined in the routable configuration set.
605
     *
606
     * @param  string $slug A slug.
607
     * @throws UnexpectedValueException If the slug affixes are invalid.
608
     * @return string
609
     */
610
    protected function finalizeSlug($slug)
611
    {
612
        $prefix = $this->slugPrefix();
613 View Code Duplication
        if ($prefix) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
614
            $prefix = $this->generateRoutePattern((string)$prefix);
615
            if ($slug === $prefix) {
616
                throw new UnexpectedValueException('The slug is the same as the prefix.');
617
            }
618
            $slug = $prefix.preg_replace('!^'.preg_quote($prefix).'\b!', '', $slug);
619
        }
620
621
        $suffix = $this->slugSuffix();
622 View Code Duplication
        if ($suffix) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
623
            $suffix = $this->generateRoutePattern((string)$suffix);
624
            if ($slug === $suffix) {
625
                throw new UnexpectedValueException('The slug is the same as the suffix.');
626
            }
627
            $slug = preg_replace('!\b'.preg_quote($suffix).'$!', '', $slug).$suffix;
628
        }
629
630
        return $slug;
631
    }
632
633
    /**
634
     * Delete all object routes.
635
     *
636
     * Should be called on object deletion {@see \Charcoal\Model\AbstractModel::preDelete()}.
637
     *
638
     * @return boolean Success or failure.
639
     */
640
    protected function deleteObjectRoutes()
641
    {
642
        if (!$this->objType()) {
0 ignored issues
show
Bug introduced by
It seems like objType() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
643
            return false;
644
        }
645
646
        if (!$this->id()) {
0 ignored issues
show
Bug introduced by
It seems like id() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
647
            return false;
648
        }
649
650
        $model = $this->modelFactory()->get($this->objectRouteClass());
651
        $loader = new CollectionLoader([
652
            'logger'  => $this->logger,
653
            'factory' => $this->modelFactory()
654
        ]);
655
656
        $loader
657
            ->setModel($model)
658
            ->addFilter('route_obj_type', $this->objType())
0 ignored issues
show
Bug introduced by
It seems like objType() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
659
            ->addFilter('route_obj_id', $this->id());
0 ignored issues
show
Bug introduced by
It seems like id() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
660
661
        $collection = $loader->load();
662
        foreach ($collection as $route) {
663
            $route->delete();
664
        }
665
666
        return true;
667
    }
668
669
    /**
670
     * Create a route object.
671
     *
672
     * @return ObjectRouteInterface
673
     */
674
    public function createRouteObject()
675
    {
676
        $route = $this->modelFactory()->create($this->objectRouteClass());
677
678
        return $route;
679
    }
680
681
    /**
682
     * Set the class name of the object route model.
683
     *
684
     * @param  string $className The class name of the object route model.
685
     * @throws InvalidArgumentException If the class name is not a string.
686
     * @return AbstractPropertyDisplay Chainable
687
     */
688
    protected function setObjectRouteClass($className)
689
    {
690
        if (!is_string($className)) {
691
            throw new InvalidArgumentException(
692
                'Route class name must be a string.'
693
            );
694
        }
695
696
        $this->objectRouteClass = $className;
697
698
        return $this;
699
    }
700
701
    /**
702
     * Retrieve the class name of the object route model.
703
     *
704
     * @return string
705
     */
706
    public function objectRouteClass()
707
    {
708
        return $this->objectRouteClass;
709
    }
710
711
    /**
712
     * Set the object's route options
713
     *
714
     * @param  mixed $options The object routes's options.
715
     * @return self
716
     */
717 View Code Duplication
    public function setRouteOptions($options)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
718
    {
719
        if (is_string($options)) {
720
            $options = json_decode($options, true);
721
        }
722
723
        $this->routeOptions = $options;
724
725
        return $this;
726
    }
727
728
    /**
729
     * Retrieve the object's route options
730
     *
731
     * @return array|null
732
     */
733
    public function routeOptions()
734
    {
735
        return $this->routeOptions;
736
    }
737
738
    /**
739
     * @param string $routeOptionsIdent Template options ident.
740
     * @return self
741
     */
742
    public function setRouteOptionsIdent($routeOptionsIdent)
743
    {
744
        $this->routeOptionsIdent = $routeOptionsIdent;
745
746
        return $this;
747
    }
748
749
    /**
750
     * @return string
751
     */
752
    public function routeOptionsIdent()
753
    {
754
        return $this->routeOptionsIdent;
755
    }
756
757
    /**
758
     * Determine if the routable object is active.
759
     *
760
     * The route controller will validate the object via this method. If the routable object
761
     * is NOT active, the route controller will usually default to _404 Not Found_.
762
     *
763
     * By default — if the object has an "active" property, that value is checked, else —
764
     * the route is always _active_.
765
     *
766
     * @return boolean
767
     */
768
    public function isActiveRoute()
769
    {
770
        if (isset($this['active'])) {
771
            return !!$this['active'];
772
        } else {
773
            return true;
774
        }
775
    }
776
777
    /**
778
     * Retrieve the object model factory.
779
     *
780
     * @return \Charcoal\Factory\FactoryInterface
781
     */
782
    abstract public function modelFactory();
783
784
    /**
785
     * Retrieve the routable object's template identifier.
786
     *
787
     * @return mixed
788
     */
789
    abstract public function templateIdent();
790
791
    /**
792
     * @return \Charcoal\Translator\Translator
793
     */
794
    abstract protected function translator();
795
}
796