Completed
Push — master ( b4e7ce...e3368d )
by
unknown
33:00
created

RoutableTrait   D

Complexity

Total Complexity 88

Size/Duplication

Total Lines 712
Duplicated Lines 6.46 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 8
Bugs 0 Features 0
Metric Value
wmc 88
c 8
b 0
f 0
lcom 1
cbo 7
dl 46
loc 712
rs 4.4444

23 Methods

Rating   Name   Duplication   Size   Complexity  
A generateRoutePattern() 0 10 3
C parseRouteToken() 0 32 7
A filterRouteToken() 0 14 3
B generateObjectRoute() 0 56 9
C getLatestObjectRoute() 0 60 9
A setSlugPattern() 0 10 2
A slugPattern() 0 18 4
A slugPrefix() 16 16 4
A slugSuffix() 16 16 4
A isSlugEditable() 0 14 3
A setSlug() 0 20 4
A slug() 0 4 1
C generateSlug() 0 44 8
B syncObjectRoutes() 0 27 4
A url() 0 15 4
B slugify() 0 60 6
B finalizeSlug() 14 22 5
B deleteObjectRoutes() 0 28 4
A createRouteObject() 0 6 1
A setObjectRouteClass() 0 12 2
A objectRouteClass() 0 4 1
modelFactory() 0 1 ?
templateIdent() 0 1 ?

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like RoutableTrait often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use RoutableTrait, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Charcoal\Object;
4
5
use \InvalidArgumentException;
6
use \UnexpectedValueException;
7
8
// From 'charcoal-core'
9
use \Charcoal\Loader\CollectionLoader;
10
11
// From 'charcoal-translation'
12
use \Charcoal\Translation\TranslationString;
13
use \Charcoal\Translation\TranslationConfig;
14
15
// From 'charcoal-view'
16
use \Charcoal\View\ViewableInterface;
17
18
// Local Dependencies
19
use \Charcoal\Object\ObjectRoute;
20
use \Charcoal\Object\ObjectRouteInterface;
21
22
/**
23
 * Full implementation, as Trait, of the `RoutableInterface`.
24
 */
