Completed
Push — master ( 308c33...4cc160 )
by Michał
303:29 queued 289:05
created

src/Sylius/Bundle/CoreBundle/Behat/CoreContext.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/*
4
 * This file is part of the Sylius package.
5
 *
6
 * (c) Paweł Jędrzejewski
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sylius\Bundle\CoreBundle\Behat;
13
14
use Behat\Gherkin\Node\TableNode;
15
use Behat\Mink\Driver\Selenium2Driver;
16
use Sylius\Bundle\ResourceBundle\Behat\DefaultContext;
17
use Sylius\Component\Addressing\Model\AddressInterface;
18
use Sylius\Component\Cart\SyliusCartEvents;
19
use Sylius\Component\Core\Model\ChannelInterface;
20
use Sylius\Component\Core\Model\CustomerInterface;
21
use Sylius\Component\Core\Model\OrderInterface;
22
use Sylius\Component\Core\Model\OrderItemInterface;
23
use Sylius\Component\Core\Model\PaymentInterface;
24
use Sylius\Component\Core\Model\ProductInterface;
25
use Sylius\Component\Core\Model\ProductVariantInterface;
26
use Sylius\Component\Core\Model\ShipmentInterface;
27
use Sylius\Component\Core\Model\ShippingMethodInterface;
28
use Sylius\Component\Core\Model\TaxRateInterface;
29
use Sylius\Component\Core\Model\UserInterface;
30
use Sylius\Component\Core\Pricing\Calculators as PriceCalculators;
31
use Sylius\Component\Currency\Model\CurrencyInterface;
32
use Sylius\Component\Locale\Model\LocaleInterface;
33
use Sylius\Component\Order\OrderTransitions;
34
use Sylius\Component\Payment\Model\PaymentMethodInterface;
35
use Sylius\Component\Rbac\Model\RoleInterface;
36
use Sylius\Component\Shipping\Calculator\DefaultCalculators;
37
use Sylius\Component\Shipping\ShipmentTransitions;
38
use Sylius\Component\Taxation\Model\TaxCategoryInterface;
39
use Sylius\Component\User\Model\GroupableInterface;
40
use Symfony\Component\EventDispatcher\GenericEvent;
41
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
42
43
class CoreContext extends DefaultContext
44
{
45
    /**
46
     * Created orders.
47
     *
48
     * @var OrderInterface[]
49
     */
50
    protected $orders = [];
51
52
    /**
53
     * @Given store has default configuration
54
     */
55
    public function storeHasDefaultConfiguration()
56
    {
57
        $manager = $this->getEntityManager();
58
59
        /** @var CurrencyInterface $currency */
60
        $currency = $this->getFactory('currency')->createNew();
61
        $currency->setCode('EUR');
62
        $currency->setExchangeRate(1);
63
        $manager->persist($currency);
64
65
        /** @var LocaleInterface $locale */
66
        $locale = $this->getFactory('locale')->createNew();
67
        $locale->setCode('en_US');
68
        $manager->persist($locale);
69
70
        /* @var ChannelInterface $channel */
71
        $channel = $this->getFactory('channel')->createNew();
72
        $channel->setCode('DEFAULT-WEB');
73
        $channel->setName('Default');
74
        $channel->setHostname('http://example.com');
75
        $channel->addCurrency($currency);
76
        $channel->setDefaultCurrency($currency);
77
        $channel->addLocale($locale);
78
        $channel->setDefaultLocale($locale);
79
        $manager->persist($channel);
80
81
        $manager->flush();
82
    }
83
84
    /**
85
     * @Given I am logged in as :role
86
     */
87
    public function iAmLoggedInAsAuthorizationRole($role)
88
    {
89
        $this->iAmLoggedInAsRole('ROLE_ADMINISTRATION_ACCESS', '[email protected]', [$role]);
90
    }
91
92
    /**
93
     * @Given /^I am logged in user$/
94
     * @Given /^I am logged in as user "([^""]*)"$/
95
     */
96
    public function iAmLoggedInUser($email = '[email protected]')
97
    {
98
        $this->iAmLoggedInAsRole('ROLE_USER', $email);
99
    }
100
101
    /**
102
     * @Given /^I am not logged in$/
103
     */
104
    public function iAmNotLoggedIn()
105
    {
106
        $this->getSession()->restart();
107
    }
