PHP code example of andy87 / knockknock
1. Go to this page and download the library: Download andy87/knockknock library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
andy87 / knockknock example snippets
use andy87\knock_knock\lib\Method;
use andy87\knock_knock\lib\ContentType;
use andy87\knock_knock\core\Operator;
use andy87\knock_knock\core\Response;
// Получаем компонент реализующий отправку запросов
$operator = new Operator( $_ENV['API_HOST'] )->disableSSL();
/**
* Краткая форма записи (с не очевидным объектом запроса)
*/
$content = $operator->send( $operator->constructRequest(Method::GET, 'info/me') )->content;
/**
* Детальная форма записи с дополнительными возможностями
*/
$request = $operator->constructRequest(Method::GET, 'info/me'); // Создаём объект запроса
$request->setCurlInfo([ CURLINFO_CONTENT_TYPE ]); // Назначаем опции cURL
$response = $operator->send($request); // Отправляем запрос и получаем ответ
$content = $response->content; // Получаем данные ответа
$curlOptions = $response->request->curlOptions; // Получаем опции cURL
$output = ( $curlOptions[CURLINFO_CONTENT_TYPE] === ContentType::JSON ) ? json_decode( $content ) : $content;
print_r( $output );
$operator = new Operator( $_ENV['API_HOST'], $commonRequestParams );
$operator = Operator::getInstance( $_ENV['API_HOST'], $commonRequestParams );
// настройки для последующих исходящих запросов
$commonRequestParams = [
Request::SETUP_PROTOCO => $_ENV['API_PROTOCOL'],
Request::SETUP_CONTENT_TYPE => Request::CONTENT_TYPE_JSON,
Request::SETUP_CURL_OPTIONS => [
CURLOPT_HEADER => false,
CURLOPT_RETURNTRANSFER => true
]
];
// Получаем компонент для отправки запросов
$operator = new Operator( $_ENV['API_HOST'], $commonRequestParams );
//Применяя, паттерн Singleton:
$operator = Operator::getInstance( $_ENV['API_HOST'], $commonRequestParams );
$operator->setupEventHandlers([
Operator::EVENT_AFTER_CONSTRUCT => function( Operator $operator ) {
// ...
},
Operator::EVENT_CREATE_REQUEST => function( Operator $operator, Request $request ) {
// ...
},
Operator::EVENT_BEFORE_SEND => function( Operator $operator, Request $request ) {
// ...
},
Operator::EVENT_CURL_HANDLER => function( Operator $operator, resource $ch ) {
// ...
},
Operator::EVENT_CREATE_RESPONSE => function( Operator $operator, Response $response ) {
// ...
},
Operator::EVENT_AFTER_SEND => function( Operator $operator, Response $response ) {
// ...
}
]);
$request = new Request( 'info/me', [
Request::METHOD => Method::POST,
Request::DATA => [ 'client_id' => 34 ],
Request::HEADERS => [ 'api-secret-key' => $_ENV['API_SECRET_KEY'] ],
Request::CURL_OPTIONS => [ CURLOPT_TIMEOUT => 10 ],
Request::CURL_INFO => [
CURLINFO_CONTENT_TYPE,
CURLINFO_HEADER_SIZE,
CURLINFO_TOTAL_TIME
],
Request::CONTENT_TYPE => ContentType::FORM_DATA,
]);
$request = $operator->constructRequest(Method::GET, 'info/me', [
Request::METHOD => Method::POST,
Request::DATA => [ 'client_id' => 45 ],
Request::HEADERS => [ 'api-secret-key' => $_ENV['API_SECRET_KEY'] ],
Request::CURL_OPTIONS => [ CURLOPT_TIMEOUT => 10 ],
Request::CURL_INFO => [
CURLINFO_CONTENT_TYPE,
CURLINFO_HEADER_SIZE,
CURLINFO_TOTAL_TIME
],
Request::CONTENT_TYPE => ContentType::FORM_DATA,
]);
$request = $operator->constructRequest(Method::GET, 'info/me');
$response = $operator->send($request);
//Клонирование объекта запроса (без статуса отправки)
$cloneRequest = $request->clone();
// Отправка клона запроса
$response = $operator->setupRequest( $cloneRequest )->send();
$request = $operator->constructRequest(Method::GET, 'info/me');
$request->setMethod( Method::GET );
$request->setData(['client_id' => 67]);
$request->setHeaders(['api-secret-key' => 'secretKey67']);
$request->setCurlOptions([
CURLOPT_TIMEOUT => 10,
CURLOPT_RETURNTRANSFER => true
]);
$request->setCurlInfo([
CURLINFO_CONTENT_TYPE,
CURLINFO_HEADER_SIZE,
CURLINFO_TOTAL_TIME
]);
$request->setContentType( ContentType::JSON );
$protocol = $request->getPrococol(); // String
$host = $request->getHost(); // String
// ... аналогичным образом доступны и другие подобные методы для получения свойств запроса
$operator->setupRequest( $request, [
Request::SETUP_HOST => $_ENV['API_HOST'],
Request::SETUP_HEADERS => [
'api-secret' => $_ENV['API_SECRET_KEY']
],
]);
$request = $operator->constructRequest(Method::GET, 'info/me');
$request->addError('Ошибка!');
$response = new Response('{"id" => 806034, "name" => "and_y87"}', 200 );
$response = $operator->constructResponse([
Response::CONTENT => [
'id' => 806034,
'name' => 'and_y87'
],
Response::HTTP_CODE => 400,
], $request );
$operator = new Operator( $_ENV['API_HOST'] );
$request = $operator->constructRequest(Method::GET, 'info/me');
$response = $operator->send($request);
// Аналог
$operator = new Operator( $_ENV['API_HOST'] );
$response = $operator->send( $operator->constructRequest(Method::GET, 'info/me') );
$operator = new Operator( $_ENV['API_HOST'] );
$request = $operator->constructRequest(Method::GET, 'info/me');
$response = $operator->send($request);
// повторная отправка запроса
$response = $operator->send($request->clone());
// параметры возвращаемого ответа
$fakeResponse = [
Response::HTTP_CODE => 200,
Response::CONTENT => '{"id" => 8060345, "nickName" => "and_y87"}'
];
$request->setFakeResponse( $fakeResponse );
$response = $operator->send( $request );
$response = $operator->send($request);
$response
->setHttpCode(200)
->setContent('{"id" => 8060345, "nickName" => "and_y87"}');
$response = $operator->send($request);
$response
->replace( Response::HTTP_CODE, 200 )
->replace( Response::CONTENT, '{"id" => 8060345, "nickName" => "and_y87"}' );
$operator = new Operator( $_ENV['API_HOST'] );
$response = $operator->setRequest( $operator->constructRequest(Method::GET, 'info/me') )->send();
// Получение компонента запроса
$request = $response->request;
$method = $request->method; // получение метода запроса
$operator = new Operator( $_ENV['API_HOST'] );
$response = $operator->setRequest( $operator->constructRequest(Method::GET, 'info/me') )->send();
$response->request;
// Получение свойств через объект запроса
$curlOptions = $response->request->curlOption;
$curlInfo = $response->request->curlInfo;
//Вариант с использованием быстрого доступа
$curlOptions = $response->curlOption;
$curlInfo = $response->curlInfo;
$response = $operator->send($request)->asArray(); // $response
$array = $response->content; // Array$response
$request = $operator->constructRequest(Method::GET, 'info/me');
$response = $operator->send($request);
$response->addError('Ошибка!');
$operator = new Operator( $_ENV['API_HOST'] );
$operator->disableSSL();
$request = $operator->constructRequest(Method::GET, 'info/me');
$response = $operator->setupRequest( $request )->send();
$operator = new Operator( $_ENV['API_HOST'] )->disableSSL();
$request = $operator->constructRequest(Method::GET, 'info/me');
$request->enableSSL();
$response = $operator->setupRequest( $request )->send();
$operator = new Operator( $_ENV['API_HOST'] );
$cookie = $_ENV['COOKIE'];
$jar = $_ENV['COOKIE_JAR'];
$operator->useCookie( $cookie, $jar );
$operator = new Operator( $_ENV['API_HOST'] );
$operator->addLog( 'Какое то сообщение' );
$knockKnockOctopus = new KnockKnockOctopus($_ENV['API_URL']);
$knockKnockOctopus->get( '/profile', [ 'id' => 806034 ] ); //GET запрос
$knockKnockOctopus->post( '/new', [ //POST запрос
'name' => 'Новая новость',
'content' => 'Текст новости'
]);
$knockKnockSecurity = new KnockKnockSecurity($_ENV['API_URL']);
// Настройка параметров запроса по умолчанию
$knockKnockSecurity
->disableSSL()
->setupAuthorization( KnockKnockSecurity::TOKEN_BEARER, 'token' )
->setupHeaders([ 'X-Api-Key' => $_ENV['X_API_KEY'] ])
->setupContentType( ContentType::JSON )
->on( Operator::EVENT_AFTER_SEND, function( Operator $operator, Response $response ) =>
{
$logFilePath = $_SERVER['DOCUMENT_ROOT'] . '/api_log.txt';
file_put_contents( $logFilePath, $response->content, FILE_APPEND );
});
// Получение ответа на запрос методом `patch`
$responsePatch = $knockKnockSecurity->patch( 'product', [
'price' => 1000
]);
$product = $responsePatch->asArray();
$price = $product['price'];
// Изменение типа контента на `application/json`, для следующего запроса
$knockKnockSecurity->useContentType( ContentType::JSON );
// Отправка POST запроса и получение ответа
$responsePost = $knockKnockSecurity->post( 'category', [
'name' => 'Фреймворки'
]);
$response = json_decode( $responsePost->content );
$category_id = $response->id;
class KnockKnockYandex extends Operator
{
private const LOGGER = 'logger';
private string $host = 'https://api.yandex.ru/'
private string $contentType = ContentType::JSON
private YandexLogger $logger;
/**
* @return void
*/
public function init(): void
{
$this->setupYandexLoggerEventHandlers();
}
/**
* @param array $callbacks
*
* @return self
*/
private function setupYandexLoggerEventHandlers( array $callbacks ): self
{
$this->on( self::AFTER_CREATE_REQUEST, function( Request $request ) =>
{
$logData = $this->getLogDataByRequest( $request );
$this->addYandexLog( $logData );
};
$this->on(self::EVENT_AFTER_SEND, function( Response $response ) =>
{
$logData = $this->getLogDataByRequest( $response->request );
$this->addYandexLog( $logData );
};
}
/**
* @param Request $request
*
* @return array
*/
private function getLogDataByRequest( Request $request ): array
{
return $request->getParams();
}
/**
* @param array $logData
*
* @return void
*/
private function addYandexLog( array $logData ): bool
{
return $logger->log( $logData );
}
}
$knockKnockYandex = KnockKnockYandex::getInstanсe( $_ENV['API_HOST'], [
KnockKnockYandex::LOGGER => new YandexLogger(),
]);
$response = $knockKnockYandex->setupRequest( 'profile', [
Request::METHOD => Method::PATCH,
Request::DATA => [ 'city' => 'Moscow' ],
]); // Логирование `afterCreateRequest`
$response = $knockKnockYandex->send(); // Логирование `afterSend`
bash
php composer.phar