Passed
Push — master ( b7b77b...565dd3 )
by Glynn
05:12 queued 03:02
created

JsonExpressionFactory::normaliseNodes()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 18
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 4
nop 1
dl 0
loc 18
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Pixie\JSON;
4
5
use Pixie\Exception;
6
use Pixie\Connection;
7
use Pixie\QueryBuilder\Raw;
8
use Pixie\QueryBuilder\TablePrefixer;
9
10
class JsonExpressionFactory
11
{
12
    use TablePrefixer;
13
14
    /** @var Connection */
15
    protected $connection;
16
17
    public function __construct(Connection $connection)
18
    {
19
        $this->connection = $connection;
20
    }
21
22
    /**
23
     * Returns the current connection instance.
24
     *
25
     * @return connection
26
     */
27
    public function getConnection(): Connection
28
    {
29
        return $this->connection;
30
    }
31
32
    /**
33
     * Normalises the values passed as nodes
34
     *
35
     * @param mixed $nodes
36
     * @return string
37
     */
38
    protected function normaliseNodes($nodes): string
39
    {
40
        // If its not an array, cast.
41
        if (!is_array($nodes)) {
42
            $nodes = [$nodes];
43
        }
44
45
        // Remove all none string.
46
        $nodes = array_filter($nodes, function ($node): bool {
47
            return is_string($node);
48
        });
49
50
        // If we have no nodes, throw.
51
        if (count($nodes) === 0) {
52
            throw new Exception("Only strings values may be passed as nodes.");
53
        }
54
55
        return \implode('.', $nodes);
56
    }
57
58
    /**
59
     * @param string          $column  The database column which holds the JSON value
60
     * @param string|string[] $nodes   The json key/index to search
61
     * @return \Pixie\QueryBuilder\Raw
62
     */
63
    public function extractAndUnquote(string $column, $nodes): Raw
64
    {
65
        // Normalise nodes.
66
        $nodes = $this->normaliseNodes($nodes);
67
68
        // Add any possible prefixes to the key
69
        $column = $this->addTablePrefix($column, true);
70
71
        return new Raw("JSON_UNQUOTE(JSON_EXTRACT({$column}, \"$.{$nodes}\"))");
72
    }
73
}
74