Completed
Push — master ( feef3d...4da284 )
by Márk
05:20
created

BaseUrlBuilder::buildUrl()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4.1755

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 16
ccs 7
cts 9
cp 0.7778
rs 9.2
cc 4
eloc 8
nc 8
nop 3
crap 4.1755
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
     * @param bool|null $secure
63
     *
64
     * @return string
65
     */
66 27
    protected function buildUrl($segment, array $params = [], $secure = null)
67
    {
68 27
        $useHttps = isset($secure) ? (bool) $secure : $this->useHttps;
69
70 27
        $endpoint = $useHttps ? self::HTTPS_ENDPOINT : self::HTTP_ENDPOINT;
71
72 27
        $params = array_filter($params);
73
74 27
        $url = sprintf('%s/%s', $endpoint, $segment);
75
76 27
        if (!empty($params)) {
77
            $url .= '?'.http_build_query($params);
78
        }
79
80 27
        return $url;
81
    }
82
}
83