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 (#387)
by Marc
01:38
created

LaravelLocalization::setRouteName()   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 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
        elseif ( !empty( $locale ) && ( $locale != $this->defaultLocale || $this->hideDefaultLocaleInURL() ) ) {
282
            $parsed_url['path'] = $this->getDefaultLocale() . '/' . ltrim($parsed_url[ 'path' ], '/');
283
        }
284
        $parsed_url['path'] = ltrim(ltrim($base_path, '/') . '/' . $parsed_url[ 'path' ], '/');
285
286
        // Make sure that the pass path is returned with a leading slash only if it come in with one.
287
        if (starts_with($path, '/') === true) {
288
            $parsed_url['path'] = '/'.$parsed_url['path'];
289
        }
290
        $parsed_url['path'] = rtrim($parsed_url['path'], '/');
291
292
        $url = $this->unparseUrl($parsed_url);
293
294
        if ($this->checkUrl($url)) {
295
            return $url;
296
        }
297
298
        return $this->createUrlFromUri($url);
299
    }
300
301
    /**
302
     * Returns an URL adapted to the route name and the locale given.
303
     *
304
     *
305
     * @param string|bool $locale       Locale to adapt
306
     * @param string      $transKeyName Translation key name of the url to adapt
307
     * @param array       $attributes   Attributes for the route (only needed if transKeyName needs them)
308
     *
309
     * @throws SupportedLocalesNotDefined
310
     * @throws UnsupportedLocaleException
311
     *
312
     * @return string|false URL translated
313
     */
314
    public function getURLFromRouteNameTranslated($locale, $transKeyName, $attributes = [])
315
    {
316
        if (!$this->checkLocaleInSupportedLocales($locale)) {
317
            throw new UnsupportedLocaleException('Locale \''.$locale.'\' is not in the list of supported locales.');
318
        }
319
320
        if (!is_string($locale)) {
321
            $locale = $this->getDefaultLocale();
322
        }
323
324
        $route = '';
325
326
        if (!($locale === $this->defaultLocale && $this->hideDefaultLocaleInURL())) {
327
            $route = '/'.$locale;
328
        }
329
        if (is_string($locale) && $this->translator->has($transKeyName, $locale)) {
330
            $translation = $this->translator->trans($transKeyName, [], '', $locale);
331
            $route .= '/'.$translation;
332
333
            $route = $this->substituteAttributesInRoute($attributes, $route);
334
        }
335
336
        if (empty($route)) {
337
            // This locale does not have any key for this route name
338
            return false;
339
        }
340
341
        return rtrim($this->createUrlFromUri($route));
342
    }
343
344
    /**
345
     * It returns an URL without locale (if it has it)
346
     * Convenience function wrapping getLocalizedURL(false).
347
     *
348
     * @param string|false $url URL to clean, if false, current url would be taken
349
     *
350
     * @return string URL with no locale in path
351
     */
352
    public function getNonLocalizedURL($url = null)
353
    {
354
        return $this->getLocalizedURL(false, $url);
355
    }
356
357
    /**
358
     * Returns default locale.
359
     *
360
     * @return string
361
     */
362
    public function getDefaultLocale()
363
    {
364
        return $this->defaultLocale;
365
    }
366
367
    /**
368
     * Return an array of all supported Locales.
369
     *
370
     * @throws SupportedLocalesNotDefined
371
     *
372
     * @return array
373
     */
374
    public function getSupportedLocales()
375
    {
376
        if (!empty($this->supportedLocales)) {
377
            return $this->supportedLocales;
378
        }
379
380
        $locales = $this->configRepository->get('laravellocalization.supportedLocales');
381
382
        if (empty($locales) || !is_array($locales)) {
383
            throw new SupportedLocalesNotDefined();
384
        }
385
386
        $this->supportedLocales = $locales;
387
388
        return $locales;
389
    }
390
391
    /**
392
     * Returns current locale name.
393
     *
394
     * @return string current locale name
395
     */
396
    public function getCurrentLocaleName()
397
    {
398
        return $this->supportedLocales[$this->getCurrentLocale()]['name'];
399
    }
400
401
    /**
402
     * Returns current locale native name.
403
     *
404
     * @return string current locale native name
405
     */
406
    public function getCurrentLocaleNative()
407
    {
408
        return $this->supportedLocales[$this->getCurrentLocale()]['native'];
409
    }
410
411
    /**
412
     * Returns selected locale native name
413
     * @param  string $locale the localeName you want the native for
414
     *
415
     * @return string selected locale native name
416
     */
417
    public function getLocalizedNative($locale)
