Passed
Push — master ( fb233a...3f7877 )
by Mathieu
03:01
created

RoutableTrait::getLatestObjectRoute()   C

Complexity

Conditions 8
Paths 9

Size

Total Lines 52
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 52
rs 6.8493
c 0
b 0
f 0
cc 8
eloc 31
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
     * Set the object's URL slug pattern.
87
     *
88
     * @param  mixed $pattern The slug pattern.
89
     * @return RoutableInterface Chainable
90
     */
91
    public function setSlugPattern($pattern)
92
    {
93
        $this->slugPattern = $this->translator()->translation($pattern);
94
95
        return $this;
96
    }
97
98
    /**
99
     * Retrieve the object's URL slug pattern.
100
     *
101
     * @throws Exception If a slug pattern is not defined.
102
     * @return \Charcoal\Translator\Translation|null
103
     */
104
    public function slugPattern()
105
    {
106
        if (!$this->slugPattern) {
107
            $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...
108
109
            if (isset($metadata['routable']['pattern'])) {
110
                $this->setSlugPattern($metadata['routable']['pattern']);
111
            } elseif (isset($metadata['slug_pattern'])) {
112
                $this->setSlugPattern($metadata['slug_pattern']);
113
            } else {
114
                throw new Exception(sprintf(
115
                    'Undefined route pattern (slug) for %s',
116
                    get_called_class()
117
                ));
118
            }
119
        }
120
121
        return $this->slugPattern;
122
    }
123
124
    /**
125
     * Retrieve route prefix for the object's URL slug pattern.
126
     *
127
     * @return \Charcoal\Translator\Translation|null
128
     */
129 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...
130
    {
131
        if (!$this->slugPrefix) {
132
            $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...
133
134
            if (isset($metadata['routable']['prefix'])) {
135
                $this->slugPrefix = $this->translator()->translation($metadata['routable']['prefix']);
136
            }
137
        }
138
139
        return $this->slugPrefix;
140
    }
141
142
    /**
143
     * Retrieve route suffix for the object's URL slug pattern.
144
     *
145
     * @return \Charcoal\Translator\Translation|null
146
     */
147 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...
148
    {
149
        if (!$this->slugSuffix) {
150
            $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...
151
152
            if (isset($metadata['routable']['suffix'])) {
153
                $this->slugSuffix = $this->translator()->translation($metadata['routable']['suffix']);
154
            }
155
        }
156
157
        return $this->slugSuffix;
158
    }
159
160
    /**
161
     * Determine if the slug is editable.
162
     *
163
     * @return boolean
164
     */
165
    public function isSlugEditable()
166
    {
167
        if ($this->isSlugEditable === null) {
168
            $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...
169
170
            if (isset($metadata['routable']['editable'])) {
171
                $this->isSlugEditable = !!$metadata['routable']['editable'];
172
            } else {
173
                $this->isSlugEditable = false;
174
            }
175
        }
176
177
        return $this->isSlugEditable;
178
    }
179
180
    /**
181
     * Set the object's URL slug.
182
     *
183
     * @param  mixed $slug The slug.
184
     * @return RoutableInterface Chainable
185
     */
186
    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...
187
    {
188
        $slug = $this->translator()->translation($slug);
189
        if ($slug !== null) {
190
            $this->slug = $slug;
191
192
            $values = $this->slug->data();
193
            foreach ($values as $lang => $val) {
194
                $this->slug[$lang] = $this->slugify($val);
195
            }
196
        } else {
197
            /** @todo Hack used for regenerating route */
198
            if (isset($_POST['slug'])) {
199
                $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...
200
            } else {
201
                $this->slug = null;
202
            }
203
        }
204
205
        return $this;
206
    }
207
208
    /**
209
     * Retrieve the object's URL slug.
210
     *
211
     * @return \Charcoal\Translator\Translation|null
212
     */
213
    public function slug()
214
    {
215
        return $this->slug;
216
    }
