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
Push — master ( 5fb98b...c01f90 )
by Marc
02:28
created

LaravelLocalization::getSupportedLocales()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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