SwiftypeCrawler::send()   B
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 72
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 43
c 1
b 0
f 0
nc 6
nop 2
dl 0
loc 72
rs 8.6097

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Ichaber\SSSwiftype\Service;
4
5
use GuzzleHttp\Client;
6
use Psr\Log\LoggerInterface;
7
use SilverStripe\Core\Injector\Injectable;
8
use SilverStripe\Core\Injector\Injector;
9
use Throwable;
10
11
/**
12
 * Credit: [Bernard Hamlin](https://github.com/blueo) and [Mojmir Fendek](https://github.com/mfendeksilverstripe)
13
 *
14
 * Class SwiftypeCrawler
15
 *
16
 * @package Ichaber\SSSwiftype\Service
17
 */
18
class SwiftypeCrawler
19
{
20
    use Injectable;
21
22
    const SWIFTYPE_API = 'https://api.swiftype.com/api/v1/engines/%s/domains/%s/crawl_url.json';
23
24
    /**
25
     * @var Client
26
     */
27
    private $client;
28
29
    /**
30
     * @var LoggerInterface
31
     */
32
    private $logger;
33
34
    /**
35
     * @var array
36
     */
37
    private $messages = [];
38
39
    /**
40
     * Crawler constructor.
41
     *
42
     * @param Client|null $client
43
     */
44
    public function __construct(?Client $client = null)
45
    {
46
        if ($client === null) {
47
            $client = new Client();
48
        }
49
50
        $this->client = $client;
51
    }
52
53
    /**
54
     * Crawls a page based on the locale
55
     *
56
     * @param string $url
57
     * @param mixed|null $additionalData If set, we assume that you want to populate your Credentials through extension
58
     * @return bool
59
     */
60
    public function send(string $url, $additionalData = null): bool
61
    {
62
        $credentials = SwiftypeCredentials::create($additionalData);
63
        if (!$credentials->isEnabled()) {
64
            $this->addMessage($credentials->getMessage());
65
            $this->getLogger()->alert($credentials->getMessage());
66
67
            return false;
68
        }
69
70
        $swiftypeEndpoint = sprintf(
71
            self::SWIFTYPE_API,
72
            $credentials->getEngineSlug(),
73
            $credentials->getDomainID()
74
        );
75
76
        try {
77
            $response = $this->client->put(
78
                $swiftypeEndpoint,
79
                [
80
                    'headers' => [
81
                        'Content-Type' => 'application/json',
82
                    ],
83
                    'body' => json_encode([
84
                        'auth_token' => $credentials->getAPIKey(),
85
                        'url' => $url,
86
                    ]),
87
                ]
88
            );
89
90
            $contents = $response->getBody()->getContents();
91
        } catch (Throwable $e) {
92
            $message = sprintf('Exception %s for url: %s message: %s', get_class($e), $url, $e->getMessage());
93
94
            $this->addMessage($message);
95
            $this->getLogger()->alert($message);
96
97
            return false;
98
        }
99
100
        // invalid response code
101
        if (strpos((string) $response->getStatusCode(), '2') !== 0) {
102
            $message = sprintf(
103
                "Swiftype Crawl request failed - invalid response code \n%s\n%s\n%s",
104
                $response->getStatusCode(),
105
                json_encode($response->getHeaders()),
106
                $contents
107
            );
108
109
            $this->addMessage($message);
110
            $this->getLogger()->alert($message);
111
112
            return false;
113
        }
114
115
        // invalid response data
116
        $data = json_decode($contents, true);
117
        if ($data && array_key_exists('error', $data)) {
118
            $message = sprintf(
119
                "Swiftype Crawl request failed - invalid response data \n%s\n%s\n%s",
120
                $response->getStatusCode(),
121
                json_encode($response->getHeaders()),
122
                $contents
123
            );
124
125
            $this->addMessage($message);
126
            $this->getLogger()->alert($message);
127
128
            return false;
129
        }
130
131
        return true;
132
    }
133
134
    /**
135
     * @return array
136
     */
137
    public function getMessages(): array
138
    {
139
        return $this->messages;
140
    }
141
142
    /**
143
     * @return LoggerInterface
144
     */
145
    protected function getLogger(): LoggerInterface
146
    {
147
        if (!$this->logger) {
148
            $this->logger = Injector::inst()->get(LoggerInterface::class);
149
        }
150
151
        return $this->logger;
152
    }
153
154
    /**
155
     * @param string $message
156
     */
157
    protected function addMessage(string $message): void
158
    {
159
        $this->messages[] = $message;
160
    }
161
}
162