108
109
    /**
110
     * @Given /^there are following orders:$/
111
     * @Given /^the following orders exist:$/
112
     * @Given /^there are orders:$/
113
     * @Given /^the following orders were placed:$/
114
     */
115
    public function thereAreOrders(TableNode $table)
116
    {
117
        $manager = $this->getEntityManager();
118
        $finite = $this->getService('sm.factory');
119
        $orderFactory = $this->getFactory('order');
120
        $shipmentProcessor = $this->getService('sylius.processor.shipment_processor');
121
122
        /** @var $paymentMethod PaymentMethodInterface */
123
        $paymentMethod = $this->getFactory('payment_method')->createNew();
124
        $paymentMethod->setName('Stripe');
125
        $paymentMethod->setGateway('stripe');
126
        $paymentMethod->setCode('PM100');
127
        $manager->persist($paymentMethod);
128
129
        $currentOrderNumber = 1;
130
        foreach ($table->getHash() as $data) {
131
            $address = $this->createAddress($data['address']);
132
133
            /* @var $order OrderInterface */
134
            $order = $orderFactory->createNew();
135
            $order->setShippingAddress($address);
136
            $order->setBillingAddress($address);
137
138
            $customer = $this->thereIsCustomer($data['customer']);
139
            $customer->addAddress($address);
140
            $order->setCustomer($customer);
141
142
            if (isset($data['shipment']) && '' !== trim($data['shipment'])) {
143
                $order->addShipment($this->createShipment($data['shipment']));
144
            }
145
146
            $order->setNumber(str_pad($currentOrderNumber, 9, 0, STR_PAD_LEFT));
147
148
            $finite->get($order, OrderTransitions::GRAPH)->apply(OrderTransitions::SYLIUS_CREATE);
149
150
            $this->createPayment($order, $paymentMethod);
151
152
            $currency = isset($data['currency']) ? trim($data['currency']) : 'EUR';
153
            $order->setCurrency($currency);
154
155
            if (isset($data['exchange_rate']) && '' !== trim($data['exchange_rate'])) {
156
                $order->setExchangeRate($data['exchange_rate']);
157
            }
158
159
            $order->setPaymentState(PaymentInterface::STATE_COMPLETED);
160
161
            $order->complete();
162
163
            $shipmentProcessor->updateShipmentStates($order->getShipments(), ShipmentTransitions::SYLIUS_PREPARE);
164
165
            $manager->persist($order);
166
167
            $this->orders[$order->getNumber()] = $order;
168
169
            ++$currentOrderNumber;
170
        }
171
172
        $manager->flush();
173
    }
174
175
    /**
176
     * @Given /^order #(\d+) has following items:$/
177
     */
178
    public function orderHasFollowingItems($number, TableNode $items)
179
    {
180
        $manager = $this->getEntityManager();
181
        $orderItemFactory = $this->getFactory('order_item');
182
        $orderItemQuantityModifier = $this->getService('sylius.order_item_quantity_modifier');
183
184
        $order = $this->orders[$number];
185
186
        foreach ($items->getHash() as $data) {
187
            $product = $this->findOneByName('product', trim($data['product']));
188
189
            /* @var $item OrderItemInterface */
190
            $item = $orderItemFactory->createNew();
191
            $item->setVariant($product->getMasterVariant());
192
            $item->setUnitPrice($product->getMasterVariant()->getPrice());
193
194
            $orderItemQuantityModifier->modify($item, $data['quantity']);
195
196
            $order->addItem($item);
197
        }
198
199
        $order->complete();
200
201
        $this->getService('sylius.order_processing.payment_processor')->processOrderPayments($order);
202
        $this->getService('event_dispatcher')->dispatch(SyliusCartEvents::CART_CHANGE, new GenericEvent($order));
203
204
        $order->setPaymentState(PaymentInterface::STATE_COMPLETED);
205
206
        $manager->persist($order);
207
        $manager->flush();
208
    }
209
210
    /**
211
     * @Given /^there are following users:$/
212
     */
213
    public function thereAreFollowingUsers(TableNode $table)
