Passed
Push — master ( c01df0...b2280f )
by Cesar
10:38 queued 06:42
created

Index::execute()   F

Complexity

Conditions 16
Paths 4571

Size

Total Lines 190
Code Lines 143

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 143
dl 0
loc 190
rs 1.1198
c 0
b 0
f 0
cc 16
nc 4571
nop 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Pagantis\Pagantis\Controller\Payment;
4
5
use Magento\Framework\App\Action\Action;
6
use Magento\Framework\App\Action\Context;
7
use Magento\Quote\Model\QuoteRepository;
8
use Magento\Sales\Model\ResourceModel\Order\Collection as OrderCollection;
9
use Magento\Checkout\Model\Session;
10
use Pagantis\Pagantis\Helper\Config;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Pagantis\Pagantis\Controller\Payment\Config. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
11
use Pagantis\Pagantis\Helper\ExtraConfig;
12
use Magento\Framework\App\ResourceConnection;
13
use Magento\Framework\App\ProductMetadataInterface;
14
use Magento\Framework\Module\ModuleList;
15
use Pagantis\OrdersApiClient\Model\Order\User\Address;
16
use Magento\Framework\DB\Ddl\Table;
17
18
/**
19
 * Class Index
20
 * @package Pagantis\Pagantis\Controller\Payment
21
 */
