Completed
Push — master ( 9bb04b...b4e7ce )
by
unknown
03:14
created

RoutableTrait::slugPatternLanguages()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 12
rs 9.4285
cc 3
eloc 7
nc 3
nop 0
1
<?php
2
3
namespace Charcoal\Object;
4
5
use \InvalidArgumentException;
6
7
// From 'charcoal-core'
8
use \Charcoal\Loader\CollectionLoader;
9
10
// From 'charcoal-translation'
11
use \Charcoal\Translation\TranslationString;
12
use \Charcoal\Translation\TranslationConfig;
13
14
// From 'charcoal-view'
15
use \Charcoal\View\ViewableInterface;
16
17
// Local Dependencies
18
use \Charcoal\Object\ObjectRoute;
19
use \Charcoal\Object\ObjectRouteInterface;
20
21
/**
22
 * Full implementation, as Trait, of the `RoutableInterface`.
23
 */
24
trait RoutableTrait
25
{
26
    /**
27
     * The object's route.
28
     *
29
     * @var TranslationString|string|null
30
     */
31
    protected $slug;
32
33
    /**
34
     * Whether the slug is editable.
35
     *
36
     * If FALSE, the slug is always auto-generated from its pattern.
37
     * If TRUE, the slug is auto-generated only if the slug is empty.
38
     *
39
     * @var boolean|null
40
     */
41
    private $isSlugEditable;
42
43
    /**
44
     * The object's route pattern.
45
     *
46
     * @var TranslationString|string|null
47
     */
48
    private $slugPattern = '';
49
50
    /**
51
     * A prefix for the object's route.
52
     *
53
     * @var TranslationString|string|null
54
     */
55
    private $slugPrefix = '';
56
57
    /**
58
     * A suffix for the object's route.
59
     *
60
     * @var TranslationString|string|null
61
     */
62
    private $slugSuffix = '';
63
64
    /**
65
     * Latest ObjectRoute object concerning the current object.
66
     *
67
     * @var ObjectRouteInterface
68
     */
69
    private $latestObjectRoute;
70
71
    /**
72
     * The class name of the object route model.
73
     *
74
     * Must be a fully-qualified PHP namespace and an implementation of
75
     * {@see \Charcoal\Object\ObjectRouteInterface}. Used by the model factory.
76
     *
77
     * @var string
78
     */
79
    private $objectRouteClass = ObjectRoute::class;
80
81
    /**
82
     * Set the object's URL slug pattern.
83
     *
84
     * @param mixed $pattern The slug pattern.
85
     * @return RoutableInterface Chainable
86
     */
87
    public function setSlugPattern($pattern)
88
    {
89
        if (TranslationString::isTranslatable($pattern)) {
90
            $this->slugPattern = new TranslationString($pattern);
91
        } else {
92
            $this->slugPattern = null;
93
        }
94
95
        return $this;
96
    }
97
98
    /**
99
     * Retrieve the object's URL slug pattern.
100
     *
101
     * @throws InvalidArgumentException If a slug pattern is not defined.
102
     * @return TranslationString|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 InvalidArgumentException(
115
                    sprintf('Undefined route pattern (slug) for %s', get_called_class())
116
                );
117
            }
118
        }
119
120
        return $this->slugPattern;
121
    }
122
123
    /**
124
     * Retrieve route prefix for the object's URL slug pattern.
125
     *
126
     * @return TranslationString|null
127
     */
128 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...
129
    {
130
        if (!$this->slugPrefix) {
131
            $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...
132
133
            if (isset($metadata['routable']['prefix'])) {
134
                $affix = $metadata['routable']['prefix'];
135
136
                if (TranslationString::isTranslatable($affix)) {
137
                    $this->slugPrefix = new TranslationString($affix);
138
                }
139
            }
140
        }
141
142
        return $this->slugPrefix;
143
    }
144
145
    /**
146
     * Retrieve route suffix for the object's URL slug pattern.
147
     *
148
     * @return TranslationString|null
149
     */
150 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...
151
    {
152
        if (!$this->slugSuffix) {
153
            $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...
154
155
            if (isset($metadata['routable']['suffix'])) {
156
                $affix = $metadata['routable']['suffix'];
157
158
                if (TranslationString::isTranslatable($affix)) {
159
                    $this->slugSuffix = new TranslationString($affix);
160
                }
161
            }
162
        }
163
164
        return $this->slugSuffix;
165
    }
166
167
    /**
168
     * Retrieve the list of languages to translate the slug into.
169
     *
170
     * @return array
171
     */
172
    private function slugPatternLanguages()
173
    {
174
        $langs  = [];
175
        $patterns = [ $this->slugPattern(), $this->slugPrefix(), $this->slugSuffix() ];
176
        foreach ($patterns as $pattern) {
177
            if ($pattern instanceof TranslationString) {
178
                $langs = array_merge($langs, $pattern->all());
179
            }
180
        }
181
182
        return array_keys($langs);
183
    }
184
185
    /**
186
     * Determine if the slug is editable.
187
     *
188
     * @return boolean
189
     */
190
    public function isSlugEditable()
191
    {
192
        if ($this->isSlugEditable === null) {
193
            $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...
194
195
            if (isset($metadata['routable']['editable'])) {
196
                $this->isSlugEditable = !!$metadata['routable']['editable'];
197
            } else {
198
                $this->isSlugEditable = false;
199
            }
200
        }
201
202
        return $this->isSlugEditable;
203
    }
204
205
    /**
206
     * Set the object's URL slug.
207
     *
208
     * @param mixed $slug The slug.
209
     * @return RoutableInterface Chainable
210
     */
211
    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...
212
    {
213
        if (TranslationString::isTranslatable($slug)) {
214
            $this->slug = new TranslationString($slug);
215
216
            $values = $this->slug->all();
217
            foreach ($values as $lang => $val) {
218
                $this->slug[$lang] = $this->slugify($val);
219
            }
220
        } else {
221
            /** @todo Hack used for regenerating route */
222
            if (isset($_POST['slug'])) {
223
                $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\Translat...tionString>|string|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...
224
            } else {
225
                $this->slug = null;
226
            }
227
        }
228
229
        return $this;
230
    }
231
232
    /**
233
     * Retrieve the object's URL slug.
234
     *
235
     * @return TranslationString|null
236
     */
237
    public function slug()
238
    {
239
        return $this->slug;
240
    }
241
242
    /**
243
     * Generate a URL slug from the object's URL slug pattern.
244
     *
245
     * @return TranslationString
246
     */
247
    public function generateSlug()
248
    {
249
        $translator = TranslationConfig::instance();
250
        $languages  = $this->slugPatternLanguages();
251
        $patterns   = $this->slugPattern();
252
        $curSlug    = $this->slug();
253
        $newSlug    = new TranslationString();
254
255
        if ($patterns instanceof TranslationString) {
256
            $patterns = $patterns->all();
257
        }
258
259
        $origLang = $translator->currentLanguage();
260
        foreach ($languages as $lang) {
261
            if (!$translator->hasLanguage($lang)) {
262
                continue;
263
            }
264
265
            if (!isset($patterns[$lang])) {
266
                $patterns[$lang] = reset($patterns);
267
            }
268
269
            $pattern = $patterns[$lang];
270
271
            $translator->setCurrentLanguage($lang);
272
            if ($this->isSlugEditable() && isset($curSlug[$lang]) && strlen($curSlug[$lang])) {
273
                $newSlug[$lang] = $curSlug[$lang];
274
            } else {
275
                $newSlug[$lang] = $this->generateRoutePattern($pattern);
0 ignored issues
show
Security Bug introduced by
It seems like $pattern defined by $patterns[$lang] on line 269 can also be of type false; however, Charcoal\Object\Routable...:generateRoutePattern() does only seem to accept string, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
276
                if (!strlen($newSlug[$lang])) {
277
                    throw new \UnexpectedValueException(
278
                        sprintf('The slug is empty. The pattern is "%s"', $pattern)
279
                    );
280
                }
281
            }
282
            $newSlug[$lang] = $this->finalizeSlug($newSlug[$lang]);
283
284
            $objectRoute = $this->createRouteObject();
285
            if ($objectRoute->source()->tableExists()) {
286
                $objectRoute->setData([
287
                    'lang'           => $lang,
288
                    'slug'           => $newSlug[$lang],
289
                    '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...
290
                    '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...
291
                ]);
292
293
                if (!$objectRoute->isSlugUnique()) {
294
                    $objectRoute->generateUniqueSlug();
295
                    $newSlug[$lang] = $objectRoute->slug();
296
                }
297
            }
298
        }
299
        $translator->setCurrentLanguage($origLang);
300
301
        return $newSlug;
302
    }
303
304
    /**
305
     * Generate a route from the given pattern.
306
     *
307
     * @uses   self::parseRouteToken() If a view renderer is unavailable.
308
     * @param  string $pattern The slug pattern.
309
     * @return string Returns the generated route.
310
     */
311
    protected function generateRoutePattern($pattern)
312
    {
313
        if ($this instanceof ViewableInterface && $this->view() !== null) {
314
            $route = $this->view()->render($pattern, $this->viewController());
315
        } else {
316
            $route = preg_replace_callback('~\{\{\s*(.*?)\s*\}\}~i', [$this, 'parseRouteToken'], $pattern);
317
        }
318
319
        return $this->slugify($route);
320
    }
321
322
    /**
323
     * Parse the given slug (URI token) for the current object.
324
     *
325
     * @used-by self::generateRoutePattern() If a view renderer is unavailable.
326
     * @uses    self::filterRouteToken() For customize the route value filtering,
327
     * @param   string|array $token The token to parse relative to the model entry.
328
     * @throws  InvalidArgumentException If a route token is not a string.
329
     * @return  string
330
     */
331
    protected function parseRouteToken($token)
332
    {
333
        // Processes matches from a regular expression operation
334
        if (is_array($token) && isset($token[1])) {
335
            $token = $token[1];
336
        }
337
338
        $token  = trim($token);
339
        $method = [$this, $token];
340
341
        if (is_callable($method)) {
342
            $value = call_user_func($method);
343
            /** @see \Charcoal\Config\AbstractEntity::offsetGet() */
344
        } elseif (isset($this[$token])) {
345
            $value = $this[$token];
346
        } else {
347
            return '';
348
        }
349
350
        $value = $this->filterRouteToken($value, $token);
351
        if (!is_string($value) && !is_numeric($value)) {
352
            throw new InvalidArgumentException(
353
                sprintf(
354
                    'Route token "%1$s" must be a string with %2$s',
355
                    $token,
356
                    get_called_class()
357
                )
358
            );
359
        }
360
361
        return $value;
362
    }
363
364
    /**
365
     * Filter the given value for a URI.
366
     *
367
     * @used-by self::parseRouteToken() To resolve the token's value.
368
     * @param   mixed  $value A value to filter.
369
     * @param   string $token The parsed token.
370
     * @return  string The filtered $value.
371
     */
372
    protected function filterRouteToken($value, $token = null)
373
    {
374
        unset($token);
375
376
        if ($value instanceof \Closure) {
377
            $value = $value();
378
        }
379
380
        if ($value instanceof \DateTime) {
381
            $value = $value->format('Y-m-d-H:i');
382
        }
383
384
        return $value;
385
    }
386
387
    /**
388
     * Route generation.
389
     *
390
     * Saves all routes to {@see \Charcoal\Object\ObjectRoute}.
391
     *
392
     * @param  mixed $slug Slug by langs.
393
     * @return void
394
     */
395
    protected function generateObjectRoute($slug = null)
396
    {
397
        $translator = TranslationConfig::instance();
398
399
        if (!$slug) {
400
            $slug = $this->generateSlug();
401
        }
402
403
        if ($slug instanceof TranslationString) {
404
            $slugs = $slug->all();
405
        }
406
407
        $origLang = $translator->currentLanguage();
408
        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...
409
            if (!$translator->hasLanguage($lang)) {
410
                continue;
411
            }
412
413
            $translator->setCurrentLanguage($lang);
414
415
            $objectRoute = $this->createRouteObject();
416
417
            $source = $objectRoute->source();
418
            if (!$source->tableExists()) {
419
                $source->createTable();
420
            } else {
421
                $oldRoute = $this->getLatestObjectRoute();
422
423
                // Unchanged
424
                if ($slug === $oldRoute->slug()) {
425
                    continue;
426
                }
427
            }
428
429
            $objectRoute->setData([
430
                'lang'           => $lang,
431
                'slug'           => $slug,
432
                '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...
433
                '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...
434
                // Not used, might be too much.
435
                'route_template' => $this->templateIdent(),
436
                'active'         => true
437
            ]);
438
439
            if (!$objectRoute->isSlugUnique()) {
440
                $objectRoute->generateUniqueSlug();
441
            }
442
443
            if ($objectRoute->id()) {
444
                $objectRoute->update();
445
            } else {
446
                $objectRoute->save();
447
            }
448
        }
449
        $translator->setCurrentLanguage($origLang);
450
    }
451
452
    /**
453
     * Retrieve the latest object route.
454
     *
455
     * @param  string|null $lang If object is multilingual, return the object route for the specified locale.
456
     * @throws InvalidArgumentException If the given language is invalid.
457
     * @return ObjectRouteInterface Latest object route.
458
     */
459
    protected function getLatestObjectRoute($lang = null)
460
    {
461
        $translator = TranslationConfig::instance();
462
463
        if ($lang === null) {
464
            $lang = $translator->currentLanguage();
465
        } elseif (!$translator->hasLanguage($lang)) {
466
            throw new InvalidArgumentException(
467
                sprintf(
468
                    'Invalid language, received %s',
469
                    (is_object($lang) ? get_class($lang) : gettype($lang))
470
                )
471
            );
472
        }
473
474
        if (isset($this->latestObjectRoute[$lang])) {
475
            return $this->latestObjectRoute[$lang];
476
        }
477
478
        $model = $this->createRouteObject();
479
480
        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...
481
            $this->latestObjectRoute[$lang] = $model;
482
483
            return $this->latestObjectRoute[$lang];
484
        }
485
486
        // For URL.
487
        $source = $model->source();
488
        $loader = new CollectionLoader([
489
            '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...
490
            'factory' => $this->modelFactory()
491
        ]);
