AbstractShopify.php 11.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
<?php
/**
 * Created by PhpStorm.
 * User: Zero
 * Date: 2020/8/18
 * Time: 8:18
 */

namespace Meibuyu\Micro\Shopify\lib;

11
use Exception;
12 13
use Meibuyu\Micro\Shopify\tools\CurlHttpRequestJson;
use Meibuyu\Micro\Shopify\tools\HttpRequestJson;
14 15 16 17 18
use Psr\Http\Message\ResponseInterface;

abstract class AbstractShopify
{

19 20 21 22 23 24
    /**
     * 资源id
     * @var int
     */
    public $id = null;

25 26 27 28 29 30 31 32 33 34 35 36
    protected $httpHeaders = [];

    protected $resourceUrl;
    protected $resourceKey;
    protected $pluralizeKey;

    /**
     * 无count方法
     * @var boolean
     */
    public $countEnabled = true;

37 38 39 40
    // 子集资源
    protected $childResource = [];

    // 自定义请求方法
41 42 43 44 45
    protected $customGetActions = [];
    protected $customPostActions = [];
    protected $customPutActions = [];
    protected $customDeleteActions = [];

46 47
    private $config;

48
    /**
49
     * @var HttpRequestJson|CurlHttpRequestJson
50 51 52
     */
    private $httpRequestJson;

53 54 55
    /**
     * AbstractShopify constructor.
     * @param $config
56 57 58
     * @param null $id
     * @param string $parentResourceUrl
     * @throws Exception
59
     */
60
    public function __construct($config, $id = null, $parentResourceUrl = null)
61
    {
62 63
        $this->config = $config;
        $this->id = $id;
64
        $this->pluralizeKey = $this->pluralizeKey ?: $this->resourceKey . 's';
65
        $this->resourceUrl = ($parentResourceUrl ? "$parentResourceUrl/" : $config['api_url']) . $this->pluralizeKey . ($this->id ? "/{$this->id}" : '');
66
        $this->httpRequestJson = make(CurlHttpRequestJson::class);
67 68 69 70 71 72 73 74 75 76 77 78 79
        if (isset($config['is_private_app']) && $config['is_private_app'] == false) {
            // 如果不是私人应用,则使用访问令牌
            if (isset($config['access_token'])) {
                $this->httpHeaders['X-Shopify-Access-Token'] = $config['access_token'];
            } elseif (!isset($config['access_token'])) {
                throw new Exception("请设置access_token值");
            }
        } else {
            if (isset($config['api_password'])) {
                $this->httpHeaders['X-Shopify-Access-Token'] = $config['api_password'];
            } elseif (!isset($config['api_password'])) {
                throw new Exception("请设置api_password值");
            }
80 81 82
        }
    }

83 84 85 86 87 88 89 90 91 92
    /**
     * 调用子集资源
     * @param $childName
     * @return mixed
     */
    public function __get($childName)
    {
        return $this->$childName();
    }

93 94 95 96 97
    /**
     * 调用自定义方法
     * @param $name
     * @param $arguments
     * @return mixed
98
     * @throws Exception
99 100 101
     */
    public function __call($name, $arguments)
    {
102 103 104 105 106 107 108 109 110
        if (ctype_upper($name[0])) {
            $childKey = array_search($name, $this->childResource);
            if ($childKey === false) {
                throw new Exception(" $name 不属于 {$this->getResourceName()}");
            }
            $childClassName = !is_numeric($childKey) ? $childKey : $name;
            $childClass = __NAMESPACE__ . "\\" . $childClassName;
            $resourceID = !empty($arguments) ? $arguments[0] : null;
            return new $childClass($this->config, $resourceID, $this->resourceUrl);
111
        } else {
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
            $actionMaps = [
                'post' => 'customPostActions',
                'put' => 'customPutActions',
                'get' => 'customGetActions',
                'delete' => 'customDeleteActions',
            ];
            //Get the array key for the action in the actions array
            foreach ($actionMaps as $httpMethod => $actionArrayKey) {
                $actionKey = array_search($name, $this->$actionArrayKey);
                if ($actionKey !== false) break;
            }
            if ($actionKey === false) {
                throw new Exception("No action named $name is defined for " . $this->getResourceName());
            }
            //If any associative key is given to the action, then it will be considered as the method name,
            //otherwise the action name will be the method name
            $customAction = !is_numeric($actionKey) ? $actionKey : $name;
            //Get the first argument if provided with the method call
            $methodArgument = !empty($arguments) ? $arguments[0] : [];
            //Url parameters
            $urlParams = [];
            //Data body
            $dataArray = [];
            //Consider the argument as url parameters for get and delete request
            //and data array for post and put request
            if ($httpMethod == 'post' || $httpMethod == 'put') {
                $dataArray = $methodArgument;
            } else {
                $urlParams = $methodArgument;
            }
            $url = $this->generateUrl($urlParams, null, $customAction);
            if ($httpMethod == 'post' || $httpMethod == 'put') {
                return $this->$httpMethod($dataArray, $url, false);
            } else {
                return $this->$httpMethod($dataArray, $url);
            }
148 149 150 151 152 153 154 155 156 157
        }
    }