25
trait RoutableTrait
26
{
27
    /**
28
     * The object's route.
29
     *
30
     * @var TranslationString|string|null
31
     */
32
    protected $slug;
33
34
    /**
35
     * Whether the slug is editable.
36
     *
37
     * If FALSE, the slug is always auto-generated from its pattern.
38
     * If TRUE, the slug is auto-generated only if the slug is empty.
39
     *
40
     * @var boolean|null
41
     */
42
    private $isSlugEditable;
43
44
    /**
45
     * The object's route pattern.
46
     *
47
     * @var TranslationString|string|null
48
     */
49
    private $slugPattern = '';
50
51
    /**
52
     * A prefix for the object's route.
53
     *
54
     * @var TranslationString|string|null
55
     */
56
    private $slugPrefix = '';
57
58
    /**
59
     * A suffix for the object's route.
60
     *
61
     * @var TranslationString|string|null
62
     */
63
    private $slugSuffix = '';
64
65
    /**
66
     * Latest ObjectRoute object concerning the current object.
67
     *
68
     * @var ObjectRouteInterface
69
     */
70
    private $latestObjectRoute;
71
72
    /**
73
     * The class name of the object route model.
74
     *
75
     * Must be a fully-qualified PHP namespace and an implementation of
76
     * {@see \Charcoal\Object\ObjectRouteInterface}. Used by the model factory.
77
     *
78
     * @var string
79
     */
80
    private $objectRouteClass = ObjectRoute::class;
81
82
    /**
83
     * Set the object's URL slug pattern.
84
     *
85
     * @param mixed $pattern The slug pattern.
86
     * @return RoutableInterface Chainable
87
     */
88
    public function setSlugPattern($pattern)
89
    {
90
        if (TranslationString::isTranslatable($pattern)) {
91
            $this->slugPattern = new TranslationString($pattern);
92
        } else {
93
            $this->slugPattern = null;
94
        }
95
96
        return $this;
97
    }
98
99
    /**
100
     * Retrieve the object's URL slug pattern.
101
     *
102
     * @throws InvalidArgumentException If a slug pattern is not defined.
103
     * @return TranslationString|null
104
     */
105
    public function slugPattern()
106
    {
107
        if (!$this->slugPattern) {
108
            $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...
109
110
            if (isset($metadata['routable']['pattern'])) {
111
                $this->setSlugPattern($metadata['routable']['pattern']);
112
            } elseif (isset($metadata['slug_pattern'])) {
113
                $this->setSlugPattern($metadata['slug_pattern']);
114
            } else {
115
                throw new InvalidArgumentException(
116
                    sprintf('Undefined route pattern (slug) for %s', 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 TranslationString|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
                $affix = $metadata['routable']['prefix'];
136
137
                if (TranslationString::isTranslatable($affix)) {
138
                    $this->slugPrefix = new TranslationString($affix);
139
                }
140
            }
141
        }
142
143
        return $this->slugPrefix;
144
    }
145
146
    /**
147
     * Retrieve route suffix for the object's URL slug pattern.
148
     *
149
     * @return TranslationString|null
150
     */
151 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...
152
    {
153
        if (!$this->slugSuffix) {
154
            $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...
155
156
            if (isset($metadata['routable']['suffix'])) {
157
                $affix = $metadata['routable']['suffix'];
158
159
                if (TranslationString::isTranslatable($affix)) {
160
                    $this->slugSuffix = new TranslationString($affix);
161
                }
162
            }
163
        }
164
165
        return $this->slugSuffix;
166
    }
167
168
    /**
169
     * Determine if the slug is editable.
170
     *
171
     * @return boolean
172
     */
173
    public function isSlugEditable()
174
    {
175
        if ($this->isSlugEditable === null) {
176
            $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...
177
178
            if (isset($metadata['routable']['editable'])) {
179
                $this->isSlugEditable = !!$metadata['routable']['editable'];
180
            } else {
181
                $this->isSlugEditable = false;
182
            }
183
        }
184
185
        return $this->isSlugEditable;
186
    }
187
188
    /**
189
     * Set the object's URL slug.
190
     *
191
     * @param mixed $slug The slug.
192
     * @return RoutableInterface Chainable
193
     */
194
    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...
195
    {
196
        if (TranslationString::isTranslatable($slug)) {
197
            $this->slug = new TranslationString($slug);
198
199
            $values = $this->slug->all();
200
            foreach ($values as $lang => $val) {
201
                $this->slug[$lang] = $this->slugify($val);
202
            }
203
        } else {
204
            /** @todo Hack used for regenerating route */
205
            if (isset($_POST['slug'])) {
206
                $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...
207
            } else {
208
                $this->slug = null;
209
            }
210
        }
211
212
        return $this;
213
    }
214
215
    /**
216
     * Retrieve the object's URL slug.
217
     *
218
     * @return TranslationString|null
219
     */
220
    public function slug()
221
    {
222
        return $this->slug;
223
    }
224
225
    /**
226
     * Generate a URL slug from the object's URL slug pattern.
227
     *
228
     * @throws UnexpectedValueException If the slug is empty.
229
     * @return TranslationString
230
     */
231
    public function generateSlug()
232
    {
233
        $translator = TranslationConfig::instance();
234
        $languages  = $translator->availableLanguages();
235
        $patterns   = $this->slugPattern();
236
        $curSlug    = $this->slug();
237
        $newSlug    = new TranslationString();
238
239
        $origLang = $translator->currentLanguage();
240
        foreach ($languages as $lang) {
241
            $pattern = $patterns[$lang];
242
243
            $translator->setCurrentLanguage($lang);
244
            if ($this->isSlugEditable() && isset($curSlug[$lang]) && strlen($curSlug[$lang])) {
245
                $newSlug[$lang] = $curSlug[$lang];
246
            } else {
247
                $newSlug[$lang] = $this->generateRoutePattern($pattern);
248
                if (!strlen($newSlug[$lang])) {
249
                    throw new UnexpectedValueException(
250
                        sprintf('The slug is empty. The pattern is "%s"', $pattern)
251
                    );
252
                }
253
            }
254
            $newSlug[$lang] = $this->finalizeSlug($newSlug[$lang]);
255
256
            $objectRoute = $this->createRouteObject();
257
            if ($objectRoute->source()->tableExists()) {
258
                $objectRoute->setData([
259
                    'lang'           => $lang,
260
                    'slug'           => $newSlug[$lang],
261
                    '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...
262
                    '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...
263
                ]);
264
265
                if (!$objectRoute->isSlugUnique()) {
266
                    $objectRoute->generateUniqueSlug();
267
                    $newSlug[$lang] = $objectRoute->slug();
268
                }
269
            }
270
        }
271
        $translator->setCurrentLanguage($origLang);
272
273
        return $newSlug;
274
    }
275
276
    /**
277
     * Generate a route from the given pattern.
278
     *
279
     * @uses   self::parseRouteToken() If a view renderer is unavailable.
280
     * @param  string $pattern The slug pattern.
281
     * @return string Returns the generated route.
282
     */
283
    protected function generateRoutePattern($pattern)
284
    {
285
        if ($this instanceof ViewableInterface && $this->view() !== null) {
286
            $route = $this->view()->render($pattern, $this->viewController());
287
        } else {
288
            $route = preg_replace_callback('~\{\{\s*(.*?)\s*\}\}~i', [$this, 'parseRouteToken'], $pattern);
289
        }
290
291
        return $this->slugify($route);
292
    }
293
294
    /**
295
     * Parse the given slug (URI token) for the current object.
296
     *
297
     * @used-by self::generateRoutePattern() If a view renderer is unavailable.
298
     * @uses    self::filterRouteToken() For customize the route value filtering,
299
     * @param   string|array $token The token to parse relative to the model entry.
300
     * @throws  InvalidArgumentException If a route token is not a string.
301
     * @return  string
302
     */
303
    protected function parseRouteToken($token)
304
    {
305
        // Processes matches from a regular expression operation
306
        if (is_array($token) && isset($token[1])) {
307
            $token = $token[1];
308
        }
309
310
        $token  = trim($token);
311
        $method = [$this, $token];
312
313
        if (is_callable($method)) {
314
            $value = call_user_func($method);
315
            /** @see \Charcoal\Config\AbstractEntity::offsetGet() */
316
        } elseif (isset($this[$token])) {
317
            $value = $this[$token];
318
        } else {
319
            return '';
320
        }
321
322
        $value = $this->filterRouteToken($value, $token);
323
        if (!is_string($value) && !is_numeric($value)) {
324
            throw new InvalidArgumentException(
325
                sprintf(
326
                    'Route token "%1$s" must be a string with %2$s',
327
                    $token,
328
                    get_called_class()
329
                )
330
            );
331
        }
332
333
        return $value;
334
    }
335
336
    /**
337
     * Filter the given value for a URI.
338
     *
339
     * @used-by self::parseRouteToken() To resolve the token's value.
340
     * @param   mixed  $value A value to filter.
341
     * @param   string $token The parsed token.
342
     * @return  string The filtered $value.
343
     */
344
    protected function filterRouteToken($value, $token = null)
345
    {
346
        unset($token);
347
348
        if ($value instanceof \Closure) {
349
            $value = $value();
350
        }
351
352
        if ($value instanceof \DateTime) {
353
            $value = $value->format('Y-m-d-H:i');
354
        }
355
356
        return $value;
357
    }
358
359
    /**
360
     * Route generation.
361
     *
362
     * Saves all routes to {@see \Charcoal\Object\ObjectRoute}.
363
     *
364
     * @param  mixed $slug Slug by langs.
365
     * @return void
366
     */
367
    protected function generateObjectRoute($slug = null)
368
    {
369
        $translator = TranslationConfig::instance();
370
371
        if (!$slug) {
372
            $slug = $this->generateSlug();
373
        }
374
375
        if ($slug instanceof TranslationString) {
376
            $slugs = $slug->all();
377
        }
378
379
        $origLang = $translator->currentLanguage();
380
        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...
381
            if (!$translator->hasLanguage($lang)) {
382
                continue;
383
            }
384
385
            $translator->setCurrentLanguage($lang);
386
387
            $objectRoute = $this->createRouteObject();
388
389
            $source = $objectRoute->source();
390
            if (!$source->tableExists()) {
391
                $source->createTable();
392
            } else {
393
                $oldRoute = $this->getLatestObjectRoute();
394
395
                // Unchanged
396
                if ($slug === $oldRoute->slug()) {
397
                    continue;
398
                }
399
            }
400
401
            $objectRoute->setData([
402
                'lang'           => $lang,
403
                'slug'           => $slug,
404
                '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...
405
                '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...
406
                // Not used, might be too much.
407
                'route_template' => $this->templateIdent(),
408
                'active'         => true
409
            ]);
410
411
            if (!$objectRoute->isSlugUnique()) {
412
                $objectRoute->generateUniqueSlug();
413
            }
414
415
            if ($objectRoute->id()) {
416
                $objectRoute->update();
417
            } else {
418
                $objectRoute->save();
419
            }
420
        }
421
        $translator->setCurrentLanguage($origLang);
422
    }
423
424
    /**
425
     * Retrieve the latest object route.
426
     *
427
     * @param  string|null $lang If object is multilingual, return the object route for the specified locale.
428
     * @throws InvalidArgumentException If the given language is invalid.
429
     * @return ObjectRouteInterface Latest object route.
430
     */
431
    protected function getLatestObjectRoute($lang = null)
432
    {
433
        $translator = TranslationConfig::instance();
434
435
        if ($lang === null) {
436
            $lang = $translator->currentLanguage();
437
        } elseif (!$translator->hasLanguage($lang)) {
438
            throw new InvalidArgumentException(
439
                sprintf(
440
                    'Invalid language, received %s',
441
                    (is_object($lang) ? get_class($lang) : gettype($lang))
442
                )
443
            );
444
        }
445
446
        if (isset($this->latestObjectRoute[$lang])) {
447
            return $this->latestObjectRoute[$lang];
448
        }
449
450
        $model = $this->createRouteObject();
451
452
        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...
453
            $this->latestObjectRoute[$lang] = $model;
454
455
            return $this->latestObjectRoute[$lang];
456
        }
457
458
        // For URL.
459
        $source = $model->source();
460
        $loader = new CollectionLoader([
461
            '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...
462
            'factory' => $this->modelFactory()
463
        ]);
464
465
        if (!$source->tableExists()) {
466
            $source->createTable();
467
        }
468
469
        $loader
470
            ->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...
471
            ->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...
472
            ->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...
473
            ->addFilter('lang', $lang)
474
            ->addFilter('active', true)
475
            ->addOrder('creation_date', 'desc')
476
            ->setPage(1)
477
            ->setNumPerPage(1);
478
479
        $collection = $loader->load()->objects();
480
481
        if (!count($collection)) {
482
            $this->latestObjectRoute[$lang] = $model;
483
484
            return $this->latestObjectRoute[$lang];
485
        }
486
487
        $this->latestObjectRoute[$lang] = $collection[0];
488
489
        return $this->latestObjectRoute[$lang];
490
    }
491
492
    /**
493
     * Sync the object routes with the object's data.
494
     * @return void
495
     */
496
    public function syncObjectRoutes()
497
    {
498
        $model = $this->createRouteObject();
499
500
        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...
501
            return;
502
        }
503
504
        $loader = new CollectionLoader([
505
            'logger'  => $this->logger,
506
            'factory' => $this->modelFactory()
507
        ]);
508
509
        $loader
510
            ->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...
511
            ->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...
512
            ->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...
513
514
        $collection = $loader->load();
515
516
        foreach ($collection as $entry) {
517
            $entry->setData([
518
                'route_template' => $this->templateIdent()
519
            ]);
520
            $entry->update();
521
        }
522
    }
