ReferenceManipulator   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 0
dl 0
loc 44
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A createReferenceName() 0 8 2
A generateUniqueReferenceName() 0 10 2
A incrementReferenceName() 0 16 3
1
<?php
2
3
namespace Knp\RadBundle\DataFixtures;
4
5
use Doctrine\Common\DataFixtures\ReferenceRepository;
6
7
class ReferenceManipulator
8
{
9
    public function __construct(ReferenceRepository $referenceRepository)
10
    {
11
        $this->referenceRepository = $referenceRepository;
0 ignored issues
show
Bug introduced by
The property referenceRepository does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
12
    }
13
14
    public function createReferenceName($className, array $attributes = array())
15
    {
16
         $className     = join('', array_slice(explode('\\', $className), -1));
17
         $referenceId   = reset($attributes);
18
         $referenceName = $referenceId ? sprintf('%s:%s', $className, $referenceId) : $className;
19
20
         return $this->generateUniqueReferenceName($referenceName);
21
    }
22
23
    private function generateUniqueReferenceName($referenceName)
24
    {
25
        if ($this->referenceRepository->hasReference($referenceName)) {
26
            $referenceName = $this->incrementReferenceName($referenceName);
27
28
            return $this->generateUniqueReferenceName($referenceName);
29
        }
30
31
        return $referenceName;
32
    }
33
34
    private function incrementReferenceName($referenceName)
35
    {
36
        if (0 === preg_match('#^(.*)(\d+)$#', $referenceName)) {
37
            if (1 === preg_match('#^(\w+):(\w+)#', $referenceName)) {
38
                return sprintf('%s-1', $referenceName);
39
            } else {
40
                return sprintf('%s:1', $referenceName);
41
            }
42
        }
43
44
        return preg_replace_callback(
45
            '#^(.*)(\d+)$#',
46
            function ($matches) { return $matches[1].intval($matches[2]+1); },
0 ignored issues
show
Coding Style introduced by
Opening brace must be the last content on the line
Loading history...
47
            $referenceName
48
        );
49
    }
50
}
51