Completed
Push — master ( bff1a4...59b7c9 )
by Filipe
03:06
created

UrlUtils::getUrl()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4.0058

Importance

Changes 2
Bugs 1 Features 1
Metric Value
c 2
b 1
f 1
dl 0
loc 22
ccs 13
cts 14
cp 0.9286
rs 8.9197
cc 4
eloc 15
nc 5
nop 1
crap 4.0058
1
<?php
2
3
/**
4
 * This file is part of slick/mvc package
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
namespace Slick\Mvc\Controller;
11
12
use Aura\Router\Exception as AuraException;
13
use Slick\Http\PhpEnvironment\Request;
14
use Slick\Mvc\Application;
15
use Slick\Mvc\Router;
16
17
/**
18
 * UrlUtils
19
 * 
20
 * @package Slick\Mvc\Controller
21
 * @author  Filipe Silva <[email protected]>
22
 */
23
trait UrlUtils
24
{
25
    /**
26
     * @return Request
27
     */
28
    abstract public function getRequest();
29
30
    /**
31
     * Gets the url for provided path
32
     * 
33
     * @param string $path
34
     * @return string
35
     */
36 4
    public function getUrl($path)
37
    {
38 4
        $regExp = '/\/\/|https?:/i';
39 4
        if (preg_match($regExp, $path)) {
40 2
            return $path;
41
        }
42
        try {
43 2
            $generated = call_user_func_array(
44 2
                [$this->getRouterGenerator(), 'generate'],
45 2
                func_get_args()
46 2
            );
47 2
        } catch (AuraException $caught) {
48
            $generated = false;
49
        }
50
51 2
        $basePath = rtrim($this->getRequest()->getBasePath(), '/');
52
        $path = $generated
53 2
            ? $generated
54 2
            : "{$basePath}/{$path}";
55
56 2
        return $path;
57
    }
58
59
    /**
60
     * Return Router path generator
61
     *
62
     * @return \Aura\Router\Generator
63
     */
64 2
    protected function getRouterGenerator()
65
    {
66
        /** @var Router $router */
67 2
        $router = Application::container()->get('router.middleware');
68 2
        return $router->getRouterContainer()->getGenerator();
69
    }
70
}