CheckCampaignsChange.php 1.66 KB
<?php

namespace App\Service\Requests\Direct;

use App\Jobs\ProcessCallLimitedAPI;
use App\Models\Campaigns;
use App\Service\API\API;
use App\Service\Requests\APIRequest;
use App\Service\Requests\DirectRequest;
use Carbon\Carbon;

class CheckCampaignsChange extends DirectRequest
{
    CONST SELF = 'SELF';
    CONST CHILDREN = 'CHILDREN';
    CONST STAT = 'STAT';

    protected $next;

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

    function handle($response)
    {
        foreach ($response['result']['Campaigns'] as $campaign) {
            if (in_array(self::SELF, $campaign['ChangesIn']) || in_array(self::CHILDREN, $campaign['ChangesIn'])) {
                $data = [
                    'token' => $this->getToken()->id,
                ];

                if (in_array(self::SELF, $campaign['ChangesIn'])) {
                    $data['updated_self'] = Carbon::now();
                }

                if (in_array(self::CHILDREN, $campaign['ChangesIn'])) {
                    $data['updated_children'] = Carbon::now();
                }

                Campaigns::firstOrCreate([
                    'external_id' => $campaign['CampaignId']
                ], $data);
            }
        }
        $this->getToken()->timestamp = $response['result']['Timestamp'];
        $this->getToken()->save();
    }

    private function requestPrepare($params)
    {
        $this->setService('changes');
        $this->setMethod('checkDictionaries');
        $this->setParams([
            "Timestamp" => $this->getToken()->timestamp
        ]);
    }
}