AbstractShopify.php 11.1 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
        if (isset($config['api_password'])) {
            $this->httpHeaders['X-Shopify-Access-Token'] = $config['api_password'];
        } elseif (!isset($config['api_password'])) {
70
            throw new Exception("请设置api_password值");
71 72 73
        }
    }

74 75 76 77 78 79 80 81 82 83
    /**
     * 调用子集资源
     * @param $childName
     * @return mixed
     */
    public function __get($childName)
    {
        return $this->$childName();
    }

84 85 86 87 88
    /**
     * 调用自定义方法
     * @param $name
     * @param $arguments
     * @return mixed
89
     * @throws Exception
90 91 92
     */
    public function __call($name, $arguments)
    {
93 94 95 96 97 98 99 100 101
        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);
102
        } else {
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 133 134 135 136 137 138
            $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);
            }
139 140 141 142 143 144 145 146 147 148
        }
    }

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

    public function generateUrl($urlParams = [], $id = null, $customAction = null)
    {
149 150 151 152 153 154 155 156 157 158 159
        $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) : '');
160 161
    }

162 163 164 165 166 167 168 169 170 171 172 173 174 175
    /**
     * 获取数量
     * @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');
    }
176

177 178 179 180 181
    /**
     * @param array $urlParams
     * @param null $url
     * @param null $dataKey
     * @return mixed
182
     * @throws Exception
183 184 185 186
     */
    public function get($urlParams = [], $url = null, $dataKey = null)
    {
        if (!$url) $url = $this->generateUrl($urlParams);
187
        $response = $this->httpRequestJson->get($url, $this->httpHeaders);
188
        if (!$dataKey) $dataKey = $this->id ? $this->resourceKey : $this->pluralizeKey;
189 190 191
        return $this->processResponse($response, $dataKey);
    }

192 193 194
    /**
     * 分页
     * @param null $url
195 196
     * @param array $urlParams
     * @return mixed ['data' => [数据], 'next_link' => '下一页链接']
197 198
     * @throws Exception
     */
199
    public function page($url = null, $urlParams = [])
200
    {
201
        if (!$url) $url = $this->generateUrl($urlParams);
202
        $response = $this->httpRequestJson->get($url, $this->httpHeaders);
203 204 205
        return $this->processPageResponse($response, $this->pluralizeKey);
    }

206 207 208 209 210
    /**
     * 根据id获取一条数据
     * @param $id
     * @param array $urlParams
     * @return mixed
211
     * @throws Exception
212 213 214 215
     */
    public function show($id, $urlParams = [])
    {
        $url = $this->generateUrl($urlParams, $id);
216
        $response = $this->httpRequestJson->get($url, $this->httpHeaders);
217 218 219 220 221 222 223 224
        return $this->processResponse($response, $this->resourceKey);
    }

    /**
     * @param $dataArray
     * @param null $url
     * @param bool $wrapData
     * @return mixed
225
     * @throws Exception
226 227 228 229 230
     */
    public function post($dataArray, $url = null, $wrapData = true)
    {
        if (!$url) $url = $this->generateUrl();
        if ($wrapData && !empty($dataArray)) $dataArray = $this->wrapData($dataArray);
231
        $response = $this->httpRequestJson->post($url, $dataArray, $this->httpHeaders);
232 233 234 235 236 237 238 239 240
        return $this->processResponse($response, $this->resourceKey);
    }

    /**
     * @param int|string $id
     * @param $dataArray
     * @param null $url
     * @param bool $wrapData
     * @return mixed
241
     * @throws Exception
242 243 244 245 246
     */
    public function put($id, $dataArray, $url = null, $wrapData = true)
    {
        if (!$url) $url = $this->generateUrl([], $id);
        if ($wrapData && !empty($dataArray)) $dataArray = $this->wrapData($dataArray);
247
        $response = $this->httpRequestJson->put($url, $dataArray, $this->httpHeaders);
248 249 250 251 252 253 254 255
        return $this->processResponse($response, $this->resourceKey);
    }

    /**
     * @param int|string $id
     * @param array $urlParams
     * @param null $url
     * @return mixed
256
     * @throws Exception
257
     */
258
    public function delete($id = null, $urlParams = [], $url = null)
259 260
    {
        if (!$url) $url = $this->generateUrl($urlParams, $id);
261
        $response = $this->httpRequestJson->delete($url, $this->httpHeaders);
262 263 264 265 266 267
        return $this->processResponse($response);
    }

    protected function wrapData($dataArray, $dataKey = null)
    {
        if (!$dataKey) $dataKey = $this->resourceKey;
268
        return [$dataKey => $dataArray];
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
    }

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

    /**
     * 处理响应
286
     * @param array $response
287 288
     * @param null $dataKey
     * @return mixed
289
     * @throws Exception
290
     */
291 292
    public function processResponse($response, $dataKey = null)
    {
293
        [$code, , $content] = $response;
294 295 296 297 298 299 300 301 302 303
        $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;
        }
    }
304

305 306
    /**
     * 处理响应
307
     * @param ResponseInterface $response
308 309 310 311 312 313
     * @param null $dataKey
     * @return mixed
     * @throws Exception
     */
    public function processPageResponse($response, $dataKey = null)
    {
314
        [$code, $headers, $content] = $response;
315 316
        $content = json_decode($content, true);
        $link = $this->getLink($headers);
317 318 319 320 321 322 323 324 325 326 327 328 329
        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')
    {
330
        if (!empty($header['x-shopify-api-version'][0]) && $header['x-shopify-api-version'][0] < '2019-07') {
331 332
            return null;
        }
333 334
        if (!empty($header['link'][0])) {
            $headerLinks = $header['link'][0];
335 336
            if (stristr($headerLinks, '; rel="' . $type . '"') > -1) {
                $headerLinks = explode(',', $headerLinks);
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
                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;
    }

353
}