Completed
Push — master ( 527364...a780c1 )
by Vinicius
05:34
created

CommonProxy   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 73.68%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 3
dl 0
loc 48
ccs 14
cts 19
cp 0.7368
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 2
A parseUrl() 0 16 2
A getHttpResponse() 0 8 1
1
<?php
2
namespace CViniciusSDias\GoogleCrawler\Proxy;
3
4
use CViniciusSDias\GoogleCrawler\Exception\InvalidResultException;
5
use CViniciusSDias\GoogleCrawler\Exception\InvalidUrlException;
6
use GuzzleHttp\Client;
7
use Psr\Http\Message\ResponseInterface;
8
9
/**
10
 * Class that can be used for multiple proxies services, including hideproxy.me, onlinecollege.info, zend2, etc.
11
 *
12
 * @package CViniciusSDias\GoogleCrawler\Proxy
13
 * @author Vinicius Dias
14
 */
15
class CommonProxy implements GoogleProxyInterface
16
{
17
    /** @var string $endpoint */
18
    protected $endpoint;
19
20
    /**
21
     * Constructor that initializes the specific proxy service
22
     *
23
     * @param string $endpoint Specific service URL
24
     * @throws InvalidUrlException
25
     */
26 3
    public function __construct(string $endpoint)
27
    {
28 3
        if (!filter_var($endpoint, FILTER_VALIDATE_URL)) {
29 1
            throw new InvalidUrlException("Invalid CommonProxy endpoint: $endpoint");
30
        }
31
32 2
        $this->endpoint = $endpoint;
33 2
    }
34
35
    /** {@inheritdoc} */
36
    public function getHttpResponse(string $url): ResponseInterface
37
    {
38
        $data = ['u' => $url, 'allowCookies' => 'on'];
39
        $httpClient = new Client(['cookies' => true, 'verify' => false]);
40
        $response = $httpClient->request('POST', $this->endpoint, ['form_params' => $data]);
41
42
        return $response;
43
    }
44
45
    /** {@inheritdoc} */
46 2
    public function parseUrl(string $url): string
47
    {
48 2
        $link = parse_url($url);
49 2
        parse_str($link['query'], $link);
50
51 2
        parse_str($link['u'], $link);
52 2
        $link = array_values($link);
53
54 2
        $url = filter_var($link[0], FILTER_VALIDATE_URL);
55
        // If this is not a valid URL, so the result is (probably) an image, news or video suggestion
56 2
        if (!$url) {
57 1
            throw new InvalidResultException();
58
        }
59
60 1
        return $url;
61
    }
62
}
63