Completed
Branch feature/pre-split (4ff102)
by Anton
03:27
created

TransactionalCommand::getLeading()   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\ORM\CommandInterface;
10
use Spiral\ORM\ContextualCommandInterface;
11
use Spiral\ORM\Exceptions\ORMException;
12
13
/**
14
 * Command to handle multiple inner commands.
15
 */
16
class TransactionalCommand extends AbstractCommand implements
17
    \IteratorAggregate,
18
    ContextualCommandInterface
19
{
20
    /**
21
     * Nested commands.
22
     *
23
     * @var CommandInterface[]
24
     */
25
    private $commands = [];
26
27
    /**
28
     * @var ContextualCommandInterface
29
     */
30
    private $leadingCommand;
31
32
    /**
33
     * {@inheritdoc}
34
     */
35
    public function addCommand(CommandInterface $command, bool $leading = false)
36
    {
37
        if ($command instanceof NullCommand) {
38
            return;
39
        }
40
41
        $this->commands[] = $command;
42
43
        if ($leading) {
44
            if (!$command instanceof ContextualCommandInterface) {
45
                throw new ORMException("Only Insert and Update commands can be used as leading");
46
            }
47
48
            $this->leadingCommand = $command;
49
        }
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    public function getContext(): array
56
    {
57
        if (empty($this->leadingCommand)) {
58
            throw new ORMException("Leading command is not set");
59
        }
60
61
        return $this->leadingCommand->getContext();
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67
    public function addContext(string $name, $value)
68
    {
69
        if (empty($this->leadingCommand)) {
70
            throw new ORMException("Leading command is not set");
71
        }
72
73
        $this->leadingCommand->addContext($name, $value);
74
    }
75
76
    /**
77
     * {@inheritdoc}
78
     */
79
    public function getLeading(): ContextualCommandInterface
80
    {
81
        if (empty($this->leadingCommand)) {
82
            throw new ORMException("Leading command is not set");
83
        }
84
85
        return $this->leadingCommand;
86
    }
87
88
    /**
89
     * {@inheritdoc}
90
     */
91
    public function getIterator()
92
    {
93
        foreach ($this->commands as $command) {
94
            if ($command instanceof \Traversable) {
95
                yield from $command;
96
            }
97
98
            yield $command;
99
        }
100
    }
101
}
102