Passed
Pull Request — 2.x (#135)
by Aleksei
18:00
created

CompileJsonContainsKey   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 23
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 23
rs 10
wmc 3

1 Method

Rating   Name   Duplication   Size   Complexity  
A compile() 0 16 3
1
<?php
2
3
/**
4
 * This file is part of Cycle ORM package.
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
declare(strict_types=1);
11
12
namespace Cycle\Database\Driver\Postgres\Injection;
13
14
class CompileJsonContainsKey extends PostgresJsonExpression
15
{
16
    /**
17
     * @param non-empty-string $statement
0 ignored issues
show
Documentation Bug introduced by
The doc comment non-empty-string at position 0 could not be parsed: Unknown type name 'non-empty-string' at position 0 in non-empty-string.
Loading history...
18
     *
19
     * @return non-empty-string
0 ignored issues
show
Documentation Bug introduced by
The doc comment non-empty-string at position 0 could not be parsed: Unknown type name 'non-empty-string' at position 0 in non-empty-string.
Loading history...
20
     */
21
    protected function compile(string $statement): string
22
    {
23
        $wrappedPath = $this->getWrappedPath($statement);
24
        $attribute = \array_pop($wrappedPath);
25
        $path = $this->getField($statement);
26
        if ($wrappedPath !== []) {
27
            $path .= '->' . \implode('->', $wrappedPath);
28
        }
29
30
        if (!\filter_var($attribute, FILTER_VALIDATE_INT)) {
31
            return \sprintf('coalesce((%s)::jsonb ?? %s, false)', $path, $attribute);
32
        }
33
34
        return \vsprintf('CASE WHEN %s THEN %s ELSE false END', [
35
            \sprintf('jsonb_typeof((%s)::jsonb) = \'array\'', $path),
36
            \sprintf('jsonb_array_length((%s)::jsonb) >= %s', $path, $attribute + 1),
37
        ]);
38
    }
39
}
40