214
    {
215
        foreach ($table->getHash() as $data) {
216
            $this->thereIsUser(
217
                $data['email'],
218
                isset($data['password']) ? $data['password'] : $this->faker->word(),
219
                'ROLE_USER',
220
                isset($data['enabled']) ? $data['enabled'] : true,
221
                isset($data['address']) && !empty($data['address']) ? $data['address'] : null,
222
                isset($data['groups']) && !empty($data['groups']) ? explode(',', $data['groups']) : [],
223
                false,
224
                [],
225
                isset($data['created at']) ? new \DateTime($data['created at']) : null
226
            );
227
        }
228
229
        $this->getEntityManager()->flush();
230
    }
231
232
    /**
233
     * @Given /^there are following customers:$/
234
     * @Given /^the following customers exist:$/
235
     */
236
    public function thereAreFollowingCustomers(TableNode $table)
237
    {
238
        foreach ($table->getHash() as $data) {
239
            $this->thereIsCustomer(
240
                $data['email'],
241
                isset($data['address']) && !empty($data['address']) ? $data['address'] : null,
242
                isset($data['groups']) && !empty($data['groups']) ? explode(',', $data['groups']) : [],
243
                false,
244
                isset($data['created at']) ? new \DateTime($data['created at']) : null
245
            );
246
        }
247
248
        $this->getEntityManager()->flush();
249
    }
250
251
    /**
252
     * @Given /^there are groups:$/
253
     * @Given /^there are following groups:$/
254
     * @Given /^the following groups exist:$/
255
     */
256
    public function thereAreGroups(TableNode $table)
257
    {
258
        $manager = $this->getEntityManager();
259
        $factory = $this->getFactory('group');
260
261
        foreach ($table->getHash() as $data) {
262
            $group = $factory->createNew();
263
            $group->setName(trim($data['name']));
264
265
            $manager->persist($group);
266
        }
267
268
        $manager->flush();
269
    }
270
271
    /**
272
     * @Given /^the following addresses exist:$/
273
     */
274
    public function theFollowingAddressesExist(TableNode $table)
275
    {
276
        $manager = $this->getEntityManager();
277
278
        foreach ($table->getHash() as $data) {
279
            $address = $this->createAddress($data['address']);
280
281
            $user = $this->thereIsUser($data['user'], 'sylius', 'ROLE_USER', 'yes', null, []);
282
            $user->getCustomer()->addAddress($address);
283
284
            $manager->persist($address);
285
            $manager->persist($user);
286
        }
287
288
        $manager->flush();
289
    }
290
291
    public function thereIsUser($email, $password, $role = null, $enabled = 'yes', $address = null, $groups = [], $flush = true, array $authorizationRoles = [], $createdAt = null)
292
    {
293
        if (null !== $user = $this->getRepository('user')->findOneByEmail($email)) {
294
            return $user;
295
        }
296
297
        /* @var $user UserInterface */
298
        $user = $this->createUser($email, $password, $role, $enabled, $address, $groups, $authorizationRoles, $createdAt);
299
300
        $this->getEntityManager()->persist($user);
301
        if ($flush) {
302
            $this->getEntityManager()->flush();
303
        }
304
305
        return $user;
306
    }
307
308
    protected function thereIsCustomer($email, $address = null, $groups = [], $flush = true, $createdAt = null)
309
    {
310
        if (null !== $customer = $this->getRepository('customer')->findOneByEmail($email)) {
311
            return $customer;
312
        }
313
314
        /* @var $customer CustomerInterface */
315
        $customer = $this->createCustomer($email, $address, $groups, $createdAt);
316
317
        $this->getEntityManager()->persist($customer);
318
        if ($flush) {
319
            $this->getEntityManager()->flush();
320
        }
321
322
        return $customer;
323
    }
324
325
    /**
326
     * @Given /^product "([^""]*)" has the following volume based pricing:$/
327
     */
328
    public function productHasTheFollowingVolumeBasedPricing($productName, TableNode $table)
329
    {
330
        /* @var $product ProductInterface */
331
        $product = $this->findOneByName('product', $productName);
332
        $masterVariant = $product->getMasterVariant();
333
334
        /* @var $masterVariant ProductVariantInterface */
335
        $masterVariant->setPricingCalculator(PriceCalculators::VOLUME_BASED);
336
        $configuration = [];
337
338
        foreach ($table->getHash() as $data) {
339
            if (false !== strpos($data['range'], '+')) {
340
                $min = (int) trim(str_replace('+', '', $data['range']));
341
                $max = null;
342
            } else {
343
                list($min, $max) = array_map(function ($value) { return (int) trim($value); }, explode('-', $data['range']));
344
            }
345
346
            $configuration[] = [
347
                'min' => $min,
348
                'max' => $max,
349
                'price' => (int) ($data['price'] * 100),
350
            ];
351
        }
352
353
        $masterVariant->setPricingConfiguration($configuration);
354
355
        $manager = $this->getEntityManager();
356
        $manager->persist($product);
357
        $manager->flush();
358
    }
