Completed
Push — master ( 054e54...525849 )
by Mathieu
03:00
created

RoutableTrait::getLatestObjectRoute()   B

Complexity

Conditions 9
Paths 13

Size

Total Lines 57
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 57
rs 7.0745
c 0
b 0
f 0
cc 9
eloc 34
nc 13
nop 1

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
namespace Charcoal\Object;
4
5
use Exception;
6
use InvalidArgumentException;
7
use UnexpectedValueException;
8
9
// From 'charcoal-core'
10
use Charcoal\Loader\CollectionLoader;
11
12
// From 'charcoal-translation'
13
use Charcoal\Translator\Translation;
14
15
// From 'charcoal-view'
16
use Charcoal\View\ViewableInterface;
17
18
// From 'charcoal-object'
19
use Charcoal\Object\ObjectRoute;
20
use Charcoal\Object\ObjectRouteInterface;
21
22
/**
23
 * Full implementation, as Trait, of the {@see \Charcoal\Object\RoutableInterface}.
24
 *
25
 * This implementation uses a secondary model, {@see \Charcoal\Object\ObjectRoute},
26
 * to collect all routes of routable models under a single source.
27
 */
28
trait RoutableTrait
29
{
30
    /**
31
     * The object's route.
32
     *
33
     * @var \Charcoal\Translator\Translation|null
34
     */
35
    protected $slug;
36
37
    /**
38
     * Whether the slug is editable.
39
     *
40
     * If FALSE, the slug is always auto-generated from its pattern.
41
     * If TRUE, the slug is auto-generated only if the slug is empty.
42
     *
43
     * @var boolean|null
44
     */
45
    private $isSlugEditable;
46
47
    /**
48
     * The object's route pattern.
49
     *
50
     * @var \Charcoal\Translator\Translation|null
51
     */
52
    private $slugPattern = '';
53
54
    /**
55
     * A prefix for the object's route.
56
     *
57
     * @var \Charcoal\Translator\Translation|null
58
     */
59
    private $slugPrefix = '';
60
61
    /**
62
     * A suffix for the object's route.
63
     *
64
     * @var \Charcoal\Translator\Translation|null
65
     */
66
    private $slugSuffix = '';
67
68
    /**
69
     * Latest ObjectRoute object concerning the current object.
70
     *
71
     * @var ObjectRouteInterface
72
     */
73
    private $latestObjectRoute;
74
75
    /**
76
     * The class name of the object route model.
77
     *
78
     * Must be a fully-qualified PHP namespace and an implementation of
79
     * {@see \Charcoal\Object\ObjectRouteInterface}. Used by the model factory.
80
     *
81
     * @var string
82
     */
83
    private $objectRouteClass = ObjectRoute::class;
84
85
    /**
86
     * Set the object's URL slug pattern.
87
     *
88
     * @param  mixed $pattern The slug pattern.
89
     * @return RoutableInterface Chainable
90
     */
91
    public function setSlugPattern($pattern)
92
    {
93
        $this->slugPattern = $this->translator()->translation($pattern);
94
        return $this;
95
    }
96
97
    /**
98
     * Retrieve the object's URL slug pattern.
99
     *
100
     * @throws Exception If a slug pattern is not defined.
101
     * @return \Charcoal\Translator\Translation|null
102
     */
103
    public function slugPattern()
104
    {
105
        if (!$this->slugPattern) {
106
            $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...
107
108
            if (isset($metadata['routable']['pattern'])) {
109
                $this->setSlugPattern($metadata['routable']['pattern']);
110
            } elseif (isset($metadata['slug_pattern'])) {
111
                $this->setSlugPattern($metadata['slug_pattern']);
112
            } else {
113
                throw new Exception(sprintf(
114
                    'Undefined route pattern (slug) for %s',
115
                    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 \Charcoal\Translator\Translation|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
                $this->slugPrefix = $this->translator()->translation($metadata['routable']['prefix']);
135
            }
136
        }
137
138
        return $this->slugPrefix;
139
    }
140
141
    /**
142
     * Retrieve route suffix for the object's URL slug pattern.
143
     *
144
     * @return \Charcoal\Translator\Translation|null
145
     */
146 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...
147
    {
148
        if (!$this->slugSuffix) {
149
            $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...
150
151
            if (isset($metadata['routable']['suffix'])) {
152
                $this->slugSuffix = $this->translator()->translation($metadata['routable']['suffix']);
153
            }
154
        }
155
156
        return $this->slugSuffix;
157
    }
158
159
    /**
160
     * Determine if the slug is editable.
161
     *
162
     * @return boolean
163
     */
164
    public function isSlugEditable()
165
    {
166
        if ($this->isSlugEditable === null) {
167
            $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...
168
169
            if (isset($metadata['routable']['editable'])) {
170
                $this->isSlugEditable = !!$metadata['routable']['editable'];
171
            } else {
172
                $this->isSlugEditable = false;
173
            }
174
        }
175
176
        return $this->isSlugEditable;
177
    }
178
179
    /**
180
     * Set the object's URL slug.
181
     *
182
     * @param  mixed $slug The slug.
183
     * @return RoutableInterface Chainable
184
     */
185
    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...
186
    {
187
        $slug = $this->translator()->translation($slug);
188
        if ($slug != null) {
189
            $this->slug = $slug;
190
191
            $values = $this->slug->data();
192
            foreach ($values as $lang => $val) {
193
                $this->slug[$lang] = $this->slugify($val);
194
            }
195
        } else {
196
            /** @todo Hack used for regenerating route */
197
            if (isset($_POST['slug'])) {
198
                $this->slug = [];
0 ignored issues
show
Documentation Bug introduced by
It seems like array() of type array is incompatible with the declared type object<Charcoal\Translator\Translation>|null of property $slug.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
255
                ]);
256
257
                if (!$objectRoute->isSlugUnique()) {
258
                    $objectRoute->generateUniqueSlug();
259
                    $newSlug[$lang] = $objectRoute->slug();
260
                }
261
            }
262
        }
263
        $this->translator()->setLocale($origLang);
264
265
        return $this->translator()->translation($newSlug);
266
    }
267
268
    /**
269
     * Generate a route from the given pattern.
270
     *
271
     * @uses   self::parseRouteToken() If a view renderer is unavailable.
272
     * @param  string $pattern The slug pattern.
273
     * @return string Returns the generated route.
274
     */
275
    protected function generateRoutePattern($pattern)
276
    {
277
        if ($this instanceof ViewableInterface && $this->view() !== null) {
278
            $route = $this->view()->render($pattern, $this->viewController());
279
        } else {
280
            $route = preg_replace_callback('~\{\{\s*(.*?)\s*\}\}~i', [$this, 'parseRouteToken'], $pattern);
281
        }
282
283
        return $this->slugify($route);
284
    }
285
286
    /**
287
     * Parse the given slug (URI token) for the current object.
288
     *
289
     * @used-by self::generateRoutePattern() If a view renderer is unavailable.
290
     * @uses    self::filterRouteToken() For customize the route value filtering,
291
     * @param   string|array $token The token to parse relative to the model entry.
292
     * @throws  InvalidArgumentException If a route token is not a string.
293
     * @return  string
294
     */
295
    protected function parseRouteToken($token)
296
    {
297
        // Processes matches from a regular expression operation
298
        if (is_array($token) && isset($token[1])) {
299
            $token = $token[1];
300
        }
301
302
        $token  = trim($token);
303
        $method = [$this, $token];
304
305
        if (is_callable($method)) {
306
            $value = call_user_func($method);
307
            /** @see \Charcoal\Config\AbstractEntity::offsetGet() */
308
        } elseif (isset($this[$token])) {
309
            $value = $this[$token];
310
        } else {
311
            return '';
312
        }
313
314
        $value = $this->filterRouteToken($value, $token);
315
        if (!is_string($value) && !is_numeric($value)) {
316
            throw new InvalidArgumentException(sprintf(
317
                'Route token "%1$s" must be a string with %2$s; received %3$s',
318
                $token,
319
                get_called_class(),
320
                (is_object($value) ? get_class($value) : gettype($value))
321
            ));
322
        }
323
324
        return $value;
325
    }
326
327
    /**
328
     * Filter the given value for a URI.
329
     *
330
     * @used-by self::parseRouteToken() To resolve the token's value.
331
     * @param   mixed  $value A value to filter.
332
     * @param   string $token The parsed token.
333
     * @return  string The filtered $value.
334
     */
335
    protected function filterRouteToken($value, $token = null)
336
    {
337
        unset($token);
338
339
        if ($value instanceof \Closure) {
340
            $value = $value();
341
        }
342
343
        if ($value instanceof \DateTime) {
344
            $value = $value->format('Y-m-d-H:i');
345
        }
346
347
        if (method_exists($value, '__toString')) {
348
            $value = strval($value);
349
        }
350
351
        return $value;
352
    }
353
354
    /**
355
     * Route generation.
356
     *
357
     * Saves all routes to {@see \Charcoal\Object\ObjectRoute}.
358
     *
359
     * @param  mixed $slug Slug by langs.
360
     * @return void
361
     */
362
    protected function generateObjectRoute($slug = null)
363
    {
364
365
        if (!$slug) {
366
            $slug = $this->generateSlug();
367
        }
368
369
        if ($slug instanceof Translation) {
370
            $slugs = $slug->all();
0 ignored issues
show
Bug introduced by
The method all() does not seem to exist on object<Charcoal\Translator\Translation>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
371
        }
372
373
        $origLang = $this->translator()->getLocale();
374
        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...
375
            if (!in_array($lang, $this->translator()->availableLocales())) {
376
                continue;
377
            }
378
379
            $this->translator()->setLocale($lang);
380
381
            $objectRoute = $this->createRouteObject();
382
383
            $source = $objectRoute->source();
384
            if (!$source->tableExists()) {
385
                $source->createTable();
386
            } else {
387
                $oldRoute = $this->getLatestObjectRoute();
388
389
                // Unchanged but sync extra properties
390
                if ($slug === $oldRoute->slug()) {
391
                    $oldRoute->setData([
392
                        'route_template' => $this->templateIdent()
393
                    ]);
394
                    $oldRoute->update(['route_template']);
395
                    continue;
396
                }
397
            }
398
399
            $objectRoute->setData([
400
                'lang'           => $lang,
401
                'slug'           => $slug,
402
                '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...
403
                '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...
404
                // Not used, might be too much.
405
                'route_template' => $this->templateIdent(),
406
                'active'         => true
407
            ]);
408
409
            if (!$objectRoute->isSlugUnique()) {
410
                $objectRoute->generateUniqueSlug();
411
            }
412
413
            if ($objectRoute->id()) {
414
                $objectRoute->update();
415
            } else {
416
                $objectRoute->save();
417
            }
418
        }
419
420
        $this->translator()->setLocale($origLang);
421
    }