217
218
    /**
219
     * Generate a URL slug from the object's URL slug pattern.
220
     *
221
     * @throws UnexpectedValueException If the slug is empty.
222
     * @return \Charcoal\Translator\Translation
223
     */
224
    public function generateSlug()
225
    {
226
        $languages = $this->translator()->availableLocales();
227
        $patterns = $this->slugPattern();
228
        $curSlug = $this->slug();
229
        $newSlug = [];
230
231
        $origLang = $this->translator()->getLocale();
232
        foreach ($languages as $lang) {
233
            $pattern = $patterns[$lang];
234
235
            $this->translator()->setLocale($lang);
236
            if ($this->isSlugEditable() && isset($curSlug[$lang]) && strlen($curSlug[$lang])) {
237
                $newSlug[$lang] = $curSlug[$lang];
238
            } else {
239
                $newSlug[$lang] = $this->generateRoutePattern($pattern);
240
                if (!strlen($newSlug[$lang])) {
241
                    throw new UnexpectedValueException(sprintf(
242
                        'The slug is empty. The pattern is "%s"',
243
                        $pattern
244
                    ));
245
                }
246
            }
247
            $newSlug[$lang] = $this->finalizeSlug($newSlug[$lang]);
248
249
            $objectRoute = $this->createRouteObject();
250
            $objectRoute->setData([
251
                'lang'           => $lang,
252
                'slug'           => $newSlug[$lang],
253
                '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...
254
                '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...
255
            ]);
256
257
            if (!$objectRoute->isSlugUnique()) {
258
                $objectRoute->generateUniqueSlug();
259
                $newSlug[$lang] = $objectRoute->slug();
260
            }
261
        }
262
        $this->translator()->setLocale($origLang);
263
264
        return $this->translator()->translation($newSlug);
265
    }
266
267
    /**
268
     * Generate a route from the given pattern.
269
     *
270
     * @uses   self::parseRouteToken() If a view renderer is unavailable.
271
     * @param  string $pattern The slug pattern.
272
     * @return string Returns the generated route.
273
     */
274
    protected function generateRoutePattern($pattern)
275
    {
276
        if ($this instanceof ViewableInterface && $this->view() !== null) {
277
            $route = $this->view()->render($pattern, $this->viewController());
278
        } else {
279
            $route = preg_replace_callback('~\{\{\s*(.*?)\s*\}\}~i', [ $this, 'parseRouteToken' ], $pattern);
280
        }
281
282
        return $this->slugify($route);
283
    }
284
285
    /**
286
     * Parse the given slug (URI token) for the current object.
287
     *
288
     * @used-by self::generateRoutePattern() If a view renderer is unavailable.
289
     * @uses    self::filterRouteToken() For customize the route value filtering,
290
     * @param   string|array $token The token to parse relative to the model entry.
291
     * @throws  InvalidArgumentException If a route token is not a string.
292
     * @return  string
293
     */
294
    protected function parseRouteToken($token)
295
    {
296
        // Processes matches from a regular expression operation
297
        if (is_array($token) && isset($token[1])) {
298
            $token = $token[1];
299
        }
300
301
        $token = trim($token);
302
        $method = [ $this, $token ];
303
304
        if (is_callable($method)) {
305
            $value = call_user_func($method);
306
            /** @see \Charcoal\Config\AbstractEntity::offsetGet() */
307
        } elseif (isset($this[$token])) {
308
            $value = $this[$token];
309
        } else {
310
            return '';
311
        }
312
313
        $value = $this->filterRouteToken($value, $token);
314
        if (!is_string($value) && !is_numeric($value)) {
315
            throw new InvalidArgumentException(sprintf(
316
                'Route token "%1$s" must be a string with %2$s; received %3$s',
317
                $token,
318
                get_called_class(),
319
                (is_object($value) ? get_class($value) : gettype($value))
320
            ));
321
        }
322
323
        return $value;
324
    }
