Completed
Push — master ( 96700d...96e717 )
by jelmer
02:14
created

UrlIcon::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 4
Ratio 100 %

Code Coverage

Tests 2
CRAP Score 1
Metric Value
dl 4
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Pageon\SlackWebhookMonolog\Slack;
4
5
use Pageon\SlackWebhookMonolog\Slack\Exceptions\InvalidUrlException;
6
use Pageon\SlackWebhookMonolog\Slack\Interfaces\IconInterface;
7
8
/**
9
 * @author Jelmer Prins <[email protected]>
10
 *
11
 * @since 0.1.0
12
 */
13 View Code Duplication
class UrlIcon extends SerializeToString implements IconInterface
14
{
15
    /**
16
     * @var string
17
     */
18
    private $iconUrl;
19
20
    /**
21
     * UrlIcon constructor.
22
     *
23
     * @param string $iconUrl
24
     */
25 5
    public function __construct($iconUrl)
26
    {
27 5
        $this->setIcon($iconUrl);
28 4
    }
29
30
    /**
31
     * This will set the icon if the url is valid.
32
     *
33
     * @param string $iconUrl
34
     *
35
     * @throws InvalidUrlException Thrown when the url is not valid
36
     *
37
     * @return $this
38
     */
39 5
    private function setIcon($iconUrl)
40
    {
41
        // remove the whitespace
42 5
        $iconUrl = trim($iconUrl);
43
44
        // @see https://gist.github.com/dperini/729294 and https://mathiasbynens.be/demo/url-regex
45 5
        $urlValidationRegex = '_^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:/[^\s]*)?$_iuS';
46 5
        if (!preg_match($urlValidationRegex, $iconUrl)) {
47 1
            throw new InvalidUrlException(sprintf('The url: "%s" is not a valid url.', $iconUrl), 400);
48
        }
49 4
        $this->iconUrl = $iconUrl;
50
51 4
        return $this;
52
    }
53
54
    /**
55
     * {@inheritdoc}
56
     */
57 3
    public function getIcon()
58
    {
59 3
        return $this->iconUrl;
60
    }
61
62
    /**
63
     * {@inheritdoc}
64
     */
65 2
    public function __toString()
66
    {
67 2
        return $this->getIcon();
68
    }
69
70
    /**
71
     * @inheritDoc
72
     */
73
    public function getType()
74
    {
75
        return 'url';
76
    }
77
}
78