AddKeywords.php 4.33 KB
<?php

namespace App\Service\Requests\Direct;

use App\Jobs\ProcessCallLimitedAPI;
use App\Models\Keyword;
use App\Models\Pivots\GoalKeyword;
use App\Models\Variable;
use App\Service\Contract\APIRequest;
use App\Service\Requests\DirectRequest;
use App\Service\StrReplaceByVariables;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;

class AddKeywords extends DirectRequest
{
    protected $max_count = 1000;

    protected $timestamp;
    /* @var Collection|GoalKeyword[]|Keyword[]|\stdClass[] */
    protected $goalKeywords;

    public function call($params = null)
    {
        $this->requestPrepare($params);
        $process = new ProcessCallLimitedAPI($this);
        dispatch($process)->onQueue('limits');
    }

    public function getObjectsCount()
    {
        return count($this->getParams()['Keywords']);
    }

    public function slice($maxObjects): ?APIRequest
    {
        $splinter = $this->sliceByKey($maxObjects, 'Keywords');

        $splinter->putParams([
            'goalKeywords' => $this->goalKeywords->slice($maxObjects)->values(),
        ]);

        $this->putParams([
            'goalKeywords' => $this->goalKeywords->slice(0, $maxObjects)
        ]);

        return $splinter;
    }

    public function handle($response)
    {
        try {
            if (!isset($response['result']['AddResults'])) {
                return;
            }

            foreach ($response['result']['AddResults'] as $key => $add_result) {

                $goalKeyword = $this->goalKeywords[$key];

                if (!isset($add_result['Id'])) {
                    Log::debug("AddKeywords, empty Id");
                    Log::debug($add_result);
                    Log::debug($this->getParams()['Keywords'][$key]);

                    GoalKeyword::whereId($goalKeyword->id)
                        ->update([
                            'reserve_create_at' => null,
                        ]);

                    continue;
                }

                $external_id = (string)$add_result['Id'];

                GoalKeyword::whereId($goalKeyword->id)
                    ->update([
                        'external_id' => $external_id,
                        'external_upload_at' => Carbon::now(),
                        'reserve_create_at' => null,
                    ]);

            }
        } catch (\Exception $e) {
            Log::debug($e);
            throw $e;
        }
    }

    public function putParams($params)
    {
        $this->goalKeywords = $params['goalKeywords'];
    }

    public function failed()
    {
        GoalKeyword::whereIn('id', $this->goalKeywords->pluck('id')->toArray())
            ->update([
                'reserve_create_at' => null,
            ]);
    }

    private function requestPrepare($params)
    {
        $this->setService('Keywords');
        $this->setMethod('add');

        $this->putParams($params);

        $variables = Variable::all();

        $lists = [];

        $this->setParams([
            'Keywords' => $this->goalKeywords->map(function ($goalKeyword) use ($variables, &$lists) {

                /* @var $goalKeyword GoalKeyword|Keyword|\stdClass */

                if (!isset($lists[$goalKeyword->dictionary_campaign_id])) {
                    $list = Variable::getListVariablesByDictionaryCampaign($goalKeyword->dictionary_campaign_id, $variables);
                    $lists[$goalKeyword->dictionary_campaign_id] = $list;
                } else {
                    $list = $lists[$goalKeyword->dictionary_campaign_id];
                }

                $data = [
                    'Keyword' => StrReplaceByVariables::getInstance($goalKeyword->keyword, $list)->get(),
                    'AdGroupId' => $goalKeyword->goal_ad_group_external_id,
                ];

                if ($goalKeyword->bid) {
                    $data['Bid'] = $goalKeyword->bid;
                }

                if ($goalKeyword->context_bid) {
                    $data['ContextBid'] = $goalKeyword->context_bid;
                }

                if ($goalKeyword->user_param_1) {
                    $data['UserParam1'] = $goalKeyword->user_param_1;
                }

                if ($goalKeyword->user_param_2) {
                    $data['UserParam2'] = $goalKeyword->user_param_2;
                }

                return $data;
            })->toArray(),
        ]);
    }

}