Completed
Push — master ( 5b5792...2b84bd )
by Schlaefer
03:33 queued 11s
created

UrlParserTrait::_url()   B

Complexity

Conditions 11
Paths 24

Size

Total Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
nc 24
nop 4
dl 0
loc 32
rs 7.3166
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Plugin\BbcodeParser\src\Lib\Helper;
4
5
use Cake\Validation\Validator;
6
use Cake\View\Helper\UrlHelper;
7
use MailObfuscator\View\Helper\MailObfuscatorHelper;
8
use Saito\DomainParser;
9
10
/**
11
 * @property MailObfuscatorHelper $MailObfuscator
12
 * @property UrlHelper $Url
13
 */
14
trait UrlParserTrait
15
{
16
    /**
17
     * Enforces HTTPS-scheme on URL
18
     *
19
     * Applied if:
20
     * - current host runs on HTTPS
21
     *
22
     * @param string $url URL
23
     * @return string
24
     */
25
    protected function _urlToHttps(string $url): string
26
    {
27
        if (!env('HTTPS')) {
28
            return $url;
29
        }
30
31
        return str_replace('http://', 'https://', $url);
32
    }
33
34
    /**
35
     * Generate email link
36
     *
37
     * @param string $url address
38
     * @param string $text title
39
     *
40
     * @return mixed
41
     */
42
    protected function _email($url, $text = null)
43
    {
44
        if (empty($text)) {
45
            $text = null;
46
        }
47
        $url = str_replace('mailto:', '', $url);
48
49
        return $this->MailObfuscator->link($url, $text);
50
    }
51
52
    /**
53
     * Generate URL
54
     *
55
     * @param string $url URL
56
     * @param string $text title
57
     * @param bool $label show label
58
     * @param bool $truncate trunctate
59
     *
60
     * @return string
61
     * @throws \Exception
62
     */
63
    protected function _url($url, $text, $label = false, $truncate = false)
64
    {
65
        // add http:// to URLs without protocol
66
        if (strpos($url, '://') === false) {
67
            // use Cakes Validation class to detect valid URL
68
            $validator = new Validator();
69
            $validator->add('url', ['url' => ['rule' => 'url']]);
70
            $errors = $validator->errors(['url' => $url]);
71
            if (empty($errors)) {
72
                $url = 'http://' . $url;
73
            }
74
        }
75
76
        if ($truncate === true) {
77
            $text = $this->_truncate($text);
78
        }
79
        $out = "<a href='$url'>$text</a>";
80
81
        $out = $this->_decorateTarget($out);
82
83
        // add domain info: `[url=domain.info]my link[/url]` -> `my link [domain.info]`
84
        if ($label !== false && $label !== 'none' && $label !== 'false') {
85
            if (!empty($url) && preg_match('/\<img\s*?src=/', $text) !== 1) {
86
                $host = DomainParser::domainAndTld($url);
87
                if ($host !== null && $host !== env('SERVER_NAME')) {
88
                    $out .= ' <span class=\'richtext-linkInfo\'>[' . $host . ']</span>';
89
                }
90
            }
91
        }
92
93
        return $out;
94
    }
95
96
    /**
97
     * Truncates long links
98
     *
99
     * @bogus does this truncate strings or the longest word in the string or
100
     *     what?
101
     * @bogus what about [url=][img]...[/img][url]. Is the [img] url truncated
102
     *     too?
103
     *
104
     * @param string $string string
105
     *
106
     * @throws \Exception
107
     * @return string
108
     */
109
    protected function _truncate($string)
110
    {
111
        $_textWordMaxLength = $this->_sOptions->get('text_word_maxlength');
0 ignored issues
show
Bug introduced by
The property _sOptions does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
112
        if (empty($_textWordMaxLength)) {
113
            throw new \Exception('Text word maxlength not set.');
114
        }
115
116
        if (mb_strlen($string) <= $_textWordMaxLength) {
117
            return $string;
118
        }
119
120
        $_placeholder = ' … ';
121
        $leftMargin = (int)floor($_textWordMaxLength / 2);
122
        $rightMargin = (int)(-1 * ($_textWordMaxLength - $leftMargin - mb_strlen($_placeholder)));
123
124
        $string = mb_substr($string, 0, $leftMargin) . $_placeholder .
125
            mb_substr($string, $rightMargin);
126
127
        return $string;
128
    }
129
130
    /**
131
     * Adds target="_blank" to *all* external links in arbitrary string $string
132
     *
133
     * @param string $string string
134
     *
135
     * @return string
136
     */
137
    protected function _decorateTarget($string)
138
    {
139
        $decorator = function ($matches) {
140
            $out = '';
141
            $url = $matches[1];
142
143
            // preventing error message for parse_url('http://');
144
            if (substr($url, -3) === '://') {
145
                return $matches[0];
146
            }
147
            $parsedUrl = parse_url($url);
148
149
            if (isset($parsedUrl['host'])) {
150
                if ($parsedUrl['host'] !== env('SERVER_NAME') && $parsedUrl['host'] !== "www." . env('SERVER_NAME')) {
151
                    $out = " rel='external' target='_blank'";
152
                }
153
            }
154
155
            return $matches[0] . $out;
156
        };
157
158
        return preg_replace_callback(
159
            '#href=["\'](.*?)["\']#is',
160
            $decorator,
161
            $string
162
        );
163
    }
164
165
    /**
166
     * Creates an URL to an uploaded file based on $id
167
     *
168
     * @param string $id currently name in uploads folder
169
     * @return string URL
170
     */
171
    protected function _linkToUploadedFile(string $id) : string
172
    {
173
        // @bogus, there's an user-config for that
174
        $root = '/useruploads/';
175
176
        return $this->Url->build($root . $id, ['fullBase' => true]);
177
    }
178
}
179