Файловый менеджер - Редактировать - /home/tuudkjt/globeasy/wp-includes/ID3/apiz.zip
Назад
PK �d,]� ��� � readme.mdnu ��� # APIZ APIZ is a PHP API Client Development Kit, it helps you to manage HTTP API call in OOP way. You can easily handle and isolate all kinds of REST API calls and their responses by using this package. ## Requirements - PHP >= 5.5.9 ## Installations ```shell composer require nahid/apiz ``` ## Configurations There are no extra configurations for this package. ## Usage Lets see an example to consume API from https://reqres.in. Suppose you need to create several API services for your project. Your service directory is `app/Services`. Now we are going to develop a service for https://reqres.in and make a class file `ReqResApiService.php` which will extend `\Apiz\AbstractApi` class. ```php namespace App\Services; use Apiz\AbstractApi; class ReqResApiService extends AbstractApi { protected function getBaseURL() { return 'https://reqres.in'; } } ``` `getBaseURL()` is an abstract method of the `AbstractApi` class. You need to override this method to set the proper base URL for your API. Few APIs have a common prefix in their URL. Like, here `reqres.in` have a prefix `api` on every endpoint. So, we'll override the `getPrefix()` method to define the Prefix. ```php namespace App\Services; use Apiz\AbstractApi; class ReqResApiService extends AbstractApi { protected function getBaseURL() { return 'https://reqres.in'; } protected function getPrefix() { return 'api'; } } ``` Now let's make a method to get all users info. ```php namespace App\Services; use Apiz\AbstractApi; class ReqResApiService extends AbstractApi { protected function getBaseURL() { return 'https://reqres.in'; } protected function getPrefix() { return 'api'; } public function getAllUsers() { $response = $this->get('users'); if ($response->getStatusCode() === 200) { return $response()->toArray(); } return []; } } ``` So, we are basically making a `GET` request to the URL `https://reqres.in/api/users`. See, how easy it is to manage an API now? Let's see another example. ## Post Request with Form Params ```php public function createUser(array $data) { $response = $this->withFormParams($data) ->post('create'); if ($response->getStatusCode() === 201) { return $response()->toArray(); } return null; } ``` ## Default Headers Sometimes we need to bind some headers with all the requests. Suppose if you want to deal with the Github API, you have to send `access_token` in every request with the headers. So APIZ provide you a handy way to deal with this problem. Just override `AbstractApi::getDefaultHeaders()`. ```php protected function getDefaultHeaders() { return [ 'access_token' => $_ENV['GITHUB_ACCESS_TOKEN'], ]; } ``` Cool, right? You can easily use all HTTP verbs like `get`, `post` etc. It's totally hassle free. See more examples in the [Examples Folder](./Examples). ## Query over Response Data Sometimes we receive huge payload as a response from the APIs. It's quite daunting to parse proper data from that big payload. No worries! We're using a powerful Query parser, named [QArray](https://github.com/nahid/qarray) by default to parse and query over the Response data. Let's see how we can use this parser to parse the response we got for `getAllUsers` method from our previous example. ```php public function getFirstUser() { $users = $this->get('users'); return $users->query()->from('data')->first(); } ``` We're getting list of users in the `data` key in the response. From that we're collecting the first data. See, how easy it is! You can find detail usage of the QArray [here](https://github.com/nahid/qarray). Additionally, there is a secret sauce for you. If you don't want to query like: `$users->query()`, you can just do it like this: `$users()`. That means the response object is invokable and behave exactly like calling the `query()` method. You're welcome. :D ## Overriding HTTP Client By default we are using `Guzzle` as our HTTP Client. But you are not bound to use this. You can easily use your own PSR7 supported HTTP Client with `Apiz`. Just pass an instance of your HTTP Client to our `setClient()` method. See an example [here](./Examples/API%20with%20Different%20Client). Here is our GuzzleClient to get an idea how your Client should look like: ```php <?php namespace Apiz\Http\Clients; use Apiz\Http\AbstractClient; use GuzzleHttp\Client; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Uri; use GuzzleHttp\Exception\GuzzleException; use Psr\Http\Message\ResponseInterface; // Your client must extend the `AbstractClient` class GuzzleClient extends AbstractClient { public function getRequestClass() { // Return the Request class name of your PSR7 supported Client // This Request class must implement the Psr\Http\Message\RequestInterface return Request::class; } public function getResponseClass() { // Return the Response class name of your PSR7 supported Client // This Response class must implement the Psr\Http\Message\ResponseInterface return Response::class; } public function getUriClass() { // Return the Uri class name of your PSR7 supported Client // This Uri class must implement the Psr\Http\Message\UriInterface return Uri::class; } /** * @param mixed ...$args * @return ResponseInterface * @throws GuzzleException */ public function send(...$args) { // In this method, implement how your Client execute the Request sending $client = new Client(); return $client->send(... $args); } } ``` ## List of methods for common HTTP verbs - `get(string $uri)` - `post(string $uri)` - `put(string $uri)` - `delete(string $uri)` - `head(string $uri)` - `options(string $uri)` ## List of Available methods - `getPrefix():string`: override this method to define the common prefix, if you need it - `setClient($client)` : pass a PSR7 supported Client instance, only if you need to override the default Guzzle HTTP Client - `withFormParams(array)`: pass Form parameters data for requests like POST, PATCH, UPDATE - `withHeaders(array)`: pass Header data - `withQueryParams(array)`: pass Query Parameter data - `withFormData(array)`: pass Multipart form data - `getDefaultHeaders():array`: override to define default Headers, if you have any - `getDefaultQueries():array`: override to define default queries, if you have any - `skipDefaultHeaders(bool)` - `skipDefaultQueries(bool)` - `allowRedirects(array)` - `basicAuth(string $username, string $password [, array $options])` - `body(string)`: Set request body - `json(array)`: Set JSON data to be passed as Request Body - `file(string $name, string $file_path, string $filename [, array $headers])` - `params(array $params)` ### Contribution Feel free send feedback and issues. Contributions to improve this package is most welcome too. PK �d,]�Y�& & LICENSEnu ��� MIT License Copyright (c) 2020 nahid Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK �d,]Z�- - src/HttpExceptionReceiver.phpnu ��� <?php namespace Rvx\Apiz; use Rvx\Apiz\Http\Response; class HttpExceptionReceiver { protected $exceptions; protected $statusCode; public function __construct(Response $response, $exceptions = []) { $this->statusCode = (int) $response->getStatusCode(); $this->exceptions = $exceptions; $this->throwExceptions(); } protected function throwExceptions() { if (\array_key_exists($this->statusCode, $this->exceptions)) { throw new $this->exceptions[$this->statusCode](); } } } PK �d,]:+�U U src/Constants/MimeType.phpnu ��� <?php namespace Rvx\Apiz\Constants; interface MimeType { const APPLICATION_JSON = 'application/json'; const TEXT_JSON = 'text/json'; const APPLICATION_JAVASCRIPT = 'application/javascript'; const APPLICATION_XML = 'application/xml'; const TEXT_XML = 'text/xml'; const APPLICATION_YAML = 'application/x-yaml'; const TEXT_YAML = 'text/yaml'; const JSON_TYPES = [self::APPLICATION_JSON, self::TEXT_JSON, self::APPLICATION_JAVASCRIPT]; const XML_TYPES = [self::APPLICATION_XML, self::TEXT_XML]; const YAML_TYPES = [self::APPLICATION_YAML, self::TEXT_YAML]; } PK �d,]Q@R�� � $ src/Constants/GraphQLRequestType.phpnu ��� <?php namespace Rvx\Apiz\Constants; interface GraphQLRequestType { const QUERY = 'query'; const MUTATION = 'mutation'; } PK �d,]�A�0 �0 src/AbstractApi.phpnu ��� <?php declare (strict_types=1); namespace Rvx\Apiz; use Rvx\Apiz\GraphQL\AbstractRequest; use Rvx\Apiz\Http\Clients\AbstractClient; use Rvx\Apiz\Http\Clients\GuzzleClient; use Rvx\Apiz\Http\Request; use Rvx\Apiz\Http\Response; use Rvx\Apiz\Traits\Hookable; use Exception; use Rvx\GuzzleHttp\Psr7\Utils; use Rvx\GuzzleHttp\RequestOptions; use Rvx\Psr\Http\Message\ResponseInterface; use Rvx\Apiz\Exceptions\InvalidResponseClassException; /** * Class AbstractApi * @template Resp * @package Apiz */ abstract class AbstractApi { use Hookable; /** * list of available http exceptions * * @var array */ protected array $httpExceptions = []; /** * skip exception when its value true * * @var bool */ protected bool $shouldSkipHttpException = \false; /** * this variable contains request details * * @var Request */ protected $request; /** * response class name * @var class-string<Resp> $response */ protected $response = Response::class; /** * @var array */ protected array $config = []; /** * AbstractApi constructor. * @param ?Request $request */ public function __construct($request = null) { if (!$request || !$request->hasClient()) { $this->request = new Request(new GuzzleClient($this->config)); } $this->setBaseURL($this->getBaseURL()); $this->setPrefix($this->getPrefix()); } /** * @return string */ protected abstract function getBaseURL() : string; /** * Get client configs * * @return array */ public function getConfig() : array { return $this->config; } /** * Set client config * * @param $config */ public function setConfig($config) { $this->config = $config; } /** * Get request instance * * @return Request */ public function getRequest() { return $this->request; } /** * set Base URL * * @param string $url */ protected function setBaseURL(string $url) { $this->request->setBaseURL($url); } /** * @return string */ public function getPrefix() : string { return ''; } /** * set url prefix * * @param string $prefix */ protected function setPrefix(string $prefix) { $this->request->setPrefix($prefix); } /** * @param AbstractClient $client */ protected function setClient(AbstractClient $client) { $this->request->setClient($client); } /** * @param Request $request * @param ResponseInterface $response * @return Resp * @throws InvalidResponseClassException */ private function makeResponse(Request $request, ResponseInterface $response) { $responseClass = $this->response; $apizResponse = new $responseClass($request, $response); if (!$apizResponse instanceof Response) { throw new InvalidResponseClassException(); } return $apizResponse; } /** * @param string $responseClass */ protected function setResponseClass($responseClass) { $this->response = $responseClass; } /** * set form parameters or form data for POST, PUT and PATCH request * * @param array $params * @return AbstractApi */ protected function withFormParams(array $params = []) { $this->request->setContentType('application/x-www-form-urlencoded'); $body = \urlencode(\http_build_query($params)); $this->request->setBodyContents($body); return $this; } /** * set request headers * * @param array $headers * @return AbstractApi */ protected function withHeaders(array $headers = []) : self { $this->request->setHeaders($headers); return $this; } /** * get default headers that will automatically bind with every request headers * * @return array */ protected function getDefaultHeaders() : array { return []; } /** * get default queries that will automatically bind with every request * * @return array */ protected function getDefaultQueries() : array { return []; } /** * @param bool $action * @return self */ protected function skipDefaultHeaders(bool $action = \true) : self { $this->request->skipDefaultHeaders($action); return $this; } /** * @param bool $action * @return self */ protected function skipDefaultQueries(bool $action = \true) : self { $this->request->skipDefaultQueries($action); return $this; } /** * set query parameters * * @param array $params * @return AbstractApi */ protected function withQueryParams(array $params = []) : self { $this->request->setQueryParams($params); return $this; } protected function withOptions(array $options = []) : self { $this->request->setOptions($options); return $this; } /** * Add allow redirects param * * @param array|null $option * @return AbstractApi */ protected function allowRedirects(?array $option = []) : self { if (empty($option)) { $option = \true; } $this->request->setOption(RequestOptions::ALLOW_REDIRECTS, $option); return $this; } /** * Set basic auth options * * @param string $username * @param string $password * @return AbstractApi */ protected function basicAuth(string $username, string $password) : self { $this->request->setHeader('Authorization', 'Basic ' . \base64_encode("{$username}:{$password}")); return $this; } /** * Set request body * * @param mixed $contents * @return AbstractApi */ protected function withBody($contents) : self { if (\is_array($contents)) { $this->request->setContentType('x-www-form-urlencoded'); $contents = \urlencode(\http_build_query($contents)); } $this->request->setBodyContents($contents); return $this; } /** * Set request param as JSON * * @param array $params * @return AbstractApi */ protected function withJson(array $params = []) : self { $this->request->setHeader('Content-Type', 'application/json'); $this->request->setBodyContents(\json_encode($params)); return $this; } /** * Send file to the request * * @param string $name * @param string $file * @param string $filename * @param array $headers * @return AbstractApi */ protected function withFile(string $name, string $file, string $filename, array $headers = []) : self { if (\file_exists($file)) { $contents = Utils::tryFopen($file, 'r'); return $this->attach($name, $contents, $filename, $headers); } return $this; } /** * Attach a raw content with request * * @param string $name * @param mixed $contents * @param string $filename * @param array $headers * @return self */ protected function attach(string $name, $contents, string $filename, array $headers = []) : self { $this->request->setBodyMultipart(['name' => $name, 'contents' => $contents, 'filename' => $filename, 'headers' => $headers]); return $this; } /** * Attach form value with multipart * * @param array $data * @return AbstractApi */ protected function withFormData(array $data = []) : self { $params = $this->prepareFormData($data); if (!empty($params)) { $this->request->setBodyParams($params); } return $this; } /** * @param array $params * @param string $prefix * @return array */ protected function prepareFormData(array $params, string $prefix = '') : array { $formParams = []; foreach ($params as $key => $value) { $newKey = empty($prefix) ? $key : $prefix . '[' . $key . ']'; if (\is_array($value)) { $formParams = \array_merge($formParams, $this->prepareFormData($value, $newKey)); } else { $formParams[] = ['name' => $newKey, 'contents' => $value]; } } return $formParams; } /** * skip default http exceptions from request * * @param array $codes * @return AbstractApi */ protected function skipHttpExceptions(array $codes = []) : self { if (!empty($codes)) { $this->shouldSkipHttpException = \true; foreach ($codes as $code) { unset($this->httpExceptions[$code]); } } return $this; } /** * push new http exceptions to current request * * @param array $exceptions * @return AbstractApi */ protected function pushHttpExceptions(array $exceptions = []) : self { foreach ($exceptions as $code => $exception) { $this->httpExceptions[$code] = $exception; } return $this; } /** * @param string $uri * @return Resp * @throws Exception */ protected function get(string $uri) { return $this->makeMethodRequest('GET', $uri); } /** * @param string $uri * @return Resp * @throws Exception */ protected function post(string $uri) { return $this->makeMethodRequest('POST', $uri); } /** * @param string $uri * @return Resp * @throws Exception */ protected function put(string $uri) { return $this->makeMethodRequest('PUT', $uri); } /** * @param string $uri * @return Resp * @throws Exception */ protected function patch(string $uri) { return $this->makeMethodRequest('PATCH', $uri); } /** * @param string $uri * @return Resp * @throws Exception */ protected function delete(string $uri) { return $this->makeMethodRequest('DELETE', $uri); } /** * @param string $uri * @return Resp * @throws Exception */ protected function head(string $uri) { return $this->makeMethodRequest('HEAD', $uri); } /** * @param string $uri * @return Resp * @throws Exception */ protected function options(string $uri) { return $this->makeMethodRequest('OPTIONS', $uri); } protected function graphqlCall(AbstractRequest $request) { return $this->graphql('', $request); } protected function graphql(string $uri, AbstractRequest $request) { return $this->withJson($request->getQuery())->post($uri); } /** * Make all request from here * * @param string $method * @param string $uri * @return Resp * @throws Exception */ private function makeMethodRequest(string $method, string $uri) { $response = null; try { $this->request->setDefaultHeaders($this->getDefaultHeaders()); $this->request->setDefaultQueries($this->getDefaultQueries()); $request = $this->request->make($method, $uri); $this->executePreHooks($this->request); $clientResponse = $this->request->send($request); $response = $this->makeResponse($this->request, $clientResponse); if (!$this->shouldSkipHttpException) { if ($response instanceof Response) { new HttpExceptionReceiver($response, $this->httpExceptions); } } $this->executeSuccessHooks($response, $this->request); } catch (Exception $e) { $this->executeFailHooks($e); throw $e; } finally { $this->resetObjects(); } return $response; } /** * Reset this class objects */ protected function resetObjects() { $this->shouldSkipHttpException = \false; $this->request->reset(); } } PK �d,]�'�t�&