492
493
        if (!$source->tableExists()) {
494
            $source->createTable();
495
        }
496
497
        $loader
498
            ->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...
499
            ->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...
500
            ->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...
501
            ->addFilter('lang', $lang)
502
            ->addFilter('active', true)
503
            ->addOrder('creation_date', 'desc')
504
            ->setPage(1)
505
            ->setNumPerPage(1);
506
507
        $collection = $loader->load()->objects();
508
509
        if (!count($collection)) {
510
            $this->latestObjectRoute[$lang] = $model;
511
512
            return $this->latestObjectRoute[$lang];
513
        }
514
515
        $this->latestObjectRoute[$lang] = $collection[0];
516
517
        return $this->latestObjectRoute[$lang];
518
    }
519
520
    /**
521
     * Sync the object routes with the object's data.
522
     * @return void
523
     */
524
    public function syncObjectRoutes()
525
    {
526
        $model = $this->createRouteObject();
527
528
        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...
529
            return;
530
        }
531
532
        $loader = new CollectionLoader([
533
            'logger'  => $this->logger,
534
            'factory' => $this->modelFactory()
535
        ]);
536
537
        $loader
538
            ->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...
539
            ->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...
540
            ->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...
541
542
        $collection = $loader->load();
543
544
        foreach ($collection as $entry) {
545
            $entry->setData([
546
                'route_template' => $this->templateIdent()
547
            ]);
548
            $entry->update();
549
        }
