Passed
Push — feature/6.x ( 53903f...32797a )
by Schlaefer
05:38 queued 02:15
created

UrlParserTrait::_url()   B

Complexity

Conditions 11
Paths 24

Size

Total Lines 31
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 17
nc 24
nop 4
dl 0
loc 31
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
declare(strict_types=1);
3
4
/**
5
 * Saito - The Threaded Web Forum
6
 *
7
 * @copyright Copyright (c) the Saito Project Developers
8
 * @link https://github.com/Schlaefer/Saito
9
 * @license http://opensource.org/licenses/MIT
10
 */
11
12
namespace BbcodeParser\Lib\Helper;
13
14
use Cake\Core\Configure;
15
use Cake\Validation\Validator;
16
use Saito\DomainParser;
17
use Saito\RememberTrait;
18
19
/**
20
 * @property \MailObfuscator\View\Helper\MailObfuscatorHelper $MailObfuscator
21
 * @property \Cake\View\Helper\UrlHelper $Url
22
 */
23
trait UrlParserTrait
24
{
25
    use RememberTrait;
26
27
    /**
28
     * Enforces HTTPS-scheme on URL
29
     *
30
     * Applied if:
31
     * - current host runs on HTTPS
32
     *
33
     * @param string $url URL
34
     * @return string
35
     */
36
    protected function _urlToHttps(string $url): string
37
    {
38
        if (!env('HTTPS')) {
39
            return $url;
40
        }
41
42
        return str_replace('http://', 'https://', $url);
43
    }
44
45
    /**
46
     * Generate email link
47
     *
48
     * @param string $url address
49
     * @param string $text title
50
     *
51
     * @return mixed
52
     */
53
    protected function _email($url, $text = null)
54
    {
55
        if (empty($text)) {
56
            $text = null;
57
        }
58
        $url = str_replace('mailto:', '', $url);
59
60
        return $this->MailObfuscator->link($url, $text);
61
    }
62
63
    /**
64
     * Generate URL
65
     *
66
     * @param string $url URL
67
     * @param string $text title
68
     * @param bool $label show label
69
     * @param bool $truncate trunctate
70
     *
71
     * @return string
72
     * @throws \Exception
73
     */
74
    protected function _url($url, $text, $label = false, $truncate = false)
75
    {
76
        // add http:// to URLs without protocol
77
        if (strpos($url, '://') === false) {
78
            // use Cakes Validation class to detect valid URL
79
            $validator = new Validator();
80
            $validator->add('url', ['url' => ['rule' => 'url']]);
81
            $errors = $validator->validate(['url' => $url]);
82
            if (empty($errors)) {
83
                $url = 'http://' . $url;
84
            }
85
        }
86
87
        $out = "<a href='$url' class=\"richtext-link";
88
        if ($truncate) {
89
            $out .= ' truncate';
90
        }
91
        $out .= "\">$text</a>";
92
        $out = $this->_decorateTarget($out);
93
94
        // add domain info: `[url=domain.info]my link[/url]` -> `my link [domain.info]`
95
        if ($label !== false && $label !== 'none' && $label !== 'false') {
96
            if (!empty($url) && preg_match('/\<img\s*?src=/', $text) !== 1) {
97
                $host = DomainParser::domainAndTld($url);
98
                if ($host !== null && $host !== env('SERVER_NAME')) {
99
                    $out .= ' <span class=\'richtext-linkInfo\'>[' . $host . ']</span>';
100
                }
101
            }
102
        }
103
104
        return $out;
105
    }
106
107
    /**
108
     * Adds target="_blank" to *all* external links in arbitrary string $string
109
     *
110
     * @param string $string string
111
     *
112
     * @return string
113
     */
114
    protected function _decorateTarget($string)
115
    {
116
        $decorator = function ($matches) {
117
            $out = '';
118
            $url = $matches[1];
119
120
            // preventing error message for parse_url('http://');
121
            if (substr($url, -3) === '://') {
122
                return $matches[0];
123
            }
124
            $parsedUrl = parse_url($url);
125
126
            if (isset($parsedUrl['host'])) {
127
                if ($parsedUrl['host'] !== env('SERVER_NAME') && $parsedUrl['host'] !== "www." . env('SERVER_NAME')) {
128
                    $out = " rel='external' target='_blank'";
129
                }
130
            }
131
132
            return $matches[0] . $out;
133
        };
134
135
        return preg_replace_callback(
136
            '#href=["\'](.*?)["\']#is',
137
            $decorator,
138
            $string
139
        );
140
    }
141
142
    /**
143
     * Creates an URL to an uploaded file based on $id
144
     *
145
     * @param string $path currently name in uploads folder
146
     * @return string URL
147
     */
148
    protected function _linkToUploadedFile(string $path): string
149
    {
150
        $generator = $this->remember('urlGenerator', function (): UploadUrlInterface {
151
            return Configure::read('Saito.Settings.UploadUrl');
152
        });
153
154
        return $generator->build($path);
155
    }
156
}
157