File: /var/www/quadcode/app/Services/ActiveCampaignService.php
<?php
namespace App\Services;
use App\Helpers\ActiveCampaignHelper;
use App\Models\ActiveCampaignList;
use Exception;
class ActiveCampaignService extends AbstractService
{
private ActiveCampaignHelper $activeCampaignHelper;
public function __construct(ActiveCampaignHelper $activeCampaignHelper)
{
$this->activeCampaignHelper = $activeCampaignHelper;
}
public function check(): bool
{
return $this->activeCampaignHelper->check();
}
private function getAllLists(): array
{
$lists = [];
$limit = 20;
$offset = 0;
$totalCount = $limit;
while ($offset < $totalCount) {
$response = $this->activeCampaignHelper->getAllLists($limit, $offset);
if (!$response->successful()) {
$error = $response->json()['message'] ?? 'Unknown error';
$this->lastError = $error;
return [];
}
$response = $response->json();
foreach ($response['lists'] as $list) {
$lists[$list['id']] = $list['name'];
}
$totalCount = $response['meta']['total'] ?? 0;
$offset += $limit;
}
return $lists;
}
public function syncLists(): bool
{
$this->cleanState();
try {
$this->addActionLog('Get all lists');
$lists = $this->getAllLists();
} catch (Exception $exception) {
$this->lastError = $exception->getMessage();
return false;
}
$this->addActionLog('All list count: ' . count($lists));
$created = 0;
$updated = 0;
$createdLists = ActiveCampaignList::query()->get()->keyBy('ac_id');
foreach ($lists as $id => $name) {
if (in_array($id, $createdLists->keys()->toArray())) {
/** @var ActiveCampaignList $createdList */
$createdList = $createdLists[$id];
if ($name === $createdList->name) {
continue;
}
$createdList->name = $name;
$createdList->save();
$updated++;
} else {
$newAcList = new ActiveCampaignList(['ac_id' => $id, 'name' => $name]);
$newAcList->save();
$created++;
}
}
$this->addActionLog('Created: ' . $created);
$this->addActionLog('Updated: ' . $updated);
return true;
}
}