Pattern   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 1
dl 0
loc 70
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 2
B generate() 0 21 5
A getPrefix() 0 7 1
A getPattern() 0 11 3
1
<?php
2
3
namespace Knp\RadBundle\Routing\Conventional\Generator;
4
5
use Knp\RadBundle\Routing\Conventional\Generator;
6
use Knp\RadBundle\Routing\Conventional\Config;
7
8
class Pattern implements Generator
9
{
10
    private $map = array(
11
        'index'  => '.{_format}',
12
        'new'    => '/new.{_format}',
13
        'create' => '/new.{_format}',
14
        'edit'   => '/{id}/edit.{_format}',
15
        'update' => '/{id}/edit.{_format}',
16
        'show'   => '/{id}.{_format}',
17
        'delete' => '/{id}.{_format}',
18
    );
19
20
    public function __construct(array $map = null)
21
    {
22
        $this->map = $map ?: $this->map;
23
    }
24
25
    /**
26
     * recursively create a pattern, prepending parent "representant"(i.e: "show") pattern
27
     * this parent pattern is modified to replace {id} with {<name>Id}, and remove {_format} if needed
28
     *
29
     * @return string
30
     **/
31
    public function generate(Config $config)
32
    {
33
        $parts = array();
34
        if ($config->parent) {
35
            $parts[] = str_replace(
36
                array('{id}', '.{_format}'),
37
                array(sprintf('{%sId}', $this->getPrefix($config->parent)), ''),
38
                $this->generate($config->parent)
39
            );
40
        }
41
        $parts[] = $this->getPrefix($config);
42
43
        $prefix = implode('/', array_filter($parts));
44
        $pattern = $this->getPattern($config);
45
46
        if (isset($pattern[0]) && '/' !== $pattern[0] && '.' !== $pattern[0]) {
47
            return rtrim($prefix, '/').'/'.$pattern;
48
        }
49
50
        return $prefix.$pattern;
51
    }
52
53
    /**
54
     * prefix is the name (by default). This name can be of form: "App:Something"
55
     *
56
     * @return string
57
     **/
58
    private function getPrefix(Config $config)
59
    {
60
        $parts = explode(':', $config->getPrefix());
61
        array_shift($parts);
62
63
        return strtolower(str_replace(array('/', '\\'), '_', implode('_', $parts)));
64
    }
65
66
    private function getPattern(Config $config)
67
    {
68
        $pattern = $config->getPattern();
69
        if (!empty($pattern)) {
70
            return $pattern;
71
        }
72
73
        if (isset($this->map[$config->name])) {
74
            return $this->map[$config->name];
75
        }
76
    }
77
}
78