AdGroupsLoadKeywords.php 1.7 KB
<?php

namespace App\Console\Commands;

use App\Models\Campaigns;
use App\Models\Tokens;
use App\Service\API\API;
use App\Service\Requests\APIRequest;
use Illuminate\Console\Command;

class AdGroupsLoadKeywords extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'adgroups:loadKeywords';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Загрузка фраз РК';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws \Exception
     */
    public function handle()
    {
        $campaigns = Campaigns::has('groupsForKeywordsLoadable')
            ->with('groupsForKeywordsLoadable')
            ->forManaged()->forEnabled()->forNotGroupsLoadable()->get();

        if (!$campaigns->count()) {
            return;
        }

        $token = Tokens::where('type', Tokens::MAIN)->first();
        if (!$token) {
            throw new \Exception('Не найден токен блин');
        }

        $ad_group_ids = $campaigns->pluck('groupsForKeywordsLoadable')
        ->collapse()
        ->pluck('external_id')
        ->toArray();

        foreach (array_chunk($ad_group_ids, 1000) as $ids_limit) {
            $factory = APIRequest::getInstance(API::YANDEX);
            $factory->setToken($token);

            $factory->getRequest('Keywords', 'get')
                ->call([
                    'AdGroupIds' => $ids_limit,
                ]);
        }

        return 0;
    }
}