Passed
Push — master ( 500a63...c8d25d )
by Glynn
03:58 queued 01:28
created

JsonExpressionFactory::extractAndUnquote()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 12
rs 10
1
<?php
2
3
namespace Pixie\JSON;
4
5
use Pixie\Connection;
6
use Pixie\QueryBuilder\Raw;
7
use Pixie\QueryBuilder\TablePrefixer;
8
9
class JsonExpressionFactory
10
{
11
    use TablePrefixer;
12
13
    /** @var Connection */
14
    protected $connection;
15
16
    public function __construct(Connection $connection)
17
    {
18
        $this->connection = $connection;
19
    }
20
21
    /**
22
     * Returns the current connection instance.
23
     *
24
     * @return connection
25
     */
26
    public function getConnection(): Connection
27
    {
28
        return $this->connection;
29
    }
30
31
    /**
32
     * @param string          $column  The database column which holds the JSON value
33
     * @param string|string[] $nodes   The json key/index to search
34
     * @return \Pixie\QueryBuilder\Raw
35
     */
36
    public function extractAndUnquote(string $column, $nodes): Raw
37
    {
38
39
        // Unpack any nodes.
40
        if (is_array($nodes)) {
41
            $nodes = \implode('.', $nodes);
42
        }
43
44
        // Add any possible prefixes to the key
45
        $column = $this->addTablePrefix($column, true);
46
47
        return new Raw("JSON_UNQUOTE(JSON_EXTRACT({$column}, \"$.{$nodes}\"))");
48
    }
49
50
    /**
51
     * @param string          $column  The database column which holds the JSON value
52
     * @param string|string[] $nodes   The json key/index to search
53
     * @param string|null     $alias   The alias to apply to this expression. Will be set as "json_{$column}" if not defined.
54
     * @return \Pixie\QueryBuilder\Raw
55
     */
56
    public function extractAndUnquoteWithAlias(string $column, $nodes, ?string $alias = null): Raw
57
    {
58
        return new Raw(sprintf(
59
            "%s AS %s",
60
            $this->extractAndUnquote($column, $nodes)->getValue(),
61
            null === $alias ? "json_{$column}" : $alias
62
        ));
63
    }
64
}
65