AbstractShopify.php 13.9 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 14 15 16 17
use Meibuyu\Micro\Tools\HttpRequestJson;
use Psr\Http\Message\ResponseInterface;

abstract class AbstractShopify
{

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

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

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

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

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

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

45 46
    private $config;

47 48 49
    /**
     * AbstractShopify constructor.
     * @param $config
50 51 52
     * @param null $id
     * @param string $parentResourceUrl
     * @throws Exception
53
     */
54
    public function __construct($config, $id = null, $parentResourceUrl = null)
55
    {
56 57
        $this->config = $config;
        $this->id = $id;
58
        $this->pluralizeKey = $this->pluralizeKey ?: $this->resourceKey . 's';
59
        $this->resourceUrl = ($parentResourceUrl ? "$parentResourceUrl/" : $config['api_url']) . $this->pluralizeKey . ($this->id ? "/{$this->id}" : '');
60 61 62 63

        if (isset($config['api_password'])) {
            $this->httpHeaders['X-Shopify-Access-Token'] = $config['api_password'];
        } elseif (!isset($config['api_password'])) {
64
            throw new Exception("请设置api_password值");
65 66 67
        }
    }

68 69 70 71 72 73 74 75 76 77
    /**
     * 调用子集资源
     * @param $childName
     * @return mixed
     */
    public function __get($childName)
    {
        return $this->$childName();
    }

78 79 80 81 82
    /**
     * 调用自定义方法
     * @param $name
     * @param $arguments
     * @return mixed
83
     * @throws Exception
84 85 86
     */
    public function __call($name, $arguments)
    {
87 88 89 90 91 92 93 94 95
        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);
96
        } else {
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
            $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);
            }
133 134 135 136 137 138 139 140 141 142
        }
    }

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

    public function generateUrl($urlParams = [], $id = null, $customAction = null)
    {
143 144 145 146 147 148 149 150 151 152 153
        $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) : '');
154 155
    }

156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
//    /**
//     * @param array $urlParams
//     * @param null $url
//     * @param null $dataKey
//     * @return mixed
//     * @throws Exception
//     */
//    public function get($urlParams = [], $url = null, $dataKey = null)
//    {
//        if (!$url) $url = $this->generateUrl($urlParams);
//        $response = HttpRequestJson::get($url, $this->httpHeaders);
//        if (!$dataKey) $dataKey = $this->id ? $this->resourceKey : $this->pluralizeKey;
//        return $this->processResponse($response, $dataKey);
//    }
//
//    /**
//     * 根据id获取一条数据
//     * @param $id
//     * @param array $urlParams
//     * @return mixed
//     * @throws Exception
//     */
//    public function show($id, $urlParams = [])
//    {
//        $url = $this->generateUrl($urlParams, $id);
//        $response = HttpRequestJson::get($url, $this->httpHeaders);
//        return $this->processResponse($response, $this->resourceKey);
//    }
//
//    /**
//     * 获取数量
//     * @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');
//    }
//
//    /**
//     * @param $dataArray
//     * @param null $url
//     * @param bool $wrapData
//     * @return mixed
//     * @throws Exception
//     */
//    public function post($dataArray, $url = null, $wrapData = true)
//    {
//        if (!$url) $url = $this->generateUrl();
//        if ($wrapData && !empty($dataArray)) $dataArray = $this->wrapData($dataArray);
//        $response = HttpRequestJson::post($url, $dataArray, $this->httpHeaders);
//        return $this->processResponse($response, $this->resourceKey);
//    }
//
//    /**
//     * @param int|string $id
//     * @param $dataArray
//     * @param null $url
//     * @param bool $wrapData
//     * @return mixed
//     * @throws Exception
//     */
//    public function put($id, $dataArray, $url = null, $wrapData = true)
//    {
//        if (!$url) $url = $this->generateUrl([], $id);
//        if ($wrapData && !empty($dataArray)) $dataArray = $this->wrapData($dataArray);
//        $response = HttpRequestJson::put($url, $dataArray, $this->httpHeaders);
//        return $this->processResponse($response, $this->resourceKey);
//    }
//
//    /**
//     * @param int|string $id
//     * @param array $urlParams
//     * @param null $url
//     * @return mixed
//     * @throws Exception
//     */
//    public function delete($id = null, $urlParams = [], $url = null)
//    {
//        if (!$url) $url = $this->generateUrl($urlParams, $id);
//        $response = HttpRequestJson::delete($url, $this->httpHeaders);
//        return $this->processResponse($response);
//    }

245 246 247 248 249
    /**
     * @param array $urlParams
     * @param null $url
     * @param null $dataKey
     * @return mixed
250
     * @throws Exception
251 252 253 254 255
     */
    public function get($urlParams = [], $url = null, $dataKey = null)
    {
        if (!$url) $url = $this->generateUrl($urlParams);
        $response = HttpRequestJson::get($url, $this->httpHeaders);
256
        if (!$dataKey) $dataKey = $this->id ? $this->resourceKey : $this->pluralizeKey;
257 258 259
        return $this->processResponse($response, $dataKey);
    }

