<?php

namespace App\Service;

use App\Integrations\Semrush\Client;
use App\Integrations\Semrush\Requests\GetBacklinksRequest;

final class BacklinksChecker implements StatCheckerInterface
{
    /**
     * @var Client
     */
    private $client;
    /**
     * @var GetBacklinksRequest
     */
    private $request;

    public function __construct(Client $client, GetBacklinksRequest $request)
    {
        $this->client = $client;
        $this->request = $request;
    }

    public function check($domain)
    {
        $this->request->
            setUrl($domain);

        $response = $this->client->execute($this->request);

        return $this->__toJson($response->getBody());
    }

    private function __toJson(string $string)
    {
        $results = preg_split('/\R/', $string);

        array_pop($results);

        $headers = str_getcsv(array_shift($results), ';');
        $result = str_getcsv(array_shift($results), ';');

        return json_encode(array_combine($headers, $result));
    }
}
