BetweenCondition::fromArrayDefinition()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\QueryBuilder\Condition;
6
7
use Yiisoft\Db\Exception\InvalidArgumentException;
8
use Yiisoft\Db\Expression\ExpressionInterface;
9
use Yiisoft\Db\QueryBuilder\Condition\Interface\BetweenConditionInterface;
10
11
/**
12
 * Condition that's represented `BETWEEN` operator is used to check if a value is between two values.
13
 */
14
final class BetweenCondition implements BetweenConditionInterface
15
{
16
    public function __construct(
17
        private string|ExpressionInterface $column,
18
        private string $operator,
19
        private mixed $intervalStart,
20
        private mixed $intervalEnd
21
    ) {
22
    }
23
24
    public function getColumn(): string|ExpressionInterface
25
    {
26
        return $this->column;
27
    }
28
29
    public function getIntervalEnd(): mixed
30
    {
31
        return $this->intervalEnd;
32
    }
33
34
    public function getIntervalStart(): mixed
35
    {
36
        return $this->intervalStart;
37
    }
38
39
    public function getOperator(): string
40
    {
41
        return $this->operator;
42
    }
43
44
    /**
45
     * Creates a condition based on the given operator and operands.
46
     *
47
     * @throws InvalidArgumentException If the number of operands isn't 3.
48
     */
49
    public static function fromArrayDefinition(string $operator, array $operands): self
50
    {
51
        if (!isset($operands[0], $operands[1], $operands[2])) {
52
            throw new InvalidArgumentException("Operator '$operator' requires three operands.");
53
        }
54
55
        return new self(self::validateColumn($operator, $operands[0]), $operator, $operands[1], $operands[2]);
56
    }
57
58
    /**
59
     * Validates the given column to be string or `ExpressionInterface`.
60
     *
61
     * @throws InvalidArgumentException If the column isn't a string or `ExpressionInterface`.
62
     */
63
    private static function validateColumn(string $operator, mixed $column): string|ExpressionInterface
64
    {
65
        if (is_string($column) || $column instanceof ExpressionInterface) {
66
            return $column;
67
        }
68
69
        throw new InvalidArgumentException(
70
            "Operator '$operator' requires column to be string or ExpressionInterface."
71
        );
72
    }
73
}
74