SluggableBehavior   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 3
c 2
b 0
f 0
lcom 0
cbo 4
dl 0
loc 56
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A beforeSave() 0 4 1
A slug() 0 6 1
A findSlug() 0 6 1
1
<?php
2
namespace Xety\Cake3Sluggable\Model\Behavior;
3
4
use Cake\Event\Event;
5
use Cake\ORM\Behavior;
6
use Cake\ORM\Entity;
7
use Cake\ORM\Query;
8
use Cake\Utility\Inflector;
9
10
class SluggableBehavior extends Behavior
11
{
12
13
    /**
14
     * Default config.
15
     *
16
     * @var array
17
     */
18
    protected $_defaultConfig = [
19
        'field' => 'title',
20
        'slug' => 'slug',
21
        'replacement' => '-',
22
    ];
23
24
    /**
25
     * Slug a field passed in the default config with its replacement.
26
     *
27
     * @param \Cake\ORM\Entity $entity The entity that is going to be updated.
28
     *
29
     * @return void
30
     */
31
    public function slug(Entity $entity)
32
    {
33
        $config = $this->config();
34
        $value = $entity->get($config['field']);
35
        $entity->set($config['slug'], strtolower(Inflector::slug($value, $config['replacement'])));
36
    }
37
38
    /**
39
     * BeforeSave handle.
40
     *
41
     * @param \Cake\Event\Event  $event  The beforeSave event that was fired.
42
     * @param \Cake\ORM\Entity $entity The entity that is going to be saved.
43
     *
44
     * @return void
45
     */
46
    public function beforeSave(Event $event, Entity $entity)
0 ignored issues
show
Unused Code introduced by
The parameter $event is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
47
    {
48
        $this->slug($entity);
49
    }
50
51
    /**
52
     * Custom finder by slug.
53
     *
54
     * @param \Cake\ORM\Query $query The query finder.
55
     * @param array $options The options passed in the query builder.
56
     *
57
     * @return \Cake\ORM\Query
58
     */
59
    public function findSlug(Query $query, array $options)
60
    {
61
        return $query->where([
62
            $options['slugField'] => $options['slug']
63
        ]);
64
    }
65
}
66