523
524
    /**
525
     * Retrieve the object's URI.
526
     *
527
     * @param  string|null $lang If object is multilingual, return the object route for the specified locale.
528
     * @return TranslationString|string
529
     */
530
    public function url($lang = null)
531
    {
532
        $url = (string)$this->getLatestObjectRoute($lang)->slug();
533
        if ($url) {
534
            return $url;
535
        }
536
537
        $slug = $this->slug();
538
539
        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...
540
            return $slug->val($lang);
541
        }
542
543
        return (string)$slug;
544
    }
545
546
    /**
547
     * Convert a string into a slug.
548
     *
549
     * @param  string $str The string to slugify.
550
     * @return string The slugified string.
551
     */
552
    public function slugify($str)
553
    {
554
        static $sluggedArray;
555
556
        if (isset($sluggedArray[$str])) {
557
            return $sluggedArray[$str];
558
        }
559
560
        $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...
561
        $separator   = isset($metadata['routable']['separator']) ? $metadata['routable']['separator'] : '-';
562
        $delimiters  = '-_|';
563
        $pregDelim   = preg_quote($delimiters);
564
        $directories = '\\/';
565
        $pregDir     = preg_quote($directories);
566
567
        // Do NOT remove forward slashes.
568
        $slug = preg_replace('![^(\p{L}|\p{N})(\s|\/)]!u', $separator, $str);
569
570
        if (!isset($metadata['routable']['lowercase']) || $metadata['routable']['lowercase'] === false) {
571
            $slug = mb_strtolower($slug, 'UTF-8');
572
        }
573
574
        // Strip HTML
575
        $slug = strip_tags($slug);
576
577
        // Remove diacritics
578
        $slug = preg_replace(
579
            '!&([a-zA-Z])(uml|acute|grave|circ|tilde|cedil|ring);!',
580
            '$1',
581
            htmlentities($slug, ENT_COMPAT, 'UTF-8')
582
        );
583
584
        // Remove unescaped HTML characters
585
        $unescaped = '!&(raquo|laquo|rsaquo|lsaquo|rdquo|ldquo|rsquo|lsquo|hellip|amp|nbsp|quot|ordf|ordm);!';
586
        $slug      = preg_replace($unescaped, '', $slug);
587
588
        // Unify all dashes/underscores as one separator character
589
        $flip = ($separator === '-') ? '_' : '-';
590
        $slug = preg_replace('!['.preg_quote($flip).']+!u', $separator, $slug);
591
592
        // Remove all whitespace and normalize delimiters
593
        $slug = preg_replace('![_\|\s]+!', $separator, $slug);
594
595
        // Squeeze multiple delimiters and whitespace with a single separator
596
        $slug = preg_replace('!['.$pregDelim.'\s]{2,}!', $separator, $slug);
597
598
        // Squeeze multiple URI path delimiters
599
        $slug = preg_replace('!['.$pregDir.']{2,}!', $separator, $slug);
600
601
        // Remove delimiters surrouding URI path delimiters
602
        $slug = preg_replace('!(?<=['.$pregDir.'])['.$pregDelim.']|['.$pregDelim.'](?=['.$pregDir.'])!', '', $slug);
603
604
        // Strip leading and trailing dashes or underscores
605
        $slug = trim($slug, $delimiters);
606
607
        // Cache the slugified string
608
        $sluggedArray[$str] = $slug;
609
610
        return $slug;
611
    }
