GetRetargetinglists.php 2.81 KB
<?php

namespace App\Service\Requests\Direct;

use App\Jobs\ProcessCallLimitedAPI;
use App\Models\Retargetinglist;
use App\Service\Contract\APIRequest;
use App\Service\Requests\DirectRequest;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class GetRetargetinglists extends DirectRequest
{
    protected $max_count = -1;
    protected $max_count_Ids = 10000;

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

    public function getObjectsCount()
    {
        $params = $this->getParams();
        if (isset($params['SelectionCriteria']['Ids'])) {
            return count($params['SelectionCriteria']['Ids']);
        }
        return -1;
    }

    public function slice($maxObjects): ?APIRequest
    {
        $params = $this->getParams();

        if (isset($params['SelectionCriteria']['Ids'])) {
            return $this->sliceByKey($maxObjects, ['SelectionCriteria', 'Ids']);
        }

        return null;
    }

    function handle($response)
    {
        if (isset($response['result']['RetargetingLists'])) {
            foreach ($response['result']['RetargetingLists'] as $retargeting_list) {

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

                if ($this->getToken()->isMain()) {

                    $data = [
                        'external_id' => $external_id,
                        'type' => $retargeting_list['Type'],
                        'name' => $retargeting_list['Name'],
                        'description' => $retargeting_list['Description'],
                        'rules' => $retargeting_list['Rules'],
                    ];

                    $retargetinglist = Retargetinglist::updateOrCreate([
                        'external_id' => $external_id
                    ], $data);

                    if (!$retargetinglist->wasRecentlyCreated && $retargetinglist->wasChanged($retargetinglist::getPropertiesWatch()->toArray())) {
                        $retargetinglist->goalRetargetinglists()->forExternal()->update([
                            'updated_need' => Carbon::now(),
                        ]);
                    }

                } else {
                    //
                }

            }
        }
    }

    private function requestPrepare($filter)
    {
        $this->setService('RetargetingLists');
        $this->setMethod('get');
        $params = [
            "FieldNames" => [
                "Id", "Type", "Name",
                "Description", "Rules",
            ],
        ];
        if (isset($filter['Ids'])) {

            $this->max_count = $this->max_count_Ids;

            $params['SelectionCriteria'] = [
                'Ids' => $filter['Ids'],
            ];
        }
        $this->setParams($params);
    }
}