    private function getResourceName()
    {
        return substr(get_called_class(), strrpos(get_called_class(), '\\') + 1);
    }

    public function generateUrl($urlParams = [], $id = null, $customAction = null)
    {
158 159 160 161 162 163 164 165 166 167 168
        $resourceUrl = $this->resourceUrl;
        if ($id) {
            if ($this->id) {
                if ($id !== $this->id) {
                    $resourceUrl = str_replace($this->id, $id, $this->resourceUrl);
                }
            } else {
                $resourceUrl = $this->resourceUrl . "/$id";
            }
        }
        return $resourceUrl . ($customAction ? "/$customAction" : '') . '.json' . (!empty($urlParams) ? '?' . http_build_query($urlParams) : '');
169 170
    }

171 172 173 174 175 176 177 178 179 180 181 182 183 184
    /**
     * 获取数量
     * @param array $urlParams
     * @return mixed
     * @throws Exception
     */
    public function count($urlParams = [])
    {
        if (!$this->countEnabled) {
            throw new Exception("当前类{$this->getResourceName()}不支持count()方法");
        }
        $url = $this->generateUrl($urlParams, null, 'count');
        return $this->get([], $url, 'count');
    }
185

186 187 188 189 190
    /**
     * @param array $urlParams
     * @param null $url
     * @param null $dataKey
     * @return mixed
191
     * @throws Exception
192 193 194 195
     */
    public function get($urlParams = [], $url = null, $dataKey = null)
    {
        if (!$url) $url = $this->generateUrl($urlParams);
196
        $response = $this->httpRequestJson->get($url, $this->httpHeaders);
197
        if (!$dataKey) $dataKey = $this->id ? $this->resourceKey : $this->pluralizeKey;
198 199 200
        return $this->processResponse($response, $dataKey);
    }

201 202 203
    /**
     * 分页
     * @param null $url
204 205
     * @param array $urlParams
     * @return mixed ['data' => [数据], 'next_link' => '下一页链接']
206 207
     * @throws Exception
     */
208
    public function page($url = null, $urlParams = [])
209
    {
210
        if (!$url) $url = $this->generateUrl($urlParams);
211
        $response = $this->httpRequestJson->get($url, $this->httpHeaders);
212 213 214
        return $this->processPageResponse($response, $this->pluralizeKey);
    }

215 216 217 218 219
    /**
     * 根据id获取一条数据
     * @param $id
     * @param array $urlParams
     * @return mixed
220
     * @throws Exception
221 222 223 224
     */
    public function show($id, $urlParams = [])
    {
        $url = $this->generateUrl($urlParams, $id);
225
        $response = $this->httpRequestJson->get($url, $this->httpHeaders);
226 227 228 229 230 231 232 233
        return $this->processResponse($response, $this->resourceKey);
    }