612
613
    /**
614
     * Finalize slug.
615
     *
616
     * Adds any prefix and suffix defined in the routable configuration set.
617
     *
618
     * @param  string $slug A slug.
619
     * @throws UnexpectedValueException If the slug affixes are invalid.
620
     * @return string
621
     */
622
    protected function finalizeSlug($slug)
623
    {
624
        $prefix = $this->slugPrefix();
625 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...
626
            $prefix = $this->generateRoutePattern((string)$prefix);
627
            if ($slug === $prefix) {
628
                throw new UnexpectedValueException('The slug is the same as the prefix.');
629
            }
630
            $slug = $prefix.preg_replace('!^'.preg_quote($prefix).'\b!', '', $slug);
631
        }
632
633
        $suffix = $this->slugSuffix();
634 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...
635
            $suffix = $this->generateRoutePattern((string)$suffix);
636
            if ($slug === $suffix) {
637
                throw new UnexpectedValueException('The slug is the same as the suffix.');
638
            }
639
            $slug = preg_replace('!\b'.preg_quote($suffix).'$!', '', $slug).$suffix;
640
        }
641
642
        return $slug;
643
    }
644
645
    /**
646
     * Delete all object routes.
647
     *
648
     * Should be called on object deletion {@see \Charcoal\Model\AbstractModel::preDelete()}.
649
     *
650
     * @return boolean Success or failure.
651
     */
