GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#384)
by Cretu
01:52
created

LaravelLocalization::getCurrentLocaleDirection()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 18
rs 8.2222
cc 7
eloc 12
nc 7
nop 0
1
<?php
2
3
namespace Mcamara\LaravelLocalization;
4
5
use Illuminate\Config\Repository;
6
use Illuminate\Foundation\Application;
7
use Illuminate\Http\Request;
8
use Illuminate\Routing\Router;
9
use Illuminate\Support\Facades\URL;
10
use Illuminate\Translation\Translator;
11
use Illuminate\View\Factory;
12
use Mcamara\LaravelLocalization\Exceptions\SupportedLocalesNotDefined;
13
use Mcamara\LaravelLocalization\Exceptions\UnsupportedLocaleException;
14
15
class LaravelLocalization
16
{
17
    /**
18
     * Config repository.
19
     *
20
     * @var \Illuminate\Config\Repository
21
     */
22
    protected $configRepository;
23
24
    /**
25
     * Illuminate view Factory.
26
     *
27
     * @var \Illuminate\View\Factory
28
     */
29
    protected $view;
30
31
    /**
32
     * Illuminate translator class.
33
     *
34
     * @var \Illuminate\Translation\Translator
35
     */
36
    protected $translator;
37
38
    /**
39
     * Illuminate router class.
40
     *
41
     * @var \Illuminate\Routing\Router
42
     */
43
    protected $router;
44
45
    /**
46
     * Illuminate request class.
47
     *
48
     * @var \Illuminate\Routing\Request
49
     */
50
    protected $request;
51
52
    /**
53
     * Illuminate url class.
54
     *
55
     * @var \Illuminate\Routing\UrlGenerator
56
     */
57
    protected $url;
58
59
    /**
60
     * Illuminate request class.
61
     *
62
     * @var Illuminate\Foundation\Application
63
     */
64
    protected $app;
65
66
    /**
67
     * Illuminate request class.
68
     *
69
     * @var string
70
     */
71
    protected $baseUrl;
72
73
    /**
74
     * Default locale.
75
     *
76
     * @var string
77
     */
78
    protected $defaultLocale;
79
80
    /**
81
     * Supported Locales.
82
     *
83
     * @var array
84
     */
85
    protected $supportedLocales;
86
87
    /**
88
     * Current locale.
89
     *
90
     * @var string
91
     */
92
    protected $currentLocale = false;
93
94
    /**
95
     * An array that contains all routes that should be translated.
96
     *
97
     * @var array
98
     */
99
    protected $translatedRoutes = [];
100
101
    /**
102
     * Name of the translation key of the current route, it is used for url translations.
103
     *
104
     * @var string
105
     */
106
    protected $routeName;
107
108
    /**
109
     * Creates new instance.
110
     *
111
     * @throws UnsupportedLocaleException
112
     */
113
    public function __construct()
114
    {
115
        $this->app = app();
116
117
        $this->configRepository = $this->app['config'];
118
        $this->view = $this->app['view'];
119
        $this->translator = $this->app['translator'];
120
        $this->router = $this->app['router'];
121
        $this->request = $this->app['request'];
122
        $this->url = $this->app['url'];
123
124
        // set default locale
125
        $this->defaultLocale = $this->configRepository->get('app.locale');
126
        $supportedLocales = $this->getSupportedLocales();
127
128
        if (empty($supportedLocales[$this->defaultLocale])) {
129
            throw new UnsupportedLocaleException('Laravel default locale is not in the supportedLocales array.');
130
        }
131
    }
132
133
    /**
134
     * Set and return current locale.
135
     *
136
     * @param string $locale Locale to set the App to (optional)
137
     *
138
     * @return string Returns locale (if route has any) or null (if route does not have a locale)
139
     */
140
    public function setLocale($locale = null)
141
    {
142
        if (empty($locale) || !is_string($locale)) {
143
            // If the locale has not been passed through the function
144
            // it tries to get it from the first segment of the url
145
            $locale = $this->request->segment(1);
146
        }
147
148
        if (!empty($this->supportedLocales[$locale])) {
149
            $this->currentLocale = $locale;
150
        } else {
151
            // if the first segment/locale passed is not valid
152
            // the system would ask which locale have to take
153
            // it could be taken by the browser
154
            // depending on your configuration
155
156
            $locale = null;
157
158
            // if we reached this point and hideDefaultLocaleInURL is true
159
            // we have to assume we are routing to a defaultLocale route.
160
            if ($this->hideDefaultLocaleInURL()) {
161
                $this->currentLocale = $this->defaultLocale;
162
            }
163
            // but if hideDefaultLocaleInURL is false, we have
164
            // to retrieve it from the browser...
165
            else {
166
                $this->currentLocale = $this->getCurrentLocale();
167
            }
168
        }
169
170
        $this->app->setLocale($this->currentLocale);
171
172
        // Regional locale such as de_DE, so formatLocalized works in Carbon
173
        $regional = $this->getCurrentLocaleRegional();
174
        if ($regional) {
175
            setlocale(LC_TIME, $regional.'.UTF-8');
176
            setlocale(LC_MONETARY, $regional.'.UTF-8');
177
        }
178
179
        return $locale;
180
    }
181
182
    /**
183
     * Set and return supported locales.
184
     *
185
     * @param array $locales Locales that the App supports
186
     */
187
    public function setSupportedLocales($locales)
188
    {
189
        $this->supportedLocales = $locales;
190
    }
191
192
    /**
193
     * Returns an URL adapted to $locale or current locale.
194
     *
195
     * @param string      $url    URL to adapt. If not passed, the current url would be taken.
196
     * @param string|bool $locale Locale to adapt, false to remove locale
197
     *
198
     * @throws UnsupportedLocaleException
199
     *
200
     * @return string URL translated
201
     */
202
    public function localizeURL($url = null, $locale = null)
203
    {
204
        return $this->getLocalizedURL($locale, $url);
205
    }
206
207
    /**
208
     * Returns an URL adapted to $locale.
209
     *
210
     *
211
     * @param string|bool  $locale     Locale to adapt, false to remove locale
212
     * @param string|false $url        URL to adapt in the current language. If not passed, the current url would be taken.
213
     * @param array        $attributes Attributes to add to the route, if empty, the system would try to extract them from the url.
214
     *
215
     * @throws SupportedLocalesNotDefined
216
     * @throws UnsupportedLocaleException
217
     *
218
     * @return string|false URL translated, False if url does not exist
219
     */
220
    public function getLocalizedURL($locale = null, $url = null, $attributes = [])
221
    {
222
        if ($locale === null) {
223
            $locale = $this->getCurrentLocale();
224
        }
225
226
        if (!$this->checkLocaleInSupportedLocales($locale)) {
227
            throw new UnsupportedLocaleException('Locale \''.$locale.'\' is not in the list of supported locales.');
228
        }
229
230
        if (empty($attributes)) {
231
            $attributes = $this->extractAttributes($url, $locale);
0 ignored issues
show
Bug introduced by
It seems like $locale defined by parameter $locale on line 220 can also be of type boolean; however, Mcamara\LaravelLocalizat...on::extractAttributes() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
232
        }
233
234
        if (empty($url)) {
235
            if (!empty($this->routeName)) {
236
                return $this->getURLFromRouteNameTranslated($locale, $this->routeName, $attributes);
237
            }
238
239
            $url = $this->request->fullUrl();
240
        } else {
241
            $url = $this->url->to($url);
242
        }
243
244
        if ($locale && $translatedRoute = $this->findTranslatedRouteByUrl($url, $attributes, $this->currentLocale)) {
245
            return $this->getURLFromRouteNameTranslated($locale, $translatedRoute, $attributes);
246
        }
247
248
        $base_path = $this->request->getBaseUrl();
249
        $parsed_url = parse_url($url);
250
        $url_locale = $this->getDefaultLocale();
251
252
        if (!$parsed_url || empty($parsed_url['path'])) {
253
            $path = $parsed_url['path'] = '';
254
        } else {
255
            $parsed_url['path'] = str_replace($base_path, '', '/'.ltrim($parsed_url['path'], '/'));
256
            $path = $parsed_url['path'];
257
            foreach ($this->getSupportedLocales() as $localeCode => $lang) {
258
                $parsed_url['path'] = preg_replace('%^/?'.$localeCode.'/%', '$1', $parsed_url['path']);
259
                if ($parsed_url['path'] !== $path) {
260
                    $url_locale = $localeCode;
261
                    break;
262
                }
263
264
                $parsed_url['path'] = preg_replace('%^/?'.$localeCode.'$%', '$1', $parsed_url['path']);
265
                if ($parsed_url['path'] !== $path) {
266
                    $url_locale = $localeCode;
267
                    break;
268
                }
269
            }
270
        }
271
272
        $parsed_url['path'] = ltrim($parsed_url['path'], '/');
273
274
        if ($translatedRoute = $this->findTranslatedRouteByPath($parsed_url['path'], $url_locale)) {
275
            return $this->getURLFromRouteNameTranslated($locale, $translatedRoute, $attributes);
276
        }
277
278
        if (!empty($locale) && ($locale != $this->defaultLocale || !$this->hideDefaultLocaleInURL())) {
279
            $parsed_url['path'] = $locale.'/'.ltrim($parsed_url['path'], '/');
280
        }
281
        $parsed_url['path'] = ltrim(ltrim($base_path, '/').'/'.$parsed_url['path'], '/');
282
283
        //Make sure that the pass path is returned with a leading slash only if it come in with one.
284
        if (starts_with($path, '/') === true) {
285
            $parsed_url['path'] = '/'.$parsed_url['path'];
286
        }
287
        $parsed_url['path'] = rtrim($parsed_url['path'], '/');
288
289
        $url = $this->unparseUrl($parsed_url);
290
291
        if ($this->checkUrl($url)) {
292
            return $url;
293
        }
294
295
        return $this->createUrlFromUri($url);
296
    }
297
298
    /**
299
     * Returns an URL adapted to the route name and the locale given.
300
     *
301
     *
302
     * @param string|bool $locale       Locale to adapt
303
     * @param string      $transKeyName Translation key name of the url to adapt
304
     * @param array       $attributes   Attributes for the route (only needed if transKeyName needs them)
305
     *
306
     * @throws SupportedLocalesNotDefined
307
     * @throws UnsupportedLocaleException
308
     *
309
     * @return string|false URL translated
310
     */
311
    public function getURLFromRouteNameTranslated($locale, $transKeyName, $attributes = [])
312
    {
313
        if (!$this->checkLocaleInSupportedLocales($locale)) {
314
            throw new UnsupportedLocaleException('Locale \''.$locale.'\' is not in the list of supported locales.');
315
        }
316
317
        if (!is_string($locale)) {
318
            $locale = $this->getDefaultLocale();
319
        }
320
321
        $route = '';
322
323
        if (!($locale === $this->defaultLocale && $this->hideDefaultLocaleInURL())) {
324
            $route = '/'.$locale;
325
        }
326
        if (is_string($locale) && $this->translator->has($transKeyName, $locale)) {
327
            $translation = $this->translator->trans($transKeyName, [], '', $locale);
328
            $route .= '/'.$translation;
329
330
            $route = $this->substituteAttributesInRoute($attributes, $route);
331
        }
332
333
        if (empty($route)) {
334
            // This locale does not have any key for this route name
335
            return false;
336
        }
337
338
        return rtrim($this->createUrlFromUri($route));
339
    }
340
341
    /**
342
     * It returns an URL without locale (if it has it)
343
     * Convenience function wrapping getLocalizedURL(false).
344
     *
345
     * @param string|false $url URL to clean, if false, current url would be taken
346
     *
347
     * @return string URL with no locale in path
348
     */
349
    public function getNonLocalizedURL($url = null)
350
    {
351
        return $this->getLocalizedURL(false, $url);
352
    }
353
354
    /**
355
     * Returns default locale.
356
     *
357
     * @return string
358
     */
359
    public function getDefaultLocale()
360
    {
361
        return $this->defaultLocale;
362
    }
363
364
    /**
365
     * Return an array of all supported Locales.
366
     *
367
     * @throws SupportedLocalesNotDefined
368
     *
369
     * @return array
370
     */
371
    public function getSupportedLocales()
372
    {
373
        if (!empty($this->supportedLocales)) {
374
            return $this->supportedLocales;
375
        }
376
377
        $locales = $this->configRepository->get('laravellocalization.supportedLocales');
378
379
        if (empty($locales) || !is_array($locales)) {
380
            throw new SupportedLocalesNotDefined();
381
        }
382
383
        $this->supportedLocales = $locales;
384
385
        return $locales;
386
    }
387
388
    /**
389
     * Returns current locale name.
390
     *
391
     * @return string current locale name
392
     */
393
    public function getCurrentLocaleName()
394
    {
395
        return $this->supportedLocales[$this->getCurrentLocale()]['name'];
396
    }
397
398
    /**
399
     * Returns current locale native name.
400
     *
401
     * @return string current locale native name
402
     */
403
    public function getCurrentLocaleNative()
404
    {
405
        return $this->supportedLocales[$this->getCurrentLocale()]['native'];
406
    }
407
408
    /**
409
     * Returns current locale direction.
410
     *
411
     * @return string current locale direction
412
     */
413
    public function getCurrentLocaleDirection()
414
    {
415
        if (!empty($this->supportedLocales[$this->getCurrentLocale()]['dir'])) {
416
            return $this->supportedLocales[$this->getCurrentLocale()]['dir'];
417
        }
418
419
        switch ($this->getCurrentLocaleScript()) {
420
            // Other (historic) RTL scripts exist, but this list contains the only ones in current use.
421
            case 'Arab':
422
            case 'Hebr':
423
            case 'Mong':
424
            case 'Tfng':
425
            case 'Thaa':
426
                return 'rtl';
427
            default:
428
                return 'ltr';
429
        }
430
    }
431
432
    /**
433
     * Returns current locale script.
434
     *
435
     * @return string current locale script
436
     */
437
    public function getCurrentLocaleScript()
438
    {
439
        return $this->supportedLocales[$this->getCurrentLocale()]['script'];
440
    }
441
442
    /**
443
     * Returns current language's native reading.
444
     *
445
     * @return string current language's native reading
446
     */
447
    public function getCurrentLocaleNativeReading()
448
    {
449
        return $this->supportedLocales[$this->getCurrentLocale()]['native'];
450
    }
451
452
    /**
453
     * Returns current language.
454
     *
455
     * @return string current language
456
     */
457
    public function getCurrentLocale()
458
    {
459
        if ($this->currentLocale) {
460
            return $this->currentLocale;
461
        }
462
463
        if ($this->useAcceptLanguageHeader()) {
464
            $negotiator = new LanguageNegotiator($this->defaultLocale, $this->getSupportedLocales(), $this->request);
465
466
            return $negotiator->negotiateLanguage();
467
        }
468
469
        // or get application default language
470
        return $this->configRepository->get('app.locale');
471
    }
472
473
    /**
474
     * Returns current regional.
475
     *
476
     * @return string current regional
477
     */
478
    public function getCurrentLocaleRegional()
479
    {
480
        // need to check if it exists, since 'regional' has been added
481
        // after version 1.0.11 and existing users will not have it
482
        if (isset($this->supportedLocales[$this->getCurrentLocale()]['regional'])) {
483
            return $this->supportedLocales[$this->getCurrentLocale()]['regional'];
484
        } else {
485
            return;
486
        }
487
    }
488
489
    /**
490
     * Returns supported languages language key.
491
     *
492
     * @return array keys of supported languages
493
     */
494
    public function getSupportedLanguagesKeys()
495
    {
496
        return array_keys($this->supportedLocales);
497
    }
498
499
    /**
500
     * Check if Locale exists on the supported locales array.
501
     *
502
     * @param string|bool $locale string|bool Locale to be checked
503
     *
504
     * @throws SupportedLocalesNotDefined
505
     *
506
     * @return bool is the locale supported?
507
     */
508
    public function checkLocaleInSupportedLocales($locale)
509
    {
510
        $locales = $this->getSupportedLocales();
511
        if ($locale !== false && empty($locales[$locale])) {
512
            return false;
513
        }
514
515
        return true;
516
    }
517
518
    /**
519
     * Change route attributes for the ones in the $attributes array.
520
     *
521
     * @param $attributes array Array of attributes
522
     * @param string $route string route to substitute
523
     *
524
     * @return string route with attributes changed
525
     */
526
    protected function substituteAttributesInRoute($attributes, $route)
527
    {
528
        foreach ($attributes as $key => $value) {
529
            $route = str_replace('{'.$key.'}', $value, $route);
530
            $route = str_replace('{'.$key.'?}', $value, $route);
531
        }
532
533
        // delete empty optional arguments that are not in the $attributes array
534
        $route = preg_replace('/\/{[^)]+\?}/', '', $route);
535
536
        return $route;
537
    }
538
539
    /**
540
     * Returns translated routes.
541
     *
542
     * @return array translated routes
543
     */
544
    protected function getTranslatedRoutes()
545
    {
546
        return $this->translatedRoutes;
547
    }
548
549
    /**
550
     * Set current route name.
551
     *
552
     * @param string $routeName current route name
553
     */
554
    public function setRouteName($routeName)
555
    {
556
        $this->routeName = $routeName;
557
    }
558
559
    /**
560
     * Translate routes and save them to the translated routes array (used in the localize route filter).
561
     *
562
     * @param string $routeName Key of the translated string
563
     *
564
     * @return string Translated string
565
     */
566
    public function transRoute($routeName)
567
    {
568
        if (!in_array($routeName, $this->translatedRoutes)) {
569
            $this->translatedRoutes[] = $routeName;
570
        }
571
572
        return $this->translator->trans($routeName);
573
    }
574
575
    /**
576
     * Returns the translation key for a given path.
577
     *
578
     * @param string $path Path to get the key translated
579
     *
580
     * @return string|false Key for translation, false if not exist
581
     */
582
    public function getRouteNameFromAPath($path)
583
    {
584
        $attributes = $this->extractAttributes($path);
585
586
        $path = str_replace(url('/'), '', $path);
587
        if ($path[0] !== '/') {
588
            $path = '/'.$path;
589
        }
590
        $path = str_replace('/'.$this->currentLocale.'/', '', $path);
591
        $path = trim($path, '/');
592
593
        foreach ($this->translatedRoutes as $route) {
594
            if ($this->substituteAttributesInRoute($attributes, $this->translator->trans($route)) === $path) {
0 ignored issues
show
Bug introduced by
It seems like $this->translator->trans($route) targeting Illuminate\Translation\Translator::trans() can also be of type array; however, Mcamara\LaravelLocalizat...tuteAttributesInRoute() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
595
                return $route;
596
            }
597
        }
598
599
        return false;
600
    }
601
602
    /**
603
     * Returns the translated route for the path and the url given.
604
     *
605
     * @param string $path       Path to check if it is a translated route
606
     * @param string $url_locale Language to check if the path exists
607
     *
608
     * @return string|false Key for translation, false if not exist
609
     */
610
    protected function findTranslatedRouteByPath($path, $url_locale)
611
    {
612
        // check if this url is a translated url
613
        foreach ($this->translatedRoutes as $translatedRoute) {
614
            if ($this->translator->trans($translatedRoute, [], '', $url_locale) == rawurldecode($path)) {
615
                return $translatedRoute;
616
            }
617
        }
618
619
        return false;
620
    }
621
622
    /**
623
     * Returns the translated route for an url and the attributes given and a locale.
624
     *
625
     *
626
     * @param string|false|null $url        Url to check if it is a translated route
627
     * @param array             $attributes Attributes to check if the url exists in the translated routes array
628
     * @param string            $locale     Language to check if the url exists
629
     *
630
     * @throws SupportedLocalesNotDefined
631
     * @throws UnsupportedLocaleException
632
     *
633
     * @return string|false Key for translation, false if not exist
634
     */
635
    protected function findTranslatedRouteByUrl($url, $attributes, $locale)
636
    {
637
        if (empty($url)) {
638
            return false;
639
        }
640
641
        // check if this url is a translated url
642
        foreach ($this->translatedRoutes as $translatedRoute) {
643
            $routeName = $this->getURLFromRouteNameTranslated($locale, $translatedRoute, $attributes);
644
645
            if ($this->getNonLocalizedURL($routeName) == $this->getNonLocalizedURL($url)) {
646
                return $translatedRoute;
647
            }
648
        }
649
650
        return false;
651
    }
652
653
    /**
654
     * Returns true if the string given is a valid url.
655
     *
656
     * @param string $url String to check if it is a valid url
657
     *
658
     * @return bool Is the string given a valid url?
659
     */
660
    protected function checkUrl($url)
661
    {
662
        return filter_var($url, FILTER_VALIDATE_URL);
663
    }
664
665
    /**
666
     * Returns the config repository for this instance.
667
     *
668
     * @return Repository Configuration repository
669
     */
670
    public function getConfigRepository()
671
    {
672
        return $this->configRepository;
673
    }
674
675
    /**
676
     * Returns the translation key for a given path.
677
     *
678
     * @return bool Returns value of useAcceptLanguageHeader in config.
679
     */
680
    protected function useAcceptLanguageHeader()
681
    {
682
        return $this->configRepository->get('laravellocalization.useAcceptLanguageHeader');
683
    }
684
685
    /**
686
     * Returns the translation key for a given path.
687
     *
688
     * @return bool Returns value of hideDefaultLocaleInURL in config.
689
     */
690
    public function hideDefaultLocaleInURL()
691
    {
692
        return $this->configRepository->get('laravellocalization.hideDefaultLocaleInURL');
693
    }
694
695
    /**
696
     * Create an url from the uri.
697
     *
698
     * @param string $uri Uri
699
     *
700
     * @return string Url for the given uri
701
     */
702
    public function createUrlFromUri($uri)
703
    {
704
        $uri = ltrim($uri, '/');
705
706
        if (empty($this->baseUrl)) {
707
            return app('url')->to($uri);
708
        }
709
710
        return $this->baseUrl.$uri;
711
    }
712
713
    /**
714
     * Sets the base url for the site.
715
     *
716
     * @param string $url Base url for the site
717
     */
718
    public function setBaseUrl($url)
719
    {
720
        if (substr($url, -1) != '/') {
721
            $url .= '/';
722
        }
723
724
        $this->baseUrl = $url;
725
    }
726
727
    /**
728
     * Extract attributes for current url.
729
     *
730
     * @param bool|false|null|string $url    to extract attributes, if not present, the system will look for attributes in the current call
731
     * @param string                 $locale
732
     *
733
     * @return array Array with attributes
734
     */
735
    protected function extractAttributes($url = false, $locale = '')
736
    {
737
        if (!empty($url)) {
738
            $attributes = [];
739
            $parse = parse_url($url);
740
            if (isset($parse['path'])) {
741
                $parse = explode('/', $parse['path']);
742
            } else {
743
                $parse = [];
744
            }
745
            $url = [];
746
            foreach ($parse as $segment) {
747
                if (!empty($segment)) {
748
                    $url[] = $segment;
749
                }
750
            }
751
752
            foreach ($this->router->getRoutes() as $route) {
753
                $path = $route->getUri();
754
                if (!preg_match("/{[\w]+}/", $path)) {
755
                    continue;
756
                }
757
758
                $path = explode('/', $path);
759
                $i = 0;
760
761
                $match = true;
762
                foreach ($path as $j => $segment) {
763
                    if (isset($url[$i])) {
764
                        if ($segment === $url[$i]) {
765
                            $i++;
766
                            continue;
767
                        }
768
                        if (preg_match("/{[\w]+}/", $segment)) {
769
                            // must-have parameters
770
                            $attribute_name = preg_replace(['/}/', '/{/', "/\?/"], '', $segment);
771
                            $attributes[$attribute_name] = $url[$i];
772
                            $i++;
773
                            continue;
774
                        }
775
                        if (preg_match("/{[\w]+\?}/", $segment)) {
776
                            // optional parameters
777
                            if (!isset($path[$j + 1]) || $path[$j + 1] !== $url[$i]) {
778
                                // optional parameter taken
779
                                $attribute_name = preg_replace(['/}/', '/{/', "/\?/"], '', $segment);
780
                                $attributes[$attribute_name] = $url[$i];
781
                                $i++;
782
                                continue;
783
                            }
784
                        }
785
                    } elseif (!preg_match("/{[\w]+\?}/", $segment)) {
786
                        // no optional parameters but no more $url given
787
                        // this route does not match the url
788
                        $match = false;
789
                        break;
790
                    }
791
                }
792
793
                if (isset($url[$i + 1])) {
794
                    $match = false;
795
                }
796
797
                if ($match) {
798
                    return $attributes;
799
                }
800
            }
801
        } else {
802
            if (!$this->router->current()) {
803
                return [];
804
            }
805
806
            $attributes = $this->router->current()->parameters();
807
            $response = event('routes.translation', [$locale, $attributes]);
808
809
            if (!empty($response)) {
810
                $response = array_shift($response);
811
            }
812
813
            if (is_array($response)) {
814
                $attributes = array_merge($attributes, $response);
815
            }
816
        }
817
818
        return $attributes;
819
    }
820
821
    /**
822
     * Build URL using array data from parse_url.
823
     *
824
     * @param array|false $parsed_url Array of data from parse_url function
825
     *
826
     * @return string Returns URL as string.
827
     */
828
    protected function unparseUrl($parsed_url)
829
    {
830
        if (empty($parsed_url)) {
831
            return '';
832
        }
833
834
        $url = '';
835
        $url .= isset($parsed_url['scheme']) ? $parsed_url['scheme'].'://' : '';
836
        $url .= isset($parsed_url['host']) ? $parsed_url['host'] : '';
837
        $url .= isset($parsed_url['port']) ? ':'.$parsed_url['port'] : '';
838
        $user = isset($parsed_url['user']) ? $parsed_url['user'] : '';
839
        $pass = isset($parsed_url['pass']) ? ':'.$parsed_url['pass'] : '';
840
        $url .= $user.(($user || $pass) ? "$pass@" : '');
841
842
        if (!empty($url)) {
843
            $url .= isset($parsed_url['path']) ? '/'.ltrim($parsed_url['path'], '/') : '';
844
        } else {
845
            $url .= isset($parsed_url['path']) ? $parsed_url['path'] : '';
846
        }
847
848
        $url .= isset($parsed_url['query']) ? '?'.$parsed_url['query'] : '';
849
        $url .= isset($parsed_url['fragment']) ? '#'.$parsed_url['fragment'] : '';
850
851
        return $url;
852
    }
853
}
854