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

BaseUrlBuilder   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 83
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 6
Bugs 0 Features 1
Metric Value
wmc 8
c 6
b 0
f 1
lcom 1
cbo 0
dl 0
loc 83
ccs 18
cts 18
cp 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A createEmailHash() 0 8 2
A buildUrl() 0 8 3
A buildUrlWithParams() 0 10 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