Completed
Push — master ( eddf66...feef3d )
by Márk
03:13
created

BaseUrlBuilder::buildUrl()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4.0582

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 21
ccs 11
cts 13
cp 0.8462
rs 9.0534
cc 4
eloc 11
nc 8
nop 2
crap 4.0582
1
<?php
2
3
namespace Gravatar;
4
5
/**
6
 * Provides common functions for UrlBuilder and SingleUrlBuilder.
7
 *
8
 * @author Márk Sági-Kazár <[email protected]>
9
 */
10
abstract class BaseUrlBuilder
11
{
12
    /**
13
     * Gravatar endpoints.
14
     */
15
    const HTTP_ENDPOINT = 'http://www.gravatar.com';
16
    const HTTPS_ENDPOINT = 'https://secure.gravatar.com';
17
18
    /**
19
     * @var bool
20
     */
21
    protected $useHttps;
22
23
    /**
24
     * @param bool $useHttps
25
     */
26 25
    public function __construct($useHttps = true)
27
    {
28 25
        $this->useHttps = (bool) $useHttps;
29 25
    }
30
31
    /**
32
     * Sets the used connection endpoint.
33
     *
34
     * @param bool $useHttps
35
     */
36 16
    public function useHttps($useHttps)
37
    {
38 16
        $this->useHttps = (bool) $useHttps;
39 16
    }
40
41
    /**
42
     * Creates a hash from an email address.
43
     *
44
     * @param string $email
45
     *
46
     * @return string
47
     */
48 37
    protected function createEmailHash($email)
49
    {
50 37
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
51 9
            throw new \InvalidArgumentException('Invalid email address');
52
        }
53
54 28
        return md5(strtolower(trim($email)));
55
    }
56
57
    /**
58
     * Builds the URL based on the given parameters.
59
     *
60
     * @param string $segment
61
     * @param array  $params
62
     *
63
     * @return string
64
     */
65 27
    protected function buildUrl($segment, array $params = [])
66
    {
67 27
        $useHttps = $this->useHttps;
68
69 27
        if (isset($params['secure'])) {
70 12
            $useHttps = (bool)$params['secure'];
71 12
            unset($params['secure']);
72 12
        }
73
74 27
        $endpoint = $useHttps ? self::HTTPS_ENDPOINT : self::HTTP_ENDPOINT;
75
76 27
        $params = array_filter($params);
77
78 27
        $url = sprintf('%s/%s', $endpoint, $segment);
79
80 27
        if (!empty($params)) {
81
            $url .= '?'.http_build_query($params);
82
        }
83
84 27
        return $url;
85
    }
86
}
87