FeatureContext::setServiceMocker()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Stfalcon\Bundle\EventBundle\Features\Context;
4
5
use Behat\Behat\Event\StepEvent;
6
use Behat\Mink\Driver\Selenium2Driver;
7
use Stfalcon\Bundle\EventBundle\Entity\Payment;
8
use Symfony\Component\HttpKernel\KernelInterface;
9
use Symfony\Component\Validator\Constraints\File;
10
use Behat\Symfony2Extension\Context\KernelAwareInterface;
11
use Behat\MinkExtension\Context\MinkContext;
12
use Behat\CommonContexts\DoctrineFixturesContext;
13
use Behat\CommonContexts\SymfonyMailerContext;
14
use Doctrine\Common\DataFixtures\Loader;
15
use Doctrine\Common\DataFixtures\Executor\ORMExecutor;
16
use Doctrine\Common\DataFixtures\Purger\ORMPurger;
17
use Application\Bundle\UserBundle\Features\Context\UserContext as ApplicationUserBundleUserContext;
18
use PSS\Behat\Symfony2MockerExtension\Context\ServiceMockerAwareInterface;
19
use PSS\Behat\Symfony2MockerExtension\ServiceMocker;
20
use PHPUnit_Framework_Assert as Assert;
21
22
/**
23
 * Feature context for StfalconEventBundle.
24
 */
