Completed
Push — master ( 283031...763f93 )
by Mihail
02:33
created

Url::download()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Ffcms\Core\Helper;
4
5
use Ffcms\Core\App;
6
use Ffcms\Core\Helper\FileSystem\File;
7
use Ffcms\Core\Helper\HTML\System\NativeGenerator;
8
use Ffcms\Core\Helper\Type\Arr;
9
use Ffcms\Core\Helper\Type\Obj;
10
use Ffcms\Core\Helper\Type\Str;
11
12
class Url extends NativeGenerator
13
{
14
15
    /**
16
     * Build link via controller/action and other params
17
     * @param string $controller_action
18
     * @param string|null $id
19
     * @param string|null $add
20
     * @param array $params
21
     * @param bool $encode
22
     * @return null|string
23
     */
24
    public static function to($controller_action, $id = null, $add = null, array $params = null, $encode = true)
25
    {
26
        $pathway = self::buildPathway([$controller_action, $id, $add, $params], $encode);
27
        return App::$Alias->baseUrl . '/' . $pathway;
28
    }
29
30
    /**
31
     * Build pathway from array $to. Example: ['controller/action', 'id', 'add', ['get' => 'value'], '#anchor']
32
     * @param array $to
33
     * @param bool $encode
34
     * @return string|null
35
     */
36
    public static function buildPathway(array $to = null, $encode = true)
37
    {
38
        
39
        // if empty passed - let show main page
40
        if ($to === null) {
41
            return null;
42
        }
43
        $response = Str::lowerCase(trim($to[0], '/')); // controller/action
44
        list($controller, $action) = explode('/', $response);
45
46
        $routing = App::$Properties->getAll('Routing');
47
        // sounds like dynamic callback
48
        if (Str::startsWith('@', $controller)) {
49
            $controller = trim($controller, '@');
50
            // search callback in properties
51
            if (isset($routing['Callback'][env_name]) && Arr::in($controller, $routing['Callback'][env_name])) {
52
                $pathInject = array_search($controller, $routing['Callback'][env_name]);
53
                // if path is founded - lets set source
54
                if ($pathInject !== false) {
55
                    $controller = Str::lowerCase($pathInject);
56
                }
57
            }
58
59
            // if controller still looks like path injection - define last entity like controller name
60
            if (Str::contains('\\', $controller)) {
61
                $controller = Str::lastIn($controller, '\\', true);
62
            }
63
64
            $response = $controller . '/' . $action;
65
        }
66
67
        // check if controller and action is defined
68
        if (Str::likeEmpty($controller) || Str::likeEmpty($action)) {
69
            return null;
70
        }
71
72
        // id is defined?
73 View Code Duplication
        if (isset($to[1]) && !Str::likeEmpty($to[1])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
74
            $response .= '/' . self::safeUri($to[1], $encode);
75
        }
76
77
        // add param is defined?
78 View Code Duplication
        if (isset($to[2]) && !Str::likeEmpty($to[2])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
79
            $response .= '/' . self::safeUri($to[2], $encode);
80
        }
81
82
        // try to find static alias
83
        if (isset($routing['Alias'][env_name]) && Arr::in('/' . $response, $routing['Alias'][env_name])) {
84
            $pathAlias = array_search('/' . $response, $routing['Alias'][env_name]);
85
            if ($pathAlias !== false) {
86
                $response = Str::lowerCase(trim($pathAlias, '/'));
87
            }
88
        }
89
90
        // parse get attributes
91
        if (isset($to[3]) && Obj::isArray($to[3]) && count($to[3]) > 0) {
92
            // check if anchor bindig is exist
93
            $anchor = false;
94
            if (isset($to[3]['#']) && Obj::isString($to[3]['#']) && Str::startsWith('#', $to[3]['#'])) {
95
                $anchor = $to[3]['#'];
96
                unset($to[3]['#']);
97
            }
98
            $queryString = http_build_query($to[3]);
99
            if (Str::length($queryString) > 0) {
100
                $response .= '?' . http_build_query($to[3]);
101
            }
102
            if ($anchor !== false) {
103
                $response .= $anchor;
104
            }
105
        }
106
        
107
        // parse anchor link part #item-related-id-1
108
        if (isset($to[4]) && Obj::isString($to[4]) && Str::startsWith('#', $to[4])) {
109
            $response .= $to[4];
110
        }
111
112
        return $response;
113
    }
114
115
    /**
116
     * Build current pathway with get data to compare in some methods
117
     * @return null|string
118
     */
119
    public static function buildPathwayFromRequest()
120
    {
121
        return self::buildPathway([
122
            Str::lowerCase(App::$Request->getController()) . '/' . Str::lowerCase(App::$Request->getAction()),
123
            App::$Request->getID(),
124
            App::$Request->getAdd(),
125
            App::$Request->query->all()
126
        ]);
127
    }
128
129
    /**
130
     * Create <a></a> block link
131
     * @param string|array $to
132
     * @param string $name
133
     * @param array|null $property
134
     * @return string
135
     */
136
    public static function link($to, $name, array $property = null)
137
    {
138
        $compile_property = self::applyProperty($property);
139
140
        if (!Obj::isArray($to)) { // callback magic (:
141
            $to = [$to];
142
        }
143
        // call Url::to(args)
144
        $callbackTo = call_user_func_array([__NAMESPACE__ . '\Url', 'to'], $to);
145
146
        return '<a href="' . $callbackTo . '"' . $compile_property . '>' . $name . '</a>';
147
    }
148
149
    /**
150
     * Build full URL link from URI string, if REQUEST data is not available (console, cron, etc)
151
     * @param string $uri
152
     * @param string|null $lang
153
     * @return string
154
     */
155
    public static function standaloneUrl($uri, $lang = null)
156
    {
157
        /** @var array $configs */
158
        $configs = \App::$Properties->getAll('default');
159
        $httpHost = $configs['baseProto'] . '://' . $configs['baseDomain'];
160
        if ($configs['basePath'] !== '/') {
161
            $httpHost .= $configs['basePath'] . '/';
162
        }
163
164
        // check if is this is URI not URL
165
        if (!Str::startsWith($httpHost, $uri)) {
166
            // check if lang is defined in URI or define it
167
            if ($lang !== null && $configs['multiLanguage'] && !Str::startsWith($lang, $uri)) {
168
                $uri = $lang . '/' . ltrim($uri, '/');
169
            }
170
            // add basic httpHost data
171
            $uri = rtrim($httpHost, '/') . '/' . ltrim($uri, '/');
172
        }
173
174
        return $uri;
175
    }
176
177
    /**
178
     * Build a.href html tag with full URL link from uri & text
179
     * @param string $text
180
     * @param string $uri
181
     * @param string|null $lang
182
     * @param array $property
183
     * @return string
184
     */
185
    public static function standaloneLink($text, $uri, $lang = null, array $property = [])
186
    {
187
        $property['href'] = self::standaloneUrl($uri, $lang);
188
        return self::buildContainerTag('a', $property, $text);
189
    }
190
191
    /**
192
     * Download remote content in binary string
193
     * @param string $url
194
     * @return null|string
195
     * @deprecated
196
     */
197
    public static function download($url)
198
    {
199
        return File::getFromUrl($url);
200
    }
201
202
}