-
Notifications
You must be signed in to change notification settings - Fork 0
/
AutoSlugField.php
94 lines (79 loc) · 2.53 KB
/
AutoSlugField.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
declare(strict_types=1);
/*
* Studio 107 (c) 2017 Maxim Falaleev
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mindy\Orm\Fields;
use Mindy\Orm\ModelInterface;
use Mindy\QueryBuilder\Expression;
/**
* Class AutoSlugField.
*/
class AutoSlugField extends AbstractSlugField
{
/**
* Internal event.
*
* @param \Mindy\Orm\TreeModel|ModelInterface $model
* @param $value
*/
public function beforeInsert(ModelInterface $model, $value)
{
if (empty($value)) {
$slug = $this->createSlug($model->getAttribute($this->source));
} else {
$slug = basename($value);
}
if ($model->parent) {
$slug = $model->parent->getAttribute($this->getAttributeName()).'/'.ltrim($slug, '/');
}
$model->setAttribute(
$this->getAttributeName(),
$this->generateUniqueUrl($slug)
);
}
/**
* Internal event.
*
* @param \Mindy\Orm\TreeModel|ModelInterface $model
* @param $value
*/
public function beforeUpdate(ModelInterface $model, $value)
{
if (empty($value)) {
$slug = $this->createSlug($model->getAttribute($this->source));
} else {
$slug = basename($value);
}
if ($model->parent) {
$parentSlug = $model->parent->getAttribute($this->getAttributeName());
$slug = implode('/', [current(explode('/', $parentSlug)), $slug]);
}
$slug = $this->generateUniqueUrl($slug, 0, $model->pk);
$conditions = [
'lft__gte' => $model->lft,
'rgt__lte' => $model->rgt,
'root' => $model->root,
];
$attributeValue = $model->getOldAttribute($this->getAttributeName());
if (empty($attributeValue)) {
$attributeValue = $model->getAttribute($this->getAttributeName());
}
if ($attributeValue !== $slug) {
$expr = sprintf(
'REPLACE(%s, %s, %s)',
$model->getConnection()->quoteIdentifier($this->getAttributeName()),
$model->getConnection()->quote($attributeValue),
$model->getConnection()->quote($slug)
);
$qs = $model->objects()->filter($conditions);
$qs->update([
$this->getAttributeName() => new Expression($expr),
]);
}
$model->setAttribute($this->getAttributeName(), $slug);
}
}