550
    }
551
552
    /**
553
     * Retrieve the object's URI.
554
     *
555
     * @param  string|null $lang If object is multilingual, return the object route for the specified locale.
556
     * @return TranslationString|string
557
     */
558
    public function url($lang = null)
559
    {
560
        $url = (string)$this->getLatestObjectRoute($lang)->slug();
561
        if ($url) {
562
            return $url;
563
        }
564
565
        $slug = $this->slug();
566
567
        if ($slug instanceof TranslationString && $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...
568
            return $slug->val($lang);
569
        }
570
571
        return (string)$slug;
572
    }
573
574
    /**
575
     * Convert a string into a slug.
576
     *
577
     * @param  string $str The string to slugify.
578
     * @return string The slugified string.
579
     */
580
    public function slugify($str)
581
    {
582
        static $sluggedArray;
583
584
        if (isset($sluggedArray[$str])) {
585
            return $sluggedArray[$str];
586
        }
587
588
        $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...
589
        $separator   = isset($metadata['routable']['separator']) ? $metadata['routable']['separator'] : '-';
590
        $delimiters  = '-_|';
591
        $pregDelim   = preg_quote($delimiters);
592
        $directories = '\\/';
593
        $pregDir     = preg_quote($directories);
594
595
        // Do NOT remove forward slashes.
596
        $slug = preg_replace('![^(\p{L}|\p{N})(\s|\/)]!u', $separator, $str);
597
598
        if (!isset($metadata['routable']['lowercase']) || $metadata['routable']['lowercase'] === false) {
599
            $slug = mb_strtolower($slug, 'UTF-8');
600
        }
601
602
        // Strip HTML
603
        $slug = strip_tags($slug);
604
605
        // Remove diacritics
606
        $slug = preg_replace(
607
            '!&([a-zA-Z])(uml|acute|grave|circ|tilde|cedil|ring);!',
608
            '$1',
609
            htmlentities($slug, ENT_COMPAT, 'UTF-8')
610
        );
611
612
        // Remove unescaped HTML characters
613
        $unescaped = '!&(raquo|laquo|rsaquo|lsaquo|rdquo|ldquo|rsquo|lsquo|hellip|amp|nbsp|quot|ordf|ordm);!';
614
        $slug      = preg_replace($unescaped, '', $slug);
615
616
        // Unify all dashes/underscores as one separator character
617
        $flip = ($separator === '-') ? '_' : '-';
618
        $slug = preg_replace('!['.preg_quote($flip).']+!u', $separator, $slug);
619
620
        // Remove all whitespace and normalize delimiters
621
        $slug = preg_replace('![_\|\s]+!', $separator, $slug);
622
623
        // Squeeze multiple delimiters and whitespace with a single separator
624
        $slug = preg_replace('!['.$pregDelim.'\s]{2,}!', $separator, $slug);
625
626
        // Squeeze multiple URI path delimiters
627
        $slug = preg_replace('!['.$pregDir.']{2,}!', $separator, $slug);
628
629
        // Remove delimiters surrouding URI path delimiters
630
        $slug = preg_replace('!(?<=['.$pregDir.'])['.$pregDelim.']|['.$pregDelim.'](?=['.$pregDir.'])!', '', $slug);
631
632
        // Strip leading and trailing dashes or underscores
633
        $slug = trim($slug, $delimiters);
634
635
        // Cache the slugified string
636
        $sluggedArray[$str] = $slug;
637
638
        return $slug;
639
    }
