Completed
Pull Request — master (#326)
by Damian
02:17
created

FixtureContext::iShouldSeeTheGalleryItem()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
3
namespace SilverStripe\AssetAdmin\Tests\Behat\Context;
4
5
use Behat\Mink\Element\DocumentElement;
6
use Behat\Mink\Element\NodeElement;
7
use SilverStripe\BehatExtension\Context\FixtureContext as BaseFixtureContext;
8
9
/**
10
 * Context used to create fixtures in the SilverStripe ORM.
11
 */
12
class FixtureContext extends BaseFixtureContext
13
{
14
15
    /**
16
     * Select a gallery item by type and name
17
     *
18
     * @Given /^I (?:(?:click on)|(?:select)) the "([^"]+)" named "([^"]+)" in the gallery$/
19
     * @param string $type
20
     * @param string $name
21
     */
22
    public function stepISelectGalleryItem($type, $name)
23
    {
24
        $item = $this->getGalleryItem($type, $name);
25
        assertNotNull($item, ucfirst($type) . " named $name could not be found");
26
        $item->click();
27
    }
28
29
    /**
30
     * Check the checkbox for a given gallery item
31
     * @Given /^I check the "([^"]+)" named "([^"]+)" in the gallery$/
32
     * @param string $type
33
     * @param string $name
34
     */
35
    public function stepICheckTheGalleryItem($type, $name) {
36
        $item = $this->getGalleryItem($type, $name);
37
        assertNotNull($item, ucfirst($type) . " named $name could not be found");
38
        $checkbox = $item->find('css', 'input[type="checkbox"]');
39
        assertNotNull($checkbox, "Could not find checkbox for file named {$name}");
40
        $checkbox->check();
41
    }
42
43
    /**
44
     * @Then /^I should see the "([^"]+)" named "([^"]+)" in the gallery$/
45
     * @param $type
46
     * @param $name
47
     */
48
    public function iShouldSeeTheGalleryItem($type, $name) {
49
        $item = $this->getGalleryItem($type, $name);
50
        assertNotNull($item, ucfirst($type) . " named {$name} could not be found");
51
    }
52
53
    /**
54
     * @Then /^I should not see the "([^"]+)" named "([^"]+)" in the gallery$/
55
     * @param $type
56
     * @param $name
57
     */
58
    public function iShouldNotSeeTheGalleryItem($type, $name) {
59
        $item = $this->getGalleryItem($type, $name, 0);
60
        assertNull($item, ucfirst($type) . " named {$name} was found when it should not be visible");
61
    }
62
63
    /**
64
     * @Then /^I should see the "([^"]*)" form$/
65
     * @param string $id HTML ID of form
66
     */
67
    public function iShouldSeeTheForm($id)
68
    {
69
        /** @var DocumentElement $page */
70
        $page = $this->getSession()->getPage();
71
        $form = $this->retry(function() use ($page, $id) {
72
            return $page->find('css', "form#{$id}");
73
        });
74
        assertNotNull($form, "form with id $id could not be found");
75
        assertTrue($form->isVisible(), "form with id $id is not visible");
76
    }
77
78
    /**
79
     * @Given /^I click on the latest history item$/
80
     */
81
    public function iClickOnTheLatestHistoryItem()
82
    {
83
        $this->getSession()->wait(
84
            5000,
85
            "window.jQuery && window.jQuery('.file-history__list li').size() > 0"
86
        );
87
88
        $page = $this->getSession()->getPage();
89
90
        $elements = $page->find('css', '.file-history__list li');
91
92
        if (null === $elements) {
93
            throw new \InvalidArgumentException(sprintf('Could not find list item'));
94
        }
95
96
        $elements->click();
97
    }
98
99
    /**
100
     * @Given /^I attach the file "([^"]*)" to dropzone$/
101
     * @see MinkContext::attachFileToField()
102
     */
103
    public function iAttachTheFileToDropzone($path)
104
    {
105
        // Get path
106
        $filesPath = $this->getMainContext()->getMinkParameter('files_path');
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Behat\Behat\Context\ExtendedContextInterface as the method getMinkParameter() does only exist in the following implementations of said interface: Behat\MinkExtension\Context\MinkContext, Behat\MinkExtension\Context\RawMinkContext, SilverStripe\AssetAdmin\...\Context\FeatureContext, SilverStripe\BehatExtens...ext\SilverStripeContext, SilverStripe\Cms\Test\Behaviour\FeatureContext.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
107
        if ($filesPath) {
108
            $fullPath = rtrim(realpath($filesPath), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$path;
109
            if (is_file($fullPath)) {
110
                $path = $fullPath;
111
            }
112
        }
113
114
        // Find field
115
        $input = $this->getSession()->getPage()->find('css', 'input[type="file"].dz-hidden-input');
116
        assertNotNull($input, "Could not find dz-hidden-input");
117
118
        // Make visible temporarily while attaching
119
        $this->getSession()->executeScript(
120
<<<EOS
121
window.jQuery('.dz-hidden-input')
122
    .css('visibility', 'visible')
123
    .width(1)
124
    .height(1);
125
EOS
126
        );
127
128
        // Attach via html5
129
        $input->attachFile($path);
130
131
        // Restore hidden state
132
        $this->getSession()->executeScript(
133
<<<EOS
134
window.jQuery('.dz-hidden-input')
135
    .css('visibility', 'hidden')
136
    .width(0)
137
    .height(0);
138
EOS
139
        );
140
    }
141
142
    /**
143
     * Helper for finding items in the visible gallery view
144
     *
145
     * @param string $type type. E.g. 'folder', 'image'
146
     * @param string $name Title of item
147
     * @param int $timeout
148
     * @return NodeElement
149
     */
150
    protected function getGalleryItem($type, $name, $timeout = 3)
151
    {
152
        /** @var DocumentElement $page */
153
        $page = $this->getSession()->getPage();
154
        return $this->retry(function() use ($page, $type, $name) {
155
            return $page->find(
156
                'xpath',
157
                "//div[contains(@class, 'gallery-item--{$type}')]//div[contains(text(), '{$name}')]"
158
            );
159
        }, $timeout);
160
    }
161
162
    /**
163
     * Invoke $try callback for a non-empty result with a given timeout
164
     *
165
     * @param callable $try
166
     * @param int $timeout Number of seconds to retry for
167
     * @return mixed Result of invoking $try, or null if timed out
168
     */
169
    protected function retry($try, $timeout = 3) {
170
        do {
171
            $result = $try();
172
            if ($result) {
173
                return $result;
174
            }
175
            sleep(1);
176
        } while(--$timeout >= 0);
177
        return null;
178
    }
179
}
180