359
360
    /**
361
     * @Given /^product "([^""]*)" has the following group based pricing:$/
362
     */
363
    public function productHasTheFollowingGroupBasedPricing($productName, TableNode $table)
364
    {
365
        $product = $this->findOneByName('product', $productName);
366
        $masterVariant = $product->getMasterVariant();
367
368
        /* @var $masterVariant ProductVariantInterface */
369
        $masterVariant->setPricingCalculator(PriceCalculators::GROUP_BASED);
370
        $configuration = [];
371
372
        foreach ($table->getHash() as $data) {
373
            $group = $this->findOneByName('group', trim($data['group']));
374
            $configuration[$group->getId()] = (float) $data['price'] * 100;
375
        }
376
377
        $masterVariant->setPricingConfiguration($configuration);
378
379
        $manager = $this->getEntityManager();
380
        $manager->persist($product);
381
        $manager->flush();
382
    }
383
384
    /**
385
     * @Given /^there are following tax rates:$/
386
     * @Given /^the following tax rates exist:$/
387
     */
388
    public function thereAreTaxRates(TableNode $table)
389
    {
390
        foreach ($table->getHash() as $data) {
391
            $this->thereIsTaxRate($data['amount'], $data['name'], $data['code'], $data['category'], $data['zone'], isset($data['included in price?']) ? $data['included in price?'] : false, false);
392
        }
393
394
        $this->getEntityManager()->flush();
395
    }
396
397
    /**
398
     * @Given /^there is (\d+)% tax "([^""]*)" with code "([^""]*)" for category "([^""]*)" with zone "([^""]*)"$/
399
     * @Given /^I created (\d+)% tax "([^""]*)" with code "([^""]*)" for category "([^""]*)" with zone "([^""]*)"$/
400
     */
401
    public function thereIsTaxRate($amount, $name, $code, $category, $zone, $includedInPrice = false, $flush = true)
402
    {
403
        /* @var $rate TaxRateInterface */
404
        $rate = $this->getFactory('tax_rate')->createNew();
405
        $rate->setName($name);
406
        $rate->setAmount($amount / 100);
407
        $rate->setIncludedInPrice($includedInPrice);
408
        $rate->setCategory($this->findOneByName('tax_category', $category));
409
        $rate->setZone($this->findOneByName('zone', $zone));
410
        $rate->setCalculator('default');
411
        $rate->setCode($code);
412
413
        $manager = $this->getEntityManager();
414
        $manager->persist($rate);
415
        if ($flush) {
416
            $manager->flush();
417
        }
418
419
        return $rate;
420
    }
421
422
    /**
423
     * @Given /^the following shipping methods are configured:$/
424
     * @Given /^the following shipping methods exist:$/
425
     * @Given /^there are shipping methods:$/
426
     */
427
    public function thereAreShippingMethods(TableNode $table)
428
    {
429
        foreach ($table->getHash() as $data) {
430
            $calculator = array_key_exists('calculator', $data) ? str_replace(' ', '_', strtolower($data['calculator'])) : DefaultCalculators::PER_UNIT_RATE;
431
            $configuration = array_key_exists('configuration', $data) ? $this->getConfiguration($data['configuration']) : null;
432
            $taxCategory = (isset($data['tax category'])) ? $this->findOneByName('tax_category', trim($data['tax category'])) : null;
433
434
            if (!isset($data['enabled'])) {
435
                $data['enabled'] = 'yes';
436
            }
437
438
            $this->thereIsShippingMethod($data['name'], $data['code'], $data['zone'], $calculator, $taxCategory, $configuration, 'yes' === $data['enabled'], false);
439
        }
440
441
        $this->getEntityManager()->flush();
442
    }
443
444
    /**
445
     * @Given /^I created shipping method "([^""]*)" with code "([^""]*)" and zone "([^""]*)"$/
446
     * @Given /^There is shipping method "([^""]*)" with code "([^""]*)" and zone "([^""]*)"$/
447
     * @Given /^there is an enabled shipping method "([^""]*)" with code "([^""]*)" and zone "([^""]*)"$/
448
     */
