Keywords::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace LaraComponents\Seo\Entities;
4
5
use Countable;
6
7
class Keywords implements Countable
8
{
9
    /**
10
     * @var array
11
     */
12
    protected $items = [];
13
14
    /**
15
     * @var int
16
     */
17
    protected $maxWords;
18
19
    /**
20
     * Create a new keywords instance.
21
     *
22
     * @param array $config
23
     */
24
    public function __construct(array $config = [])
25
    {
26
        $this->initConfig($config);
27
    }
28
29
    /**
30
     * Init config.
31
     *
32
     * @param  array  $config
33
     * @return void
34
     */
35
    protected function initConfig(array $config)
36
    {
37
        $this->setMaxWords(isset($config['max_words']) ? $config['max_words'] : 0);
38
39
        if(isset($config['default'])) {
40
            $this->set($config['default']);
41
        }
42
    }
43
44
    public function setMaxWords($max)
45
    {
46
        $this->maxWords = (int) $max;
47
48
        return $this;
49
    }
50
51
    public function getMaxWords()
52
    {
53
        return $this->maxWords;
54
    }
55
56
    public function add($items)
57
    {
58
        $items = $this->clean($items);
59
60
        $this->items = array_merge(array_diff($items, $this->items), $this->items);
61
    }
62
63
    public function set($items)
64
    {
65
        $this->items = $this->clean($items);
66
    }
67
68
    public function get()
69
    {
70
        return $this->maxWords > 0 && $this->count() > $this->maxWords
71
            ? array_slice($this->items, 0, $this->maxWords)
72
            : $this->items;
73
    }
74
75
    public function clear()
76
    {
77
        $this->items = [];
78
    }
79
80
    public function count()
81
    {
82
        return count($this->items);
83
    }
84
85
    protected function clean($items)
86
    {
87
        $items = ! is_array($items) ? explode(',', $items) : $items;
88
89
        return array_map(function ($item) {
90
            return trim(strip_tags($item));
91
        }, $items);
92
    }
93
94
    public function toString()
95
    {
96
        return implode(', ', $this->get());
97
    }
98
99
    public function __toString()
100
    {
101
        return $this->toString();
102
    }
103
}
104