Passed
Push — master ( f43456...e6a7f5 )
by Elf
09:30
created

AppManager::getDefaultRouteAttributes()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 7
ccs 5
cts 5
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace ElfSundae\Apps;
4
5
use Illuminate\Support\Arr;
6
use Illuminate\Support\Str;
7
use Illuminate\Support\Traits\Macroable;
8
use Illuminate\Contracts\Container\Container;
9
10
class AppManager
11
{
12
    use Macroable;
13
14
    /**
15
     * The container instance.
16
     *
17
     * @var \Illuminate\Contracts\Container\Container
18
     */
19
    protected $container;
20
21
    /**
22
     * The current application identifier.
23
     *
24
     * @var string
25
     */
26
    protected $appId;
27
28
    /**
29
     * Create a new app manager instance.
30
     *
31
     * @param  \Illuminate\Contracts\Container\Container  $container
32
     */
33 80
    public function __construct(Container $container)
34
    {
35 80
        $this->container = $container;
36
37 40
        $this->container->rebinding('request', function () {
38 8
            $this->refreshId();
39 80
        });
40 80
    }
41
42
    /**
43
     * Get all application URLs.
44
     *
45
     * @return array
46
     */
47 72
    public function urls()
48
    {
49 72
        return $this->container['config']->get('apps.url', []);
50
    }
51
52
    /**
53
     * Get the root URL for the application identifier.
54
     *
55
     * @param  string  $app
56
     * @return string
57
     */
58 24
    public function root($app = '')
59
    {
60 24
        return Arr::get($this->urls(), (string) $app)
61 24
            ?: $this->container['config']['app.url'];
62
    }
63
64
    /**
65
     * Get the URL domain for the application identifier.
66
     *
67
     * @param  string  $app
68
     * @return string
69
     */
70 8
    public function domain($app = '')
71
    {
72 8
        return parse_url($this->root($app), PHP_URL_HOST);
73
    }
74
75
    /**
76
     * Get the URL prefix for the application identifier.
77
     *
78
     * @param  string  $app
79
     * @return string
80
     */
81 8
    public function prefix($app = '')
82
    {
83 8
        return trim(parse_url($this->root($app), PHP_URL_PATH), '/');
84
    }
85
86
    /**
87
     * Get or check the current application identifier.
88
     *
89
     * @return string|bool
90
     */
91 44
    public function id()
92
    {
93 44
        if (is_null($this->appId)) {
0 ignored issues
show
introduced by
The condition is_null($this->appId) can never be true.
Loading history...
94 44
            $this->appId = (string) $this->idForUrl($this->container['request']->getUri());
95 22
        }
96
97 44
        if (func_num_args() > 0) {
98 4
            return in_array($this->appId, is_array(func_get_arg(0)) ? func_get_arg(0) : func_get_args());
99
        }
100
101 40
        return $this->appId;
102
    }
103
104
    /**
105
     * Get the application identifier for the given URL.
106
     *
107
     * @param  string  $url
108
     * @return string|null
109
     */
110 48
    public function idForUrl($url)
111
    {
112 48
        return collect($this->urls())
113 24
            ->filter(function ($root) use ($url) {
114 48
                return $this->urlHasRoot($url, $root);
115 48
            })
116 24
            ->sortByDesc(function ($root) {
117 44
                return strlen($root);
118 48
            })
119 48
            ->keys()
120 48
            ->first();
121
    }
122
123
    /**
124
     * Refresh the current application identifier.
125
     *
126
     * @return $this
127
     */
128 12
    public function refreshId()
129
    {
130 12
        $this->appId = null;
131
132 12
        return $this;
133
    }
134
135
    /**
136
     * Determine if a URL has the given root URL.
137
     *
138
     * @param  string  $url
139
     * @param  string  $root
140
     * @param  bool  $strict
141
     * @return bool
142
     */
143 48
    protected function urlHasRoot($url, $root, $strict = false)
144
    {
145 48
        if (! $strict) {
146 48
            $url = $this->removeScheme($url);
147 48
            $root = $this->removeScheme($root);
148 24
        }
149
150 48
        return (bool) preg_match('~^'.preg_quote($root, '~').'([/\?#].*)?$~i', $url);
151
    }
152
153
    /**
154
     * Remove scheme for a URL.
155
     *
156
     * @param  string  $url
157
     * @return string
158
     */
159 48
    protected function removeScheme($url)
160
    {
161 48
        return preg_replace('#^https?://#i', '', $url);
162
    }
163
164
    /**
165
     * Generate an absolute URL to a path for the given application identifier.
166
     *
167
     * @param  string  $app
168
     * @param  string  $path
169
     * @param  mixed  $parameters
170
     * @return string
171
     */
172 4
    public function url($app = '', $path = '', $parameters = [])
173
    {
174 4
        return $this->root($app).$this->stringAfter(
175 4
            $this->container['url']->to($path, $parameters),
176 4
            $this->container['url']->to('')
177 2
        );
178
    }
179
180
    /**
181
     * Generate the URL to an application asset.
182
     *
183
     * @param  string  $path
184
     * @param  bool|null  $secure
185
     * @return string
186
     */
187 4
    public function asset($path, $secure = null)
188
    {
189 4
        return $this->container['url']->assetFrom($this->root('assets'), $path, $secure);
190
    }
191
192
    /**
193
     * Return the remainder of a string after a given value.
194
     *
195
     * @param  string  $subject
196
     * @param  string  $search
197
     * @return string
198
     */
199 4
    protected function stringAfter($subject, $search)
200
    {
201 4
        return $search === '' ? $subject : array_reverse(explode($search, $subject, 2))[0];
202
    }
203
204
    /**
205
     * Register routes for each application.
206
     *
207
     * You may call this method in the `map` method of your `RouteServiceProvider`.
208
     *
209
     * @param  array  $attributes
210
     * @return void
211
     */
212 4
    public function routes(array $attributes = [])
213
    {
214 4
        foreach ($this->urls() as $id => $url) {
215 4
            if (! file_exists($file = base_path("routes/$id.php"))) {
216 4
                continue;
217
            }
218
219 4
            $this->container['router']->group(
220 4
                $this->getRouteAttributes($id, Arr::get($attributes, $id, [])),
221 4
                function ($router) use ($file) {
222 4
                    require $file;
223 4
                }
224 2
            );
225 2
        }
226 4
    }
227
228
    /**
229
     * Get the route attributes.
230
     *
231
     * @param  string  $app
232
     * @param  array  $attributes
233
     * @return array
234
     */
235 4
    protected function getRouteAttributes($app, array $attributes = [])
236
    {
237 4
        return array_filter(array_merge(
238 4
            $this->getDefaultRouteAttributes($app), $attributes
239 2
        ));
240
    }
241
242
    /**
243
     * Get the default route attributes for the application.
244
     *
245
     * @param  string  $app
246
     * @return array
247
     */
248 4
    protected function getDefaultRouteAttributes($app)
249
    {
250
        return [
251 4
            'domain' => $this->domain($app),
252 4
            'prefix' => $this->prefix($app),
253 4
            'middleware' => $this->container['router']->hasMiddlewareGroup($app) ? $app : 'web',
254 4
            'namespace' => $this->getRootControllerNamespace($app),
255 2
        ];
256
    }
257
258
    /**
259
     * Get the root controller namespace for the application.
260
     *
261
     * @param  string  $app
262
     * @return string
263
     */
264 4
    protected function getRootControllerNamespace($app)
265
    {
266 4
        $namespace = $this->container['url']->getRootControllerNamespace()
267 4
            ?: 'App\Http\Controllers';
268
269 4
        return trim($namespace.'\\'.Str::studly($app), '\\');
270
    }
271
}
272