Completed
Pull Request — master (#5)
by ARCANEDEV
02:37
created

Gravatar::getParams()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 11
nc 6
nop 1
dl 0
loc 21
ccs 11
cts 11
cp 1
crap 4
rs 9.0534
c 0
b 0
f 0
1
<?php namespace Arcanedev\Gravatar;
2
3
use Arcanedev\Gravatar\Helpers\HtmlBuilder;
4
use Arcanedev\Gravatar\Helpers\NumberChecker;
5
6
/**
7
 * Class     Gravatar
8
 *
9
 * @package  Arcanedev\Gravatar
10
 * @author   ARCANEDEV <[email protected]>
11
 */
12
class Gravatar implements Contracts\Gravatar
13
{
14
    /* -----------------------------------------------------------------
15
     |  Constants
16
     | -----------------------------------------------------------------
17
     */
18
19
    const BASE_URL   = 'http://www.gravatar.com/avatar/';
20
    const SECURE_URL = 'https://secure.gravatar.com/avatar/';
21
22
    /* -----------------------------------------------------------------
23
     |  Properties
24
     | -----------------------------------------------------------------
25
     */
26
27
    /**
28
     * The default image to use (gravatar-recognized type, url or false = default gravatar image)
29
     *
30
     * @var mixed
31
     */
32
    protected $defaultImage     = false;
33
34
    /**
35
     * The maximum rating to allow for the avatar.
36
     *
37
     * @var string
38
     */
39
    protected $rating           = 'g';
40
41
    /**
42
     * The avatar size.
43
     *
44
     * @var int
45
     */
46
    protected $size             = 80;
47
48
    /**
49
     * Should we use the secure (HTTPS) URL base ?
50
     *
51
     * @var bool
52
     */
53
    protected $secure           = false;
54
55
    /**
56
     * A temporary internal cache of the URL parameters.
57
     *
58
     * @var array|null
59
     */
60
    protected $cachedParams     = null;
61
62
    /**
63
     * Supported image defaults.
64
     *
65
     * @var array
66
     */
67
    private $supportedImages    = [
68
        '404',        // Do not load any image if none is associated with the email hash,
69
                      // instead return an HTTP 404 response
70
        'mm',         // (mystery-man) a simple, cartoon-style silhouetted outline of a person.
71
        'identicon',  // a geometric pattern based on an email hash
72
        'monsterid',  // a generated 'monster' with different colors, faces, etc
73
        'wavatar',    // generated faces with differing features and backgrounds
74
        'retro',      // awesome generated, 8-bit arcade-style pixelated faces
75
        // 'blank',
76
    ];
77
78
    /**
79
     * Supported image ratings.
80
     *
81
     * @var array
82
     */
83
    private $supportedRatings   = [
84
        'g',   // suitable for display on all websites with any audience type.
85
        'pg',  // may contain rude gestures, provocatively dressed individuals, the lesser swear words, or mild violence.
86
        'r',   // may contain such things as harsh profanity, intense violence, nudity, or hard drug use.
87
        'x'    // may contain hardcore sexual imagery or extremely disturbing violence.
88
    ];
89
90
    /* -----------------------------------------------------------------
91
     |  Constructor
92
     | -----------------------------------------------------------------
93
     */
94
95
    /**
96
     * Make a gravatar instance.
97
     *
98
     * @param  string  $default
99
     * @param  int     $size
100
     * @param  string  $rating
101
     */
102 32
    public function __construct($default = 'mm', $size = 80, $rating = 'g')
103
    {
104 32
        $this->setDefaultImage($default);
105 32
        $this->setSize($size);
106 32
        $this->setRating($rating);
107 32
        $this->enableSecure();
108 32
    }
109
110
    /* -----------------------------------------------------------------
111
     |  Getters & Setters
112
     | -----------------------------------------------------------------
113
     */
114
115
    /**
116
     * Get the current default image setting.
117
     *
118
     * @return string|false
119
     */
120 16
    public function getDefaultImage()
121
    {
122 16
        return $this->defaultImage;
123
    }
124
125
    /**
126
     * Set the default image to use for avatars.
127
     *
128
     * @param  string|false  $image
129
     *
130
     * @return \Arcanedev\Gravatar\Gravatar
131
     *
132
     * @throws \Arcanedev\Gravatar\Exceptions\InvalidImageUrlException
133
     */
134 32
    public function setDefaultImage($image)
135
    {
136 32
        if ($image !== false) {
137 32
            $this->cachedParams = null;
138
139 32
            $image = in_array(strtolower($image), $this->supportedImages)
140 32
                ? strtolower($image)
141 32
                : $this->checkImageUrl($image);
142
        }
143
144 32
        $this->defaultImage = $image;
145
146 32
        return $this;
147
    }
148
149
    /**
150
     * Get the currently set avatar size.
151
     *
152
     * @return int
153
     */
154 20
    public function getSize()
155
    {
156 20
        return $this->size;
157
    }
158
159
    /**
160
     * Set the avatar size to use.
161
     *
162
     * @param integer $size - The avatar size to use, must be less than 512 and greater than 0.
163
     *
164
     * @return \Arcanedev\Gravatar\Gravatar
165
     *
166
     * @throws \Arcanedev\Gravatar\Exceptions\InvalidImageSizeException
167
     */
168 32
    public function setSize($size)
169
    {
170 32
        $this->cachedParams = null;
171
172 32
        $this->checkSize($size);
173
174 32
        $this->size = $size;
175
176 32
        return $this;
177
    }
178
179
    /**
180
     * Get the current maximum allowed rating for avatars.
181
     *
182
     * @return string
183
     */
184 18
    public function getRating()
185
    {
186 18
        return $this->rating;
187
    }
188
189
    /**
190
     * Set the maximum allowed rating for avatars.
191
     *
192
     * @param  string  $rating
193
     *
194
     * @return \Arcanedev\Gravatar\Gravatar
195
     *
196
     * @throws \Arcanedev\Gravatar\Exceptions\InvalidImageRatingException
197
     */
198 32
    public function setRating($rating)
199
    {
200 32
        $this->cachedParams = null;
201
202 32
        $rating = strtolower($rating);
203
204 32
        if ( ! in_array($rating, $this->supportedRatings)) {
205 2
            throw new Exceptions\InvalidImageRatingException(
206 2
                "Invalid rating '$rating' specified, only 'g', 'pg', 'r' or 'x' are supported."
207
            );
208
        }
209
210 32
        $this->rating = $rating;
211
212 32
        return $this;
213
    }
214
215
    /**
216
     * Check if we are using the secure protocol for the image URLs.
217
     *
218
     * @return bool
219
     */
220 20
    public function isSecured()
221
    {
222 20
        return $this->secure;
223
    }
224
225
    /* -----------------------------------------------------------------
226
     |  Main Methods
227
     | -----------------------------------------------------------------
228
     */
229
230
    /**
231
     * Get Gravatar image source.
232
     *
233
     * @param  string       $email
234
     * @param  int|null     $size
235
     * @param  string|null  $rating
236
     *
237
     * @return string
238
     */
239 6
    public function src($email, $size = null, $rating = null)
240
    {
241 6
        if (is_null($size)) {
242 2
            $size = $this->getSize();
243
        }
244
245 6
        $size = max(1, min(512, $size));
246
247 6
        $this->setSize($size);
248
249 6
        if ( ! is_null($rating)) {
250 2
            $this->setRating($rating);
251
        }
252
253 6
        return $this->get($email);
254
    }
255
256
    /**
257
     * Get the avatar URL based on the provided email address.
258
     *
259
     * @param  string  $email
260
     * @param  bool    $hash
261
     *
262
     * @return string
263
     */
264 16
    public function get($email, $hash = true)
265
    {
266 16
        $url  = $this->isSecured() ? static::SECURE_URL : static::BASE_URL;
267 16
        $url .= empty($email)
268 8
            ? str_repeat('0', 32)
269 16
            : ($hash ? $this->hashEmail($email) : $email);
270
271 16
        $params = $this->getParams($email);
272
273 16
        return $url . '?' . http_build_query($params);
274
    }
275
276
    /**
277
     * Get Gravatar image tag.
278
     *
279
     * @param  string       $email
280
     * @param  string|null  $alt
281
     * @param  array        $attributes
282
     * @param  string|null  $rating
283
     *
284
     * @return string
285
     */
286 4
    public function image($email, $alt = null, array $attributes = [], $rating = null)
287
    {
288 4
        $dimensions = array_values(
289 4
            array_only($attributes, ['width', 'height'])
290
        );
291
292 4
        $size = count($dimensions)
293 2
            ? min(512, max($dimensions))
294 4
            : $this->getSize();
295
296 4
        $src  = $this->src($email, $size, $rating);
297
298 4
        return HtmlBuilder::image($src, $alt, $attributes);
299
    }
300
301
    /**
302
     * Enable the use of the secure protocol for image URLs.
303
     *
304
     * @return \Arcanedev\Gravatar\Gravatar
305
     */
306 32
    public function enableSecure()
307
    {
308 32
        $this->secure = true;
309
310 32
        return $this;
311
    }
312
313
    /**
314
     * Disable the use of the secure protocol for image URLs.
315
     *
316
     * @return \Arcanedev\Gravatar\Gravatar
317
     */
318 2
    public function disableSecure()
319
    {
320 2
        $this->secure = false;
321
322 2
        return $this;
323
    }
324
325
    /**
326
     * Check if email has a gravatar.
327
     *
328
     * @param  string  $email
329
     *
330
     * @return bool
331
     */
332 2
    public function exists($email)
333
    {
334 2
        $this->setDefaultImage('404');
335
336 2
        $headers = get_headers($this->get($email), 1);
337
338 2
        return strpos($headers[0], '200') ? true : false;
339
    }
340
341
    /**
342
     * Get a hashed email.
343
     *
344
     * @param  string  $email
345
     *
346
     * @return string
347
     */
348 12
    public function hashEmail($email)
349
    {
350 12
        return hash('md5', strtolower(trim($email)));
351
    }
352
353
    /* -----------------------------------------------------------------
354
     |  Check Methods
355
     | -----------------------------------------------------------------
356
     */
357
358
    /**
359
     * Check image url.
360
     *
361
     * @param  string  $image
362
     *
363
     * @return string
364
     *
365
     * @throws \Arcanedev\Gravatar\Exceptions\InvalidImageUrlException
366
     */
367 4
    private function checkImageUrl($image)
368
    {
369 4
        if ( ! filter_var($image, FILTER_VALIDATE_URL)) {
370 2
            throw new Exceptions\InvalidImageUrlException(
371 2
                'The default image specified is not a recognized gravatar "default" and is not a valid URL'
372
            );
373
        }
374
375 2
        return $image;
376
    }
377
378
    /* -----------------------------------------------------------------
379
     |  Other Methods
380
     | -----------------------------------------------------------------
381
     */
382
383
    /**
384
     * Get params.
385
     *
386
     * @param  string  $email
387
     *
388
     * @return array
389
     */
390 16
    private function getParams($email)
391
    {
392 16
        $params = $this->cachedParams;
393
394 16
        if (is_null($this->cachedParams)) {
395 16
            $params['s'] = $this->getSize();
396 16
            $params['r'] = $this->getRating();
397
398 16
            if ($this->getDefaultImage() !== false) {
399 14
                $params['d'] = $this->getDefaultImage();
400
            }
401
402 16
            $this->cachedParams = $params;
403
        }
404
405 16
        if (empty($email)) {
406 8
            $params['f'] = 'y';
407
        }
408
409 16
        return (array) $params;
410
    }
411
412
    /**
413
     * Check the image size.
414
     *
415
     * @param  int  $size
416
     */
417 32
    private function checkSize(&$size)
418
    {
419 32
        if ( ! NumberChecker::isIntValue($size)) {
420 2
            throw new Exceptions\InvalidImageSizeException(
421 2
                'Avatar size specified must be an integer.'
422
            );
423
        }
424
425 32
        $size = (int) $size;
426
427 32
        if ( ! NumberChecker::isIntBetween($size, 0, 512)) {
428 2
            throw new Exceptions\InvalidImageSizeException(
429 2
                'Avatar size must be within 0 pixels and 512 pixels.'
430
            );
431
        }
432 32
    }
433
}
434