418
    {
419
        if ( !$this->checkLocaleInSupportedLocales($locale) )
420
        {
421
            throw new UnsupportedLocaleException('Locale \'' . $locale . '\' is not in the list of supported locales.');
422
        }
423
424
        return $this->supportedLocales[ $locale ][ 'native' ];
425
    }
426
427
    /**
428
     * Returns current locale direction.
429
     *
430
     * @return string current locale direction
431
     */
432
    public function getCurrentLocaleDirection()
433
    {
434
        if (!empty($this->supportedLocales[$this->getCurrentLocale()]['dir'])) {
435
            return $this->supportedLocales[$this->getCurrentLocale()]['dir'];
436
        }
437
438
        switch ($this->getCurrentLocaleScript()) {
439
            // Other (historic) RTL scripts exist, but this list contains the only ones in current use.
440
            case 'Arab':
441
            case 'Hebr':
442
            case 'Mong':
443
            case 'Tfng':
444
            case 'Thaa':
445
                return 'rtl';
446
            default:
447
                return 'ltr';
448
        }
449
    }
450
451
    /**
452
     * Returns current locale script.
453
     *
454
     * @return string current locale script
455
     */
456
    public function getCurrentLocaleScript()
457
    {
458
        return $this->supportedLocales[$this->getCurrentLocale()]['script'];
459
    }
460
461
    /**
462
     * Returns current language's native reading.
463
     *
464
     * @return string current language's native reading
465
     */
466
    public function getCurrentLocaleNativeReading()
467
    {
468
        return $this->supportedLocales[$this->getCurrentLocale()]['native'];
469
    }
470
471
    /**
472
     * Returns current language.
473
     *
474
     * @return string current language
475
     */
476
    public function getCurrentLocale()
477
    {
478
        if ($this->currentLocale) {
479
            return $this->currentLocale;
480
        }
481
482
        if ($this->useAcceptLanguageHeader()) {
483
            $negotiator = new LanguageNegotiator($this->defaultLocale, $this->getSupportedLocales(), $this->request);
484
485
            return $negotiator->negotiateLanguage();
486
        }
487
488
        // or get application default language
489
        return $this->configRepository->get('app.locale');
490
    }
491
492
    /**
493
     * Returns current regional.
494
     *
495
     * @return string current regional
496
     */
497
    public function getCurrentLocaleRegional()
498
    {
499
        // need to check if it exists, since 'regional' has been added
500
        // after version 1.0.11 and existing users will not have it
501
        if (isset($this->supportedLocales[$this->getCurrentLocale()]['regional'])) {
502
            return $this->supportedLocales[$this->getCurrentLocale()]['regional'];
503
        } else {
504
            return;
505
        }
506
    }
507
508
    /**
509
     * Returns supported languages language key.
510
     *
511
     * @return array keys of supported languages
512
     */
513
    public function getSupportedLanguagesKeys()
514
    {
515
        return array_keys($this->supportedLocales);
516
    }
517
518
    /**
519
     * Check if Locale exists on the supported locales array.
520
     *
521
     * @param string|bool $locale string|bool Locale to be checked
522
     *
523
     * @throws SupportedLocalesNotDefined
524
     *
525
     * @return bool is the locale supported?
526
     */
527
    public function checkLocaleInSupportedLocales($locale)
528
    {
529
        $locales = $this->getSupportedLocales();
530
        if ($locale !== false && empty($locales[$locale])) {
531
            return false;
532
        }
533
534
        return true;
535
    }
536
537
    /**
538
     * Change route attributes for the ones in the $attributes array.
539
     *
540
     * @param $attributes array Array of attributes
541
     * @param string $route string route to substitute
542
     *
543
     * @return string route with attributes changed
544
     */
545
    protected function substituteAttributesInRoute($attributes, $route)
546
    {
547
        foreach ($attributes as $key => $value) {
548
            $route = str_replace('{'.$key.'}', $value, $route);
549
            $route = str_replace('{'.$key.'?}', $value, $route);
550
        }
551
552
        // delete empty optional arguments that are not in the $attributes array
553
        $route = preg_replace('/\/{[^)]+\?}/', '', $route);
554
555
        return $route;
556
    }
557
558
    /**
559
     * Returns translated routes.
560
     *
561
     * @return array translated routes
562
     */
563
    protected function getTranslatedRoutes()
564
    {
565
        return $this->translatedRoutes;
566
    }
567
568
    /**
569
     * Set current route name.
570
     *
571
     * @param string $routeName current route name
572
     */
573
    public function setRouteName($routeName)
574
    {
575
        $this->routeName = $routeName;
576
    }
