Commit b240a5a6 authored by 王源's avatar 王源 🎧

Merge branch 'test'

parents 917a98c4 f3469ff9
...@@ -19,6 +19,7 @@ class ConfigProvider ...@@ -19,6 +19,7 @@ class ConfigProvider
'http' => [ 'http' => [
\Meibuyu\Micro\Exceptions\Handler\MicroExceptionHandler::class, \Meibuyu\Micro\Exceptions\Handler\MicroExceptionHandler::class,
\Meibuyu\Micro\Exceptions\Handler\QueryExceptionHandler::class, \Meibuyu\Micro\Exceptions\Handler\QueryExceptionHandler::class,
\Meibuyu\Micro\Exceptions\Handler\PhpSpreadsheetExceptionHandler::class,
\Meibuyu\Micro\Exceptions\Handler\AppExceptionHandler::class, \Meibuyu\Micro\Exceptions\Handler\AppExceptionHandler::class,
], ],
], ],
......
...@@ -9,7 +9,6 @@ ...@@ -9,7 +9,6 @@
namespace Meibuyu\Micro\Exceptions\Handler; namespace Meibuyu\Micro\Exceptions\Handler;
use Hyperf\ExceptionHandler\ExceptionHandler; use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream; use Hyperf\HttpMessage\Stream\SwooleStream;
use Meibuyu\Micro\Exceptions\HttpResponseException; use Meibuyu\Micro\Exceptions\HttpResponseException;
...@@ -53,4 +52,5 @@ class MicroExceptionHandler extends ExceptionHandler ...@@ -53,4 +52,5 @@ class MicroExceptionHandler extends ExceptionHandler
{ {
return true; return true;
} }
} }
<?php
/**
* Created by PhpStorm.
* User: Zero
* Date: 2020/8/24
* Time: 18:05
*/
namespace Meibuyu\Micro\Exceptions\Handler;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use Psr\Http\Message\ResponseInterface;
use Throwable;
class PhpSpreadsheetExceptionHandler extends ExceptionHandler
{
public function handle(Throwable $throwable, ResponseInterface $response)
{
$error = $throwable->getMessage();
if ($throwable instanceof PhpSpreadsheetException) {
if (strpos($error, 'Formula Error') !== false) {
$msg = '表格公式错误, 请检查是否引用其它表格数据';
return $this->jsonResponse($msg, $response);
}
} else if (strpos($error, 'PhpOffice\PhpSpreadsheet\Writer\Xls::writeSummaryProp()') !== false) {
$msg = '表格格式兼容错误,请上传 xlsx 结尾的excel';
return $this->jsonResponse($msg, $response);
}
return $response;
}
public function jsonResponse($msg, ResponseInterface $response)
{
// 阻止异常冒泡
$this->stopPropagation();
// 格式化输出
$data = json_encode([
'code' => 400,
'msg' => $msg,
], JSON_UNESCAPED_UNICODE);
return $response->withAddedHeader('content-type', 'application/json')->withBody(new SwooleStream($data));
}
public function isValid(Throwable $throwable): bool
{
return true;
}
}
...@@ -42,4 +42,5 @@ class QueryExceptionHandler extends ExceptionHandler ...@@ -42,4 +42,5 @@ class QueryExceptionHandler extends ExceptionHandler
{ {
return $throwable instanceof QueryException; return $throwable instanceof QueryException;
} }
} }
...@@ -81,6 +81,22 @@ class MessageHandler ...@@ -81,6 +81,22 @@ class MessageHandler
$this->messageService->send($receiverIds, $application, $templateId, 0, $replace); $this->messageService->send($receiverIds, $application, $templateId, 0, $replace);
} }
/**
* 自动发送文本消息
* @param $receiverIds
* @param $content
* @throws \Exception
*/
public function sendAutoText($receiverIds, $content)
{
$application = $this->config->get('app_name');
if (!$application) {
throw new \Exception("请设置应用名app_name");
}
$receiverIds = is_array($receiverIds) ? $receiverIds : [$receiverIds];
$this->messageService->send($receiverIds, $application, 0, 0, [], $content);
}
/** /**
* 定时任务专用 发送文本消息 * 定时任务专用 发送文本消息
* @param $receiverIds * @param $receiverIds
......
...@@ -118,6 +118,50 @@ class UploadManager ...@@ -118,6 +118,50 @@ class UploadManager
} }
} }
/**
* 文件上传方法(micro-api-flow)
* @param UploadedFile $file 上传的文件
* @param array $options 配置参数
* @param bool $realPath
* @return string
* @throws HttpResponseException
*/
public static function uploadFileGetName($file, $options = [], $realPath = false)
{
$documentRoot = config('server.settings.document_root');
if (!$documentRoot) {
throw new \RuntimeException('未配置静态资源');
}
$options = self::parseOptions($options);
if ($file->isValid()) {
$extension = strtolower($file->getExtension());
// 通过扩展名判断类型
if (!in_array($extension, $options['mime'])) {
throw new HttpResponseException('文件类型不支持,目前只支持' . implode(',', $options['mime']));
}
// 判断文件大小
if ($file->getSize() > $options['maxSize']) {
throw new HttpResponseException('文件超出系统规定的大小,最大不能超过' . num_2_file_size($options['maxSize']));
}
// 文件重命名,由当前日期时间 + 唯一ID + 扩展名
$fileName = date('YmdHis') . uniqid() . '.' . $extension;
$name = $file->toArray()['name'];
$savePath = self::parsePath($options, $documentRoot) . $fileName;
$file->moveTo($savePath);
if ($file->isMoved()) {
if ($realPath) {
return $savePath.'?'.$name;
} else {
return str_replace($documentRoot, '', $savePath.'?'.$name);
}
} else {
throw new HttpResponseException('文件保存失败');
}
} else {
throw new HttpResponseException('文件无效');
}
}
/** /**
* 生成头像 * 生成头像
* @return string|string[] * @return string|string[]
......
<?php
/**
* Created by PhpStorm.
* User: Zero
* Date: 2020/8/24
* Time: 9:33
*/
namespace Meibuyu\Micro\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
class CheckWebhookMiddleware implements MiddlewareInterface
{
/**
* @inheritDoc
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$domain = $request->getHeader('x-shopify-shop-domain')[0] ?? null;
$topic = $request->getHeader('x-shopify-topic')[0] ?? null;
if ($domain && $topic) {
return $handler->handle($request);
} else {
return response()->withStatus(500);
}
}
}
<?php
namespace Meibuyu\Micro\Service\Interfaces\Flow;
interface ProcessFormServiceInterface
{
/**
* 创建流程申请
* @param $processId 流程id
* @param $url 表单图片地址
* @param $data 表单详细内容
* @return mixed
*/
public function createProcessForm($processId,$url,$data);
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: 姜克保
* Date: 2020/5/20
* Time: 15:48
*/
namespace Meibuyu\Micro\Service\Interfaces\Order;
interface ShopifyServiceInterface
{
/**
* shopify 推送订单信息
* @param string $topic 动作
* @param array $array 订单信息
* @param array $shopifySite 站点信息
* @return mixed
*/
public function pushOrder($topic, array $array = [], array $shopifySite = []);
}
...@@ -24,7 +24,7 @@ interface PlatformProductChildServiceInterface ...@@ -24,7 +24,7 @@ interface PlatformProductChildServiceInterface
/** /**
* 通过id列表获取平台子产品数组 * 通过id列表获取平台子产品数组
* @param array $idList 平台子产品id的列表, 默认去重 * @param array $idList 平台子产品id的列表, 默认去重
* @param array $relations 平台子产品的关联关系,支持:["platform_product","product_child","weight"] * @param array $relations 平台子产品的关联关系,支持:["platform_product","product_child","weight","packs"]
* @param array $columns 平台子产品表的字段,默认全部字段 * @param array $columns 平台子产品表的字段,默认全部字段
* ['id','platform_product_id','product_child_id','platform_product_child_sku','asin','fnsku','is_sale'] * ['id','platform_product_id','product_child_id','platform_product_child_sku','asin','fnsku','is_sale']
* @return array 默认keyBy('id') * @return array 默认keyBy('id')
...@@ -35,7 +35,7 @@ interface PlatformProductChildServiceInterface ...@@ -35,7 +35,7 @@ interface PlatformProductChildServiceInterface
* 获取单个数据 * 获取单个数据
* @param string $sku 平台子产品sku * @param string $sku 平台子产品sku
* @param int $siteId 平台子产品所属站点 * @param int $siteId 平台子产品所属站点
* @param array $relations 平台子产品的关联关系,支持:["platform_product","product_child","weight"] * @param array $relations 平台子产品的关联关系,支持:["platform_product","product_child","weight","packs"]
* @param array $columns 平台子产品表的字段,默认全部字段 * @param array $columns 平台子产品表的字段,默认全部字段
* ['id','platform_product_id','product_child_id','platform_product_child_sku','asin','fnsku','is_sale'] * ['id','platform_product_id','product_child_id','platform_product_child_sku','asin','fnsku','is_sale']
* @return array * @return array
...@@ -46,7 +46,7 @@ interface PlatformProductChildServiceInterface ...@@ -46,7 +46,7 @@ interface PlatformProductChildServiceInterface
* 通过sku列表获取平台子产品数组 * 通过sku列表获取平台子产品数组
* @param array $skuList 平台子产品sku的列表, 默认去重 * @param array $skuList 平台子产品sku的列表, 默认去重
* @param int $siteId 平台子产品所属站点 * @param int $siteId 平台子产品所属站点
* @param array $relations 平台子产品的关联关系,支持:["platform_product","product_child","weight"] * @param array $relations 平台子产品的关联关系,支持:["platform_product","product_child","weight","packs"]
* @param array $columns 平台子产品表的字段,默认全部字段 * @param array $columns 平台子产品表的字段,默认全部字段
* ['id','platform_product_id','product_child_id','platform_product_child_sku','asin','fnsku','is_sale'] * ['id','platform_product_id','product_child_id','platform_product_child_sku','asin','fnsku','is_sale']
* @return array 默认keyBy('platform_product_child_sku') * @return array 默认keyBy('platform_product_child_sku')
...@@ -62,7 +62,7 @@ interface PlatformProductChildServiceInterface ...@@ -62,7 +62,7 @@ interface PlatformProductChildServiceInterface
public function getIdsByChildSku(string $childSku, array $limitIds = null); public function getIdsByChildSku(string $childSku, array $limitIds = null);
/** /**
* 获取仓库子sku对应的平台子sku * 获取仓库主sku对应的平台主sku
* @param array $productChildIds 已去重 * @param array $productChildIds 已去重
* @param null $siteId 指定站点id, 不传或传null,获取全部数据 * @param null $siteId 指定站点id, 不传或传null,获取全部数据
* @param array $columns * @param array $columns
...@@ -74,7 +74,7 @@ interface PlatformProductChildServiceInterface ...@@ -74,7 +74,7 @@ interface PlatformProductChildServiceInterface
* 通过仓库产品id获取平台子产品数组 * 通过仓库产品id获取平台子产品数组
* @param $productId * @param $productId
* @param null $siteId * @param null $siteId
* @param array $relations * @param array $relations 平台子产品的关联关系,支持:["platform_product","product_child","weight","packs"]
* @param array $columns * @param array $columns
* @return array * @return array
*/ */
......
...@@ -15,7 +15,7 @@ interface ProductChildServiceInterface ...@@ -15,7 +15,7 @@ interface ProductChildServiceInterface
* 获取单个数据 * 获取单个数据
* @param int $id 子SKU id * @param int $id 子SKU id
* @param array $columns 子SKU表的字段,默认显示全部 * @param array $columns 子SKU表的字段,默认显示全部
* @param array $relations 子SKU的关联关系,可传入['brand', 'category', 'product_name', 'images', 'cost'] * @param array $relations 子SKU的关联关系,可传入['brand', 'category', 'product_name', 'images', 'cost', 'weight', 'packs']
* @return array|null * @return array|null
*/ */
public function get($id, array $columns = ['*'], array $relations = []); public function get($id, array $columns = ['*'], array $relations = []);
...@@ -24,7 +24,7 @@ interface ProductChildServiceInterface ...@@ -24,7 +24,7 @@ interface ProductChildServiceInterface
* 通过id列表获取产品数组 * 通过id列表获取产品数组
* @param array $idList 子SKUid的列表, 默认去重 * @param array $idList 子SKUid的列表, 默认去重
* @param array $columns 子SKU表的字段,默认显示全部 * @param array $columns 子SKU表的字段,默认显示全部
* @param array $relations 子SKU的关联关系,可传入['brand', 'category', 'product_name', 'images', 'cost'] * @param array $relations 子SKU的关联关系,可传入['brand', 'category', 'product_name', 'images', 'cost', 'weight', 'packs']
* @return array 默认keyBy('id') * @return array 默认keyBy('id')
*/ */
public function getByIdList(array $idList, array $columns = ['*'], array $relations = []): array; public function getByIdList(array $idList, array $columns = ['*'], array $relations = []): array;
...@@ -33,7 +33,7 @@ interface ProductChildServiceInterface ...@@ -33,7 +33,7 @@ interface ProductChildServiceInterface
* 通过sku列表获取子产品列表 * 通过sku列表获取子产品列表
* @param array $skuList 默认去重 * @param array $skuList 默认去重
* @param array $columns 子SKU表的字段,默认返回id * @param array $columns 子SKU表的字段,默认返回id
* @param array $relations 子SKU的关联关系,可传入['color', 'size','brand', 'category', 'product_name', 'images', 'cost', 'weight'] * @param array $relations 子SKU的关联关系,可传入['color', 'size','brand', 'category', 'product_name', 'images', 'cost', 'weight', 'packs']
* @return array 默认keyBy('child_sku') * @return array 默认keyBy('child_sku')
*/ */
public function getListBySkuList(array $skuList, array $columns = ['id'], array $relations = []); public function getListBySkuList(array $skuList, array $columns = ['id'], array $relations = []);
......
...@@ -23,7 +23,27 @@ interface StoreServiceInterface ...@@ -23,7 +23,27 @@ interface StoreServiceInterface
/** /**
* description:创建入库单 * description:创建入库单
* author: fuyunnan * author: fuyunnan
* @param array $data 需要入库的数组 格式请参考yapi 入库添加 * @param array $data 需要入库的数组 格式 入库添加
* *
data[master][warehousing_date]:2020-01-08 入库时间
data[master][creator_id]:12 创建人id
data[master][warehouse_id]:2 仓库id
data[master][type_id]:1 入库单类型
data[master][source_no]:no_121333 来源单号 (选填)
data[master][stock_up_status]:1二次质检状态 (选填)
data[master][remark]:备注 (选填)
data[master][status]:2 状态 (选填 不填默认1)
*
* 产品二维数组
data[goods][0][product_id]:16 产品id
data[goods][0][should_cnt]:133 应入数量
data[goods][0][real_cnt]:10 实入数量
data[goods][1][product_id]:18
data[goods][1][should_cnt]:10
data[goods][1][real_cnt]:15
*
* 或者参考yapi http://api.huaperfect.com/project/38/interface/api/1617
*
* @return array * @return array
* @throws * @throws
* Date: 2020/7/6 * Date: 2020/7/6
...@@ -31,6 +51,39 @@ interface StoreServiceInterface ...@@ -31,6 +51,39 @@ interface StoreServiceInterface
public function createWarehousing(array $data): array; public function createWarehousing(array $data): array;
/**
* description:批量创建出库单
* author: fuyunnan
* [
'main' => [
    'creator_id' => 1,
    'warehouse_id' => 1,
    'type' => 5,
],
'products' => [
[
    'source_no' => 1,
    'product_id' => 1,
    'real_cnt' => 1
],
[
    'source_no' => 1,
    'product_id' => 1,
    'real_cnt' => 1
]
]
]
*
* @param array $attributes 提交的数组 或参考yapi http://api.huaperfect.com/project/38/interface/api/6968
* @return array
* @throws
* Date: 2020/8/8
*/
public function createBatchWarehousing(array $attributes): array;
/** /**
* description:生产单结束获取统计单号值 * description:生产单结束获取统计单号值
* author: fuyunnan * author: fuyunnan
...@@ -101,7 +154,7 @@ interface StoreServiceInterface ...@@ -101,7 +154,7 @@ interface StoreServiceInterface
/** /**
* description:通过产品id数组获取库存列表 * description:通过产品id数组获取库存列表 给订单系统使用
* author: fuyunnan * author: fuyunnan
* @param array $ids 产品ids 数组 * @param array $ids 产品ids 数组
* @param int $wareId 仓库id * @param int $wareId 仓库id
...@@ -113,7 +166,7 @@ interface StoreServiceInterface ...@@ -113,7 +166,7 @@ interface StoreServiceInterface
/** /**
* description:检查是否有库存,有就返回库存数量(有记录) * description:检查是否有库存,有就返回库存数量(有记录) 给产品系统使用
* author: fuyunnan * author: fuyunnan
* @param array $ids 仓库产品的id数组 * @param array $ids 仓库产品的id数组
* @return array * @return array
......
<?php
/**
* Created by PhpStorm.
* User: Zero
* Date: 2020/8/18
* Time: 8:13
*/
namespace Meibuyu\Micro\Shopify;
use Exception;
use Meibuyu\Micro\Shopify\lib\AbstractShopify;
use Meibuyu\Micro\Shopify\lib\Collect;
use Meibuyu\Micro\Shopify\lib\Collection;
use Meibuyu\Micro\Shopify\lib\CustomCollection;
use Meibuyu\Micro\Shopify\lib\Metafield;
use Meibuyu\Micro\Shopify\lib\SmartCollection;
use Meibuyu\Micro\Shopify\lib\Webhook;
/**
* Class ShopifyApp
* @package Meibuyu\Shopify
*
* @property-read Webhook $Webhook
* @property-read Collect $Collect
* @property-read Collection $Collection
* @property-read CustomCollection $CustomCollection
* @property-read SmartCollection $SmartCollection
* @property-read Metafield $Metafield
*
* @method Webhook Webhook(integer $id = null)
* @method Collection Collection(integer $id = null)
* @method CustomCollection CustomCollection(integer $id = null)
* @method SmartCollection SmartCollection(integer $id = null)
* @method Metafield Metafield(integer $id = null)
*
*/
class ShopifyApp
{
protected $resources = [
'Webhook',
'Collect',
'Collection',
'CustomCollection',
'SmartCollection',
'Metafield',
];
protected $childResources = array(
'Fulfillment' => 'Order',
'FulfillmentEvent' => 'Fulfillment',
'OrderRisk' => 'Order',
'ProductImage' => 'Product',
'ProductVariant' => 'Product',
'DiscountCode' => 'PriceRule',
'Refund' => 'Order',
'Transaction' => 'Order',
);
public $config = [];
public $defaultApiVersion = '2020-07';
/**
* ShopifyApp constructor.
* @param array $config
*/
public function __construct($config)
{
$this->config = [
'api_version' => $this->defaultApiVersion
];
foreach ($config as $key => $value) {
$this->config[$key] = $value;
}
if (isset($config['shop_url'])) {
$this->setApiUrl();
}
}
/**
* 返回AbstractShopify实例
* @param string $className 实现的类名
* @return AbstractShopify
* @throws Exception
*/
public function __get($className)
{
return $this->$className();
}
/**
* 返回AbstractShopify实例
* @param string $className 实现的类名
* @param $arguments
* @return AbstractShopify
* @throws Exception
*/
public function __call($className, $arguments)
{
if (!in_array($className, $this->resources)) {
if (isset($this->childResources[$className])) {
$message = "$className 是属于 {$this->childResources[$className]} 的子集, 无法直接访问";
} else {
$message = "未知类 $className";
}
throw new Exception($message);
}
$resourceID = !empty($arguments) ? $arguments[0] : null;
$resourceClassName = __NAMESPACE__ . "\\lib\\$className";
return new $resourceClassName($this->config, $resourceID);
}
public function setApiUrl()
{
$shopUrl = $this->config['shop_url'];
$shopUrl = preg_replace('#^https?://|/$#', '', $shopUrl);
$apiVersion = $this->config['api_version'];
$this->config['api_url'] = "https://$shopUrl/admin/api/$apiVersion/";
}
}
<?php
/**
* Created by PhpStorm.
* User: Zero
* Date: 2020/8/19
* Time: 9:25
*/
namespace Meibuyu\Micro\Shopify;
use Hyperf\Contract\ContainerInterface;
class ShopifyFactory
{
/**
* @var ContainerInterface
*/
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function create(array $config = []): ShopifyApp
{
if (method_exists($this->container, 'make')) {
// Create by DI for AOP.
return $this->container->make(ShopifyApp::class, ['config' => $config]);
}
return new ShopifyApp($config);
}
}
<?php
/**
* Created by PhpStorm.
* User: Zero
* Date: 2020/8/18
* Time: 8:18
*/
namespace Meibuyu\Micro\Shopify\lib;
use Exception;
use Meibuyu\Micro\Tools\HttpRequestJson;
use Psr\Http\Message\ResponseInterface;
abstract class AbstractShopify
{
/**
* 资源id
* @var int
*/
public $id = null;
protected $httpHeaders = [];
protected $resourceUrl;
protected $resourceKey;
protected $pluralizeKey;
/**
* 无count方法
* @var boolean
*/
public $countEnabled = true;
// 子集资源
protected $childResource = [];
// 自定义请求方法
protected $customGetActions = [];
protected $customPostActions = [];
protected $customPutActions = [];
protected $customDeleteActions = [];
private $config;
/**
* AbstractShopify constructor.
* @param $config
* @param null $id
* @param string $parentResourceUrl
* @throws Exception
*/
public function __construct($config, $id = null, $parentResourceUrl = null)
{
$this->config = $config;
$this->id = $id;
$this->pluralizeKey = $this->resourceKey . 's';
$this->resourceUrl = ($parentResourceUrl ? "$parentResourceUrl/" : $config['api_url']) . $this->pluralizeKey . ($this->id ? "/{$this->id}" : '');
if (isset($config['api_password'])) {
$this->httpHeaders['X-Shopify-Access-Token'] = $config['api_password'];
} elseif (!isset($config['api_password'])) {
throw new Exception("请设置api_password值");
}
}
/**
* 调用子集资源
* @param $childName
* @return mixed
*/
public function __get($childName)
{
return $this->$childName();
}
/**
* 调用自定义方法
* @param $name
* @param $arguments
* @return mixed
* @throws Exception
*/
public function __call($name, $arguments)
{
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);
} else {
$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);
}
}
}
private function getResourceName()
{
return substr(get_called_class(), strrpos(get_called_class(), '\\') + 1);
}
public function generateUrl($urlParams = [], $id = null, $customAction = null)
{
$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) : '');
}
/**
* @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);
}
protected function wrapData($dataArray, $dataKey = null)
{
if (!$dataKey) $dataKey = $this->resourceKey;
return [$dataKey => $dataArray];
}
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
* @throws Exception
*/
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;
}
}
}
<?php
/**
* Created by PhpStorm.
* User: Zero
* Date: 2020/8/24
* Time: 16:50
*/
namespace Meibuyu\Micro\Shopify\lib;
class Collect extends AbstractShopify
{
protected $resourceKey = 'collect';
}
<?php
/**
* Created by PhpStorm.
* User: Zero
* Date: 2020/8/24
* Time: 16:50
*/
namespace Meibuyu\Micro\Shopify\lib;
/**
* Class Collection
* @package Meibuyu\Micro\Shopify\lib
*
* @property-read Metafield $Metafield
*
* @method Metafield Metafield(integer $id = null)
*/
class Collection extends AbstractShopify
{
protected $resourceKey = 'collection';
protected $childResource = [
'Metafield',
];
}
<?php
/**
* Created by PhpStorm.
* User: Zero
* Date: 2020/8/22
* Time: 16:14
*/
namespace Meibuyu\Micro\Shopify\lib;
/**
* Class CustomCollection
* @package Meibuyu\Micro\Shopify\lib
*
* @property-read Metafield $Metafield
*
* @method Metafield Metafield(integer $id = null)
*/
class CustomCollection extends AbstractShopify
{
protected $resourceKey = 'custom_collection';
protected $childResource = [
'Metafield',
];
}
<?php
/**
* Created by PhpStorm.
* User: Zero
* Date: 2020/8/26
* Time: 15:50
*/
namespace Meibuyu\Micro\Shopify\lib;
class Metafield extends AbstractShopify
{
protected $resourceKey = 'metafield';
}
<?php
/**
* Created by PhpStorm.
* User: Zero
* Date: 2020/8/24
* Time: 16:50
*/
namespace Meibuyu\Micro\Shopify\lib;
/**\
* Class SmartCollection
* @package Meibuyu\Micro\Shopify\lib
*
* @property-read Metafield $Metafield
*
* @method Metafield Metafield(integer $id = null)
*/
class SmartCollection extends AbstractShopify
{
protected $resourceKey = 'smart_collection';
protected $childResource = [
'Metafield',
];
}
<?php
/**
* Created by PhpStorm.
* User: Zero
* Date: 2020/8/18
* Time: 8:13
*/
namespace Meibuyu\Micro\Shopify\lib;
class Webhook extends AbstractShopify
{
protected $resourceKey = 'webhook';
}
<?php
/**
* Created by PhpStorm.
* User: Zero
* Date: 2020/8/19
* Time: 9:06
*/
namespace Meibuyu\Micro\Tools;
use GuzzleHttp\Client;
use Psr\Http\Message\ResponseInterface;
/**
* json格式请求(非协程)
* Class HttpRequestJson
* @package Meibuyu\Micro\Tools
*/
class HttpRequestJson
{
/**
* get请求
* @param $url
* @param array $httpHeaders
* @return ResponseInterface
*/
public static function get($url, $httpHeaders = [])
{
$client = new Client();
return $client->get($url, ['headers' => $httpHeaders]);
}
/**
* post请求
* @param $url
* @param $dataArray
* @param array $httpHeaders
* @return ResponseInterface
*/
public static function post($url, $dataArray, $httpHeaders = [])
{
$client = new Client();
return $client->post($url, ['headers' => $httpHeaders, 'json' => $dataArray]);
}
/**
* put请求
* @param $url
* @param $dataArray
* @param array $httpHeaders
* @return ResponseInterface
*/
public static function put($url, $dataArray, $httpHeaders = [])
{
$client = new Client();
return $client->put($url, ['headers' => $httpHeaders, 'json' => $dataArray]);
}
/**
* delete请求
* @param $url
* @param array $httpHeaders
* @return ResponseInterface
*/
public static function delete($url, $httpHeaders = [])
{
$client = new Client();
return $client->delete($url, ['headers' => $httpHeaders]);
}
}
...@@ -719,6 +719,29 @@ if (!function_exists('check_diff_val')) { ...@@ -719,6 +719,29 @@ if (!function_exists('check_diff_val')) {
} }
} }
if (!function_exists('to_camel_case')) {
/**
* 下划线命名转驼峰命名
* 例:demo_function : demoFunction
* @param $dirSep 分隔符
* @param $str
* @return mixed|string
*/
function to_camel_case($dirSep, $str)
{
$array = explode($dirSep, $str);
$result = $array[0];
$len=count($array);
if($len>1) {
for($i=1;$i<$len;$i++) {
$result.= ucfirst($array[$i]);
}
}
return $result;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment