Completed
Push — master ( af58be...5693bf )
by Stefano
17s queued 11s
created

I18nRoute::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 3
1
<?php
2
/**
3
 * BEdita, API-first content management framework
4
 * Copyright 2019 ChannelWeb Srl, Chialab Srl
5
 *
6
 * This file is part of BEdita: you can redistribute it and/or modify
7
 * it under the terms of the GNU Lesser General Public License as published
8
 * by the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * See LICENSE.LGPL or <http://gnu.org/licenses/lgpl-3.0.html> for more details.
12
 */
13
namespace BEdita\I18n\Routing\Route;
14
15
use BEdita\I18n\Core\I18nTrait;
16
use Cake\Core\Configure;
17
use Cake\Routing\Route\Route;
18
use Psr\Http\Message\ServerRequestInterface;
19
20
/**
21
 * I18n Route class.
22
 *
23
 * It helps to build and match I18n routing rules.
24
 */
25
class I18nRoute extends Route
26
{
27
    use I18nTrait;
28
29
    /**
30
     * {@inheritDoc}
31
     */
32
    public function __construct($template, $defaults = [], array $options = [])
33
    {
34
        parent::__construct($this->buildTemplate($template), $defaults, $options);
35
36
        if (empty($options['lang'])) {
37
            $this->setPatterns(['lang' => implode('|', array_keys($this->getLanguages()))]);
38
        }
39
    }
40
41
    /**
42
     * Build the right route template adding :lang if needed.
43
     *
44
     * If :lang is not found add it at the beginning, for example /simple/path becomes /:lang/simple/path
45
     *
46
     * @param string $template The initial template.
47
     * @return string
48
     */
49
    protected function buildTemplate(string $template) : string
50
    {
51
        if ($template === '/') {
52
            return '/:lang';
53
        }
54
55
        if (preg_match('/\/:lang(\/.*|$)/', $template)) {
56
            return $template;
57
        }
58
59
        return $template = '/:lang' . $template;
0 ignored issues
show
Unused Code introduced by
The assignment to $template is dead and can be removed.
Loading history...
60
    }
61
62
    /**
63
     * {@inheritDoc}
64
     */
65
    public function match(array $url, array $context = [])
66
    {
67
        if (!array_key_exists('lang', $url)) {
68
            $url['lang'] = $this->getLang();
69
        }
70
71
        return parent::match($url, $context);
72
    }
73
}
74