1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Sirius\Orm\Action; |
5
|
|
|
|
6
|
|
|
use Sirius\Orm\Entity\StateEnum; |
7
|
|
|
use Sirius\Orm\Helpers\Arr; |
8
|
|
|
|
9
|
|
|
class Update extends Save |
10
|
|
|
{ |
11
|
|
|
protected $entityState; |
12
|
|
|
|
13
|
|
|
protected $extraColumns = []; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Add extra columns to be added to the insert. |
17
|
|
|
* To be used by behaviours relations |
18
|
|
|
* |
19
|
|
|
* @param array $columns |
20
|
|
|
* |
21
|
|
|
* @return self |
22
|
|
|
*/ |
23
|
|
|
public function addColumns(array $columns) |
24
|
|
|
{ |
25
|
|
|
foreach ($columns as $name => $value) { |
26
|
|
|
$this->extraColumns[$name] = $value; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
return $this; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
protected function execute() |
33
|
|
|
{ |
34
|
|
|
$conditions = $this->getConditions(); |
35
|
|
|
|
36
|
|
|
if (empty($conditions)) { |
37
|
|
|
return; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
$this->entityState = $this->entity->getState(); |
41
|
|
|
|
42
|
|
|
$connection = $this->mapper->getWriteConnection(); |
43
|
|
|
|
44
|
|
|
$columns = $this->entityHydrator->extract($this->entity); |
45
|
|
|
$changes = Arr::renameKeys($this->entity->getChanges(), array_flip($this->mapper->getConfig()->getColumnAttributeMap())); |
46
|
|
|
$columns = Arr::only($columns, array_keys($changes)); |
47
|
|
|
$columns = array_merge( |
48
|
|
|
$columns, |
49
|
|
|
$this->extraColumns, |
50
|
|
|
$this->mapper->getConfig()->getGuards() |
51
|
|
|
); |
52
|
|
|
$columns = Arr::except($columns, $this->mapper->getConfig()->getPrimaryKey()); |
53
|
|
|
|
54
|
|
|
if (count($columns) > 0) { |
55
|
|
|
$updateSql = new \Sirius\Sql\Update($connection); |
56
|
|
|
$updateSql->table($this->mapper->getConfig()->getTable()) |
57
|
|
|
->columns($columns) |
58
|
|
|
->whereAll($conditions, false); |
59
|
|
|
$updateSql->perform(); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
public function onSuccess() |
64
|
|
|
{ |
65
|
|
|
foreach ($this->extraColumns as $col => $value) { |
66
|
|
|
$this->entityHydrator->set($this->entity, $col, $value); |
67
|
|
|
} |
68
|
|
|
$this->entity->setState(StateEnum::SYNCHRONIZED); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|