25
class FeatureContext extends MinkContext implements KernelAwareInterface, ServiceMockerAwareInterface
26
{
27
    /**
28
     * @var ServiceMocker
29
     */
30
    private $mocker = null;
31
32
    /**
33
     * Constructor.
34
     */
35
    public function __construct()
36
    {
37
        $this->useContext('DoctrineFixturesContext', new DoctrineFixturesContext());
38
        $this->useContext('MinkRedirectContext', new MinkRedirectContext());
39
        $this->useContext('SymfonyMailerContext', new SymfonyMailerContext());
40
        $this->useContext('ApplicationUserBundleUserContext', new ApplicationUserBundleUserContext($this));
41
    }
42
43
    /**
44
     * @param ServiceMocker $mocker
45
     *
46
     * @return null|void
47
     */
48
    public function setServiceMocker(ServiceMocker $mocker)
49
    {
50
        $this->mocker = $mocker;
51
    }
52
53
    /**
54
     * @var \Symfony\Component\HttpKernel\KernelInterface
55
     */
56
    protected $kernel;
57
58
    /**
59
     * @param \Symfony\Component\HttpKernel\KernelInterface $kernel
60
     */
61
    public function setKernel(KernelInterface $kernel)
62
    {
63
        $this->kernel = $kernel;
64
    }
65
66
    /**
67
     * @BeforeScenario
68
     */
69
    public function beforeScen()
70
    {
71
        $loader = new Loader();
72
        $this->getMainContext()
73
            ->getSubcontext('DoctrineFixturesContext')
74
            ->loadFixtureClasses($loader, array(
0 ignored issues
show
Bug introduced by
The method loadFixtureClasses() does not exist on Behat\Behat\Context\ExtendedContextInterface. It seems like you code against a sub-type of Behat\Behat\Context\ExtendedContextInterface such as Behat\CommonContexts\Behat1BCContext or Behat\CommonContexts\DoctrineFixturesContext. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

74
            ->/** @scrutinizer ignore-call */ loadFixtureClasses($loader, array(
Loading history...
75
                'Stfalcon\Bundle\EventBundle\DataFixtures\ORM\LoadNewsData',
76
                'Stfalcon\Bundle\EventBundle\DataFixtures\ORM\LoadPagesData',
77
                'Stfalcon\Bundle\EventBundle\DataFixtures\ORM\LoadReviewData',
78
                'Stfalcon\Bundle\EventBundle\DataFixtures\ORM\LoadMailQueueData',
79
                'Application\Bundle\UserBundle\DataFixtures\ORM\LoadUserData',
80
                'Stfalcon\Bundle\EventBundle\DataFixtures\ORM\LoadEventData',
81
                'Stfalcon\Bundle\EventBundle\DataFixtures\ORM\LoadPromoCodeData',
82
                'Stfalcon\Bundle\EventBundle\DataFixtures\ORM\LoadPaymentData',
83
                'Stfalcon\Bundle\EventBundle\DataFixtures\ORM\LoadMailQueueData',
84
                'Stfalcon\Bundle\EventBundle\DataFixtures\ORM\LoadTicketData',
85
                'Stfalcon\Bundle\EventBundle\DataFixtures\ORM\LoadMailQueueData',
86
            ));
87
88
        /** @var $em \Doctrine\ORM\EntityManager */
89
        $em = $this->kernel->getContainer()->get('doctrine.orm.entity_manager');
90
91
        $em->getConnection()->executeUpdate('SET foreign_key_checks = 0;');
92
        $purger = new ORMPurger();
93
        $purger->setPurgeMode(ORMPurger::PURGE_MODE_TRUNCATE);
94
        $executor = new ORMExecutor($em, $purger);
95
        $executor->purge();
96
        $executor->execute($loader->getFixtures(), true);
97
        $em->getConnection()->executeUpdate('SET foreign_key_checks = 1;');
98
        /** Maximize browser window */
99
        $driver = $this->getSession()->getDriver();
100
        if ($driver instanceof Selenium2Driver) {
101
            $driver->maximizeWindow();
102
        }
103
    }
104
105
    /**
106
     * Wait while jQuery finished on page
107
     * Works only with Selenium2Driver.
108
     *
109
     * @param StepEvent $event
110
     *
111
     * @AfterStep
112
     */
113
    public function checkFinishJS(StepEvent $event)
0 ignored issues
show
Unused Code introduced by
The parameter $event is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

113
    public function checkFinishJS(/** @scrutinizer ignore-unused */ StepEvent $event)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
114
    {
115
        $driver = $this->getSession()->getDriver();
116
        if ($driver instanceof Selenium2Driver) {
117
            $currentUrl = $this->getSession()->getCurrentUrl();
118
            if (false !== strpos($currentUrl, $this->getMinkParameter('base_url'))) {
119
                $this->getSession()->wait(
120
                    10000,
121
                    '(typeof window.jQuery == "function" && 0 === jQuery.active && 0 === jQuery(\':animated\').length)'
122
                );
123
            }
124
        }
125
    }
126
127
    /**
128
     * @Then /^я жду$/
129
     */
130
    public function iWait()
131
    {
132
        $this->getSession()->wait(5000);
133
    }
134
135
    /**
136
     * Проверка или файл является PDF-файлом
137
     *
138
     * @Then /^это PDF-файл$/
139
     */
140
    public function thisIsPdfFile()
141
    {
142
        $filename = rtrim($this->getMinkParameter('show_tmp_dir'), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.uniqid().'.html';
143
        file_put_contents($filename, $this->getSession()->getPage()->getContent());
144
145
        $pdfFileConstraint = new File();
146
        $pdfFileConstraint->mimeTypes = array('application/pdf', 'application/x-pdf');
147
148
        /** @var \Symfony\Component\Validator\Validator $validator */
149
        $validator = $this->kernel->getContainer()->get('validator');
150
        $errorList = $validator->validateValue(
151
            $filename,
152
            $pdfFileConstraint
153
        );
154
155
        Assert::assertCount(0, $errorList, 'Это не PDF-файл');
156
    }
157
158
    /**
159
     * @param string $user E-mail Ticket owner
160
     *
161
     * @Given /^я оплатил билет для "([^"]*)"$/
162
     */
163
    public function iPayTicket($user)
164
    {
165
        /** @var $em \Doctrine\ORM\EntityManager */
166
        $em = $this->kernel->getContainer()->get('doctrine')->getManager();
167
        $user = $em->getRepository('ApplicationUserBundle:User')->findOneBy(array('username' => $user));
168
        $ticket = $em->getRepository('StfalconEventBundle:Ticket')->findOneBy(array('user' => $user->getId()));
169
        $payment = $em->getRepository('StfalconEventBundle:Payment')->findOneBy(array('user' => $user->getId()));
170
        $payment->setStatus('paid');
171
        $ticket->setPayment($payment);
172
173
        $em->persist($ticket);
174
        $em->flush();
175
    }
176
177
    /**
178
     * @param string $user E-mail Ticket owner
179
     *
180
     * @Given /^я не оплатил билет для "([^"]*)"$/
181
     */
182
    public function iDontPayTicket($user)
183
    {
184
        /** @var $em \Doctrine\ORM\EntityManager */
185
        $em = $this->kernel->getContainer()->get('doctrine')->getManager();
186
        $user = $em->getRepository('ApplicationUserBundle:User')->findOneBy(array('username' => $user));
187
        $ticket = $em->getRepository('StfalconEventBundle:Ticket')->findOneBy(array('user' => $user->getId()));
188
        $payment = $em->getRepository('StfalconEventBundle:Payment')->findOneBy(array('user' => $user->getId()));
189
        $payment->setStatus('pending');
190
        $ticket->setPayment($payment);
191
192
        $em->persist($ticket);
193
        $em->flush();
194
    }
195
196
    /**
197
     * @param string $mail E-mail Ticket owner
198
     *
199
     * @Given /^я должен видеть полное имя для "([^"]*)"$/
200
     */
201
    public function iMustSeeFullname($mail)
202
    {
203
        /** @var $em \Doctrine\ORM\EntityManager */
204
        $em = $this->kernel->getContainer()->get('doctrine')->getManager();
205
        $user = $em->getRepository('ApplicationUserBundle:User')->findOneBy(array('username' => $mail));
206
        $this->assertPageContainsText($user->getFullname());
207
    }
208
209
    /**
210
     * @param string $mail      E-mail Ticket owner
211
     * @param string $eventSlug Event slug
212
     *
213
     * @Given /^я перехожу на страницу регистрации билета для пользователя "([^"]*)" для события "([^"]*)"$/
214
     */
215
    public function goToTicketRegistrationPage($mail, $eventSlug)
216
    {
217
        $this->visit($this->getTicketRegistrationUrl($mail, $eventSlug));
218
    }
219
220
    /**
221
     * @param string $mail      E-mail Ticket owner
222
     * @param string $eventSlug Event slug
223
     *
224
     * @Given /^я перехожу на страницу регистрации билета с битым хешем для пользователя "([^"]*)" для события "([^"]*)"$/
225
     */
226
    public function goToTicketRegistrationPageWithWrongHash($mail, $eventSlug)
227
    {
228
        $this->visit($this->getTicketRegistrationUrl($mail, $eventSlug).'fffuu');
229
    }
230
231
    /**
232
     * Generate URL for check ticket.
233
     *
234
     * @param string $mail      E-mail Ticket owner
235
     * @param string $eventSlug Event slug
236
     *
237
     * @return string
238
     */
239
    public function getTicketRegistrationUrl($mail, $eventSlug)
240
    {
241
        /** @var $em \Doctrine\ORM\EntityManager */
242
        $em = $this->kernel->getContainer()->get('doctrine')->getManager();
243
244
        $user = $em->getRepository('ApplicationUserBundle:User')->findOneBy(array('username' => $mail));
245
        $event = $em->getRepository('StfalconEventBundle:Event')->findOneBy(array('slug' => $eventSlug));
246
247
        $ticket = $em->getRepository('StfalconEventBundle:Ticket')->findOneByUserAndEvent($user, $event);
248
249
        return $this->kernel->getContainer()->get('router')->generate('event_ticket_registration',
250
            array(
251
                'ticket' => $ticket->getId(),
252
                'hash' => $ticket->getHash(),
253
            ),
254
            true
255
        );
256
    }
257
258
    /**
259
     * Проверка что имейл не был отправлен тем, кому не положено (т.е. не админам).
260
     *
261
     * @param string $subject Subject
262
     * @param string $to      Receiver
263
     *
264
     * @Then /^email with subject "([^"]*)" should have not been sent(?: to "([^"]+)")?$/
265
     *
266
     * @throws \RuntimeException
267
     */
268
    public function emailWithSubjectShouldHaveBeenSent($subject, $to)
269
    {
270
        /** @var \Swift_Mailer $mailer */
271
        $mailer = $this->loadProfile()->getCollector('swiftmailer');
272
        if ($mailer->getMessageCount() > 0) {
0 ignored issues
show
Bug introduced by
The method getMessageCount() does not exist on Swift_Mailer. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

272
        if ($mailer->/** @scrutinizer ignore-call */ getMessageCount() > 0) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
273
            foreach ($mailer->getMessages() as $message) {
0 ignored issues
show
Bug introduced by
The method getMessages() does not exist on Swift_Mailer. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

273
            foreach ($mailer->/** @scrutinizer ignore-call */ getMessages() as $message) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
274
                if (trim($subject) === trim($message->getSubject())) {
275
                    if (array_key_exists($to, $message->getTo())) {
276
                        throw new \RuntimeException(sprintf('Message with subject "%s" and receiver "%s" was sent, but should not', $subject, $to));
277
                    }
278
                }
279
            }
280
        }
281
    }
282
283
    /**
284
     * Loads the profiler's profile.
285
     *
286
     * If no token has been given, the debug token of the last request will be used
287
     *
288
     * @param string $token
289
     *
290
     * @return \Symfony\Component\HttpKernel\Profiler\Profile
291
     *
292
     * @throws \RuntimeException
293
     */
294
    public function loadProfile($token = null)
295
    {
296
        if (null === $token) {
297
            $headers = $this->getSession()->getResponseHeaders();
298
299
            if (!isset($headers['X-Debug-Token']) && !isset($headers['x-debug-token'])) {
300
                throw new \RuntimeException('Debug-Token not found in response headers. Have you turned on the debug flag?');
301
            }
302
            $token = isset($headers['X-Debug-Token']) ? $headers['X-Debug-Token'] : $headers['x-debug-token'];
303
            if (is_array($token)) {
304
                $token = end($token);
305
            }
306
        }
307
308
        return $this->kernel->getContainer()->get('profiler')->loadProfile($token);
309
    }
310
311
    /**
312
     * @param string $userName
313
     *
314
     * @Given /^пользователь "([^"]*)" должен быть в списке только один раз$/
315
     */
316
    public function singleUser($userName)
317
    {
318
        $result = $this->getSession()->getPage()->find('css', '.table.table-bordered.table-striped');
319
        Assert::assertEquals(1, mb_substr_count($result->getHtml(), $userName));
320
    }
321
322
    /**
323
     * @Given /^я перехожу на страницу со списком рассылок$/
324
     */
325
    public function iGoToTheMailListPage()
326
    {
327
        $this->visit('/admin/stfalcon/event/mail/list');
328
    }
329
330
    /**
331
     * @Then /^я на странице создания рассылки$/
332
     */
333
    public function iAmOnTheMailCreatePage()
334
    {
335
        $this->visit('/admin/stfalcon/event/mail/create');
336
    }
337
338
    /**
339
     * @Given /^я перехожу на страницу со списком промо кодов$/
340
     */
341
    public function iGoToThePromoCodesListPage()
342
    {
343
        $this->visit('/admin/stfalcon/event/promocode/list');
344
    }
345
346
    /**
347
     * @Then /^я на странице создания промо кодов$/
348
     */
349
    public function iAmOnThePromoCodeCreatePage()
350
    {
351
        $this->visit('/admin/stfalcon/event/promocode/create');
352
    }
353
354
    /**
355
     * Проверяем дату по формату.
356
     *
357
     * @Then /^я должен видеть в елементе "([^"]*)" дату "([^"]*)" в формате "([^"]*)"$/
358
     */
359
    public function iShouldSeeDateInFormat($elem, $date, $format)
360
    {
361
        $date = new \DateTime($date);
362
363
        $this->assertFieldContains($elem, $date->format($format));
364
    }
365
366
    /**
367
     * @Given /^Interkassa API is available$/
368
     */
369
    public function interkassaApiIsAvailable()
370
    {
371
        $this->mocker->mockService('stfalcon_event.interkassa.service', 'Application\Bundle\DefaultBundle\Service\InterkassaService')
372
            ->shouldReceive('checkPayment')
373
            ->andReturn(true);
374
    }
375
376
    /**
377
     * @param int $paymentId
378
     *
379
     * @Given /^я перехожу на страницу обработки платежа "([^"]*)"$/
380
     */
381
    public function goToInterkassaInteraction($paymentId)
382
    {
383
        $params = [
384
            'ik_pm_no' => $paymentId,
385
        ];
386
387
        $this->visit('/payment/interaction?'.http_build_query($params));
388
    }
389
390
    /**
391
     * @param int $paymentId
392
     *
393
     * @Given /^платеж "([^"]*)" должен быть помечен как оплачен/
394
     */
395
    public function paymentEqualTo($paymentId)
396
    {
397
        /** @var $em \Doctrine\ORM\EntityManager */
398
        $em = $this->kernel->getContainer()->get('doctrine')->getManager();
399
400
        /** @var Payment $payment */
401
        $payment = $em->getRepository('StfalconEventBundle:Payment')->find($paymentId);
402
403
        Assert::assertTrue($payment->isPaid());
404
    }
405
}
406