325
326
    /**
327
     * Filter the given value for a URI.
328
     *
329
     * @used-by self::parseRouteToken() To resolve the token's value.
330
     * @param   mixed  $value A value to filter.
331
     * @param   string $token The parsed token.
332
     * @return  string The filtered $value.
333
     */
334
    protected function filterRouteToken($value, $token = null)
335
    {
336
        unset($token);
337
338
        if ($value instanceof \Closure) {
339
            $value = $value();
340
        }
341
342
        if ($value instanceof \DateTime) {
343
            $value = $value->format('Y-m-d-H:i');
344
        }
345
346
        if (method_exists($value, '__toString')) {
347
            $value = strval($value);
348
        }
349
350
        return $value;
351
    }
352
353
    /**
354
     * Route generation.
355
     *
356
     * Saves all routes to {@see \Charcoal\Object\ObjectRoute}.
357
     *
358
     * @param  mixed $slug Slug by langs.
359
     * @return void
360
     */
361
    protected function generateObjectRoute($slug = null)
362
    {
363
364
        if (!$slug) {
365
            $slug = $this->generateSlug();
366
        }
367
368
        if ($slug instanceof Translation) {
369
            $slugs = $slug->data();
370
        }
371
372
        $origLang = $this->translator()->getLocale();
373
        foreach ($slugs as $lang => $slug) {
0 ignored issues
show
Bug introduced by
The variable $slugs does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
374
            if (!in_array($lang, $this->translator()->availableLocales())) {
375
                continue;
376
            }
377
378
            $this->translator()->setLocale($lang);
379
380
            $objectRoute = $this->createRouteObject();
381
382
            $oldRoute = $this->getLatestObjectRoute();
383
384
            // Unchanged but sync extra properties
385
            if ($slug === $oldRoute->slug()) {
386
                $oldRoute->setData([
387
                    'route_template' => $this->templateIdent()
388
                ]);
389
                $oldRoute->update([ 'route_template' ]);
390
                continue;
391
            }
392
393
            $objectRoute->setData([
394
                'lang'           => $lang,
395
                'slug'           => $slug,
396
                '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...
397
                '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...
398
                // Not used, might be too much.
399
                'route_template' => $this->templateIdent(),
400
                'active'         => true
401
            ]);
402
403
            if (!$objectRoute->isSlugUnique()) {
404
                $objectRoute->generateUniqueSlug();
405
            }
406
407
            if ($objectRoute->id()) {
408
                $objectRoute->update();
409
            } else {
410
                $objectRoute->save();
411
            }
412
        }
413
414
        $this->translator()->setLocale($origLang);
415
    }
416
417
    /**
418
     * Retrieve the latest object route.
419
     *
420
     * @param  string|null $lang If object is multilingual, return the object route for the specified locale.
421
     * @throws InvalidArgumentException If the given language is invalid.
422
     * @return ObjectRouteInterface Latest object route.
423
     */
424
    protected function getLatestObjectRoute($lang = null)
425
    {
426
427
        if ($lang === null) {
428
            $lang = $this->translator()->getLocale();
429
        } elseif (!in_array($lang, $this->translator()->availableLocales())) {
430
            throw new InvalidArgumentException(sprintf(
431
                'Invalid language, received %s',
432
                (is_object($lang) ? get_class($lang) : gettype($lang))
433
            ));
434
        }
435
436
        if (isset($this->latestObjectRoute[$lang])) {
437
            return $this->latestObjectRoute[$lang];
438
        }
439
440
        $model = $this->createRouteObject();
441
442
        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...
443
            $this->latestObjectRoute[$lang] = $model;
444
445
            return $this->latestObjectRoute[$lang];
446
        }
447
448
        // For URL.
449
        $loader = new CollectionLoader([
450
            '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...
451
            'factory' => $this->modelFactory()
452
        ]);
453
454
        $loader
455
            ->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...
456
            ->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...
457
            ->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...
458
            ->addFilter('lang', $lang)
459
            ->addFilter('active', true)
460
            ->addOrder('creation_date', 'desc')