640
641
    /**
642
     * Finalize slug.
643
     *
644
     * Adds any prefix and suffix defined in the routable configuration set.
645
     *
646
     * @param  string $slug A slug.
647
     * @return string
648
     */
649
    protected function finalizeSlug($slug)
650
    {
651
        $prefix = $this->slugPrefix();
652 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...
653
            $prefix = $this->generateRoutePattern((string)$prefix);
654
            if ($slug === $prefix) {
655
                throw new \UnexpectedValueException('The slug is the same as the prefix.');
656
            }
657
            $slug = $prefix.preg_replace('!^'.preg_quote($prefix).'\b!', '', $slug);
658
        }
659
660
        $suffix = $this->slugSuffix();
661 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...
662
            $suffix = $this->generateRoutePattern((string)$suffix);
663
            if ($slug === $suffix) {
664
                throw new \UnexpectedValueException('The slug is the same as the suffix.');
665
            }
666
            $slug = preg_replace('!\b'.preg_quote($suffix).'$!', '', $slug).$suffix;
667
        }
668
669
        return $slug;
670
    }
671
672
    /**
673
     * Delete all object routes.
674
     *
675
     * Should be called on object deletion {@see \Charcoal\Model\AbstractModel::preDelete()}.
676
     *
677
     * @return boolean Success or failure.
678
     */
679
    protected function deleteObjectRoutes()
680
    {
681
        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...
682
            return false;
683
        }
684
685
        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...
686
            return false;
687
        }
688
689
        $model  = $this->modelFactory()->get($this->objectRouteClass());
690
        $loader = new CollectionLoader([
691
            'logger'  => $this->logger,
692
            'factory' => $this->modelFactory()
693
        ]);
694
695
        $loader
696
            ->setModel($model)
697
            ->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...
698
            ->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...
699
700
        $collection = $loader->load();
701
        foreach ($collection as $route) {
702
            $route->delete();
703
        }
704
705
        return true;
706
    }
707
708
    /**
709
     * Create a route object.
710
     *
711
     * @return ObjectRouteInterface
712
     */
713
    public function createRouteObject()
714
    {
715
        $route = $this->modelFactory()->create($this->objectRouteClass());
716
717
        return $route;
718
    }
719
720
    /**
721
     * Set the class name of the object route model.
722
     *
723
     * @param  string $className The class name of the object route model.
724
     * @throws InvalidArgumentException If the class name is not a string.
725
     * @return AbstractPropertyDisplay Chainable
726
     */
727
    protected function setObjectRouteClass($className)
728
    {
729
        if (!is_string($className)) {
730
            throw new InvalidArgumentException(
731
                'Route class name must be a string.'
732
            );
733
        }
734
735
        $this->objectRouteClass = $className;
736
737
        return $this;
738
    }
739
740
    /**
741
     * Retrieve the class name of the object route model.
742
     *
743
     * @return string
744
     */
745
    public function objectRouteClass()
746
    {
747
        return $this->objectRouteClass;
748
    }
749
750
    /**
751
     * Retrieve the object model factory.
752
     *
753
     * @return \Charcoal\Factory\FactoryInterface
754
     */
755
    abstract public function modelFactory();
756
757
    /**
758
     * Retrieve the routable object's template identifier.
759
     *
760
     * @return mixed
761
     */
762
    abstract public function templateIdent();
763
}
764