422
423
    /**
424
     * Retrieve the latest object route.
425
     *
426
     * @param  string|null $lang If object is multilingual, return the object route for the specified locale.
427
     * @throws InvalidArgumentException If the given language is invalid.
428
     * @return ObjectRouteInterface Latest object route.
429
     */
430
    protected function getLatestObjectRoute($lang = null)
431
    {
432
433
        if ($lang === null) {
434
            $lang = $this->translator()->getLocale();
435
        } elseif (!in_array($lang, $this->translator()->availableLocales())) {
436
            throw new InvalidArgumentException(sprintf(
437
                'Invalid language, received %s',
438
                (is_object($lang) ? get_class($lang) : gettype($lang))
439
            ));
440
        }
441
442
        if (isset($this->latestObjectRoute[$lang])) {
443
            return $this->latestObjectRoute[$lang];
444
        }
445
446
        $model = $this->createRouteObject();
447
448
        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...
449
            $this->latestObjectRoute[$lang] = $model;
450
451
            return $this->latestObjectRoute[$lang];
452
        }
453
454
        // For URL.
455
        $source = $model->source();
456
        $loader = new CollectionLoader([
457
            '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...
458
            'factory' => $this->modelFactory()
459
        ]);
460
461
        if (!$source->tableExists()) {
462
            $source->createTable();
463
        }
