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;
use andy87\knock_knock\core\Request;

// Получаем компонент реализующий отправку запросов
$operator = new Operator($_ENV['API_HOST'], [
    Request::SETUP_CURL_OPTIONS => [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10],
]);

/**
 * Краткая форма записи (с не очевидным объектом запроса) 
 */
$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; // Получаем данные ответа
$curlInfo = $response->request->curlInfo; // Получаем информацию о выполненном запросе

$output = str_starts_with($curlInfo[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_PROTOCOL => $_ENV['API_PROTOCOL'],
    Request::SETUP_CONTENT_TYPE => ContentType::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_INIT => function( Operator $operator ) {
        // ...
    },
    Operator::EVENT_CONSTRUCT_REQUEST => function( Operator $operator, Request $request ) {
        // ...
    },
    Operator::EVENT_BEFORE_SEND => function( Operator $operator, Request $request ) {
        // ...
    },
    Operator::EVENT_CURL_HANDLER => function( Operator $operator, CurlHandle $ch ) {
        // ...
    },
    Operator::EVENT_CONSTRUCT_RESPONSE => function( Operator $operator, Response $response ) {
        // ...
    },
    Operator::EVENT_AFTER_SEND => function( Operator $operator, Response $response ) {
        // ...
    }
]);

$request = new Request( 'info/me', [
    Request::SETUP_HOST => $_ENV['API_HOST'], // URL с протоколом, например https://api.example.com
    Request::SETUP_METHOD => Method::POST,
    Request::SETUP_DATA => [ 'client_id' => 34 ],
    Request::SETUP_HEADERS => [ 'api-secret-key' => $_ENV['API_SECRET_KEY'] ],
    Request::SETUP_CURL_OPTIONS => [ CURLOPT_TIMEOUT => 10 ],
    Request::SETUP_CURL_INFO => [
        CURLINFO_CONTENT_TYPE,
        CURLINFO_HEADER_SIZE,
        CURLINFO_TOTAL_TIME
    ],
    Request::SETUP_CONTENT_TYPE => ContentType::FORM,
]);

$request = $operator->constructRequest(Method::GET, 'info/me', [
    Request::SETUP_METHOD => Method::POST,
    Request::SETUP_DATA => [ 'client_id' => 45 ],
    Request::SETUP_HEADERS => [ 'api-secret-key' => $_ENV['API_SECRET_KEY'] ],
    Request::SETUP_CURL_OPTIONS => [ CURLOPT_TIMEOUT => 10 ],
    Request::SETUP_CURL_INFO => [
        CURLINFO_CONTENT_TYPE,
        CURLINFO_HEADER_SIZE,
        CURLINFO_TOTAL_TIME
    ],
    Request::SETUP_CONTENT_TYPE => ContentType::FORM,
]);

$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->addHeaders(['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->protocol; // String
$host = $request->host; // String
// Остальные значения также доступны через read-only свойства Request.

$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 ): void
    {
        $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()->content;

$price = $product['price'];

// Изменение типа контента на `application/json`, для следующего запроса
$knockKnockSecurity->useContentType( ContentType::JSON );

// Отправка POST запроса и получение ответа
$responsePost = $knockKnockSecurity->post( 'category', [
    'name' => 'Фреймворки'
]);

$response = json_decode( $responsePost->content );

$category_id = $response->id;


/** HTTP-клиент с JSON-телами и журналом HTTP-кодов без записи токенов и содержимого. */
class KnockKnockYandex extends Operator
{
    /**
     * Настраивает JSON-запросы, получение тела и журналирование ответа.
     * @return void
     * @throws \Exception При ошибке установки параметров или обработчика.
     */
    public function init(): void
    {
        $this->commonRequest->setContentType(ContentType::JSON);
        $this->commonRequest->addCurlOptions([
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 10,
        ]);
        $this->on(self::EVENT_AFTER_SEND, [$this, 'logResponse']);
    }

    /**
     * Сохраняет HTTP-код выполненной попытки в журнал клиента.
     * @param Operator $operator Клиент, вызвавший событие.
     * @param Response $response Полученный ответ.
     * @return void
     * @throws \Exception При ошибке чтения ответа.
     */
    public function logResponse(Operator $operator, Response $response): void
    {
        $operator->addLog('HTTP ' . $response->httpCode);
    }
}



$knockKnockYandex = KnockKnockYandex::getInstance($_ENV['API_HOST']);

$request = $knockKnockYandex->constructRequest(Method::PATCH, 'profile', [
    Request::SETUP_DATA => [ 'city' => 'Moscow' ],
]);

$response = $knockKnockYandex->send($request); // Логирование afterSend
bash
php composer.phar 
bash
php vendor/phpunit/phpunit/phpunit --exclude-group external
bash
php vendor/phpunit/phpunit/phpunit --group external