Completed
Push — master ( afecc6...1c3d75 )
by Sergii
02:31
created

FormValueAssertion::selectable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 13
rs 9.4286
cc 1
eloc 9
nc 1
nop 0
1
<?php
2
/**
3
 * @author Sergey Bondarenko, <[email protected]>
4
 */
5
namespace Drupal\TqExtension\Utils;
6
7
// Contexts.
8
use Drupal\TqExtension\Context\RawTqContext;
9
10
// Helpers.
11
use Behat\Mink\Element\NodeElement;
12
13
class FormValueAssertion
14
{
15
    /**
16
     * @var RawTqContext
17
     */
18
    private $context;
19
    /**
20
     * @var string
21
     *   Field selector.
22
     */
23
    private $selector = '';
24
    /**
25
     * @var NodeElement
26
     *   Found element.
27
     */
28
    private $element;
29
    /**
30
     * @var string
31
     *   Expected value.
32
     */
33
    private $expected = '';
34
    /**
35
     * @var string
36
     *   Field element value.
37
     */
38
    private $value = '';
39
    /**
40
     * @var string
41
     *   Tag name of found element.
42
     */
43
    private $tag = '';
44
    /**
45
     * @var bool
46
     *   Negate the condition.
47
     */
48
    private $not = FALSE;
49
50
    /**
51
     * @param RawTqContext $context
52
     *      Behat context.
53
     * @param string $selector
54
     *   Field selector.
55
     * @param bool $not
56
     *   Negate the condition.
57
     * @param string $expected
58
     *   Expected value.
59
     */
60
    public function __construct(RawTqContext $context, $selector, $not, $expected = '')
61
    {
62
        $this->not = (bool) $not;
63
        $this->context = $context;
64
        $this->selector = $selector;
65
        $this->expected = $expected;
66
67
        $this->element = $this->context->element('field', $selector);
68
        $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...
69
        $this->tag = $this->element->getTagName();
70
    }
71
72
    /**
73
     * Check value in inputs and text areas.
74
     */
75
    public function textual()
76
    {
77
        $this->restrictElements([
0 ignored issues
show
Documentation introduced by
array('textarea' => array(), 'input' => array()) is of type array<string,array,{"tex...rray","input":"array"}>, but the function expects a array<integer,string>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
78
            'textarea' => [],
79
            'input' => [],
80
        ]);
81
82
        $this->context->debug([
83
            "Expected: $this->expected",
84
            "Value: $this->value",
85
            "Tag: $this->tag",
86
        ]);
87
88
        $this->assert(trim($this->expected) === $this->value);
89
    }
90
91
    /**
92
     * Ensure option is selected.
93
     */
94
    public function selectable()
95
    {
96
        $this->restrictElements(['select' => []]);
0 ignored issues
show
Documentation introduced by
array('select' => array()) is of type array<string,array,{"select":"array"}>, but the function expects a array<integer,string>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
97
        $data = [$this->value, $this->element->find('xpath', "//option[@value='$this->value']")->getText()];
98
99
        $this->context->debug([
100
            "Expected: $this->expected",
101
            "Value: %s",
102
            "Tag: $this->tag",
103
        ], implode(' => ', $data));
104
105
        $this->assert(in_array($this->expected, $data), 'selected');
106
    }
107
108
    /**
109
     * Ensure that checkbox/radio button is checked.
110
     */
111
    public function checkable()
112
    {
113
        $this->restrictElements(['input' => ['radio', 'checkbox']]);
0 ignored issues
show
Documentation introduced by
array('input' => array('radio', 'checkbox')) is of type array<string,array<integ...",\"1\":\"string\"}>"}>, but the function expects a array<integer,string>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
114
115
        if (!in_array($this->element->getAttribute('type'), ['radio', 'checkbox'])) {
116
            throw new \RuntimeException('Element cannot be checked.');
117
        }
118
119
        $this->context->debug([$this->element->getOuterHtml()]);
120
        $this->assert($this->element->isChecked(), 'checked');
121
    }
122
123
    /**
124
     * @param string[] $allowedElements
125
     *   Element machine names.
126
     */
127
    private function restrictElements(array $allowedElements)
128
    {
129
        // Match element tag with allowed.
130
        if (!isset($allowedElements[$this->tag])) {
131
            throw new \RuntimeException("Tag is not allowed: $this->tag.");
132
        }
133
134
        $types = $allowedElements[$this->tag];
135
136
        // Restrict by types only if they are specified.
137
        if (!empty($types)) {
138
            $type = $this->element->getAttribute('type');
139
140
            if (!in_array($type, $types)) {
141
              throw new \RuntimeException(sprintf('Type "%s" is not allowed for "%s" tag', $type, $this->tag));
142
            }
143
        }
144
    }
145
146
    /**
147
     * @param bool $value
148
     *   Value for checking.
149
     * @param string $word
150
     *   A word for default message (e.g. "checked", "selected", etc).
151
     *
152
     * @throws \Exception
153
     */
154
    private function assert($value, $word = '')
155
    {
156
        if ($value) {
157
            if ($this->not) {
158
                throw new \Exception(
159
                    empty($word)
160
                      ? 'Field contain a value, but should not.'
161
                      : "Element is $word, but should not be."
162
                );
163
            }
164
        }
165
        else {
166
            if (!$this->not) {
167
                throw new \Exception(
168
                    empty($word)
169
                      ? 'Field does not contain a value.'
170
                      : "Element is not $word."
171
                );
172
            }
173
        }
174
    }
175
}
176