Completed
Push — master ( c5d644...a435b5 )
by Guillaume
02:45
created

GenererDataTestCommand::configure()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 0
1
<?php
2
3
namespace Starkerxp\StructureBundle\Command;
4
5
6
use Symfony\Component\Yaml\Yaml;
7
8
/**
9
 * Class GenererDataTestCommand
10
 */
11
class GenererDataTestCommand extends LockCommand
12
{
13
14
    /**
15
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be false|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
16
     */
17
    public function treatment()
18
    {
19
        if (preg_match("#prod#", $this->getEnvironment())) {
20
            $this->output->writeln("<error>Command disallow</error>");
21
22
            return false;
23
        }
24
25
        $allMetadata = $this->getEntityManager()->getMetadataFactory()->getAllMetadata();
26
        // On récupère la liste des entites en fonction des nom de tables supposés.
27
        $namespaces = [];
28
        foreach ($allMetadata as $metadata) {
29
            if ($metadata->isMappedSuperclass) {
30
                continue;
31
            }
32
            if (count($metadata->subClasses)) {
33
                $namespaces[$metadata->getName()] = [
34
                    'tableName' => $metadata->getTableName(),
35
                ];
36
                continue;
37
            }
38
            $columns = array_flip($metadata->columnNames);
39
            $fields = [];
40
            foreach ($columns as $column => $field) {
41
                $fields[$column] = [
42
                    'field' => $field,
43
                    'type' => $metadata->getFieldMapping($field)['type'],
44
                ];
45
            }
46
            $mapping = $metadata->getAssociationMappings();
47
            foreach ($mapping as $detail) {
48
                if (!array_key_exists("sourceToTargetKeyColumns", $detail)) {
49
                    continue;
50
                }
51
                $column = array_keys($detail['sourceToTargetKeyColumns'])[0];
52
                $fields[$column] = [
53
                    'field' => $detail['fieldName'],
54
                    'type' => 'integer',
55
                    'sourceToTargetKeyColumns' => $detail['sourceToTargetKeyColumns'][$column],
56
                    'targetEntity' => $detail['targetEntity'],
57
                ];
58
            }
59
            $namespaces[$metadata->getName()] = [
60
                'tableName' => $metadata->getTableName(),
61
                'fields' => $fields,
62
                'discriminatorValue' => $metadata->discriminatorValue,
63
                'discriminatorColumn' => !empty($metadata->discriminatorValue) ? $metadata->discriminatorColumn['name'] : null,
64
            ];
65
        }
66
        ksort($namespaces);
67
        $contenu = "";
68
        foreach ($namespaces as $namespace => $data) {
69
            if (empty($data['fields'])) {
70
                continue;
71
            }
72
            $export = [];
73
            $where = (!empty($data['discriminatorValue']) ? $data['discriminatorColumn']."='".$data['discriminatorValue']."'" : "1=1");
74
            $query = "SELECT ".implode(",", array_keys($data['fields']))." FROM ".$data['tableName']." WHERE ".$where;
75
            if (!$resultats = $this->getConnection()->fetchAll($query)) {
76
                continue;
77
78
            }
79
80
            foreach ($resultats as $key => $row) {
81
                $dataExport = [];
82
                foreach ($row as $element => $value) {
83
                    if ($element == 'id') {
84
                        continue;
85
                    }
86
                    $field = $data['fields'][$element]['field'];
87
                    if (!empty($data['fields'][$element]['targetEntity'])) {
88
                        $value = empty($value) ? null : strtolower("@".$namespaces[$data['fields'][$element]['targetEntity']]['tableName'])."_".$value;
89
                        $dataExport[$data['fields'][$element]['field']] = $value;
90
                        continue;
91
                    }
92
                    $dataExport[$field] = $this->formatValue($data['fields'][$element]['type'], $value);
93
                }
94
                $export[strtolower($data['tableName']).'_'.$row['id']] = $dataExport;
95
            }
96
            $contenu .= Yaml::dump([$namespace => $export,], 2, 4)."\n";
97
        }
98
        echo $contenu;
99
    }
100
101
    public function formatValue($type, $value)
102
    {
103
        if (in_array($type, ['datetime', 'date']) && !empty($value)) {
104
            return $value = '<(new \DateTime("'.$value.'"))>';
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $value. This often makes code more readable.
Loading history...
Unused Code introduced by
$value is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
105
        }
106
        if (in_array($type, ['json_array'])) {
107
            return json_decode($value, true);
108
        }
109
        if (in_array($type, ['array'])) {
110
            return unserialize($value);
111
        }
112
113
        return $value;
114
    }
115
116
    protected function configure()
117
    {
118
        parent::configure();
119
        $this->setName('starkerxp:dump-database')
120
            ->setDescription("Extract development database to yaml fixtures.");
121
    }
122
123
124
}
0 ignored issues
show
Coding Style introduced by
As per coding style, files should not end with a newline character.

This check marks files that end in a newline character, i.e. an empy line.

Loading history...
125