EmptyCoalesceExpression::empty()   B
last analyzed

Complexity

Conditions 7
Paths 6

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
cc 7
eloc 6
nc 6
nop 1
dl 0
loc 11
ccs 0
cts 9
cp 0
crap 56
rs 8.8333
c 0
b 0
f 0
1
<?php
2
/**
3
 * SEOmatic plugin for Craft CMS 3.x
4
 *
5
 * A turnkey SEO implementation for Craft CMS that is comprehensive, powerful,
6
 * and flexible
7
 *
8
 * @link      https://nystudio107.com
9
 * @copyright Copyright (c) 2017 nystudio107
10
 */
11
12
namespace nystudio107\seomatic\Node\Expression;
13
14
use Twig\Compiler;
15
use Twig\Node\Expression\AbstractExpression;
16
use Twig\Node\Node;
17
18
/**
19
 * @author    nystudio107
20
 * @package   SEOmatic
21
 * @since     3.1.50
22
 */
23
class EmptyCoalesceExpression extends AbstractExpression
24
{
25
    /**
26
     * Checks if a variable is empty.
27
     *
28
     *    {# evaluates to true if the foo variable is null, false, or the empty string #}
29
     *    {% if foo is empty %}
30
     *        {# ... #}
31
     *    {% endif %}
32
     *
33
     * @param mixed $value A variable
34
     *
35
     * @return bool true if the value is empty, false otherwise
36
     */
37
    public static function empty($value): bool
38
    {
39
        if ($value instanceof \Countable) {
40
            return 0 == \count($value);
41
        }
42
43
        if (\is_object($value) && method_exists($value, '__toString')) {
44
            return '' === (string) $value;
45
        }
46
47
        return '' === $value || false === $value || null === $value || [] === $value;
48
    }
49
50
    public function __construct(Node $left, Node $right, $lineno)
51
    {
52
        $left->setAttribute('ignore_strict_check', true);
53
        $left->setAttribute('is_defined_test', false);
54
        $right->setAttribute('ignore_strict_check', true);
55
        $right->setAttribute('is_defined_test', false);
56
        parent::__construct(
57
            ['left' => $left, 'right' => $right],
58
            ['ignore_strict_check' => true, 'is_defined_test' => false],
59
            $lineno
60
        );
61
    }
62
63
    public function compile(Compiler $compiler)
64
    {
65
        //$this->getNode('expr1')->setAttribute('always_defined', true);
66
        $compiler
67
            ->raw('((' . self::class . '::empty(')
68
            ->subcompile($this->getNode('left'))
69
            ->raw(') ? null : ')
70
            ->subcompile($this->getNode('left'))
71
            ->raw(') ?? (' . self::class . '::empty(')
72
            ->subcompile($this->getNode('right'))
73
            ->raw(') ? null : ')
74
            ->subcompile($this->getNode('right'))
75
            ->raw('))')
76
        ;
77
    }
78
}
79