1
|
|
|
<?php |
2
|
|
|
/* |
3
|
|
|
* This file is part of the QueryResourcesLoaderBundle, an RunOpenCode project. |
4
|
|
|
* |
5
|
|
|
* (c) 2016 RunOpenCode |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
*/ |
10
|
|
|
namespace RunOpenCode\Bundle\QueryResourcesLoader\Twig; |
11
|
|
|
|
12
|
|
|
use Symfony\Bridge\Doctrine\RegistryInterface; |
13
|
|
|
|
14
|
|
|
class DoctrineOrmExtension extends \Twig_Extension |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var RegistryInterface |
18
|
|
|
*/ |
19
|
|
|
private $doctrine; |
20
|
|
|
|
21
|
|
|
public function __construct(RegistryInterface $doctrine) |
22
|
|
|
{ |
23
|
|
|
$this->doctrine = $doctrine; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* {@inheritdoc} |
28
|
|
|
*/ |
29
|
|
|
public function getName() |
30
|
|
|
{ |
31
|
|
|
return 'run_open_code_query_resources_loader'; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* {@inheritdoc} |
36
|
|
|
*/ |
37
|
|
View Code Duplication |
public function getFunctions() |
|
|
|
|
38
|
|
|
{ |
39
|
|
|
return array( |
40
|
|
|
new \Twig_SimpleFunction('table_name', \Closure::bind(function($entity) { |
41
|
|
|
return $this->getTableName($entity); |
42
|
|
|
}, $this)), |
43
|
|
|
new \Twig_SimpleFunction('column_name', \Closure::bind(function($field, $entity) { |
44
|
|
|
return $this->getColumnName($field, $entity); |
45
|
|
|
}, $this)) |
46
|
|
|
); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
View Code Duplication |
public function getFilters() |
|
|
|
|
50
|
|
|
{ |
51
|
|
|
return array( |
52
|
|
|
new \Twig_SimpleFilter('table_name', \Closure::bind(function($entity) { |
53
|
|
|
return $this->getTableName($entity); |
54
|
|
|
}, $this)), |
55
|
|
|
new \Twig_SimpleFilter('column_name', \Closure::bind(function($field, $entity) { |
56
|
|
|
return $this->getColumnName($field, $entity); |
57
|
|
|
}, $this)) |
58
|
|
|
); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
View Code Duplication |
private function getTableName($entity) |
|
|
|
|
62
|
|
|
{ |
63
|
|
|
if (is_object($entity)) { |
64
|
|
|
$entity = get_class($entity); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
return $this->doctrine->getEntityManagerForClass($entity)->getClassMetadata($entity)->getTableName(); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
View Code Duplication |
private function getColumnName($field, $entity) |
|
|
|
|
71
|
|
|
{ |
72
|
|
|
if (is_object($entity)) { |
73
|
|
|
$entity = get_class($entity); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
return $this->doctrine->getEntityManagerForClass($entity)->getClassMetadata($entity)->getColumnName($field); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.