464
465
        $loader
466
            ->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...
467
            ->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...
468
            ->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...
469
            ->addFilter('lang', $lang)
470
            ->addFilter('active', true)
471
            ->addOrder('creation_date', 'desc')
472
            ->setPage(1)
473
            ->setNumPerPage(1);
474
475
        $collection = $loader->load()->objects();
476
477
        if (!count($collection)) {
478
            $this->latestObjectRoute[$lang] = $model;
479
480
            return $this->latestObjectRoute[$lang];
481
        }
482
483
        $this->latestObjectRoute[$lang] = $collection[0];
484
485
        return $this->latestObjectRoute[$lang];
486
    }
487
488
    /**
489
     * Retrieve the object's URI.
490
     *
491
     * @param  string|null $lang If object is multilingual, return the object route for the specified locale.
492
     * @return string
493
     */
494
    public function url($lang = null)
495
    {
496
        $url = (string)$this->getLatestObjectRoute($lang)->slug();
497
        if ($url) {
498
            return $url;
499
        }
500
501
        $slug = $this->slug();
502
503
        if ($slug instanceof Translation && $lang) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $lang of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

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

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

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

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
504
            return $slug->val($lang);
0 ignored issues
show
Bug introduced by
The method val() does not seem to exist on object<Charcoal\Translator\Translation>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
505
        }
