GridSourceGenerator::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Dtc\GridBundle\Generator;
4
5
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
0 ignored issues
show
Bug introduced by
The type Doctrine\ODM\MongoDB\Mapping\ClassMetadata was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use Doctrine\ORM\Mapping\ClassMetadataInfo;
0 ignored issues
show
Bug introduced by
The type Doctrine\ORM\Mapping\ClassMetadataInfo was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
use Dtc\GridBundle\Util\CamelCase;
8
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\HttpKe...\Bundle\BundleInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
9
use Symfony\Component\Yaml\Yaml;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\Yaml\Yaml was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
10
11
/**
12
 * @deprecated
13
 * Class GridSourceGenerator
14
 */
15
class GridSourceGenerator extends Generator
16
{
17
    private $saveCache;
18
    private $skeletonDir;
19
20
    public function __construct($skeletonDir)
21
    {
22
        $this->skeletonDir = $skeletonDir;
23
    }
24
25
    protected function generateColumns(BundleInterface $bundle, $entity, $metadata)
26
    {
27
        $parts = explode('\\', $entity);
28
        $entityClass = array_pop($parts);
29
        $entityNamespace = implode('\\', $parts);
30
31
        $gridColumnsNamespace = $bundle->getNamespace().'\\Grid\\Columns';
32
        $gridColumnsNamespace .= ($entityNamespace) ? '\\'.$entityNamespace : '';
33
34
        $gridColumnClass = $entityClass.'GridColumn';
35
        $dirPath = $bundle->getPath().'/Grid/Columns';
36
        $gridColumnPath = $dirPath.'/'.str_replace('\\', '/', $entity).'GridColumn.php';
37
        $templatePath = $bundle->getPath().'/Resources/views/'.str_replace('\\', '/', $entity).'/_grid.html.twig';
38
39
        $fields = [];
40
        foreach ($this->getFieldsFromMetadata($metadata) as $field) {
41
            $fields[$field] = CamelCase::fromCamelCase($field);
42
        }
43
44
        $params = [
45
                'fields' => $fields,
46
                'namespace' => $gridColumnsNamespace,
47
                'class' => $gridColumnClass,
48
                'template_name' => "{$bundle->getName()}:{$entity}:_grid.html.twig",
49
        ];
50
51
        $this->saveCache[$templatePath] = $this->render($this->skeletonDir, 'grid_template.html.twig', $params);
52
        $this->saveCache[$gridColumnPath] = $this->render($this->skeletonDir, 'GridColumns.php.twig', $params);
53
54
        return [$gridColumnClass, $gridColumnsNamespace, $gridColumnPath, $templatePath];
55
    }
56
57
    public function generate(BundleInterface $bundle, $entityDocument, $metadata, $columns = false)
58
    {
59
        if ($metadata instanceof ClassMetadataInfo) {
60
            $manager = '@doctrine.orm.default_entity_manager';
61
            $class = 'Dtc\GridBundle\Grid\Source\EntityGridSource';
62
        } elseif ($metadata instanceof \Doctrine\ODM\MongoDB\Mapping\ClassMetadataInfo) {
0 ignored issues
show
Bug introduced by
The type Doctrine\ODM\MongoDB\Mapping\ClassMetadataInfo was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
63
            $manager = '@doctrine_mongodb.odm.default_document_manager';
64
            $class = 'Dtc\GridBundle\Grid\Source\DocumentGridSource';
65
        } else {
66
            throw new \Exception(__METHOD__.' - Unknown class for metadata: '.get_class($metadata));
67
        }
68
        $entityDocumentClassPath = $metadata->getReflectionClass()->getName();
69
70
        $parts = explode('\\', $entityDocument);
71
        $entityDocumentClass = array_pop($parts);
72
        $files = [];
73
74
        if ($columns) {
75
            list($gridColumnClass, $gridColumnsNamespace, $gridColumnPath, $templatePath) =
76
                $this->generateColumns($bundle, $entityDocument, $metadata);
77
78
            $files = [
79
                'grid_columns' => $gridColumnPath,
80
                'grid_template' => $templatePath,
81
            ];
82
        }
83
84
        // Check to see if the files exists
85
        if ($this->saveCache) {
86
            foreach ($this->saveCache as $file => $output) {
87
                $this->saveFile($file, $output);
88
            }
89
        }
90
91
        $config = [];
92
        $serviceName = 'grid.source.'.strtolower($entityDocumentClass);
93
        $config[$serviceName] = [
94
                'class' => $class,
95
                'arguments' => [$manager, $entityDocumentClassPath],
96
                'tags' => [['name' => 'dtc_grid.source']],
97
                'calls' => [
98
                    ['autoDiscoverColumns'],
99
        ], ];
100
101
        if ($columns && isset($gridColumnsNamespace) && isset($gridColumnClass)) {
102
            $config[$serviceName]['calls'] = [
103
                ['setColumns', [
104
                    '@'.$serviceName.'.columns',
105
                ],
106
                ],
107
            ];
108
109
            $config[$serviceName.'.columns'] = [
110
                'class' => $gridColumnsNamespace.'\\'.$gridColumnClass,
111
                'arguments' => ['@twig'],
112
            ];
113
        }
114
115
        $configFile = $bundle->getPath().'/Resources/config/grid.yml';
116
        $services = [];
117
        if (file_exists($configFile)) {
118
            $services = Yaml::parse($contents = file_get_contents($configFile));
119
            if (isset($services['services'])) {
120
                $services['services'] = array_merge($services['services'], $config);
121
            } else {
122
                $services['services'] = $config;
123
            }
124
        } else {
125
            $services['services'] = $config;
126
        }
127
128
        $this->saveFile($configFile, Yaml::dump($services, 3));
129
130
        $params = [
131
            'gridsource_id' => $serviceName,
132
            'files' => $files,
133
        ];
134
135
        $output = $this->render($this->skeletonDir, 'controller.php.twig', $params);
136
        echo $output;
137
        exit();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
138
    }
139
140
    private function getFieldsFromMetadata($metadata)
141
    {
142
        if ($metadata instanceof ClassMetadataInfo) {
143
            $fields = $metadata->getFieldNames();
144
145
            // Remove the primary key field if it's not managed manually
146
            if (!$metadata->isIdentifierNatural()) {
147
                $fields = array_diff($fields, $metadata->getIdentifier());
148
            }
149
150
            foreach ($metadata->associationMappings as $fieldName => $relation) {
151
                if (ClassMetadataInfo::ONE_TO_MANY !== $relation['type']) {
152
                    $fields[] = $fieldName;
153
                }
154
            }
155
156
            return $fields;
157
        } elseif ($metadata instanceof ClassMetadata) {
158
            $fields = $metadata->getFieldNames();
159
            $retFields = [];
160
            $identifier = $metadata->getIdentifier();
161
            $identifier = isset($identifier[0]) ? $identifier[0] : null;
162
            foreach ($fields as $field) {
163
                if ($identifier === $field) {
164
                    $mapping = $metadata->getFieldMapping($field);
165
                    if (isset($mapping['strategy']) && 'auto' == $mapping['strategy']) {
166
                        continue;
167
                    }
168
                }
169
                $retFields[] = $field;
170
            }
171
172
            return $retFields;
173
        }
174
    }
175
}
176