Completed
Branch feature/pre-split (289154)
by Anton
03:22
created

UpdateCommand::execute()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * components
4
 *
5
 * @author    Wolfy-J
6
 */
7
namespace Spiral\ORM\Commands;
8
9
use Spiral\Database\Entities\Table;
10
use Spiral\ORM\Commands\Traits\ContextTrait;
11
use Spiral\ORM\Commands\Traits\PrimaryTrait;
12
use Spiral\ORM\Commands\Traits\WhereTrait;
13
use Spiral\ORM\ContextualCommandInterface;
14
15
/**
16
 * Update data CAN be modified by parent commands using context.
17
 *
18
 * This is conditional command, it would not be executed when no fields are given!
19
 */
20
class UpdateCommand extends TableCommand implements ContextualCommandInterface
21
{
22
    use ContextTrait, PrimaryTrait, WhereTrait;
23
24
    /**
25
     * Columns to be updated.
26
     *
27
     * @var array
28
     */
29
    private $values = [];
30
31
    /**
32
     * UpdateCommand constructor.
33
     *
34
     * @param Table $table
35
     * @param array $where
36
     * @param array $values
37
     * @param mixed $primaryKey
38
     */
39
    public function __construct(Table $table, array $where, array $values = [], $primaryKey = null)
40
    {
41
        parent::__construct($table);
42
        $this->where = $where;
43
        $this->values = $values;
44
        $this->primaryKey = $primaryKey;
45
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50
    public function getDriver()
51
    {
52
        if (empty($this->context) && empty($this->values)) {
53
            //Nothing to do
54
            return null;
55
        }
56
57
        return $this->table->getDatabase()->getDriver();
58
    }
59
60
    /**
61
     * {@inheritdoc}
62
     */
63
    public function isEmpty(): bool
64
    {
65
        return empty($this->values) && empty($this->context);
66
    }
67
68
    /**
69
     * Update values, context not included.
70
     *
71
     * @return array
72
     */
73
    public function getValues(): array
74
    {
75
        return $this->values;
76
    }
77
78
    /**
79
     * Inserting data into associated table.
80
     */
81
    public function execute()
82
    {
83
        if (!$this->isEmpty()) {
84
            $this->table->update($this->context + $this->values, $this->where)->run();
85
        }
86
87
        parent::execute();
88
    }
89
}