461
            ->setPage(1)
462
            ->setNumPerPage(1);
463
464
        $collection = $loader->load()->objects();
465
466
        if (!count($collection)) {
467
            $this->latestObjectRoute[$lang] = $model;
468
469
            return $this->latestObjectRoute[$lang];
470
        }
471
472
        $this->latestObjectRoute[$lang] = $collection[0];
473
474
        return $this->latestObjectRoute[$lang];
475
    }
476
477
    /**
478
     * Retrieve the object's URI.
479
     *
480
     * @param  string|null $lang If object is multilingual, return the object route for the specified locale.
481
     * @return string
482
     */
483
    public function url($lang = null)
484
    {
485
        $url = (string)$this->getLatestObjectRoute($lang)->slug();
486
        if ($url) {
487
            return $url;
488
        }
489
490
        $slug = $this->slug();
491
492
        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...
493
            return $slug[$lang];
494
        }
495
496
        return (string)$slug;
497
    }
498
499
    /**
500
     * Convert a string into a slug.
501
     *
502
     * @param  string $str The string to slugify.
503
     * @return string The slugified string.
504
     */
505
    public function slugify($str)
506
    {
507
        static $sluggedArray;
508
509
        if (isset($sluggedArray[$str])) {
510
            return $sluggedArray[$str];
511
        }
512
513
        $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...
514
        $separator = isset($metadata['routable']['separator']) ? $metadata['routable']['separator'] : '-';
515
        $delimiters = '-_|';
516
        $pregDelim = preg_quote($delimiters);
517
        $directories = '\\/';
518
        $pregDir = preg_quote($directories);
519
520
        // Do NOT remove forward slashes.
521
        $slug = preg_replace('![^(\p{L}|\p{N})(\s|\/)]!u', $separator, $str);
522
523
        if (!isset($metadata['routable']['lowercase']) || $metadata['routable']['lowercase'] === false) {
524
            $slug = mb_strtolower($slug, 'UTF-8');
525
        }
526
527
        // Strip HTML
528
        $slug = strip_tags($slug);
529
530
        // Remove diacritics
531
        $slug = htmlentities($slug, ENT_COMPAT, 'UTF-8');
532
        $slug = preg_replace('!&([a-zA-Z])(uml|acute|grave|circ|tilde|cedil|ring);!', '$1', $slug);
533
534
        // Simplify ligatures
535
        $slug = preg_replace('!&([a-zA-Z]{2})(lig);!', '$1', $slug);
536
537
        // Remove unescaped HTML characters
538
        $unescaped = '!&(raquo|laquo|rsaquo|lsaquo|rdquo|ldquo|rsquo|lsquo|hellip|amp|nbsp|quot|ordf|ordm);!';
539
        $slug = preg_replace($unescaped, '', $slug);
540
541
        // Unify all dashes/underscores as one separator character
542
        $flip = ($separator === '-') ? '_' : '-';
543
        $slug = preg_replace('!['.preg_quote($flip).']+!u', $separator, $slug);
544
545
        // Remove all whitespace and normalize delimiters
546
        $slug = preg_replace('![_\|\s]+!', $separator, $slug);
547
548
        // Squeeze multiple delimiters and whitespace with a single separator
549
        $slug = preg_replace('!['.$pregDelim.'\s]{2,}!', $separator, $slug);
550
551
        // Squeeze multiple URI path delimiters
552
        $slug = preg_replace('!['.$pregDir.']{2,}!', $separator, $slug);
553
554
        // Remove delimiters surrouding URI path delimiters
555
        $slug = preg_replace('!(?<=['.$pregDir.'])['.$pregDelim.']|['.$pregDelim.'](?=['.$pregDir.'])!', '', $slug);
556
557
        // Strip leading and trailing dashes or underscores
558
        $slug = trim($slug, $delimiters);
559
560
        // Cache the slugified string
561
        $sluggedArray[$str] = $slug;
562
563
        return $slug;
564
    }