577
578
    /**
579
     * Translate routes and save them to the translated routes array (used in the localize route filter).
580
     *
581
     * @param string $routeName Key of the translated string
582
     *
583
     * @return string Translated string
584
     */
585
    public function transRoute($routeName)
586
    {
587
        if (!in_array($routeName, $this->translatedRoutes)) {
588
            $this->translatedRoutes[] = $routeName;
589
        }
590
591
        return $this->translator->trans($routeName);
592
    }
593
594
    /**
595
     * Returns the translation key for a given path.
596
     *
597
     * @param string $path Path to get the key translated
598
     *
599
     * @return string|false Key for translation, false if not exist
600
     */
601
    public function getRouteNameFromAPath($path)
602
    {
603
        $attributes = $this->extractAttributes($path);
604
605
        $path = str_replace(url('/'), '', $path);
606
        if ($path[0] !== '/') {
607
            $path = '/'.$path;
608
        }
609
        $path = str_replace('/'.$this->currentLocale.'/', '', $path);
610
        $path = trim($path, '/');
611
612
        foreach ($this->translatedRoutes as $route) {
613
            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...
614
                return $route;
615
            }
616
        }
617
618
        return false;
619
    }
620
621
    /**
622
     * Returns the translated route for the path and the url given.
623
     *
624
     * @param string $path       Path to check if it is a translated route
625
     * @param string $url_locale Language to check if the path exists
626
     *
627
     * @return string|false Key for translation, false if not exist
628
     */
629
    protected function findTranslatedRouteByPath($path, $url_locale)
630
    {
631
        // check if this url is a translated url
632
        foreach ($this->translatedRoutes as $translatedRoute) {
633
            if ($this->translator->trans($translatedRoute, [], '', $url_locale) == rawurldecode($path)) {
634
                return $translatedRoute;
635
            }
636
        }
637
638
        return false;
639
    }
640
641
    /**
642
     * Returns the translated route for an url and the attributes given and a locale.
643
     *
644
     *
645
     * @param string|false|null $url        Url to check if it is a translated route
646
     * @param array             $attributes Attributes to check if the url exists in the translated routes array
647
     * @param string            $locale     Language to check if the url exists
648
     *
649
     * @throws SupportedLocalesNotDefined
650
     * @throws UnsupportedLocaleException
651
     *
652
     * @return string|false Key for translation, false if not exist
653
     */
654
    protected function findTranslatedRouteByUrl($url, $attributes, $locale)
655
    {
656
        if (empty($url)) {
657
            return false;
658
        }
659
660
        // check if this url is a translated url
661
        foreach ($this->translatedRoutes as $translatedRoute) {
662
            $routeName = $this->getURLFromRouteNameTranslated($locale, $translatedRoute, $attributes);
663
664
            if ($this->getNonLocalizedURL($routeName) == $this->getNonLocalizedURL($url)) {
665
                return $translatedRoute;
666
            }
667
        }
668
669
        return false;
670
    }
671
672
    /**
673
     * Returns true if the string given is a valid url.
674
     *
675
     * @param string $url String to check if it is a valid url
676
     *
677
     * @return bool Is the string given a valid url?
678
     */
679
    protected function checkUrl($url)
680
    {
681
        return filter_var($url, FILTER_VALIDATE_URL);
682
    }
683
684
    /**
685
     * Returns the config repository for this instance.
686
     *
687
     * @return Repository Configuration repository
688
     */
689
    public function getConfigRepository()
690
    {
691
        return $this->configRepository;
692
    }
693
694
    /**
695
     * Returns the translation key for a given path.
696
     *
697
     * @return bool Returns value of useAcceptLanguageHeader in config.
698
     */
699
    protected function useAcceptLanguageHeader()
700
    {
701
        return $this->configRepository->get('laravellocalization.useAcceptLanguageHeader');
702
    }
703
704
    /**
705
     * Returns the translation key for a given path.
706
     *
707
     * @return bool Returns value of hideDefaultLocaleInURL in config.
708
     */
709
    public function hideDefaultLocaleInURL()
710
    {
711
        return $this->configRepository->get('laravellocalization.hideDefaultLocaleInURL');
712
    }
713
714
    /**
715
     * Create an url from the uri.
716
     *
717
     * @param string $uri Uri
718
     *
719
     * @return string Url for the given uri
720
     */
721
    public function createUrlFromUri($uri)
722
    {
723
        $uri = ltrim($uri, '/');
724
725
        if (empty($this->baseUrl)) {
726
            return app('url')->to($uri);
727
        }
728
729
        return $this->baseUrl.$uri;
730
    }
731
732
    /**
733
     * Sets the base url for the site.
734
     *
735
     * @param string $url Base url for the site
736
     */
