Set::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 3
1
<?php
2
declare(strict_types=1);
3
4
namespace Redislabs\Module\ReJSON\Command;
5
6
use Redislabs\Interfaces\CommandInterface;
7
use Redislabs\Command\CommandAbstract;
8
use Redislabs\Module\ReJSON\Path;
9
use function in_array;
10
use Redislabs\Module\ReJSON\Exceptions\InvalidExistentialModifierException;
11
12
final class Set extends CommandAbstract implements CommandInterface
13
{
14
    protected static $command = 'JSON.SET';
15
    private static $validExistentialModifiers = ['NX', 'XX'];
16
17
    private function __construct(
18
        string $key,
19
        Path $path,
20
        string $json
21
    ) {
22
        $this->arguments = [$key, $path->getPath(),  $json];
23
    }
24
25
    public function withExistentialModifier(string $existentialModifier) : CommandInterface
26
    {
27
        if (!in_array($existentialModifier, self::$validExistentialModifiers, true)) {
28
            throw new InvalidExistentialModifierException(
29
                sprintf('Invalid existential modifier (%s) used for the command JSON.SET', $existentialModifier)
30
            );
31
        }
32
        $this->arguments[] = $existentialModifier;
33
        return $this;
34
    }
35
36
    public static function createCommandWithArguments(
37
        string $key,
38
        string $path,
39
        $json,
40
        ?string $existentialModifier = null
41
    ) : CommandInterface {
42
        $command = new self(
43
            $key,
44
            new Path($path),
45
            json_encode($json)
46
        );
47
        if ($existentialModifier !== null) {
48
             return $command->withExistentialModifier($existentialModifier);
49
        }
50
        return $command;
51
    }
52
}
53