Completed
Push — master ( f4fe64...9bb04b )
by
unknown
07:55
created

RoutableTrait::syncObjectRoutes()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 16
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
     * Determine if the slug is editable.
169
     *
170
     * @return boolean
171
     */
172
    public function isSlugEditable()
173
    {
174
        if ($this->isSlugEditable === null) {
175
            $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...
176
177
            if (isset($metadata['routable']['editable'])) {
178
                $this->isSlugEditable = !!$metadata['routable']['editable'];
179
            } else {
180
                $this->isSlugEditable = false;
181
            }
182
        }
183
184
        return $this->isSlugEditable;
185
    }
186
187
    /**
188
     * Set the object's URL slug.
189
     *
190
     * @param mixed $slug The slug.
191
     * @return RoutableInterface Chainable
192
     */
193
    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...
194
    {
195
        if (TranslationString::isTranslatable($slug)) {
196
            $this->slug = new TranslationString($slug);
197
198
            $values = $this->slug->all();
199
            foreach ($values as $lang => $val) {
200
                $this->slug[$lang] = $this->slugify($val);
201
            }
202
        } else {
203
            /** @todo Hack used for regenerating route */
204
            if (isset($_POST['slug'])) {
205
                $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...
206
            } else {
207
                $this->slug = null;
208
            }
209
        }
210
211
        return $this;
212
    }
213
214
    /**
215
     * Retrieve the object's URL slug.
216
     *
217
     * @return TranslationString|null
218
     */
219
    public function slug()
220
    {
221
        return $this->slug;
222
    }
223
224
    /**
225
     * Generate a URL slug from the object's URL slug pattern.
226
     *
227
     * @return TranslationString
228
     */
229
    public function generateSlug()
230
    {
231
        $translator = TranslationConfig::instance();
232
        $patterns   = $this->slugPattern();
233
        $curSlug    = $this->slug();
234
        $newSlug    = new TranslationString();
235
236
        if ($patterns instanceof TranslationString) {
237
            $patterns = $patterns->all();
238
        }
239
240
        $origLang = $translator->currentLanguage();
241
        foreach ($patterns as $lang => $pattern) {
0 ignored issues
show
Bug introduced by
The expression $patterns of type array<integer,string>|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

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