WordpressUtil.php 2.45 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
<?php

namespace App\Util;

use App\Entity\User;
use App\Entity\GlobalParameter;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

class WordpressUtil
{
    protected $em;
    protected $client;
    protected $apiKey = null;
    protected $isUsed = null;
    protected $url = null;

    public function __construct(EntityManagerInterface $em, HttpClientInterface $client)
    {
        $this->em = $em;
        $this->client = $client;
    }

    public function getApiKey(): string
    {
        if (null !== $this->apiKey) {
            return $this->apiKey;
        }

        $users = $this->em->getRepository(User::class)->findByRole('ROLE_API');

        return $this->apiKey = $users[0]->getApiKey() ?? '';
    }

    public function getUrl(): string
    {
        if (null !== $this->url) {
            return $this->url;
        }

        return $this->url = $this->em->getRepository(GlobalParameter::class)
                                     ->val(GlobalParameter::WORDPRESS_URL);
    }

    /**
     * Determine whether Wordpress is used or not.
     *
     * @return bool
     */
    public function isUsed(): bool
    {
        if (null !== $this->isUsed) {
            return $this->isUsed;
        }

        return $this->isUsed = (
            'true' === $this->em->getRepository(GlobalParameter::class)
                                ->val(GlobalParameter::USE_WORDPRESS)
            ? true
            : false
        );
    }

    /**
     * Determine whether synchronization with Wordpress is available or not.
     *
     * @return bool
     */
    public function canSync(): bool
    {
        return $this->isUsed() && $this->getUrl();
    }

    /**
     * Run the synchronization with Wordpress, through an API call.
     * Actually, only 'Prestataires' can be sync.
     *
     * @param array|int|null $id  If null, ask for a full sync.
     *
     * @return bool  Return false if the sync isn't run. Else true.
     */
    public function runSync($id = null): bool
    {
        if (! $this->canSync()) {
            return false;
        }

        $endpoint = sprintf("%s/%s/%s",
            $this->getUrl(),
            "wp-json/wosmpl/v1/sync_partners",
            null === $id ? '' : ('?ids=' . \implode(',', (array) $id))
        );

        $this->client->request('GET', $endpoint, [
            'headers' => [
                'API-AUTH-TOKEN' => $this->getApiKey(),
            ],
        ]);

        return true;
    }
}