Completed
Push — ezp_30973 ( 1b82fd...a5777c )
by
unknown
12:50
created

QueryControllerContext::createPhpFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Copyright (C) eZ Systems AS. All rights reserved.
4
 * @license For full copyright and license information view LICENSE file distributed with this source code.
5
 */
6
namespace eZ\Bundle\EzPublishCoreBundle\Features\Context;
7
8
use Behat\Behat\Context\Context;
9
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
10
use Behat\Gherkin\Node\PyStringNode;
11
use Behat\Mink\Element\NodeElement;
12
use Behat\MinkExtension\Context\RawMinkContext;
13
use eZ\Publish\API\Repository\Repository;
14
use eZ\Publish\API\Repository\Values\Content\Content;
15
use PHPUnit\Framework\Assert;
16
use Symfony\Component\Filesystem\Filesystem;
17
use Symfony\Component\Yaml\Yaml;
18
19
class QueryControllerContext extends RawMinkContext implements Context
20
{
21
    /** @var YamlConfigurationContext */
22
    private $configurationContext;
23
24
    /**
25
     * Content item matched by the view configuration.
26
     * @var Content
27
     */
28
    private $matchedContent;
29
30
    /**
31
     * QueryControllerContext constructor.
32
     * @injectService $repository @ezpublish.api.repository
33
     */
34
    public function __construct(Repository $repository)
35
    {
36
        $this->repository = $repository;
37
    }
38
39
    /** @BeforeScenario */
40
    public function gatherContexts(BeforeScenarioScope $scope)
41
    {
42
        $environment = $scope->getEnvironment();
43
44
        $this->configurationContext = $environment->getContext(
45
            'eZ\Bundle\EzPublishCoreBundle\Features\Context\YamlConfigurationContext'
46
        );
47
    }
48
49
    /**
50
     * @Given /^the following content view configuration block:$/
51
     */
52 View Code Duplication
    public function addContentViewConfigurationBlock(PyStringNode $string)
53
    {
54
        $configurationBlock = array_merge(
55
            Yaml::parse($string),
56
            [
57
                'template' => '@eZBehat/tests/dump.html.twig',
58
                'match' => [
59
                    'Id\Content' => $this->matchedContent->id,
60
                ],
61
            ]
62
        );
63
64
        $configurationBlockName = 'behat_query_controller_' . $this->matchedContent->id;
65
66
        $configuration = [
67
            'ezpublish' => [
68
                'system' => [
69
                    'default' => [
70
                        'content_view' => [
71
                            'full' => [
72
                                $configurationBlockName => $configurationBlock,
73
                            ],
74
                        ],
75
                    ],
76
                ],
77
            ],
78
        ];
79
80
        $this->configurationContext->addConfiguration($configuration);
81
    }
82
83
    /**
84
     * @Given /^the following content view configuration block with paging action:$/
85
     */
86 View Code Duplication
    public function addContentViewConfigurationBlockWithPagingAction(PyStringNode $string)
87
    {
88
        $configurationBlock = array_merge(
89
            Yaml::parse($string),
90
            [
91
                'template' => '@eZBehat/tests/dump.html.twig',
92
                'match' => [
93
                    'Id\Content' => $this->matchedContent->id,
94
                ],
95
            ]
96
        );
97
98
        $configurationBlockName = 'behat_paging_query_controller_' . $this->matchedContent->id;
99
100
        $configuration = [
101
            'ezpublish' => [
102
                'system' => [
103
                    'default' => [
104
                        'content_view' => [
105
                            'full' => [
106
                                $configurationBlockName => $configurationBlock,
107
                            ],
108
                        ],
109
                    ],
110
                ],
111
            ],
112
        ];
113
114
        $this->configurationContext->addConfiguration($configuration);
115
    }
116
117
    /**
118
     * @Given /^a content item that matches the view configuration block below$/
119
     */
120
    public function aContentItemThatMatchesTheViewConfigurationBlockBelow()
121
    {
122
        $this->matchedContent = $this->repository->sudo(function (Repository $repository) {
123
            return $this->createFolder($repository);
124
        });
125
    }
126
127
    /**
128
     * @Given :arg1 contents are created to test paging
129
     */
130
    public function contentsAreCreatedToTestPaging2($numberOfContents)
131
    {
132
        for ($i = 0; $i < $numberOfContents; ++$i) {
133
            $this->repository->sudo(function (Repository $repository) {
134
                return $this->createFolder($repository);
135
            });
136
        }
137
    }
138
139
    /**
140
     * @return Content
141
     */
142
    private function createFolder(Repository $repository)
143
    {
144
        $contentService = $repository->getContentService();
145
        $contentTypeService = $repository->getContentTypeService();
146
        $locationService = $repository->getLocationService();
147
148
        $struct = $contentService->newContentCreateStruct(
149
            $contentTypeService->loadContentTypeByIdentifier('folder'),
150
            'eng-GB'
151
        );
152
153
        $struct->setField('name', uniqid('Query Controller BDD ', true));
154
155
        $contentDraft = $contentService->createContent(
156
            $struct,
157
            [$locationService->newLocationCreateStruct(2)]
158
        );
159
        $contentService->publishVersion($contentDraft->versionInfo);
160
161
        return $contentService->loadContent($contentDraft->id);
162
    }
163
164
    /**
165
     * @Given /^a LocationChildren QueryType defined in "([^"]*)":$/
166
     */
167
    public function createPhpFile($phpFilePath, PyStringNode $phpFileContents)
168
    {
169
        $fs = new Filesystem();
170
        $fs->mkdir(\dirname($phpFilePath));
171
        $fs->dumpFile($phpFilePath, $phpFileContents);
172
        shell_exec('php bin/console --env=behat cache:clear');
173
    }
174
175
    /**
176
     * @When /^I view a content matched by the view configuration above$/
177
     */
178 View Code Duplication
    public function visitMatchedContent()
179
    {
180
        $urlAliasService = $this->repository->getURLAliasService();
181
        $urlAlias = $urlAliasService->reverseLookup(
182
            $this->repository->getLocationService()->loadLocation(
183
                $this->matchedContent->contentInfo->mainLocationId
184
            )
185
        );
186
187
        $this->visitPath($urlAlias->path);
188
189
        if ($this->getSession()->getStatusCode() !== 200) {
190
            $page = $this->getSession()->getPage();
191
            $exceptionElements = $page->findAll('xpath', "//div[@class='text-exception']/h1");
192
            $exceptionStackTraceItems = $page->findAll('xpath', "//ol[@id='traces-0']/li");
193
            if (\count($exceptionElements) > 0) {
194
                $exceptionElement = $exceptionElements[0];
195
                $exceptionLines = [$exceptionElement->getText(), ''];
196
197
                foreach ($exceptionStackTraceItems as $stackTraceItem) {
198
                    $html = $stackTraceItem->getHtml();
199
                    $html = substr($html, 0, strpos($html, '<a href', 1));
200
                    $html = htmlspecialchars_decode(strip_tags($html));
201
                    $html = preg_replace('/\s+/', ' ', $html);
202
                    $html = str_replace('  (', '(', $html);
203
                    $html = str_replace(' ->', '->', $html);
204
                    $exceptionLines[] = trim($html);
205
                }
206
                $message = 'An exception occurred during rendering:' . implode("\n", $exceptionLines);
207
                Assert::assertTrue(false, $message);
208
            }
209
        }
210
        $this->assertSession()->statusCodeEquals(200);
211
    }
212
213
    /**
214
     * @Then /^the viewed content's main location id is mapped to the parentLocationId QueryType parameter$/
215
     */
216
    public function theViewedContentSMainLocationIdIsMappedToTheParentLocationIdQueryTypeParameter()
217
    {
218
        // not sure how to assert that
219
    }
220
221
    /**
222
     * @Then /^a LocationChildren Query is built from the LocationChildren QueryType$/
223
     */
224
    public function aLocationChildrenQueryIsBuiltFromTheLocationChildrenQueryType()
225
    {
226
        // not sure how to assert that either
227
    }
228
229
    /**
230
     * @Given /^a Location Search is executed with the LocationChildren Query$/
231
     */
232
    public function aLocationSearchIsExecutedWithTheLocationChildrenQuery()
233
    {
234
        // still not sure...
235
    }
236
237
    /**
238
     * @Given /^the Query results are assigned to the "([^"]*)" twig variable$/
239
     */
240
    public function theQueryResultsAreAssignedToTheTwigVariable($twigVariableName)
241
    {
242
        $variableFound = false;
243
244
        $page = $this->getSession()->getPage();
245
        $variableNodes = $page->findAll('css', 'pre.sf-dump > samp > span.sf-dump-key');
246
247
        /** @var NodeElement $variableNode */
248
        foreach ($variableNodes as $variableNode) {
249
            if ($variableNode->getText() === $twigVariableName) {
250
                $variableFound = true;
251
            }
252
        }
253
254
        Assert::assertTrue(
255
            $variableFound,
256
            "The $twigVariableName twig variable was not set"
257
        );
258
    }
259
260
    /**
261
     * @Then the Query results assigned to the :arg1 twig variable is a :arg2 object
262
     */
263 View Code Duplication
    public function theQueryResultsAssignedToTheTwigVariableIsAObject($twigVariableName, $className)
264
    {
265
        $variableFound = false;
266
        $classNameFound = false;
267
268
        $page = $this->getSession()->getPage();
269
        $variableNodes = $page->findAll('css', 'pre.sf-dump > samp > span.sf-dump-key');
270
        $valueNodes = $page->findAll('css', 'pre.sf-dump > samp > abbr.sf-dump-note');
271
272
        /** @var NodeElement $variableNode */
273
        foreach ($variableNodes as $variableNode) {
274
            if ($variableNode->getText() === $twigVariableName) {
275
                $variableFound = true;
276
            }
277
        }
278
279
        /** @var NodeElement $valueNodes */
280
        foreach ($valueNodes as $valueNode) {
281
            if ($valueNode->getText() === $className) {
282
                $classNameFound = true;
283
            }
284
        }
285
286
        Assert::assertTrue(
287
            $variableFound,
288
            "The $twigVariableName twig variable was not set"
289
        );
290
291
        Assert::assertTrue(
292
            $classNameFound,
293
            "The $className twig variable object was not set"
294
        );
295
    }
296
297
    /**
298
     * @Given /^the following template defined in "([^"]*)":$/
299
     */
300
    public function createTemplateFile($tplFilePath, PyStringNode $tplFileContents)
301
    {
302
        $fs = new Filesystem();
303
        $fs->mkdir(\dirname($tplFilePath));
304
        $fs->dumpFile($tplFilePath, $tplFileContents);
305
    }
306
307
    /**
308
     * @Given the following content view configuration block with paging action and the template set above:
309
     */
310 View Code Duplication
    public function theFollowingContentViewConfigurationBlockWithPagingActionAndTheTemplateSetAbove(PyStringNode $string)
311
    {
312
        $configurationBlock = array_merge(
313
            Yaml::parse($string),
314
            [
315
                'match' => [
316
                    'Id\Content' => $this->matchedContent->id,
317
                ],
318
            ]
319
        );
320
321
        $configurationBlockName = 'behat_paging_query_controller_' . $this->matchedContent->id;
322
323
        $configuration = [
324
            'ezpublish' => [
325
                'system' => [
326
                    'default' => [
327
                        'content_view' => [
328
                            'full' => [
329
                                $configurationBlockName => $configurationBlock,
330
                            ],
331
                        ],
332
                    ],
333
                ],
334
            ],
335
        ];
336
337
        $this->configurationContext->addConfiguration($configuration);
338
    }
339
340
    /**
341
     * @When I view a content matched by the view configuration above on page :arg1 with the :arg2 parameter
342
     */
343 View Code Duplication
    public function iViewAContentMatchedByTheViewConfigurationAboveOnPageWithTheParameter($pageNumber, $pageParam)
344
    {
345
        $urlAliasService = $this->repository->getURLAliasService();
346
        $urlAlias = $urlAliasService->reverseLookup(
347
            $this->repository->getLocationService()->loadLocation(
348
                $this->matchedContent->contentInfo->mainLocationId
349
            )
350
        );
351
352
        $this->visitPath($urlAlias->path . "?$pageParam=$pageNumber");
353
354
        if ($this->getSession()->getStatusCode() !== 200) {
355
            $page = $this->getSession()->getPage();
356
            $exceptionElements = $page->findAll('xpath', "//div[@class='text-exception']/h1");
357
            $exceptionStackTraceItems = $page->findAll('xpath', "//ol[@id='traces-0']/li");
358
            if (\count($exceptionElements) > 0) {
359
                $exceptionElement = $exceptionElements[0];
360
                $exceptionLines = [$exceptionElement->getText(), ''];
361
362
                foreach ($exceptionStackTraceItems as $stackTraceItem) {
363
                    $html = $stackTraceItem->getHtml();
364
                    $html = substr($html, 0, strpos($html, '<a href', 1));
365
                    $html = htmlspecialchars_decode(strip_tags($html));
366
                    $html = preg_replace('/\s+/', ' ', $html);
367
                    $html = str_replace('  (', '(', $html);
368
                    $html = str_replace(' ->', '->', $html);
369
                    $exceptionLines[] = trim($html);
370
                }
371
                $message = 'An exception occurred during rendering:' . implode("\n", $exceptionLines);
372
                Assert::assertTrue(false, $message);
373
            }
374
        }
375
        $this->assertSession()->statusCodeEquals(200);
376
    }
377
378
    /**
379
     * @Then the Query results assigned to the twig variable is a Pagerfanta object and has limit :arg1 and selected page :arg2
380
     */
381 View Code Duplication
    public function theQueryResultsAssignedToTheTwigVariableIsAObjectAndHasLimitAndCountParams($pageLimit, $pageValue)
382
    {
383
        $pageLimitFound = false;
384
        $currentPageFound = false;
385
386
        $page = $this->getSession()->getPage();
387
        $maxPerPage = $page->findAll('css', 'div#maxPerPage');
388
        $currentPage = $page->findAll('css', 'div#currentPage');
389
390
        /** @var NodeElement $variableNode */
391
        foreach ($maxPerPage as $variableNode) {
392
            if ($variableNode->getText() === $pageLimit) {
393
                $pageLimitFound = true;
394
            }
395
        }
396
397
        /** @var NodeElement $valueNodes */
398
        foreach ($currentPage as $valueNode) {
399
            if ($valueNode->getText() === $pageValue) {
400
                $currentPageFound = true;
401
            }
402
        }
403
404
        Assert::assertTrue(
405
            $pageLimitFound,
406
            "The maxPerPage $pageLimit twig variable was not set"
407
        );
408
409
        Assert::assertTrue(
410
            $currentPageFound,
411
            "The currentPage $pageValue twig variable  was not set"
412
        );
413
    }
414
}
415