Completed
Push — master ( aec546...27a395 )
by Filipe
04:35
created

UrlUtils::getUrl()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4.0047

Importance

Changes 2
Bugs 1 Features 1
Metric Value
c 2
b 1
f 1
dl 0
loc 22
ccs 14
cts 15
cp 0.9333
rs 8.9197
cc 4
eloc 15
nc 5
nop 1
crap 4.0047
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: filipesilva
5
 * Date: 04/04/16
6
 * Time: 22:10
7
 */
8
9
namespace Slick\Mvc\Controller;
10
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
trait UrlUtils
18
{
19
    /**
20
     * @return Request
21
     */
22
    abstract public function getRequest();
23
24
    /**
25
     * Gets the url for provided path
26
     * 
27
     * @param string $path
28
     * @return string
29
     */
30 4
    public function getUrl($path)
31
    {
32 4
        $regExp = '/\/\/|https?:/i';
33 4
        if (preg_match($regExp, $path)) {
34 2
            return $path;
35
        }
36
        try {
37 2
            $generated = call_user_func_array(
38 2
                [$this->getRouterGenerator(), 'generate'],
39 1
                func_get_args()
40 1
            );
41 1
        } catch (AuraException $caught) {
42
            $generated = false;
43
        }
44
45 2
        $basePath = rtrim($this->getRequest()->getBasePath(), '/');
46 1
        $path = $generated
47 1
            ? $generated
48 2
            : "{$basePath}/{$path}";
49
50 2
        return $path;
51
    }
52
53
    /**
54
     * Return Router path generator
55
     *
56
     * @return \Aura\Router\Generator
57
     */
58 2
    protected function getRouterGenerator()
59
    {
60
        /** @var Router $router */
61 2
        $router = Application::container()->get('router.middleware');
62 2
        return $router->getRouterContainer()->getGenerator();
63
    }
64
}