22
class Index extends Action
23
{
24
    /** Orders tablename */
25
    const ORDERS_TABLE = 'cart_process';
26
27
    /** Concurrency tablename */
28
    const LOGS_TABLE = 'Pagantis_logs';
29
30
    /** @var Context $context */
31
    protected $context;
32
33
    /** @var QuoteRepository  $quoteRepository */
34
    protected $quoteRepository;
35
36
    /** @var OrderCollection $orderCollection */
37
    protected $orderCollection;
38
39
    /** @var Session $session */
40
    protected $session;
41
42
    /** @var mixed $config */
43
    protected $config;
44
45
    /** @var ResourceConnection $dbObject */
46
    protected $dbObject;
47
48
    /** @var ProductMetadataInterface $productMetadataInterface */
49
    protected $productMetadataInterface;
50
51
    /** @var ModuleList $moduleList */
52
    protected $moduleList;
53
54
    /** @var ExtraConfig $extraConfig */
55
    protected $extraConfig;
56
57
    /**
58
     * Index constructor.
59
     *
60
     * @param Context                  $context
61
     * @param QuoteRepository          $quoteRepository
62
     * @param OrderCollection          $orderCollection
63
     * @param Session                  $session
64
     * @param Config                   $config
65
     * @param ResourceConnection       $dbObject
66
     * @param ProductMetadataInterface $productMetadataInterface
67
     * @param ModuleList               $moduleList
68
     * @param ExtraConfig              $extraConfig
69
     */
70
    public function __construct(
71
        Context $context,
72
        QuoteRepository $quoteRepository,
73
        OrderCollection $orderCollection,
74
        Session $session,
75
        Config $config,
76
        ResourceConnection $dbObject,
77
        ProductMetadataInterface $productMetadataInterface,
78
        ModuleList $moduleList,
79
        ExtraConfig $extraConfig
80
    ) {
81
        parent::__construct($context);
82
        $this->session = $session;
83
        $this->context = $context;
84
        $this->config = $config->getConfig();
85
        $this->quoteRepository = $quoteRepository;
86
        $this->orderCollection = $orderCollection;
87
        $this->dbObject = $dbObject;
88
        $this->moduleList = $moduleList;
89
        $this->productMetadataInterface = $productMetadataInterface;
90
        $this->extraConfig = $extraConfig->getExtraConfig();
0 ignored issues
show
Documentation Bug introduced by
It seems like $extraConfig->getExtraConfig() of type array or array is incompatible with the declared type Pagantis\Pagantis\Helper\ExtraConfig of property $extraConfig.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
91
    }
92
93
    /**
94
     * Main function
95
     *
96
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface|void
97
     * @throws \Zend_Db_Exception
98
     */
99
    public function execute()
100
    {
101
        try {
102
            $cancelUrl = $this->_url->getUrl('checkout', ['_fragment' => 'payment']);
103
            $quote = $this->session->getQuote();
104
            /** @var Order $order */
105
            $lastOrder = $this->session->getLastRealOrder();
0 ignored issues
show
Unused Code introduced by
The assignment to $lastOrder is dead and can be removed.
Loading history...
106
            $params = $this->getRequest()->getParams();
107
            $customer = $quote->getCustomer();
108
            $shippingAddress = $quote->getShippingAddress();
109
110
            if (isset($params['email']) && $params['email']!='') {
111
                $this->session->setEmail($params['email']); //Get guest email after refresh page
112
                $customer->setEmail($params['email']);
0 ignored issues
show
Bug introduced by
The method setEmail() does not exist on Magento\Framework\Api\ExtensibleDataInterface. It seems like you code against a sub-type of Magento\Framework\Api\ExtensibleDataInterface such as Magento\Sales\Api\Data\OrderAddressInterface or Magento\Sales\Model\Order\Shipment\Track or Magento\Store\Model\Website or Magento\CatalogInventory\Model\Stock\Status or Magento\Sales\Model\Order\Creditmemo\Item or Magento\Tax\Model\Sales\Quote\QuoteDetails or Magento\Catalog\Model\ProductLink\Link or Magento\Framework\Model\AbstractExtensibleModel or Magento\Quote\Api\Data\AddressInterface or Magento\Customer\Api\Data\CustomerInterface or Magento\CatalogRule\Model\Rule or Magento\Catalog\Model\Product or Magento\Quote\Model\AddressAdditionalData or Magento\Quote\Model\Cart\TotalsAdditionalData or Magento\Framework\View\E...t\DataProvider\Document or Magento\Checkout\Model\TotalsInformation or Magento\CatalogRule\Model\Data\Condition or Magento\Customer\Model\Data\Customer or Magento\Quote\Model\EstimateAddress or Magento\Catalog\Model\Category or Magento\Eav\Model\Entity...ibute\AbstractAttribute or Magento\Catalog\Model\ResourceModel\Eav\Attribute or Magento\Catalog\Model\Category\Attribute or Magento\Checkout\Model\ShippingInformation or Magento\Tax\Model\Calculation\Rule or Magento\Sales\Model\Order\Status\History or Magento\Store\Model\Group or Magento\Catalog\Model\Product\Option or Magento\Catalog\Model\Product\Gallery\Entry or Magento\Quote\Model\Quote\ProductOption or Magento\Tax\Model\Sales\Quote\ItemDetails or Magento\Tax\Model\TaxDetails\AppliedTax or Magento\Sales\Model\Order\Tax\Item or Magento\Bundle\Model\Option or Magento\Eav\Model\Entity\Attribute\Set or Magento\Quote\Model\Cart\Currency or Magento\Sales\Model\Order\Shipment\Comment or Magento\Catalog\Model\Product\Price\Cost or Magento\Quote\Model\Cart\Totals or Magento\Sales\Model\Order\Invoice\Item or Magento\Downloadable\Model\File\Content or Magento\Catalog\Model\ProductRender\PriceInfo or Magento\CatalogInventory\Model\Stock or Magento\Quote\Model\ShippingAssignment or Magento\Quote\Model\Quote\Payment or Magento\Checkout\Model\PaymentDetails or Magento\Catalog\Model\ProductRender\Image or Magento\Tax\Model\TaxClass\Key or Magento\Sales\Model\Order\Creditmemo\Comment or Magento\Sales\Model\Order\Payment or Magento\Sales\Model\Order\Payment\Transaction or Magento\GiftMessage\Model\Message or Magento\Sales\Model\Order\Shipment\Item or Magento\Catalog\Model\Product\Price\TierPrice or Magento\Catalog\Model\Product\Attribute\Type or Magento\Tax\Model\TaxDetails\ItemDetails or Magento\Store\Model\Store or Magento\Catalog\Model\CustomOptions\CustomOption or Magento\Catalog\Model\Pr...nder\FormattedPriceInfo or Magento\Catalog\Model\ProductRender or Magento\Sales\Model\Order or Magento\Catalog\Model\Product\Option\Type or Magento\Quote\Model\Quote or Magento\Tax\Model\Calculation\Rate or Magento\Catalog\Model\Product\TierPrice or Magento\Tax\Model\Sales\Order\Details or Magento\Framework\Api\Te...erator\ExtensibleSample or Magento\Sales\Model\Order\Invoice\Comment or Magento\Sales\Model\Order\ShippingAssignment or Magento\Msrp\Model\ProductRender\MsrpPriceInfo or Magento\Sales\Model\Order\Item or Magento\Sales\Model\Order\Creditmemo or Magento\Sales\Model\Order\Invoice or Magento\Quote\Model\Shipping or Magento\Catalog\Model\Product\Price\BasePrice or Magento\Downloadable\Model\Sample or Magento\Eav\Model\Entity\Attribute\Group or Magento\Tax\Model\Sales\Order\Tax or Magento\Quote\Model\Cart\TotalSegment or Magento\Downloadable\Model\Link or Magento\CatalogInventory\Model\Stock\Item or Magento\Catalog\Model\Pr...Price\PriceUpdateResult or Magento\Tax\Model\Calculation\Rate\Title or Magento\Sales\Model\Order\Shipment or Magento\Catalog\Model\Product\Price\SpecialPrice or Magento\Tax\Model\ClassModel or Magento\Bundle\Model\Link or Magento\Bundle\Model\BundleOption or Magento\Tax\Model\TaxDetails\AppliedTaxRate or Magento\Bundle\Model\Source\Option\Type or Magento\Sales\Model\Order\Shipping or Magento\Quote\Model\Quote\Item or Magento\SalesRule\Model\Coupon or Magento\Tax\Model\TaxDetails\TaxDetails or Magento\Sales\Model\Order\ShippingTotal or Magento\Catalog\Model\ProductOption or Magento\Catalog\Model\ProductRender\Button. ( Ignorable by Annotation )

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

112
                $customer->/** @scrutinizer ignore-call */ 
113
                           setEmail($params['email']);
Loading history...
113
                $quote->setCheckoutMethod('guest');
114
                $quote->getBillingAddress()->setEmail($params['email']);
115
            } elseif ($customer->getEmail()=='') {
0 ignored issues
show
Bug introduced by
The method getEmail() does not exist on Magento\Framework\Api\ExtensibleDataInterface. It seems like you code against a sub-type of Magento\Framework\Api\ExtensibleDataInterface such as Magento\Sales\Api\Data\OrderAddressInterface or Magento\Sales\Model\Order\Shipment\Track or Magento\Store\Model\Website or Magento\CatalogInventory\Model\Stock\Status or Magento\Sales\Model\Order\Creditmemo\Item or Magento\Tax\Model\Sales\Quote\QuoteDetails or Magento\Catalog\Model\ProductLink\Link or Magento\Framework\Model\AbstractExtensibleModel or Magento\Quote\Api\Data\AddressInterface or Magento\Customer\Api\Data\CustomerInterface or Magento\CatalogRule\Model\Rule or Magento\Catalog\Model\Product or Magento\Quote\Model\AddressAdditionalData or Magento\Quote\Model\Cart\TotalsAdditionalData or Magento\Framework\View\E...t\DataProvider\Document or Magento\Checkout\Model\TotalsInformation or Magento\CatalogRule\Model\Data\Condition or Magento\Customer\Model\Data\Customer or Magento\Quote\Model\EstimateAddress or Magento\Catalog\Model\Category or Magento\Eav\Model\Entity...ibute\AbstractAttribute or Magento\Catalog\Model\ResourceModel\Eav\Attribute or Magento\Catalog\Model\Category\Attribute or Magento\Checkout\Model\ShippingInformation or Magento\Tax\Model\Calculation\Rule or Magento\Sales\Model\Order\Status\History or Magento\Store\Model\Group or Magento\Catalog\Model\Product\Option or Magento\Catalog\Model\Product\Gallery\Entry or Magento\Quote\Model\Quote\ProductOption or Magento\Tax\Model\Sales\Quote\ItemDetails or Magento\Tax\Model\TaxDetails\AppliedTax or Magento\Sales\Model\Order\Tax\Item or Magento\Bundle\Model\Option or Magento\Eav\Model\Entity\Attribute\Set or Magento\Quote\Model\Cart\Currency or Magento\Sales\Model\Order\Shipment\Comment or Magento\Catalog\Model\Product\Price\Cost or Magento\Quote\Model\Cart\Totals or Magento\Sales\Model\Order\Invoice\Item or Magento\Downloadable\Model\File\Content or Magento\Catalog\Model\ProductRender\PriceInfo or Magento\CatalogInventory\Model\Stock or Magento\Quote\Model\ShippingAssignment or Magento\Quote\Model\Quote\Payment or Magento\Checkout\Model\PaymentDetails or Magento\Catalog\Model\ProductRender\Image or Magento\Tax\Model\TaxClass\Key or Magento\Sales\Model\Order\Creditmemo\Comment or Magento\Sales\Model\Order\Payment or Magento\Sales\Model\Order\Payment\Transaction or Magento\GiftMessage\Model\Message or Magento\Sales\Model\Order\Shipment\Item or Magento\Catalog\Model\Product\Price\TierPrice or Magento\Catalog\Model\Product\Attribute\Type or Magento\Tax\Model\TaxDetails\ItemDetails or Magento\Store\Model\Store or Magento\Catalog\Model\CustomOptions\CustomOption or Magento\Catalog\Model\Pr...nder\FormattedPriceInfo or Magento\Catalog\Model\ProductRender or Magento\Sales\Model\Order or Magento\Catalog\Model\Product\Option\Type or Magento\Quote\Model\Quote or Magento\Tax\Model\Calculation\Rate or Magento\Catalog\Model\Product\TierPrice or Magento\Tax\Model\Sales\Order\Details or Magento\Framework\Api\Te...erator\ExtensibleSample or Magento\Sales\Model\Order\Invoice\Comment or Magento\Sales\Model\Order\ShippingAssignment or Magento\Msrp\Model\ProductRender\MsrpPriceInfo or Magento\Sales\Model\Order\Item or Magento\Sales\Model\Order\Creditmemo or Magento\Sales\Model\Order\Invoice or Magento\Quote\Model\Shipping or Magento\Catalog\Model\Product\Price\BasePrice or Magento\Downloadable\Model\Sample or Magento\Eav\Model\Entity\Attribute\Group or Magento\Tax\Model\Sales\Order\Tax or Magento\Quote\Model\Cart\TotalSegment or Magento\Downloadable\Model\Link or Magento\CatalogInventory\Model\Stock\Item or Magento\Catalog\Model\Pr...Price\PriceUpdateResult or Magento\Tax\Model\Calculation\Rate\Title or Magento\Sales\Model\Order\Shipment or Magento\Catalog\Model\Product\Price\SpecialPrice or Magento\Tax\Model\ClassModel or Magento\Bundle\Model\Link or Magento\Bundle\Model\BundleOption or Magento\Tax\Model\TaxDetails\AppliedTaxRate or Magento\Bundle\Model\Source\Option\Type or Magento\Sales\Model\Order\Shipping or Magento\Quote\Model\Quote\Item or Magento\SalesRule\Model\Coupon or Magento\Tax\Model\TaxDetails\TaxDetails or Magento\Sales\Model\Order\ShippingTotal or Magento\Catalog\Model\ProductOption or Magento\Catalog\Model\ProductRender\Button. ( Ignorable by Annotation )

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

115
            } elseif ($customer->/** @scrutinizer ignore-call */ getEmail()=='') {
Loading history...
116
                $customer->setEmail($this->session->getEmail());
0 ignored issues
show
Bug introduced by
It seems like $this->session->getEmail() can also be of type Magento\Checkout\Model\Session; however, parameter $email of Magento\Customer\Api\Dat...erInterface::setEmail() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

116
                $customer->setEmail(/** @scrutinizer ignore-type */ $this->session->getEmail());
Loading history...
117
                $quote->setCheckoutMethod('guest');
118
                $quote->getBillingAddress()->setEmail($this->session->getEmail());
119
            }
120
121
            /** @var Quote $currentQuote */
122
            $currentQuote = $this->quoteRepository->get($quote->getId());
123
            $currentQuote->setCustomerEmail($customer->getEmail());
124
            $this->quoteRepository->save($currentQuote);
125
126
            $userAddress =  new Address();
127
            $userAddress
128
                ->setZipCode($shippingAddress->getPostcode())
129
                ->setFullName($shippingAddress->getFirstname()." ".$shippingAddress->getLastname())
130
                ->setCountryCode('ES')
131
                ->setCity($shippingAddress->getCity())
132
                ->setAddress($shippingAddress->getStreetFull())
133
            ;
134
135
            $orderShippingAddress = new Address();
136
            $orderShippingAddress
137
                ->setZipCode($shippingAddress->getPostcode())
138
                ->setFullName($shippingAddress->getFirstname()." ".$shippingAddress->getLastname())
139
                ->setCountryCode('ES')
140
                ->setCity($shippingAddress->getCity())
141
                ->setAddress($shippingAddress->getStreetFull())
142
                ->setFixPhone($shippingAddress->getTelephone())
143
                ->setMobilePhone($shippingAddress->getTelephone())
144
            ;
145
146
            $orderBillingAddress =  new Address();
147
            $billingAddress = $quote->getBillingAddress();
148
            $orderBillingAddress
149
                ->setZipCode($billingAddress->getPostcode())
150
                ->setFullName($billingAddress->getFirstname()." ".$shippingAddress->getLastname())
151
                ->setCountryCode('ES')
152
                ->setCity($billingAddress->getCity())
153
                ->setAddress($billingAddress->getStreetFull())
154
                ->setFixPhone($billingAddress->getTelephone())
155
                ->setMobilePhone($billingAddress->getTelephone())
156
            ;
157
158
            $orderUser = new \Pagantis\OrdersApiClient\Model\Order\User();
159
            $billingAddress->setEmail($customer->getEmail());
160
            $orderUser
161
                ->setAddress($userAddress)
162
                ->setFullName($shippingAddress->getFirstname()." ".$shippingAddress->getLastname())
163
                ->setBillingAddress($orderBillingAddress)
164
                ->setEmail($customer->getEmail())
165
                ->setFixPhone($shippingAddress->getTelephone())
166
                ->setMobilePhone($shippingAddress->getTelephone())
167
                ->setShippingAddress($orderShippingAddress)
168
            ;
169
170
            if ($customer->getDob()) {
0 ignored issues
show
Bug introduced by
The method getDob() does not exist on Magento\Framework\Api\ExtensibleDataInterface. It seems like you code against a sub-type of Magento\Framework\Api\ExtensibleDataInterface such as Magento\Sales\Model\Order\Shipment\Track or Magento\Store\Model\Website or Magento\CatalogInventory\Model\Stock\Status or Magento\Sales\Model\Order\Creditmemo\Item or Magento\Tax\Model\Sales\Quote\QuoteDetails or Magento\Catalog\Model\ProductLink\Link or Magento\Framework\Model\AbstractExtensibleModel or Magento\Customer\Api\Data\CustomerInterface or Magento\CatalogRule\Model\Rule or Magento\Catalog\Model\Product or Magento\Quote\Model\AddressAdditionalData or Magento\Quote\Model\Quote\Address or Magento\Quote\Model\Cart\TotalsAdditionalData or Magento\Framework\View\E...t\DataProvider\Document or Magento\Checkout\Model\TotalsInformation or Magento\CatalogRule\Model\Data\Condition or Magento\Customer\Model\Data\Customer or Magento\Quote\Model\EstimateAddress or Magento\Catalog\Model\Category or Magento\Eav\Model\Entity...ibute\AbstractAttribute or Magento\Catalog\Model\ResourceModel\Eav\Attribute or Magento\Catalog\Model\Category\Attribute or Magento\Checkout\Model\ShippingInformation or Magento\Tax\Model\Calculation\Rule or Magento\Sales\Model\Order\Status\History or Magento\Store\Model\Group or Magento\Catalog\Model\Product\Option or Magento\Catalog\Model\Product\Gallery\Entry or Magento\Quote\Model\Quote\ProductOption or Magento\Tax\Model\Sales\Quote\ItemDetails or Magento\Tax\Model\TaxDetails\AppliedTax or Magento\Sales\Model\Order\Tax\Item or Magento\Bundle\Model\Option or Magento\Eav\Model\Entity\Attribute\Set or Magento\Quote\Model\Cart\Currency or Magento\Sales\Model\Order\Shipment\Comment or Magento\Catalog\Model\Product\Price\Cost or Magento\Quote\Model\Cart\Totals or Magento\Sales\Model\Order\Invoice\Item or Magento\Downloadable\Model\File\Content or Magento\Catalog\Model\ProductRender\PriceInfo or Magento\CatalogInventory\Model\Stock or Magento\Quote\Model\ShippingAssignment or Magento\Quote\Model\Quote\Payment or Magento\Checkout\Model\PaymentDetails or Magento\Catalog\Model\ProductRender\Image or Magento\Sales\Model\Order\Address or Magento\Tax\Model\TaxClass\Key or Magento\Sales\Model\Order\Creditmemo\Comment or Magento\Sales\Model\Order\Payment or Magento\Sales\Model\Order\Payment\Transaction or Magento\GiftMessage\Model\Message or Magento\Sales\Model\Order\Shipment\Item or Magento\Catalog\Model\Product\Price\TierPrice or Magento\Catalog\Model\Product\Attribute\Type or Magento\Tax\Model\TaxDetails\ItemDetails or Magento\Store\Model\Store or Magento\Catalog\Model\CustomOptions\CustomOption or Magento\Catalog\Model\Pr...nder\FormattedPriceInfo or Magento\Catalog\Model\ProductRender or Magento\Sales\Model\Order or Magento\Catalog\Model\Product\Option\Type or Magento\Quote\Model\Quote or Magento\Tax\Model\Calculation\Rate or Magento\Catalog\Model\Product\TierPrice or Magento\Tax\Model\Sales\Order\Details or Magento\Framework\Api\Te...erator\ExtensibleSample or Magento\Sales\Model\Order\Invoice\Comment or Magento\Sales\Model\Order\ShippingAssignment or Magento\Msrp\Model\ProductRender\MsrpPriceInfo or Magento\Sales\Model\Order\Item or Magento\Sales\Model\Order\Creditmemo or Magento\Sales\Model\Order\Invoice or Magento\Quote\Model\Shipping or Magento\Catalog\Model\Product\Price\BasePrice or Magento\Downloadable\Model\Sample or Magento\Eav\Model\Entity\Attribute\Group or Magento\Tax\Model\Sales\Order\Tax or Magento\Quote\Model\Cart\TotalSegment or Magento\Downloadable\Model\Link or Magento\CatalogInventory\Model\Stock\Item or Magento\Catalog\Model\Pr...Price\PriceUpdateResult or Magento\Tax\Model\Calculation\Rate\Title or Magento\Sales\Model\Order\Shipment or Magento\Catalog\Model\Product\Price\SpecialPrice or Magento\Tax\Model\ClassModel or Magento\Bundle\Model\Link or Magento\Bundle\Model\BundleOption or Magento\Tax\Model\TaxDetails\AppliedTaxRate or Magento\Bundle\Model\Source\Option\Type or Magento\Sales\Model\Order\Shipping or Magento\Quote\Model\Quote\Item or Magento\SalesRule\Model\Coupon or Magento\Tax\Model\TaxDetails\TaxDetails or Magento\Sales\Model\Order\ShippingTotal or Magento\Catalog\Model\ProductOption or Magento\Catalog\Model\ProductRender\Button. ( Ignorable by Annotation )

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

170
            if ($customer->/** @scrutinizer ignore-call */ getDob()) {
Loading history...
171
                $orderUser->setDateOfBirth($customer->getDob());
172
            }
173
            if ($customer->getTaxvat()!='') {
0 ignored issues
show
Bug introduced by
The method getTaxvat() does not exist on Magento\Framework\Api\ExtensibleDataInterface. It seems like you code against a sub-type of Magento\Framework\Api\ExtensibleDataInterface such as Magento\Sales\Model\Order\Shipment\Track or Magento\Store\Model\Website or Magento\CatalogInventory\Model\Stock\Status or Magento\Sales\Model\Order\Creditmemo\Item or Magento\Tax\Model\Sales\Quote\QuoteDetails or Magento\Catalog\Model\ProductLink\Link or Magento\Framework\Model\AbstractExtensibleModel or Magento\Customer\Api\Data\CustomerInterface or Magento\CatalogRule\Model\Rule or Magento\Catalog\Model\Product or Magento\Quote\Model\AddressAdditionalData or Magento\Quote\Model\Quote\Address or Magento\Quote\Model\Cart\TotalsAdditionalData or Magento\Framework\View\E...t\DataProvider\Document or Magento\Checkout\Model\TotalsInformation or Magento\CatalogRule\Model\Data\Condition or Magento\Customer\Model\Data\Customer or Magento\Quote\Model\EstimateAddress or Magento\Catalog\Model\Category or Magento\Eav\Model\Entity...ibute\AbstractAttribute or Magento\Catalog\Model\ResourceModel\Eav\Attribute or Magento\Catalog\Model\Category\Attribute or Magento\Checkout\Model\ShippingInformation or Magento\Tax\Model\Calculation\Rule or Magento\Sales\Model\Order\Status\History or Magento\Store\Model\Group or Magento\Catalog\Model\Product\Option or Magento\Catalog\Model\Product\Gallery\Entry or Magento\Quote\Model\Quote\ProductOption or Magento\Tax\Model\Sales\Quote\ItemDetails or Magento\Tax\Model\TaxDetails\AppliedTax or Magento\Sales\Model\Order\Tax\Item or Magento\Bundle\Model\Option or Magento\Eav\Model\Entity\Attribute\Set or Magento\Quote\Model\Cart\Currency or Magento\Sales\Model\Order\Shipment\Comment or Magento\Catalog\Model\Product\Price\Cost or Magento\Quote\Model\Cart\Totals or Magento\Sales\Model\Order\Invoice\Item or Magento\Downloadable\Model\File\Content or Magento\Catalog\Model\ProductRender\PriceInfo or Magento\CatalogInventory\Model\Stock or Magento\Quote\Model\ShippingAssignment or Magento\Quote\Model\Quote\Payment or Magento\Checkout\Model\PaymentDetails or Magento\Catalog\Model\ProductRender\Image or Magento\Sales\Model\Order\Address or Magento\Tax\Model\TaxClass\Key or Magento\Sales\Model\Order\Creditmemo\Comment or Magento\Sales\Model\Order\Payment or Magento\Sales\Model\Order\Payment\Transaction or Magento\GiftMessage\Model\Message or Magento\Sales\Model\Order\Shipment\Item or Magento\Catalog\Model\Product\Price\TierPrice or Magento\Catalog\Model\Product\Attribute\Type or Magento\Tax\Model\TaxDetails\ItemDetails or Magento\Store\Model\Store or Magento\Catalog\Model\CustomOptions\CustomOption or Magento\Catalog\Model\Pr...nder\FormattedPriceInfo or Magento\Catalog\Model\ProductRender or Magento\Sales\Model\Order or Magento\Catalog\Model\Product\Option\Type or Magento\Quote\Model\Quote or Magento\Tax\Model\Calculation\Rate or Magento\Catalog\Model\Product\TierPrice or Magento\Tax\Model\Sales\Order\Details or Magento\Framework\Api\Te...erator\ExtensibleSample or Magento\Sales\Model\Order\Invoice\Comment or Magento\Sales\Model\Order\ShippingAssignment or Magento\Msrp\Model\ProductRender\MsrpPriceInfo or Magento\Sales\Model\Order\Item or Magento\Sales\Model\Order\Creditmemo or Magento\Sales\Model\Order\Invoice or Magento\Quote\Model\Shipping or Magento\Catalog\Model\Product\Price\BasePrice or Magento\Downloadable\Model\Sample or Magento\Eav\Model\Entity\Attribute\Group or Magento\Tax\Model\Sales\Order\Tax or Magento\Quote\Model\Cart\TotalSegment or Magento\Downloadable\Model\Link or Magento\CatalogInventory\Model\Stock\Item or Magento\Catalog\Model\Pr...Price\PriceUpdateResult or Magento\Tax\Model\Calculation\Rate\Title or Magento\Sales\Model\Order\Shipment or Magento\Catalog\Model\Product\Price\SpecialPrice or Magento\Tax\Model\ClassModel or Magento\Bundle\Model\Link or Magento\Bundle\Model\BundleOption or Magento\Tax\Model\TaxDetails\AppliedTaxRate or Magento\Bundle\Model\Source\Option\Type or Magento\Sales\Model\Order\Shipping or Magento\Quote\Model\Quote\Item or Magento\SalesRule\Model\Coupon or Magento\Tax\Model\TaxDetails\TaxDetails or Magento\Sales\Model\Order\ShippingTotal or Magento\Catalog\Model\ProductOption or Magento\Catalog\Model\ProductRender\Button. ( Ignorable by Annotation )

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

173
            if ($customer->/** @scrutinizer ignore-call */ getTaxvat()!='') {
Loading history...
174
                $orderUser->setDni($customer->getTaxvat());
175
                $orderBillingAddress->setDni($customer->getTaxvat());
176
                $orderShippingAddress->setDni($customer->getTaxvat());
177
            }
178
179
            $previousOrders = $this->getOrders($customer->getId());
0 ignored issues
show
Bug introduced by
The method getId() does not exist on Magento\Framework\Api\ExtensibleDataInterface. It seems like you code against a sub-type of Magento\Framework\Api\ExtensibleDataInterface such as Magento\Store\Api\Data\WebsiteInterface or Magento\Tax\Api\Data\TaxRuleInterface or Magento\Store\Api\Data\GroupInterface or Magento\Customer\Api\Data\GroupInterface or Magento\Catalog\Api\Data...iaGalleryEntryInterface or Magento\Directory\Api\Da...tryInformationInterface or Magento\Store\Api\Data\StoreInterface or Magento\Catalog\Api\Data\ProductRenderInterface or Magento\Quote\Api\Data\CartInterface or Magento\Store\Api\Data\StoreConfigInterface or Magento\Tax\Api\Data\TaxRateInterface or Magento\Downloadable\Api\Data\SampleInterface or Magento\Directory\Api\Da...ionInformationInterface or Magento\Downloadable\Api\Data\LinkInterface or Magento\Bundle\Api\Data\LinkInterface or Magento\Sales\Model\Order\Shipment\Track or Magento\CatalogInventory\Model\Stock\Status or Magento\Sales\Model\Order\Creditmemo\Item or Magento\Tax\Model\Sales\Quote\QuoteDetails or Magento\Catalog\Model\ProductLink\Link or Magento\Framework\Model\AbstractExtensibleModel or Magento\Catalog\Api\Data\ProductInterface or Magento\Quote\Api\Data\AddressInterface or Magento\Customer\Api\Data\CustomerInterface or Magento\Framework\Api\Search\DocumentInterface or Magento\Catalog\Api\Data\CategoryInterface or Magento\Customer\Api\Data\AddressInterface or Magento\CatalogRule\Model\Rule or Magento\Quote\Model\AddressAdditionalData or Magento\Quote\Model\Cart\TotalsAdditionalData or Magento\Checkout\Model\TotalsInformation or Magento\CatalogRule\Model\Data\Condition or Magento\Store\Model\Data\StoreConfig or Magento\Customer\Model\Data\Customer or Magento\Directory\Model\Data\RegionInformation or Magento\Customer\Model\Data\Group or Magento\Directory\Model\Data\CountryInformation or Magento\Customer\Model\Data\Address or Magento\Quote\Model\EstimateAddress or Magento\Eav\Model\Entity...ibute\AbstractAttribute or Magento\Catalog\Model\ResourceModel\Eav\Attribute or Magento\Catalog\Model\Category\Attribute or Magento\Checkout\Model\ShippingInformation or Magento\Sales\Model\Order\Status\History or Magento\Catalog\Model\Product\Option or Magento\Quote\Model\Quote\ProductOption or Magento\Tax\Model\Sales\Quote\ItemDetails or Magento\Tax\Model\TaxDetails\AppliedTax or Magento\Sales\Model\Order\Tax\Item or Magento\Bundle\Model\Option or Magento\Eav\Model\Entity\Attribute\Set or Magento\Quote\Model\Cart\Currency or Magento\Sales\Model\Order\Shipment\Comment or Magento\Catalog\Model\Product\Price\Cost or Magento\Quote\Model\Cart\Totals or Magento\Sales\Model\Order\Invoice\Item or Magento\Downloadable\Model\File\Content or Magento\Catalog\Model\ProductRender\PriceInfo or Magento\CatalogInventory\Model\Stock or Magento\Quote\Model\ShippingAssignment or Magento\Quote\Model\Quote\Payment or Magento\Checkout\Model\PaymentDetails or Magento\Catalog\Model\ProductRender\Image or Magento\Sales\Model\Order\Address or Magento\Tax\Model\TaxClass\Key or Magento\Sales\Model\Order\Creditmemo\Comment or Magento\Sales\Model\Order\Payment or Magento\Sales\Model\Order\Payment\Transaction or Magento\GiftMessage\Model\Message or Magento\Sales\Model\Order\Shipment\Item or Magento\Catalog\Model\Product\Price\TierPrice or Magento\Catalog\Model\Product\Attribute\Type or Magento\Tax\Model\TaxDetails\ItemDetails or Magento\Catalog\Model\CustomOptions\CustomOption or Magento\Catalog\Model\Pr...nder\FormattedPriceInfo or Magento\Sales\Model\Order or Magento\Catalog\Model\Product\Option\Type or Magento\Catalog\Model\Product\TierPrice or Magento\Tax\Model\Sales\Order\Details or Magento\Framework\Api\Te...erator\ExtensibleSample or Magento\Sales\Model\Order\Invoice\Comment or Magento\Sales\Model\Order\ShippingAssignment or Magento\Msrp\Model\ProductRender\MsrpPriceInfo or Magento\Sales\Model\Order\Item or Magento\Sales\Model\Order\Creditmemo or Magento\Sales\Model\Order\Invoice or Magento\Quote\Model\Shipping or Magento\Catalog\Model\Product\Price\BasePrice or Magento\Eav\Model\Entity\Attribute\Group or Magento\Tax\Model\Sales\Order\Tax or Magento\Quote\Model\Cart\TotalSegment or Magento\CatalogInventory\Model\Stock\Item or Magento\Catalog\Model\Pr...Price\PriceUpdateResult or Magento\Tax\Model\Calculation\Rate\Title or Magento\Sales\Model\Order\Shipment or Magento\Catalog\Model\Product\Price\SpecialPrice or Magento\Tax\Model\ClassModel or Magento\Bundle\Model\BundleOption or Magento\Tax\Model\TaxDetails\AppliedTaxRate or Magento\Bundle\Model\Source\Option\Type or Magento\Sales\Model\Order\Shipping or Magento\Quote\Model\Quote\Item or Magento\SalesRule\Model\Coupon or Magento\Tax\Model\TaxDetails\TaxDetails or Magento\Sales\Model\Order\ShippingTotal or Magento\Catalog\Model\ProductOption or Magento\Catalog\Model\ProductRender\Button. ( Ignorable by Annotation )

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

179
            $previousOrders = $this->getOrders($customer->/** @scrutinizer ignore-call */ getId());
Loading history...
180
            foreach ($previousOrders as $orderElement) {
181
                $orderHistory = new \Pagantis\OrdersApiClient\Model\Order\User\OrderHistory();
182
                $orderHistory
183
                    ->setAmount(intval(100 * $orderElement['grand_total']))
184
                    ->setDate(new \DateTime($orderElement['created_at']))
0 ignored issues
show
Bug introduced by
new DateTime($orderElement['created_at']) of type DateTime is incompatible with the type string expected by parameter $date of Pagantis\OrdersApiClient...OrderHistory::setDate(). ( Ignorable by Annotation )

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

184
                    ->setDate(/** @scrutinizer ignore-type */ new \DateTime($orderElement['created_at']))
Loading history...
185
                ;
186
                $orderUser->addOrderHistory($orderHistory);
187
            }
188
189
            $details = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details();
190
            $shippingCost = $quote->collectTotals()->getTotals()['shipping']->getData('value');
191
            $details->setShippingCost(intval(strval(100 * $shippingCost)));
192
            $items = $quote->getAllVisibleItems();
193
            foreach ($items as $key => $item) {
194
                $product = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details\Product();
195
                $product
196
                    ->setAmount(intval(100 * $item->getPrice()))
197
                    ->setQuantity($item->getQty())
198
                    ->setDescription($item->getName());
199
                $details->addProduct($product);
200
            }
201
202
            $orderShoppingCart = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart();
203
            $orderShoppingCart
204
                ->setDetails($details)
205
                ->setOrderReference($quote->getId())
206
                ->setPromotedAmount(0)
207
                ->setTotalAmount(intval(strval(100 * $quote->getGrandTotal())))
208
            ;
209
210
            $metadataOrder = new \Pagantis\OrdersApiClient\Model\Order\Metadata();
211
            $metadata = $this->getMetadata();
212
            foreach ($metadata as $key => $metadatum) {
213
                $metadataOrder->addMetadata($key, $metadatum);
214
            }
215
216
            $orderConfigurationUrls = new \Pagantis\OrdersApiClient\Model\Order\Configuration\Urls();
217
            $quoteId = $quote->getId();
218
            $okUrl = $this->_url->getUrl(
219
                'pagantis/notify/index',
220
                ['_query' => ['quoteId'=>$quoteId]]
221
            );
222
            if (version_compare($metadata['magento'], '2.3.0') >= 0) {
223
                $okUrl = $this->_url->getUrl('pagantis/notify/indexV2', ['_query' => ['quoteId'=>$quoteId]]);
224
            }
225
226
            $orderConfigurationUrls
227
                ->setCancel($cancelUrl)
228
                ->setKo($okUrl)
229
                ->setAuthorizedNotificationCallback($okUrl)
230
                ->setRejectedNotificationCallback($okUrl)
231
                ->setOk($okUrl)
232
            ;
233
234
            $orderChannel = new \Pagantis\OrdersApiClient\Model\Order\Configuration\Channel();
235
            $orderChannel
236
                ->setAssistedSale(false)
237
                ->setType(\Pagantis\OrdersApiClient\Model\Order\Configuration\Channel::ONLINE)
238
            ;
239
            $orderConfiguration = new \Pagantis\OrdersApiClient\Model\Order\Configuration();
240
            $orderConfiguration
241
                ->setChannel($orderChannel)
242
                ->setUrls($orderConfigurationUrls)
243
            ;
244
245
            $order = new \Pagantis\OrdersApiClient\Model\Order();
246
            $order
247
                ->setConfiguration($orderConfiguration)
248
                ->setMetadata($metadataOrder)
249
                ->setShoppingCart($orderShoppingCart)
250
                ->setUser($orderUser)
251
            ;
252
253
            if ($this->config['pagantis_public_key']=='' || $this->config['pagantis_private_key']=='') {
254
                throw new \Exception('Public and Secret Key not found');
255
            }
256
257
            $orderClient = new \Pagantis\OrdersApiClient\Client(
258
                $this->config['pagantis_public_key'],
259
                $this->config['pagantis_private_key']
260
            );
261
262
            $order = $orderClient->createOrder($order);
263
            if ($order instanceof \Pagantis\OrdersApiClient\Model\Order) {
0 ignored issues
show
introduced by
$order is always a sub-type of Pagantis\OrdersApiClient\Model\Order.
Loading history...
264
                $url = $order->getActionUrls()->getForm();
265
                $result = $this->insertRow($quote->getId(), $order->getId());
266
                if (!$result) {
267
                    throw new \Exception('Unable to save pagantis-order-id');
268
                }
269
            } else {
270
                throw new \Exception('Order not created');
271
            }
272
        } catch (\Exception $exception) {
273
            $this->insertLog($exception);
274
            echo $cancelUrl;
275
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
276
        }
277
278
        $displayMode = $this->extraConfig['PAGANTIS_FORM_DISPLAY_TYPE'];
279
        if ($displayMode==='0') {
280
            echo $url;
281
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
282
        } else {
283
            $iframeUrl = $this->_url->getUrl(
284
                "pagantis/Payment/iframe",
285
                ['_query' => ["orderId"=>$order->getId()]]
286
            );
287
            echo $iframeUrl;
288
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
289
        }
290
    }
291
292
    /**
293
     * Get the orders of a customer
294
     * @param $customerId
295
     *
296
     * @return array
297
     */
298
    private function getOrders($customerId)
299
    {
300
        $orderCollection = array();
301
        if ($customerId!='') {
302
            $this->orderCollection->addAttributeToFilter('customer_id', $customerId)
303
                            ->addAttributeToFilter(
304
                                'status',
305
                                ['in' => ['processing','pending','complete']]
306
                            )
307
                            ->load();
308
            $orderCollection = $this->orderCollection->getData();
309
        }
310
        return $orderCollection;
311
    }
312
313
    /**
314
     * @return void|\Zend_Db_Statement_Interface
315
     * @throws \Zend_Db_Exception
316
     */
317
    private function checkDbTable()
318
    {
319
        $dbConnection = $this->dbObject->getConnection();
320
        $tableName = $this->dbObject->getTableName(self::ORDERS_TABLE);
321
        if (!$dbConnection->isTableExists($tableName)) {
322
            $table = $dbConnection
323
                ->newTable($tableName)
324
                ->addColumn('id', Table::TYPE_SMALLINT, null, array('primary'=>true, 'nullable' => false))
325
                ->addColumn('order_id', Table::TYPE_TEXT, 50)
326
                ->addColumn('mg_order_id', Table::TYPE_TEXT, 50);
327
            return $dbConnection->createTable($table);
328
        }
329
330
        return;
331
    }
332
333
    /**
334
     * Create relationship between quote_id & Pagantis_order_id
335
     * @param $quoteId
336
     * @param $pagantisOrderId
337
     *
338
     * @return int
339
     * @throws \Zend_Db_Exception
340
     */
341
    private function insertRow($quoteId, $pagantisOrderId)
342
    {
343
        $this->checkDbTable();
344
        $dbConnection = $this->dbObject->getConnection();
345
        $tableName = $this->dbObject->getTableName(self::ORDERS_TABLE);
346
        return $dbConnection->insertOnDuplicate(
347
            $tableName,
348
            array('id'=>$quoteId,'order_id'=>$pagantisOrderId),
349
            array('order_id')
350
        );
351
    }
352
353
    /**
354
     * @return array
355
     */
356
    private function getMetadata()
357
    {
358
        $curlInfo = curl_version();
359
        $curlVersion = $curlInfo['version'];
360
        $magentoVersion = $this->productMetadataInterface->getVersion();
361
        $moduleInfo = $this->moduleList->getOne('Pagantis_Pagantis');
362
        return array(  'magento' => $magentoVersion,
363
                       'pagantis' => $moduleInfo['setup_version'],
364
                       'php' => phpversion(),
365
                       'curl' => $curlVersion);
366
    }
367
368
    /**
369
     * Check if log table exists, otherwise create it
370
     *
371
     * @return void|\Zend_Db_Statement_Interface
372
     * @throws \Zend_Db_Exception
373
     */
374
    private function checkDbLogTable()
375
    {
376
        /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
377
        $dbConnection = $this->dbObject->getConnection();
378
        $tableName = $this->dbObject->getTableName(self::LOGS_TABLE);
379
        if (!$dbConnection->isTableExists($tableName)) {
380
            $table = $dbConnection
381
                ->newTable($tableName)
382
                ->addColumn('id', Table::TYPE_SMALLINT, null, array('nullable'=>false, 'auto_increment'=>true, 'primary'=>true))
383
                ->addColumn('log', Table::TYPE_TEXT, null, array('nullable'=>false))
384
                ->addColumn('createdAt', Table::TYPE_TIMESTAMP, null, array('nullable'=>false, 'default'=>Table::TIMESTAMP_INIT));
385
            return $dbConnection->createTable($table);
386
        }
387
388
        return;
389
    }
390
391
    /**
392
     * @param $exceptionMessage
393
     *
394
     * @throws \Zend_Db_Exception
395
     */
396
    private function insertLog($exceptionMessage)
397
    {
398
        if ($exceptionMessage instanceof \Exception) {
399
            $this->checkDbLogTable();
400
            $logObject          = new \stdClass();
401
            $logObject->message = $exceptionMessage->getMessage();
402
            $logObject->code    = $exceptionMessage->getCode();
403
            $logObject->line    = $exceptionMessage->getLine();
404
            $logObject->file    = $exceptionMessage->getFile();
405
            $logObject->trace   = $exceptionMessage->getTraceAsString();
406
407
            /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
408
            $dbConnection = $this->dbObject->getConnection();
409
            $tableName    = $this->dbObject->getTableName(self::LOGS_TABLE);
410
            $dbConnection->insert($tableName, array('log' => json_encode($logObject)));
411
        }
412
    }
413
}
414