FormValueAssertion::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 11
ccs 0
cts 9
cp 0
rs 9.4285
cc 1
eloc 8
nc 1
nop 4
crap 2
1
<?php
2
/**
3
 * @author Sergii Bondarenko, <[email protected]>
4
 */
5
namespace Drupal\TqExtension\Utils;
6
7
// Contexts.
8
use Drupal\TqExtension\Context\RawTqContext;
9
// Helpers.
10
use Behat\DebugExtension\Debugger;
11
use Behat\Mink\Element\NodeElement;
12
13
class FormValueAssertion
14
{
15
    use Debugger;
16
17
    /**
18
     * @var RawTqContext
19
     */
20
    private $context;
21
    /**
22
     * @var string
23
     *   Field selector.
24
     */
25
    private $selector = '';
26
    /**
27
     * Found element.
28
     *
29
     * @var NodeElement
30
     */
31
    private $element;
32
    /**
33
     * Expected value.
34
     *
35
     * @var string
36
     */
37
    private $expected = '';
38
    /**
39
     * Field element value.
40
     *
41
     * @var string
42
     */
43
    private $value = '';
44
    /**
45
     * Tag name of found element.
46
     *
47
     * @var string
48
     */
49
    private $tag = '';
50
    /**
51
     * Negate the condition.
52
     *
53
     * @var bool
54
     */
55
    private $not = false;
56
57
    /**
58
     * @param RawTqContext $context
59
     *   Behat context.
60
     * @param string $selector
61
     *   Field selector.
62
     * @param bool $not
63
     *   Negate the condition.
64
     * @param string $expected
65
     *   Expected value.
66
     */
67
    public function __construct(RawTqContext $context, $selector, $not, $expected = '')
68
    {
69
        $this->not = (bool) $not;
70
        $this->context = $context;
71
        $this->selector = $selector;
72
        $this->expected = $expected;
73
74
        $this->element = $this->context->element('field', $selector);
75
        $this->value = $this->element->getValue();
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->element->getValue() can also be of type boolean or array. However, the property $value is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
76
        $this->tag = $this->element->getTagName();
77
    }
78
79
    /**
80
     * Check value in inputs and text areas.
81
     */
82
    public function textual()
83
    {
84
        $this->restrictElements([
85
            'textarea' => [],
86
            'input' => [],
87
        ]);
88
89
        self::debug([
90
            'Expected: %s',
91
            'Value: %s',
92
            'Tag: %s',
93
        ], [
94
            $this->expected,
95
            $this->value,
96
            $this->tag,
97
        ]);
98
99
        $this->assert(trim($this->expected) === $this->value);
100
    }
101
102
    /**
103
     * Ensure option is selected.
104
     */
105
    public function selectable()
106
    {
107
        $this->restrictElements(['select' => []]);
108
        $data = [$this->value, $this->element->find('xpath', "//option[@value='$this->value']")->getText()];
109
110
        self::debug([
111
            'Expected: %s',
112
            'Value: %s',
113
            'Tag: %s',
114
        ], [
115
            $this->expected,
116
            implode(' => ', $data),
117
            $this->tag,
118
        ]);
119
120
        $this->assert(in_array($this->expected, $data), 'selected');
121
    }
122
123
    /**
124
     * Ensure that checkbox/radio button is checked.
125
     */
126
    public function checkable()
127
    {
128
        $this->restrictElements(['input' => ['radio', 'checkbox']]);
129
130
        if (!in_array($this->element->getAttribute('type'), ['radio', 'checkbox'])) {
131
            throw new \RuntimeException('Element cannot be checked.');
132
        }
133
134
        self::debug(['%s'], [$this->element->getOuterHtml()]);
135
136
        $this->assert($this->element->isChecked(), 'checked');
137
    }
138
139
    /**
140
     * @param array[] $allowedElements
141
     *   Element machine names.
142
     */
143
    private function restrictElements(array $allowedElements)
144
    {
145
        // Match element tag with allowed.
146
        if (!isset($allowedElements[$this->tag])) {
147
            throw new \RuntimeException("Tag is not allowed: $this->tag.");
148
        }
149
150
        $types = $allowedElements[$this->tag];
151
152
        // Restrict by types only if they are specified.
153
        if (!empty($types)) {
154
            $type = $this->element->getAttribute('type');
155
156
            if (!in_array($type, $types)) {
157
                throw new \RuntimeException(sprintf('Type "%s" is not allowed for "%s" tag', $type, $this->tag));
158
            }
159
        }
160
    }
161
162
    /**
163
     * @param bool $value
164
     *   Value for checking.
165
     * @param string $word
166
     *   A word for default message (e.g. "checked", "selected", etc).
167
     *
168
     * @throws \Exception
169
     */
170
    private function assert($value, $word = '')
171
    {
172
        if ($value) {
173
            if ($this->not) {
174
                throw new \Exception(
175
                    empty($word)
176
                    ? 'Field contain a value, but should not.'
177
                    : "Element is $word, but should not be."
178
                );
179
            }
180
        } else {
181
            if (!$this->not) {
182
                throw new \Exception(
183
                    empty($word)
184
                    ? 'Field does not contain a value.'
185
                    : "Element is not $word."
186
                );
187
            }
188
        }
189
    }
190
}
191