Completed
Push — master ( 4da284...7cdfcc )
by Márk
03:21
created

BaseUrlBuilder::buildUrlWithParams()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 9.4285
cc 2
eloc 5
nc 2
nop 3
crap 2
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 array
20
     */
21
    protected $defaultParams = [];
22
23
    /**
24
     * Whether to use HTTPS endpoint.
25
     *
26
     * @var bool
27
     */
28
    protected $secure;
29
30
    /**
31
     * @param array $defaultParams
32
     * @param bool  $secure
33
     */
34 43
    public function __construct(array $defaultParams = [], $secure = true)
35
    {
36 43
        $this->defaultParams = array_filter($defaultParams);
37 43
        $this->secure = (bool) $secure;
38 43
    }
39
40
    /**
41
     * Creates a hash from an email address.
42
     *
43
     * @param string $email
44
     *
45
     * @return string
46
     */
47 42
    protected function createEmailHash($email)
48
    {
49 42
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
50 9
            throw new \InvalidArgumentException('Invalid email address');
51
        }
52
53 33
        return md5(strtolower(trim($email)));
54
    }
55
56
    /**
57
     * Builds the URL based on the given parameters.
58
     *
59
     * @param string    $resource
60
     * @param bool|null $secure
61
     *
62
     * @return string
63
     */
64 32
    protected function buildUrl($resource, $secure = null)
65
    {
66 32
        $secure = isset($secure) ? (bool) $secure : $this->secure;
67
68 32
        $endpoint = $secure ? self::HTTPS_ENDPOINT : self::HTTP_ENDPOINT;
69
70 32
        return sprintf('%s/%s', $endpoint, $resource);
71
    }
72
73
    /**
74
     * Builds the URL based on the given parameters.
75
     *
76
     * @param string    $resource
77
     * @param array     $params
78
     * @param bool|null $secure
79
     *
80
     * @return string
81
     */
82 11
    protected function buildUrlWithParams($resource, array $params = [], $secure = null)
83
    {
84 11
        $params = array_merge($this->defaultParams, array_filter($params));
85
86 11
        if (!empty($params)) {
87 5
            $resource .= '?'.http_build_query($params);
88 5
        }
89
90 11
        return $this->buildUrl($resource, $secure);
91
    }
92
}
93