565
566
    /**
567
     * Finalize slug.
568
     *
569
     * Adds any prefix and suffix defined in the routable configuration set.
570
     *
571
     * @param  string $slug A slug.
572
     * @throws UnexpectedValueException If the slug affixes are invalid.
573
     * @return string
574
     */
575
    protected function finalizeSlug($slug)
576
    {
577
        $prefix = $this->slugPrefix();
578 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...
579
            $prefix = $this->generateRoutePattern((string)$prefix);
580
            if ($slug === $prefix) {
581
                throw new UnexpectedValueException('The slug is the same as the prefix.');
582
            }
583
            $slug = $prefix.preg_replace('!^'.preg_quote($prefix).'\b!', '', $slug);
584
        }
585
586
        $suffix = $this->slugSuffix();
587 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...
588
            $suffix = $this->generateRoutePattern((string)$suffix);
589
            if ($slug === $suffix) {
590
                throw new UnexpectedValueException('The slug is the same as the suffix.');
591
            }
592
            $slug = preg_replace('!\b'.preg_quote($suffix).'$!', '', $slug).$suffix;
593
        }
594
595
        return $slug;
596
    }
597
598
    /**
599
     * Delete all object routes.
600
     *
601
     * Should be called on object deletion {@see \Charcoal\Model\AbstractModel::preDelete()}.
602
     *
603
     * @return boolean Success or failure.
604
     */
605
    protected function deleteObjectRoutes()
606
    {
607
        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...
608
            return false;
609
        }
610
611
        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...
612
            return false;
613
        }
614
615
        $model = $this->modelFactory()->get($this->objectRouteClass());
616
        $loader = new CollectionLoader([
617
            'logger'  => $this->logger,
618
            'factory' => $this->modelFactory()
619
        ]);
620
621
        $loader
622
            ->setModel($model)
623
            ->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...
624
            ->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...
625
626
        $collection = $loader->load();
627
        foreach ($collection as $route) {
628
            $route->delete();
629
        }
630
631
        return true;
632
    }
633
634
    /**
635
     * Create a route object.
636
     *
637
     * @return ObjectRouteInterface
638
     */
639
    public function createRouteObject()
640
    {
641
        $route = $this->modelFactory()->create($this->objectRouteClass());
642
643
        return $route;
644
    }
645
646
    /**
647
     * Set the class name of the object route model.
648
     *
649
     * @param  string $className The class name of the object route model.
650
     * @throws InvalidArgumentException If the class name is not a string.
651
     * @return AbstractPropertyDisplay Chainable
652
     */
653
    protected function setObjectRouteClass($className)
654
    {
655
        if (!is_string($className)) {
656
            throw new InvalidArgumentException(
657
                'Route class name must be a string.'
658
            );
659
        }
660
661
        $this->objectRouteClass = $className;
662
663
        return $this;
664
    }
665
666
    /**
667
     * Retrieve the class name of the object route model.
668
     *
669
     * @return string
670
     */
671
    public function objectRouteClass()
672
    {
673
        return $this->objectRouteClass;
674
    }
675
676
    /**
677
     * Defaults to active property, used in the GenericRoute class.
678
     * Defines if the route is active, else it sends the user to the 404 page.
679
     *
680
     * @return boolean
681
     */
682
    public function isActiveRoute()
683
    {
684
        return ($this->active());
0 ignored issues
show
Bug introduced by
The method active() does not exist on Charcoal\Object\RoutableTrait. Did you maybe mean isActiveRoute()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
685
    }
686
687
    /**
688
     * Retrieve the object model factory.
689
     *
690
     * @return \Charcoal\Factory\FactoryInterface
691
     */
692
    abstract public function modelFactory();
693
694
    /**
695
     * Retrieve the routable object's template identifier.
696
     *
697
     * @return mixed
698
     */
699
    abstract public function templateIdent();
700
701
    /**
702
     * @return \Charcoal\Translator\Translator
703
     */
704
    abstract protected function translator();
705
}
706