506
507
        return (string)$slug;
508
    }
509
510
    /**
511
     * Convert a string into a slug.
512
     *
513
     * @param  string $str The string to slugify.
514
     * @return string The slugified string.
515
     */
516
    public function slugify($str)
517
    {
518
        static $sluggedArray;
519
520
        if (isset($sluggedArray[$str])) {
521
            return $sluggedArray[$str];
522
        }
523
524
        $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...
525
        $separator   = isset($metadata['routable']['separator']) ? $metadata['routable']['separator'] : '-';
526
        $delimiters  = '-_|';
527
        $pregDelim   = preg_quote($delimiters);
528
        $directories = '\\/';
529
        $pregDir     = preg_quote($directories);
530
531
        // Do NOT remove forward slashes.
532
        $slug = preg_replace('![^(\p{L}|\p{N})(\s|\/)]!u', $separator, $str);
533
534
        if (!isset($metadata['routable']['lowercase']) || $metadata['routable']['lowercase'] === false) {
535
            $slug = mb_strtolower($slug, 'UTF-8');
536
        }
537
538
        // Strip HTML
539
        $slug = strip_tags($slug);
540
541
        // Remove diacritics
542
        $slug = preg_replace(
543
            '!&([a-zA-Z])(uml|acute|grave|circ|tilde|cedil|ring);!',
544
            '$1',
545
            htmlentities($slug, ENT_COMPAT, 'UTF-8')
546
        );
547
548
        // Remove unescaped HTML characters
549
        $unescaped = '!&(raquo|laquo|rsaquo|lsaquo|rdquo|ldquo|rsquo|lsquo|hellip|amp|nbsp|quot|ordf|ordm);!';
550
        $slug      = preg_replace($unescaped, '', $slug);
551
552
        // Unify all dashes/underscores as one separator character
553
        $flip = ($separator === '-') ? '_' : '-';
554
        $slug = preg_replace('!['.preg_quote($flip).']+!u', $separator, $slug);
555
556
        // Remove all whitespace and normalize delimiters
557
        $slug = preg_replace('![_\|\s]+!', $separator, $slug);
558
559
        // Squeeze multiple delimiters and whitespace with a single separator
560
        $slug = preg_replace('!['.$pregDelim.'\s]{2,}!', $separator, $slug);
561
562
        // Squeeze multiple URI path delimiters
563
        $slug = preg_replace('!['.$pregDir.']{2,}!', $separator, $slug);
564
565
        // Remove delimiters surrouding URI path delimiters
566
        $slug = preg_replace('!(?<=['.$pregDir.'])['.$pregDelim.']|['.$pregDelim.'](?=['.$pregDir.'])!', '', $slug);
567
568
        // Strip leading and trailing dashes or underscores
569
        $slug = trim($slug, $delimiters);
570
571
        // Cache the slugified string
572
        $sluggedArray[$str] = $slug;
573
574
        return $slug;
575
    }