260 261 262
    /**
     * 分页
     * @param null $url
263 264
     * @param array $urlParams
     * @return mixed ['data' => [数据], 'next_link' => '下一页链接']
265 266
     * @throws Exception
     */
267
    public function page($url = null, $urlParams = [])
268
    {
269
        if (!$url) $url = $this->generateUrl($urlParams);
270 271 272 273
        $response = HttpRequestJson::get($url, $this->httpHeaders);
        return $this->processPageResponse($response, $this->pluralizeKey);
    }

274 275 276 277 278
    /**
     * 根据id获取一条数据
     * @param $id
     * @param array $urlParams
     * @return mixed
279
     * @throws Exception
280 281 282 283 284 285 286 287 288 289 290 291 292
     */
    public function show($id, $urlParams = [])
    {
        $url = $this->generateUrl($urlParams, $id);
        $response = HttpRequestJson::get($url, $this->httpHeaders);
        return $this->processResponse($response, $this->resourceKey);
    }

    /**
     * @param $dataArray
     * @param null $url
     * @param bool $wrapData
     * @return mixed
293
     * @throws Exception
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
     */
    public function post($dataArray, $url = null, $wrapData = true)
    {
        if (!$url) $url = $this->generateUrl();
        if ($wrapData && !empty($dataArray)) $dataArray = $this->wrapData($dataArray);
        $response = HttpRequestJson::post($url, $dataArray, $this->httpHeaders);
        return $this->processResponse($response, $this->resourceKey);
    }

    /**
     * @param int|string $id
     * @param $dataArray
     * @param null $url
     * @param bool $wrapData
     * @return mixed
309
     * @throws Exception
310 311 312 313 314 315 316 317 318 319 320 321 322 323
     */
    public function put($id, $dataArray, $url = null, $wrapData = true)
    {
        if (!$url) $url = $this->generateUrl([], $id);
        if ($wrapData && !empty($dataArray)) $dataArray = $this->wrapData($dataArray);
        $response = HttpRequestJson::put($url, $dataArray, $this->httpHeaders);
        return $this->processResponse($response, $this->resourceKey);
    }

    /**
     * @param int|string $id
     * @param array $urlParams
     * @param null $url
     * @return mixed
324
     * @throws Exception
325
     */
326
    public function delete($id = null, $urlParams = [], $url = null)
327 328 329 330 331 332 333 334 335
    {
        if (!$url) $url = $this->generateUrl($urlParams, $id);
        $response = HttpRequestJson::delete($url, $this->httpHeaders);
        return $this->processResponse($response);
    }

    protected function wrapData($dataArray, $dataKey = null)
    {
        if (!$dataKey) $dataKey = $this->resourceKey;
336
        return [$dataKey => $dataArray];
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
    }

    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;
    }

    /**
     * 处理响应
     * @param ResponseInterface $response
     * @param null $dataKey
     * @return mixed
357
     * @throws Exception
358
     */
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
//    public function processResponse($response, $dataKey = null)
//    {
//        $httpCode = $response->getStatusCode();
//        $content = $response->getBody()->getContents();
//        $content = json_decode($content, true);
//
//        if (isset($content['errors'])) {
//            throw new Exception($this->castString($content['errors']), $httpCode);
//        }
//        if ($dataKey && isset($content[$dataKey])) {
//            return $content[$dataKey];
//        } else {
//            return $content;
//        }
//    }

    /**
     * 处理响应
     * @param array $response
     * @param null $dataKey
     * @return mixed
     * @throws Exception
     */
382 383
    public function processResponse($response, $dataKey = null)
    {
384 385
        [$code, $header, $body] = $response;
        $content = json_decode($body, true);
386 387

        if (isset($content['errors'])) {
388
            throw new Exception($this->castString($content['errors']), $code);
389 390 391 392 393 394 395 396
        }
        if ($dataKey && isset($content[$dataKey])) {
            return $content[$dataKey];
        } else {
            return $content;
        }
    }

397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
    /**
     * 处理响应
     * @param array $response
     * @param null $dataKey
     * @return mixed
     * @throws Exception
     */
    public function processPageResponse($response, $dataKey = null)
    {
        [$code, $header, $body] = $response;
        $content = json_decode($body, true);

        $link = $this->getLink($header);

        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')
    {
        if (array_key_exists('x-shopify-api-version', $header) && $header['x-shopify-api-version'] < '2019-07') {
            return null;
        }
        if (!empty($header['link'])) {
            if (stristr($header['link'], '; rel="' . $type . '"') > -1) {
                $headerLinks = explode(',', $header['link']);
                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;
    }

446
}