GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

PayPalPayment::executePayment()   B
last analyzed

Complexity

Conditions 6
Paths 27

Size

Total Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 33
rs 8.7697
c 0
b 0
f 0
cc 6
nc 27
nop 0
1
<?php
2
namespace app\components\payment;
3
4
use app\modules\shop\helpers\CurrencyHelper;
5
use app\modules\shop\helpers\PriceHelper;
6
use app\modules\shop\models\Currency;
7
use app\modules\shop\models\Order;
8
use app\modules\shop\models\OrderItem;
9
use app\modules\shop\models\OrderTransaction;
10
use app\modules\shop\models\Product;
11
use PayPal\Api\Amount;
12
use PayPal\Api\Details;
13
use PayPal\Api\Item;
14
use PayPal\Api\ItemList;
15
use PayPal\Api\Payer;
16
use PayPal\Api\Payment;
17
use PayPal\Api\PaymentExecution;
18
use PayPal\Api\RedirectUrls;
19
use PayPal\Api\Transaction;
20
use PayPal\Auth\OAuthTokenCredential;
21
use PayPal\Rest\ApiContext;
22
use yii\helpers\Url;
23
use yii\web\BadRequestHttpException;
24
25
class PayPalPayment extends AbstractPayment
26
{
27
    /**
28
     * @var string $clientId
29
     * @var string $clientSecret
30
     * @var bool $sandbox
31
     * @var Currency|string $currency
32
     */
33
    public $clientId = null;
34
    public $clientSecret = null;
35
    public $sandbox = false;
36
    public $currency = null;
37
    public $transactionDescription = '';
38
39
    private $apiContext = null;
40
41
    const STATE_APPROVED = 'approved';
42
43
    /**
44
     * @inheritdoc
45
     */
46
    public function init()
47
    {
48
        parent::init();
49
50
        $this->apiContext = new ApiContext(new OAuthTokenCredential($this->clientId, $this->clientSecret));
51
        $this->apiContext->setConfig([
52
            'mode' => true === $this->sandbox ? 'sandbox' : 'live',
53
            'log.LogEnabled' => false,
54
            'cache.enabled' => true,
55
            'cache.FileName' => \Yii::getAlias('@runtime/paypal.cache'),
56
        ]);
57
58
        if (false === $this->currency instanceof Currency) {
59
            $this->currency = CurrencyHelper::findCurrencyByIso($this->currency);
60
        }
61
    }
62
63
    /**
64
     * @inheritdoc
65
     */
66
    public function content()
67
    {
68
        /** @var Order $order */
69
        $order = $this->order;
70
        $order->calculate();
71
72
        $payer = (new Payer())->setPaymentMethod('paypal');
73
74
        $priceSubTotal = 0;
75
        /** @var ItemList $itemList */
76
        $itemList = array_reduce($order->items, function($result, $item) use (&$priceSubTotal) {
77
            /** @var OrderItem $item */
78
            /** @var Product $product */
79
            $product = $item->product;
80
            $price = CurrencyHelper::convertFromMainCurrency($item->price_per_pcs, $this->currency);
81
            $priceSubTotal = $priceSubTotal + ($price * $item->quantity);
82
83
            /** @var ItemList $result */
84
            return $result->addItem(
85
                (new Item())
86
                    ->setName($product->name)
87
                    ->setCurrency($this->currency->iso_code)
88
                    ->setPrice($price)
89
                    ->setQuantity($item->quantity)
90
                    ->setUrl(Url::toRoute([
91
                        '@product',
92
                        'model' => $product,
93
                        'category_group_id' => $product->category->category_group_id
94
                    ], true))
95
            );
96
        }, new ItemList());
97
98
        $priceTotal = CurrencyHelper::convertFromMainCurrency($order->total_price, $this->currency);
99
100
        $details = (new Details())
101
            ->setShipping($priceTotal - $priceSubTotal)
102
            ->setSubtotal($priceSubTotal)
103
            ->setTax(0);
104
105
        $amount = (new Amount())
106
            ->setCurrency($this->currency->iso_code)
107
            ->setTotal($priceTotal)
108
            ->setDetails($details);
109
110
        $transaction = (new Transaction())
111
            ->setAmount($amount)
112
            ->setItemList($itemList)
113
            ->setDescription($this->transactionDescription)
114
            ->setInvoiceNumber($this->transaction->id);
115
116
        $urls = (new RedirectUrls())
117
            ->setReturnUrl($this->createResultUrl(['id' => $this->order->payment_type_id]))
118
            ->setCancelUrl($this->createFailUrl());
119
120
        $payment = (new Payment())
121
            ->setIntent('sale')
122
            ->setPayer($payer)
123
            ->setTransactions([$transaction])
124
            ->setRedirectUrls($urls);
125
126
        $link = null;
127
        try {
128
            $link = $payment->create($this->apiContext)->getApprovalLink();
129
        } catch (\Exception $e) {
130
            $link = null;
131
        }
132
133
        return $this->render('paypal', [
134
            'order' => $order,
135
            'transaction' => $this->transaction,
136
            'approvalLink' => $link,
137
        ]);
138
    }
139
140
    /**
141
     * @inheritdoc
142
     * @throws BadRequestHttpException
143
     */
144
    public function checkResult($hash = '')
145
    {
146
        if (false === $this->executePayment()) {
147
            throw new BadRequestHttpException();
148
        }
149
150
        return $this->redirect(
151
            $this->createSuccessUrl()
152
        );
153
    }
154
155
    /**
156
     * @inheritdoc
157
     * @throws BadRequestHttpException
158
     */
159
    public function customCheck()
160
    {
161
        if (false === $this->executePayment()) {
162
            throw new BadRequestHttpException();
163
        }
164
165
        return $this->redirect(
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->redirect($...s->createSuccessUrl()); (yii\web\Response) is incompatible with the return type of the parent method app\components\payment\A...actPayment::customCheck of type string|null.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
166
            $this->createSuccessUrl()
167
        );
168
    }
169
170
    /**
171
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean|Payment?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
172
     */
173
    private function executePayment()
174
    {
175
        $result = false;
176
        try {
177
            $request = \Yii::$app->request;
178
179
            $result = Payment::get($request->get('paymentId'), $this->apiContext)
180
                ->execute(
181
                    (new PaymentExecution())->setPayerId($request->get('PayerID')),
182
                    $this->apiContext
183
                );
184
185
            $status = static::STATE_APPROVED === $result->getState()
186
                ? OrderTransaction::TRANSACTION_SUCCESS
187
                : OrderTransaction::TRANSACTION_ERROR;
188
189
            $detail = Payment::get($request->get('paymentId'), $this->apiContext);
190
191
            foreach ($detail->getTransactions() as $transaction) {
192
                /** @var Transaction $transaction */
193
                if (null !== $orderTransaction = OrderTransaction::findOne(['id' => $transaction->getInvoiceNumber()])) {
194
                    /** @var OrderTransaction $orderTransaction */
195
                    $orderTransaction->updateStatus($status);
196
                    $this->transaction = $orderTransaction;
197
198
                    $result = OrderTransaction::TRANSACTION_SUCCESS === $status ? true : false;
199
                }
200
            }
201
        } catch (\Exception $e) {
202
        }
203
204
        return $result;
205
    }
206
}
207