652
    protected function deleteObjectRoutes()
653
    {
654
        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...
655
            return false;
656
        }
657
658
        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...
659
            return false;
660
        }
661
662
        $model  = $this->modelFactory()->get($this->objectRouteClass());
663
        $loader = new CollectionLoader([
664
            'logger'  => $this->logger,
665
            'factory' => $this->modelFactory()
666
        ]);
667
668
        $loader
669
            ->setModel($model)
670
            ->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...
671
            ->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...
672
673
        $collection = $loader->load();
674
        foreach ($collection as $route) {
675
            $route->delete();
676
        }
677
678
        return true;
679
    }
680
681
    /**
682
     * Create a route object.
683
     *
684
     * @return ObjectRouteInterface
685
     */
686
    public function createRouteObject()
687
    {
688
        $route = $this->modelFactory()->create($this->objectRouteClass());
689
690
        return $route;
691
    }
692
693
    /**
694
     * Set the class name of the object route model.
695
     *
696
     * @param  string $className The class name of the object route model.
697
     * @throws InvalidArgumentException If the class name is not a string.
698
     * @return AbstractPropertyDisplay Chainable
699
     */
700
    protected function setObjectRouteClass($className)
701
    {
702
        if (!is_string($className)) {
703
            throw new InvalidArgumentException(
704
                'Route class name must be a string.'
705
            );
706
        }
707
708
        $this->objectRouteClass = $className;
709
710
        return $this;
711
    }
712
713
    /**
714
     * Retrieve the class name of the object route model.
715
     *
716
     * @return string
717
     */
718
    public function objectRouteClass()
719
    {
720
        return $this->objectRouteClass;
721
    }
722
723
    /**
724
     * Retrieve the object model factory.
725
     *
726
     * @return \Charcoal\Factory\FactoryInterface
727
     */
728
    abstract public function modelFactory();
729
730
    /**
731
     * Retrieve the routable object's template identifier.
732
     *
733
     * @return mixed
734
     */
735
    abstract public function templateIdent();
736
}
737