449
    public function thereIsShippingMethod($name, $code, $zoneName, $calculator = DefaultCalculators::PER_UNIT_RATE, TaxCategoryInterface $taxCategory = null, array $configuration = null, $enabled = true, $flush = true)
450
    {
451
        $repository = $this->getRepository('shipping_method');
452
        $factory = $this->getFactory('shipping_method');
453
454
        /* @var $method ShippingMethodInterface */
455
        if (null === $method = $repository->findOneByName($name)) {
456
            $method = $factory->createNew();
457
            $method->setName($name);
458
            $method->setCode($code);
459
            $method->setZone($this->findOneByName('zone', $zoneName));
460
            $method->setCalculator($calculator);
461
            $method->setTaxCategory($taxCategory);
462
            $method->setConfiguration($configuration ?: ['amount' => 2500]);
463
        };
464
465
        $method->setEnabled($enabled);
466
467
        $manager = $this->getEntityManager();
468
        $manager->persist($method);
469
        if ($flush) {
470
            $manager->flush();
471
        }
472
473
        return $method;
474
    }
475
476
    /**
477
     * @Given /^there is a disabled shipping method "([^""]*)" with code "([^""]*)" and zone "([^""]*)"$/
478
     */
479
    public function thereIsDisabledShippingMethod($name, $code, $zoneName)
480
    {
481
        $this->thereIsShippingMethod($name, $code, $zoneName, DefaultCalculators::PER_UNIT_RATE, null, null, false);
482
    }
483
484
    /**
485
     * @Given /^the following locales are defined:$/
486
     * @Given /^there are following locales configured:$/
487
     */
488
    public function thereAreLocales(TableNode $table)
489
    {
490
        $repository = $this->getRepository('locale');
491
        $manager = $this->getEntityManager();
492
        $factory = $this->getFactory('locale');
493
494
        $locales = $repository->findAll();
495
        foreach ($locales as $locale) {
496
            $manager->remove($locale);
497
        }
498
499
        $manager->flush();
500
        $manager->clear();
501
502
        foreach ($table->getHash() as $data) {
503
            $locale = $factory->createNew();
504
505
            if (isset($data['code'])) {
506
                $locale->setCode($data['code']);
507
            } elseif (isset($data['name'])) {
508
                $locale->setCode($this->getLocaleCodeByEnglishLocaleName($data['name']));
509
            } else {
510
                throw new \InvalidArgumentException('Locale definition should have either code or name');
511
            }
512
513
            if (isset($data['enabled'])) {
514
                $locale->setEnabled('yes' === $data['enabled']);
515
            }
516
517
            $manager->persist($locale);
518
        }
519
520
        $manager->flush();
521
    }
522
523
    /**
524
     * @Given /^there are following locales configured and assigned to the default channel:$/
525
     */
526
    public function thereAreLocalesAssignedToDefaultChannel(TableNode $table)
527
    {
528
        $this->thereAreLocales($table);
529
530
        /** @var ChannelInterface $defaultChannel */
531
        $defaultChannel = $this->getRepository('channel')->findOneBy(['code' => 'DEFAULT-WEB']);
532
533
        /** @var LocaleInterface[] $locales */
534
        $locales = $this->getRepository('locale')->findAll();
535
        foreach ($locales as $locale) {
536
            $defaultChannel->addLocale($locale);
537
        }
538
539
        $this->getEntityManager()->flush();
540
    }
541
542
    /**
543
     * @Given /^product "([^""]*)" is available in all variations$/
544
     */
545
    public function productIsAvailableInAllVariations($productName)
546
    {
547
        /** @var ProductInterface $product */
548
        $product = $this->findOneByName('product', $productName);
549
550
        $this->generateProductVariations($product);
551
552
        $this->getEntityManager()->flush();
553
    }
554
555
    /**
556
     * @Given all products are available in all variations
557
     */
558
    public function allProductsAreAvailableInAllVariations()
559
    {
560
        /** @var ProductInterface[] $products */
561
        $products = $this->getRepository('product')->findAll();
562
        foreach ($products as $product) {
563
            if ($product->hasOptions()) {
564
                $this->generateProductVariations($product);
565
            }
566
        }
567
568
        $this->getEntityManager()->flush();
569
    }