737
    public function setBaseUrl($url)
738
    {
739
        if (substr($url, -1) != '/') {
740
            $url .= '/';
741
        }
742
743
        $this->baseUrl = $url;
744
    }
745
746
    /**
747
     * Extract attributes for current url.
748
     *
749
     * @param bool|false|null|string $url    to extract attributes, if not present, the system will look for attributes in the current call
750
     * @param string                 $locale
751
     *
752
     * @return array Array with attributes
753
     */
754
    protected function extractAttributes($url = false, $locale = '')
755
    {
756
        if (!empty($url)) {
757
            $attributes = [];
758
            $parse = parse_url($url);
759
            if (isset($parse['path'])) {
760
                $parse = explode('/', $parse['path']);
761
            } else {
762
                $parse = [];
763
            }
764
            $url = [];
765
            foreach ($parse as $segment) {
766
                if (!empty($segment)) {
767
                    $url[] = $segment;
768
                }
769
            }
770
771
            foreach ($this->router->getRoutes() as $route) {
772
                $path = $route->getUri();
773
                if (!preg_match("/{[\w]+}/", $path)) {
774
                    continue;
775
                }
776
777
                $path = explode('/', $path);
778
                $i = 0;
779
780
                $match = true;
781
                foreach ($path as $j => $segment) {
782
                    if (isset($url[$i])) {
783
                        if ($segment === $url[$i]) {
784
                            $i++;
785
                            continue;
786
                        }
787
                        if (preg_match("/{[\w]+}/", $segment)) {
788
                            // must-have parameters
789
                            $attribute_name = preg_replace(['/}/', '/{/', "/\?/"], '', $segment);
790
                            $attributes[$attribute_name] = $url[$i];
791
                            $i++;
792
                            continue;
793
                        }
794
                        if (preg_match("/{[\w]+\?}/", $segment)) {
795
                            // optional parameters
796
                            if (!isset($path[$j + 1]) || $path[$j + 1] !== $url[$i]) {
797
                                // optional parameter taken
798
                                $attribute_name = preg_replace(['/}/', '/{/', "/\?/"], '', $segment);
799
                                $attributes[$attribute_name] = $url[$i];
800
                                $i++;
801
                                continue;
802
                            }
803
                        }
804
                    } elseif (!preg_match("/{[\w]+\?}/", $segment)) {
805
                        // no optional parameters but no more $url given
806
                        // this route does not match the url
807
                        $match = false;
808
                        break;
809
                    }
810
                }
811
812
                if (isset($url[$i + 1])) {
813
                    $match = false;
814
                }
815
816
                if ($match) {
817
                    return $attributes;
818
                }
819
            }
820
        } else {
821
            if (!$this->router->current()) {
822
                return [];
823
            }
824
825
            $attributes = $this->router->current()->parameters();
826
            $response = event('routes.translation', [$locale, $attributes]);
827
828
            if (!empty($response)) {
829
                $response = array_shift($response);
830
            }
831
832
            if (is_array($response)) {
833
                $attributes = array_merge($attributes, $response);
834
            }
835
        }
836
837
        return $attributes;
838
    }
839
840
    /**
841
     * Build URL using array data from parse_url.
842
     *
843
     * @param array|false $parsed_url Array of data from parse_url function
844
     *
845
     * @return string Returns URL as string.
846
     */
847
    protected function unparseUrl($parsed_url)
848
    {
849
        if (empty($parsed_url)) {
850
            return '';
851
        }
852
853
        $url = '';
854
        $url .= isset($parsed_url['scheme']) ? $parsed_url['scheme'].'://' : '';
855
        $url .= isset($parsed_url['host']) ? $parsed_url['host'] : '';
856
        $url .= isset($parsed_url['port']) ? ':'.$parsed_url['port'] : '';
857
        $user = isset($parsed_url['user']) ? $parsed_url['user'] : '';
858
        $pass = isset($parsed_url['pass']) ? ':'.$parsed_url['pass'] : '';
859
        $url .= $user.(($user || $pass) ? "$pass@" : '');
860
861
        if (!empty($url)) {
862
            $url .= isset($parsed_url['path']) ? '/'.ltrim($parsed_url['path'], '/') : '';
863
        } else {
864
            $url .= isset($parsed_url['path']) ? $parsed_url['path'] : '';
865
        }
866
867
        $url .= isset($parsed_url['query']) ? '?'.$parsed_url['query'] : '';
868
        $url .= isset($parsed_url['fragment']) ? '#'.$parsed_url['fragment'] : '';
869
870
        return $url;
871
    }
872
}
873