Completed
Push — master ( e78aa7...260413 )
by AJ
06:05
created

ShopifyAPIComponent::_urlEncode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
/**
3
 * CakePHPify : CakePHP Plugin for Shopify API Authentication
4
 * Copyright (c) Multidimension.al (http://multidimension.al)
5
 * Github : https://github.com/multidimension-al/cakephpify
6
 *
7
 * Licensed under The MIT License
8
 * For full copyright and license information, please see the LICENSE file
9
 * Redistributions of files must retain the above copyright notice.
10
 *
11
 * @copyright     (c) Multidimension.al (http://multidimension.al)
12
 * @link          https://github.com/multidimension-al/cakephpify CakePHPify Github
13
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
14
 */
15
16
namespace Multidimensional\Cakephpify\Controller\Component;
17
18
use Cake\Core\Configure;
19
use Cake\Controller\Component;
20
use Cake\Routing\Router;
21
use Cake\Network\Http\Client;
22
use Cake\Event\Event;
23
use Cake\Network\Exception\NotImplementedException;
24
25
class ShopifyAPIComponent extends Component
0 ignored issues
show
Coding Style introduced by
The property $api_key is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style introduced by
The property $shop_domain is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style introduced by
The property $shared_secret is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style introduced by
The property $is_private_app is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style introduced by
The property $private_app_password is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
26
{
27
28
    public $api_key;
0 ignored issues
show
Coding Style introduced by
$api_key does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
29
30
    private $shop_domain;
0 ignored issues
show
Coding Style introduced by
$shop_domain does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
31
    private $token;
32
    private $shared_secret;
0 ignored issues
show
Coding Style introduced by
$shared_secret does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
33
    private $is_private_app;
0 ignored issues
show
Coding Style introduced by
$is_private_app does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
34
    private $private_app_password;
0 ignored issues
show
Coding Style introduced by
$private_app_password does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
35
    private $nonce;
36
37
    public $controller = null;
38
39
    public function initialize(array $config = [])
40
    {
41
42
        parent::initialize($config);
43
44
        $this->api_key = isset($config['api_key']) ? $config['api_key'] : '';
45
46
        if (!empty($this->api_key)) {
47
            $this->shared_secret = Configure::read('Multidimensional/Cakephpify.' . $this->api_key . '.shared_secret');
48
            $this->scope = Configure::read('Multidimensional/Cakephpify.' . $this->api_key . '.scope');
0 ignored issues
show
Bug introduced by
The property scope does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
49
            $this->is_private_app = Configure::read('Multidimensional/Cakephpify.' . $this->api_key . '.is_private_app');
50
            $this->private_app_password = Configure::read('Multidimensional/Cakephpify.' . $this->api_key . '.private_app_password');
51
        } else {
52
            throw new NotImplementedException(__('Shopify API key not found'));
53
        }
54
55
        if (!$this->shared_secret) {
56
            throw new NotImplementedException(__('Shopify shared secret not found'));
57
        }
58
    }
59
60
    public function startup(Event $event)
61
    {
62
        $this->setController($event->subject());
63
    }
64
65
    public function setController($controller)
66
    {
67
        $this->controller = $controller;
68
        if (!isset($this->controller->paginate)) {
69
            $this->controller->paginate = [];
70
        }
71
    }
72
73
    public function setShopDomain($shopDomain)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
74
    {
75
        return $this->shop_domain = $shopDomain;
76
    }
77
78
    public function getShopDomain()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
79
    {
80
        return $this->shop_domain;
81
    }
82
83
    public function setAccessToken($token)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
84
    {
85
        return $this->token = $token;
86
    }
87
88
    public function callsMade()
89
    {
90
        return $this->shopApiCallLimitParam(0);
91
    }
92
93
    public function callLimit()
94
    {
95
        return $this->shopApiCallLimitParam(1);
96
    }
97
98
    public function callsLeft($responseHeaders)
0 ignored issues
show
Unused Code introduced by
The parameter $responseHeaders is not used and could be removed.

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

Loading history...
99
    {
100
        return $this->callLimit() - $this->callsMade();
101
    }
102
103
    /**
104
     * @param string $method
105
     * @param string $path
106
     */
107
    public function call($method, $path, $params = [])
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
108
    {
109
110
        if (!$this->_isReady()) {
111
            return false;
112
        }
113
114
        if (!in_array($method, ['POST', 'PUT', 'GET', 'DELETE'])) {
115
            return false;
116
        }
117
118
        $http = new Client([
119
            'host' => $this->shop_domain,
120
            'scheme' => 'https',
121
            'headers' => (($this->is_private_app != 'true') ? (['X-Shopify-Access-Token' => $this->token]) : []),
122
            'auth' => (($this->is_private_app != 'true') ? [] : (['username' => $this->api_key, 'password' => $this->private_app_password]))
123
        ]);
124
125
        $this->response = $http->{strtolower($method)}(
126
            $path,
127
            ((in_array($method, ['POST', 'PUT'])) ? json_encode($params) : $params),
128
            ((in_array($method, ['POST', 'PUT'])) ? ['type' => 'json'] : [])
129
        );
130
        $this->response = $this->response->json;
131
132
        return (is_array($this->response) && (count($this->response) > 0)) ? array_shift($this->response) : $this->response;
133
    }
134
135
    /**
136
     * @param int $index
137
     */
138
    private function shopApiCallLimitParam($index)
139
    {
140
        $params = explode("/", $this->response->getHeaderLine('http_x_shopify_shop_api_call_limit'));
0 ignored issues
show
Bug introduced by
The method getHeaderLine() does not exist on Cake\Network\Response. Did you maybe mean header()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
141
142
        return (int)$params[$index];
143
    }
144
145
    public function getAuthorizeUrl($shopDomain, $redirectUrl)
146
    {
147
148
        $url = 'https://' . $shopDomain . '/admin/oauth/authorize?client_id=' . $this->api_key;
149
        $url .= '&scope=' . urlencode($this->scope);
150
        $url .= '&redirect_uri=' . urlencode($redirectUrl);
151
        $url .= '&state=' . $this->getNonce($shopDomain);
0 ignored issues
show
Unused Code introduced by
The call to ShopifyAPIComponent::getNonce() has too many arguments starting with $shopDomain.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
152
153
        return $url;
154
    }
155
156
    public function getAccessToken($shopDomain, $code)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
157
    {
158
159
        $this->shop_domain = $shopDomain;
160
161
        $http = new Client([
162
            'host' => $shopDomain,
163
            'scheme' => 'https'
164
        ]);
165
166
        $response = $http->post('/admin/oauth/access_token', 'client_id=' . $this->api_key .
167
                                    '&client_secret=' . $this->shared_secret .
168
                                    '&code=' . $code);
169
        $response = $response->json;
170
        ;
171
172
        if (isset($response['access_token'])) {
173
            $this->token = $response['access_token'];
174
175
            return $this->token;
176
        } else {
177
            return false;
178
        }
179
    }
180
181
    public function setNonce($shopDomain)
182
    {
183
184
        return $this->nonce = md5(strtolower($shopDomain));
185
    }
186
187
188
    public function getNonce()
189
    {
190
191
        return $this->nonce;
192
    }
193
194
    public function validDomain($shopDomain)
0 ignored issues
show
Coding Style introduced by
function validDomain() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
Unused Code introduced by
The parameter $shopDomain is not used and could be removed.

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

Loading history...
195
    {
196
197
        return true;
198
    }
199
200
    public function getShopData()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
201
    {
202
203
        return $this->call('GET', '/admin/shop.json');
204
    }
205
206
    public function validateHMAC($query)
0 ignored issues
show
Coding Style introduced by
function validateHMAC() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
207
    {
208
209
        if (!is_array($query) || empty($query['hmac']) || !is_string($query['hmac']) || (isset($query['state']) && $query['state'] != $this->getNonce($query['shop']))) {
0 ignored issues
show
Unused Code introduced by
The call to ShopifyAPIComponent::getNonce() has too many arguments starting with $query['shop'].

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
210
            return false;
211
        }
212
213
        $dataString = [];
214
215
        foreach ($query as $key => $value) {
216
            $key = $this->_urlEncode(str_replace('=', '%3D', $key));
217
            $value = $this->_urlEncode($value);
218
            if ($key != 'hmac') {
219
                $dataString[] = $key . '=' . $value;
220
            }
221
        }
222
223
        sort($dataString);
224
        $string = implode("&", $dataString);
225
226
        return $query['hmac'] == hash_hmac('sha256', $string, $this->shared_secret);
227
    }
228
229
    /**
230
     * @param string $url
231
     */
232
    private function _urlEncode($url)
233
    {
234
235
        $url = str_replace('&', '%26', $url);
236
        $url = str_replace('%', '%25', $url);
237
238
        return $url;
239
    }
240
241
    private function _isReady()
0 ignored issues
show
Coding Style introduced by
function _isReady() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
242
    {
243
        return strlen($this->shop_domain) > 0 && strlen($this->token) > 0;
244
    }
245
}
246