570
571
    /**
572
     * @Given /^user "([^"]*)" has been deleted$/
573
     */
574
    public function userHasBeenDeleted($customerEmail)
575
    {
576
        $userRepository = $this->getRepository('user');
577
578
        $user = $userRepository->findOneByEmail($customerEmail);
579
580
        $userRepository->remove($user);
581
    }
582
583
    /**
584
     * Create an address instance from string.
585
     *
586
     * @param string $string
587
     *
588
     * @return AddressInterface
589
     */
590
    private function createAddress($string)
591
    {
592
        $addressData = $this->processAddress($string);
593
594
        list($firstname, $lastname) = explode(' ', $addressData[0]);
595
596
        /* @var $address AddressInterface */
597
        $address = $this->getFactory('address')->createNew();
598
        $address->setFirstname(trim($firstname));
599
        $address->setLastname(trim($lastname));
600
        $address->setStreet($addressData[1]);
601
        $address->setPostcode($addressData[2]);
602
        $address->setCity($addressData[3]);
603
        $address->setCountryCode($this->getCountryCodeByEnglishCountryName($addressData[4]));
0 ignored issues
show
$this->getCountryCodeByE...ryName($addressData[4]) is of type false|integer, but the function expects a string|null.

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...
604
605
        return $address;
606
    }
607
608
    /**
609
     * @param string $address
610
     *
611
     * @return array
612
     */
613
    protected function processAddress($address)
614
    {
615
        $addressData = explode(',', $address);
616
        $addressData = array_map('trim', $addressData);
617
618
        return $addressData;
619
    }
620
621
    /**
622
     * Create an payment instance.
623
     *
624
     * @param OrderInterface         $order
625
     * @param PaymentMethodInterface $method
626
     */
627
    private function createPayment(OrderInterface $order, PaymentMethodInterface $method)
628
    {
629
        /** @var $payment PaymentInterface */
630
        $payment = $this->getFactory('payment')->createNew();
631
        $payment->setOrder($order);
632
        $payment->setMethod($method);
633
        $payment->setAmount($order->getTotal());
634
        $payment->setCurrency($order->getCurrency() ?: 'EUR');
635
        $payment->setState(PaymentInterface::STATE_COMPLETED);
636
637
        $order->addPayment($payment);
638
    }
639
640
    /**
641
     * Create an shipment instance from string.
642
     *
643
     * @param string $string
644
     *
645
     * @return ShipmentInterface
646
     */
647
    private function createShipment($string)
648
    {
649
        $shipmentData = explode(',', $string);
650
        $shipmentData = array_map('trim', $shipmentData);
651
652
        /* @var $shippingMethod ShippingMethodInterface */
653
        $shippingMethod = $this->getRepository('shipping_method')->findOneByName($shipmentData[0]);
654
655
        /* @var $shipment ShipmentInterface */
656
        $shipment = $this->getFactory('shipment')->createNew();
657
        $shipment->setMethod($shippingMethod);
658
        if (isset($shipmentData[1])) {
659
            $shipment->setState($shipmentData[1]);
660
        }
661
        if (isset($shipmentData[2])) {
662
            $shipment->setTracking($shipmentData[2]);
663
        }
664
665
        return $shipment;
666
    }
667
668
    /**
669
     * Create user and login with given role.
670
     *
671
     * @param string $role
672
     * @param string $email
673
     * @param array  $authorizationRoles
674
     */
675
    private function iAmLoggedInAsRole($role, $email = '[email protected]', array $authorizationRoles = [])
676
    {
677
        $user = $this->thereIsUser($email, 'sylius', $role, 'yes', null, [], true, $authorizationRoles);
678
679
        $token = new UsernamePasswordToken($user, $user->getPassword(), 'administration', $user->getRoles());
680
681
        $session = $this->getService('session');
682
        $session->set('_security_user', serialize($token));
683
        $session->save();
684
685
        $this->prepareSessionIfNeeded();
686
687
        $this->getSession()->setCookie($session->getName(), $session->getId());
688
        $this->getService('security.token_storage')->setToken($token);
689
    }
690
691
    /**
692
     * @param GroupableInterface $groupableObject
693
     * @param array              $groups
694
     */
695
    protected function assignGroups(GroupableInterface $groupableObject, array $groups)
