├── .gitignore ├── LICENSE ├── README.md ├── composer.json ├── publish ├── config │ └── vk-requester.php └── database │ └── 2016_01_01_100000_create_vk_requester_tables.php └── src ├── Commands └── VkRequesterGeneratorCommand.php ├── Contracts ├── Request.php ├── Subscriber.php └── Traits │ └── MagicApiMethod.php ├── Jobs ├── Send.php └── SendBatch.php ├── Models └── VkRequest.php └── VkRequesterServiceProvider.php /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | vendor/ 3 | composer.lock -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Andrey Sosnov aka ATehnix 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Laravel VK Requester 2 | [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/atehnix/laravel-vk-requester/master/LICENSE) 3 | [![Packagist Version](https://img.shields.io/packagist/v/atehnix/laravel-vk-requester.svg)](https://packagist.org/packages/atehnix/laravel-vk-requester) 4 | [![Packagist Stats](https://poser.pugx.org/atehnix/laravel-vk-requester/downloads)](https://packagist.org/packages/atehnix/laravel-vk-requester/stats) 5 | 6 | 7 | 8 | Пакет предоставляет удобный способ выполнения запросов к API социальной сети Vk.Сom. 9 | 10 | Запросы выполняются в фоновом режиме, используя систему очередей Laravel. 11 | На каждый ответ от API генерируется событие, на которое можно подписаться, обработать/сохранить полученные данные и, при необходимости, добавить новые запросы. 12 | 13 | Благодаря такому подходу можно гибко выстраивать цепочки из нескольких взаимосвязанных запросов, добавляя в очередь "дочерние" запросы при получении ответа от "родительского". 14 | 15 | #### Например: 16 | ```yaml 17 | # Получить группы по списку ID 18 | - groups.getByIds 19 | 20 | # Для каждой группы получить участников 21 | - groups.getMembers 22 | 23 | # Каждого участника добавить себе в друзья 24 | - friends.add 25 | 26 | # Для каждой группы получить посты 27 | - wall.get 28 | 29 | # Для каждого поста получить комментарии 30 | - wall.getComments 31 | 32 | ``` 33 | 34 | А благодаря автоматическому оборачиванию запросов в ["execute-запросы"](https://vk.com/dev/execute) (по 25 в каждом), выполнение происходит в разы быстрее и понижается вероятность превышения лимитов Vk.Com на кол-во и частоту запросов. 35 | 36 | ## А можно я без очереди? Мне только спросить.. 37 | Конечно можно! В состав пакета входит простой и удобный API-клиент - [atehnix/vk-client](https://github.com/atehnix/vk-client), о возможностях которого можно узнать в его документации. 38 | 39 | Впрочем, можно и вовсе установить только его, если вам не нужны очереди запросов :). 40 | 41 | А если нужны, то продолжим: 42 | 43 | ## Установка 44 | ##### Для установки через [Composer](https://getcomposer.org/), выполнить: 45 | ``` 46 | composer require atehnix/laravel-vk-requester 47 | ``` 48 | 49 | ##### Добавить в массив `providers` в файле `config/app.php`: 50 | ```php 51 | ATehnix\LaravelVkRequester\VkRequesterServiceProvider::class, 52 | ``` 53 | 54 | ##### Выполнить: 55 | ``` 56 | php artisan vendor:publish --provider="ATehnix\LaravelVkRequester\VkRequesterServiceProvider" 57 | ``` 58 | ##### и 59 | ``` 60 | php artisan migrate 61 | ``` 62 | 63 | > Внимание! Предполагается, что в вашем Laravel проекте уже настроены [очереди](https://laravel.com/docs/master/queues) и [планировщик задач](https://laravel.com/docs/master/scheduling) (Cron). 64 | 65 | 66 | ## Добавление запроса в очередь 67 | ```php 68 | 'wall.get', 73 | 'parameters' => ['owner_id' => 1], 74 | 'token' => 'some_token', 75 | ]); 76 | ``` 77 | 78 | Раз в минуту (по Cron'у) из таблицы временного хранения все новые запросы переносятся в основную очередь Laravel. 79 | 80 | Для уменьшения кол-ва реальных обращений к API, все запросы будут автоматически обернуты в ["execute-запросы"](https://vk.com/dev/execute) по 25 в каждом. 81 | 82 | 83 | ## Подписка на ответы API 84 | В качестве удобного способа подписки на ответы API рекомендуется использовать классы, наследованные от `ATehnix\LaravelVkRequester\Contracts\Subscriber`. 85 | 86 | Метод `onSuccess($request, $response)` будет вызываться при успешном выполнении запроса, а метод `onFail($request, $error)` при неудачном. 87 | 88 | #### Пример: 89 | ```php 90 | context`). 151 | 152 | ## Где взять API токен? 153 | Перед тем как начать отправлять запросы, необходимо получить API Token. 154 | Ниже представлен один из способов его получить. 155 | 156 | ##### Добавьте в `config/services.php`: 157 | ```php 158 | [ 162 | 'client_id' => env('VKONTAKTE_KEY'), 163 | 'client_secret' => env('VKONTAKTE_SECRET'), 164 | 'redirect' => env('VKONTAKTE_REDIRECT_URI'), 165 | ], 166 | ]; 167 | ``` 168 | 169 | В файле `.env` укажите соответствующие параметры авторизации вашего [VK-приложения](https://vk.com/apps?act=manage). 170 | 171 | ##### Пример получения токена 172 | ```php 173 | getUrl()}'> Войти через VK.Com
"; 177 | 178 | if (Request::exists('code')) { 179 | echo 'Token: '.$auth->getToken(Request::get('code')); 180 | } 181 | }); 182 | ``` 183 | 184 | > Пример демонстрирует лишь сам принцип получения токена. Как и где вы будете его получать и хранить вы решаете сами. 185 | 186 | ## License 187 | [MIT](https://raw.github.com/atehnix/laravel-vk-requester/master/LICENSE) 188 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "atehnix/laravel-vk-requester", 3 | "license": "MIT", 4 | "description": "Laravel package for Vk.com API", 5 | "keywords": [ 6 | "laravel", 7 | "php", 8 | "queue", 9 | "api", 10 | "client", 11 | "vk", 12 | "vk.com", 13 | "vkontakte" 14 | ], 15 | "authors": [ 16 | { 17 | "name": "ATehnix", 18 | "email": "atehnix@gmail.com" 19 | } 20 | ], 21 | "require": { 22 | "php": ">=5.5.9", 23 | "laravel/framework": ">=5.2", 24 | "atehnix/vk-client": "^1.0.0" 25 | }, 26 | "autoload": { 27 | "psr-4": { 28 | "ATehnix\\LaravelVkRequester\\": "src" 29 | } 30 | }, 31 | "extra": { 32 | "laravel": { 33 | "providers": [ 34 | "ATehnix\\LaravelVkRequester\\VkRequesterServiceProvider" 35 | ] 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /publish/config/vk-requester.php: -------------------------------------------------------------------------------- 1 | '5.53', 15 | 16 | /* 17 | |-------------------------------------------------------------------------- 18 | | Scope 19 | |-------------------------------------------------------------------------- 20 | | 21 | | To receive necessary permissions during authorization, fill scope 22 | | parameter containing names of the required permissions as array items. 23 | | 24 | | See more at: https://vk.com/dev/permissions 25 | | 26 | */ 27 | 28 | 'scope' => [ 29 | 'offline', 30 | ], 31 | 32 | /* 33 | |-------------------------------------------------------------------------- 34 | | Table name 35 | |-------------------------------------------------------------------------- 36 | | 37 | | The name of the table for temporary storage requests. 38 | | 39 | */ 40 | 41 | 'table' => 'vk_requests', 42 | 43 | /* 44 | |-------------------------------------------------------------------------- 45 | | Delay before request 46 | |-------------------------------------------------------------------------- 47 | | 48 | | The delay before sending the request in milliseconds. 49 | | 50 | */ 51 | 52 | 'delay' => 350, 53 | 54 | /* 55 | |-------------------------------------------------------------------------- 56 | | Pass errors 57 | |-------------------------------------------------------------------------- 58 | | 59 | | Pass API errors without throwing exception. 60 | | If false - throw VkException when an API errors occurs. 61 | | 62 | */ 63 | 64 | 'pass_error' => true, 65 | 66 | /* 67 | |-------------------------------------------------------------------------- 68 | | Auto dispatch 69 | |-------------------------------------------------------------------------- 70 | | 71 | | Auto dispatch of job for sending batch requests. 72 | | 73 | | When "auto_dispatch" option is false, you can manually define 74 | | VkRequesterGeneratorCommand command in task scheduler. Or you may pass 75 | | array of VkRequests to the SendBatch job and manually dispatch it. 76 | | 77 | */ 78 | 79 | 'auto_dispatch' => true, 80 | 81 | ]; 82 | -------------------------------------------------------------------------------- /publish/database/2016_01_01_100000_create_vk_requester_tables.php: -------------------------------------------------------------------------------- 1 | table = config('vk-requester.table', VkRequest::DEFAULT_TABLE); 18 | } 19 | 20 | /** 21 | * Run the migrations. 22 | */ 23 | public function up() 24 | { 25 | Schema::create($this->table, function (Blueprint $table) { 26 | $table->increments('id'); 27 | $table->string('method'); 28 | $table->text('parameters')->nullable(); 29 | $table->string('token')->nullable(); 30 | $table->string('tag')->default('default'); 31 | $table->text('context')->nullable(); 32 | $table->timestamps(); 33 | }); 34 | } 35 | 36 | /** 37 | * Reverse the migrations. 38 | */ 39 | public function down() 40 | { 41 | Schema::dropIfExists($this->table); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/Commands/VkRequesterGeneratorCommand.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | namespace ATehnix\LaravelVkRequester\Commands; 11 | 12 | use ATehnix\LaravelVkRequester\Jobs\SendBatch; 13 | use ATehnix\LaravelVkRequester\Models\VkRequest; 14 | use Illuminate\Console\Command; 15 | use Illuminate\Database\Eloquent\Collection; 16 | use Illuminate\Foundation\Bus\DispatchesJobs; 17 | 18 | class VkRequesterGeneratorCommand extends Command 19 | { 20 | use DispatchesJobs; 21 | 22 | /** 23 | * Default number of nested requests 24 | */ 25 | const NUMBER_OF_REQUESTS = 25; 26 | 27 | /** 28 | * The name and signature of the console command. 29 | * 30 | * @var string 31 | */ 32 | protected $signature = 'vk-requester:generate'; 33 | 34 | /** 35 | * The console command description. 36 | * 37 | * @var string 38 | */ 39 | protected $description = 'Generate request jobs in queue.'; 40 | 41 | /** 42 | * Execute the console command. 43 | */ 44 | public function handle() 45 | { 46 | VkRequest::all()->groupBy('token')->each(function (Collection $requests, $token) { 47 | foreach ($requests->chunk(self::NUMBER_OF_REQUESTS) as $chunkRequests) { 48 | $this->dispatch(new SendBatch($chunkRequests, $token)); 49 | } 50 | }); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/Contracts/Request.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | namespace ATehnix\LaravelVkRequester\Contracts; 11 | 12 | use ATehnix\LaravelVkRequester\Contracts\Traits\MagicApiMethod; 13 | use ATehnix\LaravelVkRequester\Models\VkRequest; 14 | 15 | /** 16 | * @inheritdoc 17 | */ 18 | abstract class Request extends VkRequest 19 | { 20 | use MagicApiMethod; 21 | 22 | /** 23 | * @inheritdoc 24 | */ 25 | protected static function boot() 26 | { 27 | static::saving(function (self $request) { 28 | $request->setAttribute('method', $request->getApiMethod()); 29 | }); 30 | } 31 | 32 | /** 33 | * Get or set value of parameter 34 | * 35 | * @param string $key 36 | * @param null $newValue 37 | * @return mixed 38 | */ 39 | public function parameter(string $key, $newValue = null) 40 | { 41 | if (func_num_args() >= 2) { 42 | $this->parameters = array_merge($this->parameters, [$key => $newValue]); 43 | } 44 | 45 | return isset($this->parameters[$key]) ? $this->parameters[$key] : null; 46 | } 47 | 48 | /** 49 | * Setter for Parameters 50 | * 51 | * @param array $parameters 52 | */ 53 | public function setParametersAttribute(array $parameters) 54 | { 55 | $defaultParameters = $this->getDefaultParameters(); 56 | $this->attributes['parameters'] = json_encode( 57 | array_merge($defaultParameters, $parameters) 58 | ); 59 | } 60 | 61 | /** 62 | * Define default parameters for request 63 | * 64 | * @return array 65 | */ 66 | abstract protected function getDefaultParameters(); 67 | } 68 | -------------------------------------------------------------------------------- /src/Contracts/Subscriber.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | namespace ATehnix\LaravelVkRequester\Contracts; 11 | 12 | use ATehnix\LaravelVkRequester\Contracts\Traits\MagicApiMethod; 13 | use ATehnix\LaravelVkRequester\Models\VkRequest; 14 | use ATehnix\VkClient\Client; 15 | use ATehnix\VkClient\Exceptions\VkException; 16 | use Illuminate\Events\Dispatcher; 17 | 18 | /** 19 | * @inheritdoc 20 | */ 21 | abstract class Subscriber 22 | { 23 | use MagicApiMethod; 24 | 25 | /** 26 | * Expected tag 27 | * 28 | * @var string 29 | */ 30 | protected $tag = 'default'; 31 | 32 | /** 33 | * Handling success event 34 | * 35 | * @param VkRequest $request 36 | * @param mixed $response 37 | */ 38 | abstract public function onSuccess(VkRequest $request, $response); 39 | 40 | /** 41 | * Handling fail event 42 | * 43 | * @param VkRequest $request 44 | * @param array $error 45 | */ 46 | public function onFail(VkRequest $request, array $error) 47 | { 48 | // 49 | } 50 | 51 | /** 52 | * Register the listeners for the subscriber. 53 | * 54 | * @param Dispatcher $events 55 | */ 56 | public function subscribe(Dispatcher $events) 57 | { 58 | $events->listen( 59 | sprintf(VkRequest::EVENT_FORMAT, VkRequest::STATUS_SUCCESS, $this->getApiMethod(), $this->tag), 60 | static::class.'@onSuccess' 61 | ); 62 | $events->listen( 63 | sprintf(VkRequest::EVENT_FORMAT, VkRequest::STATUS_FAIL, $this->getApiMethod(), $this->tag), 64 | static::class.'@onFail' 65 | ); 66 | } 67 | 68 | /** 69 | * Convert error to Exception object 70 | * 71 | * @param array $error 72 | * @return VkException 73 | */ 74 | protected function toException(array $error) 75 | { 76 | return Client::toException($error); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/Contracts/Traits/MagicApiMethod.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | namespace ATehnix\LaravelVkRequester\Contracts\Traits; 11 | 12 | use Illuminate\Support\Str; 13 | 14 | /** 15 | * Trait MagicApiMethod 16 | */ 17 | trait MagicApiMethod 18 | { 19 | protected $apiMethod; 20 | 21 | /** 22 | * Get API Method by class name. 23 | * 24 | * @return string 25 | */ 26 | protected function getApiMethod() 27 | { 28 | if (!isset($this->apiMethod)) { 29 | $words = explode('_', Str::snake(class_basename($this)), -1); 30 | $endpoint = strtolower(array_shift($words)); 31 | $action = Str::camel(implode('_', $words)) ?: '*'; 32 | $method = sprintf('%s.%s', $endpoint, $action); 33 | $this->apiMethod = $endpoint ? $method : 'undefined'; 34 | } 35 | 36 | return $this->apiMethod; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Jobs/Send.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | namespace ATehnix\LaravelVkRequester\Jobs; 11 | 12 | use ATehnix\LaravelVkRequester\Models\VkRequest; 13 | use ATehnix\VkClient\Client; 14 | use ATehnix\VkClient\Requests\Request; 15 | use Illuminate\Bus\Queueable; 16 | use Illuminate\Contracts\Queue\ShouldQueue; 17 | 18 | /** 19 | * Class Send 20 | */ 21 | class Send implements ShouldQueue 22 | { 23 | use Queueable; 24 | 25 | /** 26 | * Default delay before sending request (in milliseconds) 27 | */ 28 | const DEFAULT_DELAY = 350; 29 | 30 | /** 31 | * API Client 32 | * 33 | * @var Client 34 | */ 35 | protected $api; 36 | 37 | /** 38 | * Instance of request 39 | * 40 | * @var VkRequest 41 | */ 42 | protected $request; 43 | 44 | /** 45 | * Data of response 46 | * 47 | * @var array 48 | */ 49 | protected $response; 50 | 51 | /** 52 | * Create a new job instance. 53 | * 54 | * @param VkRequest $request 55 | */ 56 | public function __construct(VkRequest $request) 57 | { 58 | $this->request = $request; 59 | $request->delete(); 60 | } 61 | 62 | /** 63 | * Execute the job. 64 | * 65 | * @param Client $api Pre-configured instance of the Client 66 | */ 67 | public function handle(Client $api) 68 | { 69 | // Initialize 70 | $this->api = $api; 71 | $this->api->setPassError(config('vk-requester.pass_error', true)); 72 | 73 | // Processing 74 | $this->sendToApi(); 75 | $this->fireEvent(); 76 | } 77 | 78 | /** 79 | * Send request to Vk.com API 80 | */ 81 | protected function sendToApi() 82 | { 83 | usleep(config('vk-requester.delay', self::DEFAULT_DELAY) * 1000); 84 | $clientRequest = new Request($this->request->method, $this->request->parameters, $this->request->token); 85 | $clientResponse = $this->api->send($clientRequest); 86 | $this->response = $this->getResponse($clientResponse); 87 | } 88 | 89 | /** 90 | * Get data array from response 91 | * 92 | * @param array $clientResponse 93 | * @return array 94 | */ 95 | protected function getResponse(array $clientResponse) 96 | { 97 | if (isset($clientResponse['error'])) { 98 | return $clientResponse['error']; 99 | } 100 | 101 | return isset($clientResponse['response']) ? $clientResponse['response'] : []; 102 | } 103 | 104 | /** 105 | * Fire an event for response 106 | */ 107 | private function fireEvent() 108 | { 109 | $status = isset($this->response['error_code']) ? VkRequest::STATUS_FAIL : VkRequest::STATUS_SUCCESS; 110 | $event = sprintf(VkRequest::EVENT_FORMAT, $status, $this->request->method, $this->request->tag); 111 | event($event, [$this->request, $this->response]); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/Jobs/SendBatch.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | namespace ATehnix\LaravelVkRequester\Jobs; 11 | 12 | use ATehnix\LaravelVkRequester\Models\VkRequest; 13 | use ATehnix\VkClient\Client; 14 | use ATehnix\VkClient\Requests\ExecuteRequest; 15 | use ATehnix\VkClient\Requests\Request; 16 | use Illuminate\Bus\Queueable; 17 | use Illuminate\Contracts\Queue\ShouldQueue; 18 | use Illuminate\Database\Eloquent\Collection; 19 | 20 | /** 21 | * Class SendBatch 22 | */ 23 | class SendBatch implements ShouldQueue 24 | { 25 | use Queueable; 26 | 27 | /** 28 | * Default delay before sending request (in milliseconds) 29 | */ 30 | const DEFAULT_DELAY = 350; 31 | 32 | /** 33 | * API Token 34 | * 35 | * @var string 36 | */ 37 | protected $token; 38 | 39 | /** 40 | * API Client 41 | * 42 | * @var Client 43 | */ 44 | protected $api; 45 | 46 | /** 47 | * Collection of requests 48 | * 49 | * @var Collection 50 | */ 51 | protected $requests; 52 | 53 | /** 54 | * Collection of data responses 55 | * 56 | * @var array 57 | */ 58 | protected $responses; 59 | 60 | /** 61 | * Create a new job instance. 62 | * 63 | * @param Collection $requests 64 | * @param string $token Access token for Vk.com API 65 | */ 66 | public function __construct(Collection $requests, $token) 67 | { 68 | $this->requests = $requests; 69 | $this->token = (string)$token; 70 | VkRequest::whereIn('id', $requests->pluck('id')->all())->delete(); 71 | } 72 | 73 | /** 74 | * Execute the job. 75 | * 76 | * @param Client $api Pre-configured instance of the Client 77 | */ 78 | public function handle(Client $api) 79 | { 80 | // Initialize 81 | $this->api = $api; 82 | $this->api->setDefaultToken($this->token); 83 | $this->api->setPassError(config('vk-requester.pass_error', true)); 84 | 85 | // Processing 86 | if (!$this->requests->isEmpty()) { 87 | $this->sendToApi(); 88 | $this->fireEvents(); 89 | } 90 | } 91 | 92 | /** 93 | * Send requests to Vk.com API 94 | */ 95 | protected function sendToApi() 96 | { 97 | usleep(config('vk-requester.delay', self::DEFAULT_DELAY) * 1000); 98 | $executeRequest = $this->makeExecuteRequest($this->requests); 99 | $executeResponse = $this->api->send($executeRequest); 100 | $this->responses = $this->getResponses($executeResponse); 101 | } 102 | 103 | /** 104 | * Make a new "execute" request instanse with nested requests. 105 | * 106 | * @param Collection $requests 107 | * @return ExecuteRequest 108 | */ 109 | protected function makeExecuteRequest(Collection $requests) 110 | { 111 | $clientRequests = $requests->map(function (VkRequest $request) { 112 | return new Request($request->method, $request->parameters); 113 | }); 114 | 115 | return ExecuteRequest::make($clientRequests->all()); 116 | } 117 | 118 | /** 119 | * Get array of nested responses in "execute" response 120 | * 121 | * @param array $executeResponse 122 | * @return array 123 | */ 124 | protected function getResponses(array $executeResponse) 125 | { 126 | if (isset($executeResponse['error'])) { 127 | return array_fill(0, $this->requests->count(), $executeResponse['error']); 128 | } 129 | 130 | $errors = isset($executeResponse['execute_errors']) ? $executeResponse['execute_errors'] : []; 131 | 132 | return array_map(function ($response) use (&$errors) { 133 | return $response ?: array_shift($errors); 134 | }, $executeResponse['response']); 135 | } 136 | 137 | /** 138 | * Fire an event for each of response 139 | */ 140 | protected function fireEvents() 141 | { 142 | array_map(function (VkRequest $request, $response) { 143 | $status = isset($response['error_code']) ? VkRequest::STATUS_FAIL : VkRequest::STATUS_SUCCESS; 144 | $event = sprintf(VkRequest::EVENT_FORMAT, $status, $request->method, $request->tag); 145 | event($event, [$request, $response]); 146 | }, $this->requests->all(), $this->responses); 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /src/Models/VkRequest.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | namespace ATehnix\LaravelVkRequester\Models; 11 | 12 | use Illuminate\Database\Eloquent\Model; 13 | 14 | /** 15 | * Class VkRequest 16 | * 17 | * @property int $id 18 | * @property string $method 19 | * @property array $parameters 20 | * @property string $token 21 | * @property string $tag 22 | * @property array $context 23 | */ 24 | class VkRequest extends Model 25 | { 26 | /** 27 | * Default table for associating with requests 28 | */ 29 | const DEFAULT_TABLE = 'vk_requests'; 30 | 31 | /** 32 | * Format for name of events 33 | */ 34 | const EVENT_FORMAT = 'vk-requester.%s: %s #%s'; 35 | 36 | /** 37 | * Name of fail status 38 | */ 39 | const STATUS_FAIL = 'fail'; 40 | 41 | /** 42 | * Name of success status 43 | */ 44 | const STATUS_SUCCESS = 'success'; 45 | 46 | /** 47 | * The attributes that are mass assignable. 48 | * 49 | * @var array 50 | */ 51 | protected $fillable = [ 52 | 'method', 53 | 'parameters', 54 | 'token', 55 | 'tag', 56 | 'context', 57 | ]; 58 | 59 | /** 60 | * The attributes that should be hidden for arrays. 61 | * 62 | * @var array 63 | */ 64 | protected $hidden = [ 65 | 'token', 66 | 'created_at', 67 | 'updated_at', 68 | ]; 69 | 70 | /** 71 | * The attributes that should be cast to native types. 72 | * 73 | * @var array 74 | */ 75 | protected $casts = [ 76 | 'parameters' => 'array', 77 | 'context' => 'array', 78 | ]; 79 | 80 | /** 81 | * Create a new VkRequest instance. 82 | * 83 | * @param array $attributes 84 | */ 85 | public function __construct(array $attributes = []) 86 | { 87 | $this->table = config('vk-requester.table', self::DEFAULT_TABLE); 88 | 89 | parent::__construct($attributes); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/VkRequesterServiceProvider.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | namespace ATehnix\LaravelVkRequester; 11 | 12 | use ATehnix\LaravelVkRequester\Commands\VkRequesterGeneratorCommand; 13 | use ATehnix\VkClient\Auth; 14 | use ATehnix\VkClient\Client; 15 | use Illuminate\Console\Scheduling\Schedule; 16 | use Illuminate\Support\ServiceProvider; 17 | 18 | class VkRequesterServiceProvider extends ServiceProvider 19 | { 20 | /** 21 | * Bootstrap the application services. 22 | */ 23 | public function boot() 24 | { 25 | $this->publishes([__DIR__.'/../publish/config/' => config_path()], 'config'); 26 | $this->publishes([__DIR__.'/../publish/database/' => database_path('migrations')], 'database'); 27 | 28 | if (config('vk-requester.auto_dispatch', true)) { 29 | $this->app->booted(function () { 30 | $schedule = $this->app->make(Schedule::class); 31 | $schedule->command('vk-requester:generate')->everyMinute(); 32 | }); 33 | } 34 | } 35 | 36 | /** 37 | * Register the application services. 38 | */ 39 | public function register() 40 | { 41 | $this->app->singleton(Client::class, function () { 42 | return new Client(config('vk-requester.version', '5.53')); 43 | }); 44 | 45 | $this->app->singleton(Auth::class, function () { 46 | return new Auth( 47 | config('services.vkontakte.client_id'), 48 | config('services.vkontakte.client_secret'), 49 | config('services.vkontakte.redirect'), 50 | implode(',', config('vk-requester.scope', [])) 51 | ); 52 | }); 53 | 54 | $this->commands([VkRequesterGeneratorCommand::class]); 55 | } 56 | } 57 | --------------------------------------------------------------------------------