    /**
     * @param $dataArray
     * @param null $url
     * @param bool $wrapData
     * @return mixed
234
     * @throws Exception
235 236 237 238 239
     */
    public function post($dataArray, $url = null, $wrapData = true)
    {
        if (!$url) $url = $this->generateUrl();
        if ($wrapData && !empty($dataArray)) $dataArray = $this->wrapData($dataArray);
240
        $response = $this->httpRequestJson->post($url, $dataArray, $this->httpHeaders);
241 242 243 244 245 246 247 248 249
        return $this->processResponse($response, $this->resourceKey);
    }

    /**
     * @param int|string $id
     * @param $dataArray
     * @param null $url
     * @param bool $wrapData
     * @return mixed
250
     * @throws Exception
251 252 253 254 255
     */
    public function put($id, $dataArray, $url = null, $wrapData = true)
    {
        if (!$url) $url = $this->generateUrl([], $id);
        if ($wrapData && !empty($dataArray)) $dataArray = $this->wrapData($dataArray);
256
        $response = $this->httpRequestJson->put($url, $dataArray, $this->httpHeaders);
257 258 259 260 261 262 263 264
        return $this->processResponse($response, $this->resourceKey);
    }

    /**
     * @param int|string $id
     * @param array $urlParams
     * @param null $url
     * @return mixed
265
     * @throws Exception
266
     */
267
    public function delete($id = null, $urlParams = [], $url = null)
268 269
    {
        if (!$url) $url = $this->generateUrl($urlParams, $id);
270
        $response = $this->httpRequestJson->delete($url, $this->httpHeaders);
271 272 273 274 275 276
        return $this->processResponse($response);
    }

    protected function wrapData($dataArray, $dataKey = null)
    {
        if (!$dataKey) $dataKey = $this->resourceKey;
277
        return [$dataKey => $dataArray];
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
    }

    protected function castString($array)
    {
        if (!is_array($array)) return (string)$array;
        $string = '';
        $i = 0;
        foreach ($array as $key => $val) {
            $string .= ($i === $key ? '' : "$key - ") . $this->castString($val) . ', ';
            $i++;
        }
        $string = rtrim($string, ', ');
        return $string;
    }

    /**
     * 处理响应
295
     * @param array $response
296 297
     * @param null $dataKey
     * @return mixed
298
     * @throws Exception
299
     */
300 301
    public function processResponse($response, $dataKey = null)
    {
302
        [$code, , $content] = $response;
303 304 305 306 307 308 309 310 311 312
        $content = json_decode($content, true);
        if (isset($content['errors'])) {
            throw new Exception($this->castString($content['errors']), $code);
        }
        if ($dataKey && isset($content[$dataKey])) {
            return $content[$dataKey];
        } else {
            return $content;
        }
    }
313

314 315
    /**
     * 处理响应
316
     * @param ResponseInterface $response
317 318 319 320 321 322
     * @param null $dataKey
     * @return mixed
     * @throws Exception
     */
    public function processPageResponse($response, $dataKey = null)
    {
323
        [$code, $headers, $content] = $response;
324 325
        $content = json_decode($content, true);
        $link = $this->getLink($headers);
326 327 328 329 330 331 332 333 334 335 336 337 338
        if (isset($content['errors'])) {
            throw new Exception($this->castString($content['errors']), $code);
        }
        if ($dataKey && isset($content[$dataKey])) {
            $data = $content[$dataKey];
        } else {
            $data = $content;
        }
        return ['data' => $data, 'next_link' => $link];
    }

    public function getLink($header, $type = 'next')
    {
339
        if (!empty($header['x-shopify-api-version'][0]) && $header['x-shopify-api-version'][0] < '2019-07') {
340 341
            return null;
        }
342 343
        if (!empty($header['link'][0])) {
            $headerLinks = $header['link'][0];
344 345
            if (stristr($headerLinks, '; rel="' . $type . '"') > -1) {
                $headerLinks = explode(',', $headerLinks);
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
                foreach ($headerLinks as $headerLink) {
                    if (stristr($headerLink, '; rel="' . $type . '"') === -1) {
                        continue;
                    }

                    $pattern = '#<(.*?)>; rel="' . $type . '"#m';
                    preg_match($pattern, $headerLink, $linkResponseHeaders);
                    if ($linkResponseHeaders) {
                        return $linkResponseHeaders[1];
                    }
                }
            }
        }
        return null;
    }

362
}