696
    {
697
        foreach ($groups as $groupName) {
698
            if ($group = $this->findOneByName('group', $groupName)) {
699
                $groupableObject->addGroup($group);
700
            }
701
        }
702
    }
703
704
    /**
705
     * @param array         $authorizationRoles
706
     * @param UserInterface $user
707
     */
708
    protected function assignAuthorizationRoles(UserInterface $user, array $authorizationRoles = [])
709
    {
710
        foreach ($authorizationRoles as $role) {
711
            try {
712
                $authorizationRole = $this->findOneByName('role', $role);
713
            } catch (\InvalidArgumentException $exception) {
714
                $authorizationRole = $this->createAuthorizationRole($role);
715
                $this->getEntityManager()->persist($authorizationRole);
716
            }
717
718
            $user->addAuthorizationRole($authorizationRole);
719
        }
720
    }
721
722
    /**
723
     * @param $email
724
     * @param $address
725
     * @param $groups
726
     * @param $createdAt
727
     *
728
     * @return CustomerInterface
729
     */
730
    protected function createCustomer($email, $address = null, $groups = [], $createdAt = null)
731
    {
732
        $addressData = $this->processAddress($address);
733
734
        $customer = $this->getFactory('customer')->createNew();
735
        $customer->setFirstname(null === $address ? $this->faker->firstName : $addressData[0]);
736
        $customer->setLastname(null === $address ? $this->faker->lastName : $addressData[1]);
737
        $customer->setEmail($email);
738
        $customer->setEmailCanonical($email);
739
        $customer->setCreatedAt(null === $createdAt ? new \DateTime() : $createdAt);
740
        if (null !== $address) {
741
            $customer->setShippingAddress($this->createAddress($address));
742
        }
743
        $this->assignGroups($customer, $groups);
744
745
        return $customer;
746
    }
747
748
    /**
749
     * @param $email
750
     * @param $password
751
     * @param $role
752
     * @param $enabled
753
     * @param $address
754
     * @param $groups
755
     * @param array $authorizationRoles
756
     * @param $createdAt
757
     *
758
     * @return UserInterface
759
     */
760
    protected function createUser($email, $password, $role = null, $enabled = 'yes', $address = null, array $groups = [], array $authorizationRoles = [], $createdAt = null)
761
    {
762
        $user = $this->getFactory('user')->createNew();
763
        $customer = $this->createCustomer($email, $address, $groups, $createdAt);
764
        $user->setCustomer($customer);
765
        $user->setUsername($email);
766
        $user->setEmail($email);
767
        $user->setEnabled('yes' === $enabled);
768
        $user->setCreatedAt(null === $createdAt ? new \DateTime() : $createdAt);
769
        $user->setPlainPassword($password);
770
        $user->setUsernameCanonical($email);
771
        $user->setEmailCanonical($email);
772
        $this->getService('sylius.user.password_updater')->updatePassword($user);
773
774
        if (null !== $role) {
775
            $user->addRole($role);
776
        }
777
        $this->assignAuthorizationRoles($user, $authorizationRoles);
778
779
        return $user;
780
    }
781
782
    /**
783
     * @param string $role
784
     *
785
     * @return RoleInterface
786
     */
787
    protected function createAuthorizationRole($role)
788
    {
789
        $authorizationRole = $this->getFactory('role')->createNew();
790
        $authorizationRole->setCode($role);
791
        $authorizationRole->setName(ucfirst($role));
792
        $authorizationRole->setSecurityRoles(['ROLE_ADMINISTRATION_ACCESS']);
793
794
        return $authorizationRole;
795
    }
796
797
    /**
798
     * @param ProductInterface $product
799
     */
800
    private function generateProductVariations($product)
801
    {
802
        $this->getService('sylius.generator.product_variant')->generate($product);
803
804
        foreach ($product->getVariants() as $variant) {
805
            $variant->setPrice($product->getMasterVariant()->getPrice());
806
        }
807
808
        $this->getEntityManager()->persist($product);
809
    }
810
811
    private function prepareSessionIfNeeded()
812
    {
813
        if (!$this->getSession()->getDriver() instanceof Selenium2Driver) {
814
            return;
815
        }
816
817
        if (false !== strpos($this->getSession()->getCurrentUrl(), $this->getMinkParameter('base_url'))) {
818
            return;
819
        }
820
821
        $this->visitPath('/');
822
    }
823
}
824