576
577
    /**
578
     * Finalize slug.
579
     *
580
     * Adds any prefix and suffix defined in the routable configuration set.
581
     *
582
     * @param  string $slug A slug.
583
     * @throws UnexpectedValueException If the slug affixes are invalid.
584
     * @return string
585
     */
586
    protected function finalizeSlug($slug)
587
    {
588
        $prefix = $this->slugPrefix();
589 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...
590
            $prefix = $this->generateRoutePattern((string)$prefix);
591
            if ($slug === $prefix) {
592
                throw new UnexpectedValueException('The slug is the same as the prefix.');
593
            }
594
            $slug = $prefix.preg_replace('!^'.preg_quote($prefix).'\b!', '', $slug);
595
        }
596
597
        $suffix = $this->slugSuffix();
598 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...
599
            $suffix = $this->generateRoutePattern((string)$suffix);
600
            if ($slug === $suffix) {
601
                throw new UnexpectedValueException('The slug is the same as the suffix.');
602
            }
603
            $slug = preg_replace('!\b'.preg_quote($suffix).'$!', '', $slug).$suffix;
604
        }
605
606
        return $slug;
607
    }
608
609
    /**
610
     * Delete all object routes.
611
     *
612
     * Should be called on object deletion {@see \Charcoal\Model\AbstractModel::preDelete()}.
613
     *
614
     * @return boolean Success or failure.
615
     */
616
    protected function deleteObjectRoutes()
617
    {
618
        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...
619
            return false;
620
        }
621
622
        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...
623
            return false;
624
        }
625
626
        $model  = $this->modelFactory()->get($this->objectRouteClass());
627
        $loader = new CollectionLoader([
628
            'logger'  => $this->logger,
629
            'factory' => $this->modelFactory()
630
        ]);
631
632
        $loader
633
            ->setModel($model)
634
            ->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...
635
            ->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...
636
637
        $collection = $loader->load();
638
        foreach ($collection as $route) {
639
            $route->delete();
640
        }
641
642
        return true;
643
    }
644
645
    /**
646
     * Create a route object.
647
     *
648
     * @return ObjectRouteInterface
649
     */
650
    public function createRouteObject()
651
    {
652
        $route = $this->modelFactory()->create($this->objectRouteClass());
653
654
        return $route;
655
    }
656
657
    /**
658
     * Set the class name of the object route model.
659
     *
660
     * @param  string $className The class name of the object route model.
661
     * @throws InvalidArgumentException If the class name is not a string.
662
     * @return AbstractPropertyDisplay Chainable
663
     */
664
    protected function setObjectRouteClass($className)
665
    {
666
        if (!is_string($className)) {
667
            throw new InvalidArgumentException(
668
                'Route class name must be a string.'
669
            );
670
        }
671
672
        $this->objectRouteClass = $className;
673
674
        return $this;
675
    }
676
677
    /**
678
     * Retrieve the class name of the object route model.
679
     *
680
     * @return string
681
     */
682
    public function objectRouteClass()
683
    {
684
        return $this->objectRouteClass;
685
    }
686
687
    /**
688
     * Retrieve the object model factory.
689
     *
690
     * @return \Charcoal\Factory\FactoryInterface
691
     */
692
    abstract public function modelFactory();
693
694
    /**
695
     * Retrieve the routable object's template identifier.
696
     *
697
     * @return mixed
698
     */
699
    abstract public function templateIdent();
700
701
    /**
702
     * @return \Charcoal\Translator\Translator
703
     */
704
    abstract protected function translator();
705
}
706