Completed
Pull Request — master (#254)
by Anton
11:18
created

Row::beforeUpdate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 4
rs 10
ccs 0
cts 3
cp 0
crap 2
1
<?php
2
/**
3
 * @copyright Bluz PHP Team
4
 * @link https://github.com/bluzphp/skeleton
5
 */
6
7
/**
8
 * @namespace
9
 */
10
namespace Application\Categories;
11
12
use Bluz\Validator\Traits\Validator;
13
use Bluz\Validator\Validator as v;
14
15
/**
16
 * Class Row
17
 * @package Application\Categories
18
 *
19
 * @property integer $id
20
 * @property integer $rootId
21
 * @property integer $parentId
22
 * @property string $name
23
 * @property string $alias
24
 * @property string $created
25
 * @property string $updated
26
 */
27
class Row extends \Bluz\Db\Row
28
{
29
    use Validator;
30
31
    /**
32
     * @var Row[]
33
     */
34
    protected $children;
35
36
    /**
37
     * @return void
38
     */
39
    public function beforeSave()
40
    {
41
        $this->addValidator(
42
            'name',
43
            v::required(),
44
            v::length(2, 128)
45
        );
46
47
        $this->addValidator(
48
            'alias',
49
            v::required(),
50
            v::length(2, 64),
51
            v::slug(),
52
            v::callback(function ($input) {
53
                $select = $this->getTable()->select()
54
                    ->where('alias = ?', $input);
55
56
                if ($this->id) {
57
                    $select->andWhere('id != ?', $this->id);
58
                }
59
60
                if ($this->parentId) {
61
                    $select->andWhere('parentId = ?', $this->parentId);
62
                } else {
63
                    $select->andWhere('parentId IS NULL');
64
                }
65
66
                return !sizeof($select->execute());
67
            })->setError('Category with alias "{{input}}" already exists')
68
        );
69
    }
70
71
    /**
72
     * @return void
73
     */
74
    public function beforeInsert()
75
    {
76
        $this->created = gmdate('Y-m-d H:i:s');
77
        if ($this->parentId == '') {
78
            $this->parentId = null;
79
        }
80
    }
81
82
    /**
83
     * @return void
84
     */
85
    public function beforeUpdate()
86
    {
87
        $this->updated = gmdate('Y-m-d H:i:s');
88
    }
89
90
    /**
91
     * Add child
92
     *
93
     * @param Row $row
94
     */
95
    public function addChild(Row $row)
96
    {
97
        $this->children[$row->id] = $row;
98
    }
99
100
    /**
101
     * Get children directories
102
     *
103
     * @return array
104
     */
105 1
    public function getChildren()
106
    {
107 1
        return $this->children;
108
    }
109
}
110