Passed
Pull Request — 4.2 (#140)
by David
05:21
created
src/Mouf/Database/TDBM/Commands/AlteredConfiguration.php 1 patch
Indentation   +99 added lines, -99 removed lines patch added patch discarded remove patch
@@ -19,103 +19,103 @@
 block discarded – undo
19 19
  */
20 20
 class AlteredConfiguration implements ConfigurationInterface
21 21
 {
22
-    /**
23
-     * @var ConfigurationInterface
24
-     */
25
-    private $configuration;
26
-
27
-    /**
28
-     * @var LoggerInterface
29
-     */
30
-    private $logger;
31
-
32
-    public function __construct(ConfigurationInterface $configuration)
33
-    {
34
-        $this->configuration = $configuration;
35
-        $this->logger = $configuration->getLogger();
36
-    }
37
-
38
-
39
-    /**
40
-     * @return string
41
-     */
42
-    public function getBeanNamespace(): string
43
-    {
44
-        return $this->configuration->getBeanNamespace();
45
-    }
46
-
47
-    /**
48
-     * @return string
49
-     */
50
-    public function getDaoNamespace(): string
51
-    {
52
-        return $this->configuration->getDaoNamespace();
53
-    }
54
-
55
-    /**
56
-     * @return Connection
57
-     */
58
-    public function getConnection(): Connection
59
-    {
60
-        return $this->configuration->getConnection();
61
-    }
62
-
63
-    /**
64
-     * @return Cache
65
-     */
66
-    public function getCache(): Cache
67
-    {
68
-        return $this->configuration->getCache();
69
-    }
70
-
71
-    /**
72
-     * @return NamingStrategyInterface
73
-     */
74
-    public function getNamingStrategy(): NamingStrategyInterface
75
-    {
76
-        return $this->configuration->getNamingStrategy();
77
-    }
78
-
79
-    /**
80
-     * @return SchemaAnalyzer
81
-     */
82
-    public function getSchemaAnalyzer(): SchemaAnalyzer
83
-    {
84
-        return $this->configuration->getSchemaAnalyzer();
85
-    }
86
-
87
-    /**
88
-     * @return LoggerInterface
89
-     */
90
-    public function getLogger(): ?LoggerInterface
91
-    {
92
-        return $this->configuration->getLogger();
93
-    }
94
-
95
-    /**
96
-     * @return GeneratorListenerInterface
97
-     */
98
-    public function getGeneratorEventDispatcher(): GeneratorListenerInterface
99
-    {
100
-        return $this->configuration->getGeneratorEventDispatcher();
101
-    }
102
-
103
-    /**
104
-     * @param LoggerInterface $logger
105
-     */
106
-    public function setLogger(LoggerInterface $logger)
107
-    {
108
-        $this->logger = $logger;
109
-    }
110
-
111
-    /**
112
-     * Get the Composer file used to detect the path where files should be written.
113
-     * Path is relative to the root directory (this function will typically return 'composer.json' unless you want to write the beans and DAOs in a package).
114
-     *
115
-     * @return null|string
116
-     */
117
-    public function getComposerFile(): string
118
-    {
119
-        return $this->configuration->getComposerFile();
120
-    }
22
+	/**
23
+	 * @var ConfigurationInterface
24
+	 */
25
+	private $configuration;
26
+
27
+	/**
28
+	 * @var LoggerInterface
29
+	 */
30
+	private $logger;
31
+
32
+	public function __construct(ConfigurationInterface $configuration)
33
+	{
34
+		$this->configuration = $configuration;
35
+		$this->logger = $configuration->getLogger();
36
+	}
37
+
38
+
39
+	/**
40
+	 * @return string
41
+	 */
42
+	public function getBeanNamespace(): string
43
+	{
44
+		return $this->configuration->getBeanNamespace();
45
+	}
46
+
47
+	/**
48
+	 * @return string
49
+	 */
50
+	public function getDaoNamespace(): string
51
+	{
52
+		return $this->configuration->getDaoNamespace();
53
+	}
54
+
55
+	/**
56
+	 * @return Connection
57
+	 */
58
+	public function getConnection(): Connection
59
+	{
60
+		return $this->configuration->getConnection();
61
+	}
62
+
63
+	/**
64
+	 * @return Cache
65
+	 */
66
+	public function getCache(): Cache
67
+	{
68
+		return $this->configuration->getCache();
69
+	}
70
+
71
+	/**
72
+	 * @return NamingStrategyInterface
73
+	 */
74
+	public function getNamingStrategy(): NamingStrategyInterface
75
+	{
76
+		return $this->configuration->getNamingStrategy();
77
+	}
78
+
79
+	/**
80
+	 * @return SchemaAnalyzer
81
+	 */
82
+	public function getSchemaAnalyzer(): SchemaAnalyzer
83
+	{
84
+		return $this->configuration->getSchemaAnalyzer();
85
+	}
86
+
87
+	/**
88
+	 * @return LoggerInterface
89
+	 */
90
+	public function getLogger(): ?LoggerInterface
91
+	{
92
+		return $this->configuration->getLogger();
93
+	}
94
+
95
+	/**
96
+	 * @return GeneratorListenerInterface
97
+	 */
98
+	public function getGeneratorEventDispatcher(): GeneratorListenerInterface
99
+	{
100
+		return $this->configuration->getGeneratorEventDispatcher();
101
+	}
102
+
103
+	/**
104
+	 * @param LoggerInterface $logger
105
+	 */
106
+	public function setLogger(LoggerInterface $logger)
107
+	{
108
+		$this->logger = $logger;
109
+	}
110
+
111
+	/**
112
+	 * Get the Composer file used to detect the path where files should be written.
113
+	 * Path is relative to the root directory (this function will typically return 'composer.json' unless you want to write the beans and DAOs in a package).
114
+	 *
115
+	 * @return null|string
116
+	 */
117
+	public function getComposerFile(): string
118
+	{
119
+		return $this->configuration->getComposerFile();
120
+	}
121 121
 }
122 122
\ No newline at end of file
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/ConfigurationInterface.php 1 patch
Indentation   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -11,51 +11,51 @@
 block discarded – undo
11 11
 
12 12
 interface ConfigurationInterface
13 13
 {
14
-    /**
15
-     * @return string
16
-     */
17
-    public function getBeanNamespace(): string;
18
-
19
-    /**
20
-     * @return string
21
-     */
22
-    public function getDaoNamespace(): string;
23
-
24
-    /**
25
-     * @return Connection
26
-     */
27
-    public function getConnection(): Connection;
28
-
29
-    /**
30
-     * @return Cache
31
-     */
32
-    public function getCache(): Cache;
33
-
34
-    /**
35
-     * @return NamingStrategyInterface
36
-     */
37
-    public function getNamingStrategy(): NamingStrategyInterface;
38
-
39
-    /**
40
-     * @return SchemaAnalyzer
41
-     */
42
-    public function getSchemaAnalyzer(): SchemaAnalyzer;
43
-
44
-    /**
45
-     * @return LoggerInterface
46
-     */
47
-    public function getLogger(): ?LoggerInterface;
48
-
49
-    /**
50
-     * @return GeneratorListenerInterface
51
-     */
52
-    public function getGeneratorEventDispatcher(): GeneratorListenerInterface;
53
-
54
-    /**
55
-     * Get the Composer file used to detect the path where files should be written.
56
-     * Path is relative to the root directory (this function will typically return 'composer.json' unless you want to write the beans and DAOs in a package).
57
-     *
58
-     * @return null|string
59
-     */
60
-    public function getComposerFile() : string;
14
+	/**
15
+	 * @return string
16
+	 */
17
+	public function getBeanNamespace(): string;
18
+
19
+	/**
20
+	 * @return string
21
+	 */
22
+	public function getDaoNamespace(): string;
23
+
24
+	/**
25
+	 * @return Connection
26
+	 */
27
+	public function getConnection(): Connection;
28
+
29
+	/**
30
+	 * @return Cache
31
+	 */
32
+	public function getCache(): Cache;
33
+
34
+	/**
35
+	 * @return NamingStrategyInterface
36
+	 */
37
+	public function getNamingStrategy(): NamingStrategyInterface;
38
+
39
+	/**
40
+	 * @return SchemaAnalyzer
41
+	 */
42
+	public function getSchemaAnalyzer(): SchemaAnalyzer;
43
+
44
+	/**
45
+	 * @return LoggerInterface
46
+	 */
47
+	public function getLogger(): ?LoggerInterface;
48
+
49
+	/**
50
+	 * @return GeneratorListenerInterface
51
+	 */
52
+	public function getGeneratorEventDispatcher(): GeneratorListenerInterface;
53
+
54
+	/**
55
+	 * Get the Composer file used to detect the path where files should be written.
56
+	 * Path is relative to the root directory (this function will typically return 'composer.json' unless you want to write the beans and DAOs in a package).
57
+	 *
58
+	 * @return null|string
59
+	 */
60
+	public function getComposerFile() : string;
61 61
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/TDBMDaoGenerator.php 1 patch
Indentation   +416 added lines, -416 removed lines patch added patch discarded remove patch
@@ -19,157 +19,157 @@  discard block
 block discarded – undo
19 19
  */
20 20
 class TDBMDaoGenerator
21 21
 {
22
-    /**
23
-     * @var Schema
24
-     */
25
-    private $schema;
26
-
27
-    /**
28
-     * The root directory of the project.
29
-     *
30
-     * @var string
31
-     */
32
-    private $rootPath;
33
-
34
-    /**
35
-     * Name of composer file.
36
-     *
37
-     * @var string
38
-     */
39
-    private $composerFile;
40
-
41
-    /**
42
-     * @var TDBMSchemaAnalyzer
43
-     */
44
-    private $tdbmSchemaAnalyzer;
45
-
46
-    /**
47
-     * @var EventDispatcherInterface
48
-     */
49
-    private $eventDispatcher;
50
-
51
-    /**
52
-     * @var NamingStrategyInterface
53
-     */
54
-    private $namingStrategy;
55
-    /**
56
-     * @var ConfigurationInterface
57
-     */
58
-    private $configuration;
59
-
60
-    /**
61
-     * Constructor.
62
-     *
63
-     * @param ConfigurationInterface $configuration
64
-     * @param Schema $schema
65
-     * @param TDBMSchemaAnalyzer $tdbmSchemaAnalyzer
66
-     */
67
-    public function __construct(ConfigurationInterface $configuration, Schema $schema, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer)
68
-    {
69
-        $this->configuration = $configuration;
70
-        $this->schema = $schema;
71
-        $this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
72
-        $this->rootPath = __DIR__.'/../../../../../../../../';
73
-        $this->composerFile = $configuration->getComposerFile();
74
-        $this->namingStrategy = $configuration->getNamingStrategy();
75
-        $this->eventDispatcher = $configuration->getGeneratorEventDispatcher();
76
-    }
77
-
78
-    /**
79
-     * Generates all the daos and beans.
80
-     *
81
-     * @throws TDBMException
82
-     */
83
-    public function generateAllDaosAndBeans(): void
84
-    {
85
-        $classNameMapper = ClassNameMapper::createFromComposerFile($this->rootPath.$this->composerFile);
86
-        // TODO: check that no class name ends with "Base". Otherwise, there will be name clash.
87
-
88
-        $tableList = $this->schema->getTables();
89
-
90
-        // Remove all beans and daos from junction tables
91
-        $junctionTables = $this->configuration->getSchemaAnalyzer()->detectJunctionTables(true);
92
-        $junctionTableNames = array_map(function (Table $table) {
93
-            return $table->getName();
94
-        }, $junctionTables);
95
-
96
-        $tableList = array_filter($tableList, function (Table $table) use ($junctionTableNames) {
97
-            return !in_array($table->getName(), $junctionTableNames);
98
-        });
99
-
100
-        $beanDescriptors = [];
101
-
102
-        foreach ($tableList as $table) {
103
-            $beanDescriptors[] = $this->generateDaoAndBean($table, $classNameMapper);
104
-        }
105
-
106
-
107
-        $this->generateFactory($tableList, $classNameMapper);
108
-
109
-        // Let's call the list of listeners
110
-        $this->eventDispatcher->onGenerate($this->configuration, $beanDescriptors);
111
-    }
112
-
113
-    /**
114
-     * Generates in one method call the daos and the beans for one table.
115
-     *
116
-     * @param Table $table
117
-     * @param ClassNameMapper $classNameMapper
118
-     *
119
-     * @return BeanDescriptor
120
-     * @throws TDBMException
121
-     */
122
-    private function generateDaoAndBean(Table $table, ClassNameMapper $classNameMapper) : BeanDescriptor
123
-    {
124
-        // TODO: $storeInUtc is NOT USED.
125
-        $tableName = $table->getName();
126
-        $daoName = $this->namingStrategy->getDaoClassName($tableName);
127
-        $beanName = $this->namingStrategy->getBeanClassName($tableName);
128
-        $baseBeanName = $this->namingStrategy->getBaseBeanClassName($tableName);
129
-        $baseDaoName = $this->namingStrategy->getBaseDaoClassName($tableName);
130
-
131
-        $beanDescriptor = new BeanDescriptor($table, $this->configuration->getSchemaAnalyzer(), $this->schema, $this->tdbmSchemaAnalyzer, $this->namingStrategy);
132
-        $this->generateBean($beanDescriptor, $beanName, $baseBeanName, $table, $classNameMapper);
133
-        $this->generateDao($beanDescriptor, $daoName, $baseDaoName, $beanName, $table, $classNameMapper);
134
-        return $beanDescriptor;
135
-    }
136
-
137
-    /**
138
-     * Writes the PHP bean file with all getters and setters from the table passed in parameter.
139
-     *
140
-     * @param BeanDescriptor  $beanDescriptor
141
-     * @param string          $className       The name of the class
142
-     * @param string          $baseClassName   The name of the base class which will be extended (name only, no directory)
143
-     * @param Table           $table           The table
144
-     * @param ClassNameMapper $classNameMapper
145
-     *
146
-     * @throws TDBMException
147
-     */
148
-    public function generateBean(BeanDescriptor $beanDescriptor, $className, $baseClassName, Table $table, ClassNameMapper $classNameMapper)
149
-    {
150
-        $beannamespace = $this->configuration->getBeanNamespace();
151
-        $str = $beanDescriptor->generatePhpCode($beannamespace);
152
-
153
-        $possibleBaseFileNames = $classNameMapper->getPossibleFileNames($beannamespace.'\\Generated\\'.$baseClassName);
154
-        if (empty($possibleBaseFileNames)) {
155
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$beannamespace.'\\'.$baseClassName.'" is not autoloadable.');
156
-        }
157
-        $possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0];
158
-
159
-        $this->ensureDirectoryExist($possibleBaseFileName);
160
-        file_put_contents($possibleBaseFileName, $str);
161
-        @chmod($possibleBaseFileName, 0664);
162
-
163
-        $possibleFileNames = $classNameMapper->getPossibleFileNames($beannamespace.'\\'.$className);
164
-        if (empty($possibleFileNames)) {
165
-            // @codeCoverageIgnoreStart
166
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$beannamespace.'\\'.$className.'" is not autoloadable.');
167
-            // @codeCoverageIgnoreEnd
168
-        }
169
-        $possibleFileName = $this->rootPath.$possibleFileNames[0];
170
-        if (!file_exists($possibleFileName)) {
171
-            $tableName = $table->getName();
172
-            $str = "<?php
22
+	/**
23
+	 * @var Schema
24
+	 */
25
+	private $schema;
26
+
27
+	/**
28
+	 * The root directory of the project.
29
+	 *
30
+	 * @var string
31
+	 */
32
+	private $rootPath;
33
+
34
+	/**
35
+	 * Name of composer file.
36
+	 *
37
+	 * @var string
38
+	 */
39
+	private $composerFile;
40
+
41
+	/**
42
+	 * @var TDBMSchemaAnalyzer
43
+	 */
44
+	private $tdbmSchemaAnalyzer;
45
+
46
+	/**
47
+	 * @var EventDispatcherInterface
48
+	 */
49
+	private $eventDispatcher;
50
+
51
+	/**
52
+	 * @var NamingStrategyInterface
53
+	 */
54
+	private $namingStrategy;
55
+	/**
56
+	 * @var ConfigurationInterface
57
+	 */
58
+	private $configuration;
59
+
60
+	/**
61
+	 * Constructor.
62
+	 *
63
+	 * @param ConfigurationInterface $configuration
64
+	 * @param Schema $schema
65
+	 * @param TDBMSchemaAnalyzer $tdbmSchemaAnalyzer
66
+	 */
67
+	public function __construct(ConfigurationInterface $configuration, Schema $schema, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer)
68
+	{
69
+		$this->configuration = $configuration;
70
+		$this->schema = $schema;
71
+		$this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
72
+		$this->rootPath = __DIR__.'/../../../../../../../../';
73
+		$this->composerFile = $configuration->getComposerFile();
74
+		$this->namingStrategy = $configuration->getNamingStrategy();
75
+		$this->eventDispatcher = $configuration->getGeneratorEventDispatcher();
76
+	}
77
+
78
+	/**
79
+	 * Generates all the daos and beans.
80
+	 *
81
+	 * @throws TDBMException
82
+	 */
83
+	public function generateAllDaosAndBeans(): void
84
+	{
85
+		$classNameMapper = ClassNameMapper::createFromComposerFile($this->rootPath.$this->composerFile);
86
+		// TODO: check that no class name ends with "Base". Otherwise, there will be name clash.
87
+
88
+		$tableList = $this->schema->getTables();
89
+
90
+		// Remove all beans and daos from junction tables
91
+		$junctionTables = $this->configuration->getSchemaAnalyzer()->detectJunctionTables(true);
92
+		$junctionTableNames = array_map(function (Table $table) {
93
+			return $table->getName();
94
+		}, $junctionTables);
95
+
96
+		$tableList = array_filter($tableList, function (Table $table) use ($junctionTableNames) {
97
+			return !in_array($table->getName(), $junctionTableNames);
98
+		});
99
+
100
+		$beanDescriptors = [];
101
+
102
+		foreach ($tableList as $table) {
103
+			$beanDescriptors[] = $this->generateDaoAndBean($table, $classNameMapper);
104
+		}
105
+
106
+
107
+		$this->generateFactory($tableList, $classNameMapper);
108
+
109
+		// Let's call the list of listeners
110
+		$this->eventDispatcher->onGenerate($this->configuration, $beanDescriptors);
111
+	}
112
+
113
+	/**
114
+	 * Generates in one method call the daos and the beans for one table.
115
+	 *
116
+	 * @param Table $table
117
+	 * @param ClassNameMapper $classNameMapper
118
+	 *
119
+	 * @return BeanDescriptor
120
+	 * @throws TDBMException
121
+	 */
122
+	private function generateDaoAndBean(Table $table, ClassNameMapper $classNameMapper) : BeanDescriptor
123
+	{
124
+		// TODO: $storeInUtc is NOT USED.
125
+		$tableName = $table->getName();
126
+		$daoName = $this->namingStrategy->getDaoClassName($tableName);
127
+		$beanName = $this->namingStrategy->getBeanClassName($tableName);
128
+		$baseBeanName = $this->namingStrategy->getBaseBeanClassName($tableName);
129
+		$baseDaoName = $this->namingStrategy->getBaseDaoClassName($tableName);
130
+
131
+		$beanDescriptor = new BeanDescriptor($table, $this->configuration->getSchemaAnalyzer(), $this->schema, $this->tdbmSchemaAnalyzer, $this->namingStrategy);
132
+		$this->generateBean($beanDescriptor, $beanName, $baseBeanName, $table, $classNameMapper);
133
+		$this->generateDao($beanDescriptor, $daoName, $baseDaoName, $beanName, $table, $classNameMapper);
134
+		return $beanDescriptor;
135
+	}
136
+
137
+	/**
138
+	 * Writes the PHP bean file with all getters and setters from the table passed in parameter.
139
+	 *
140
+	 * @param BeanDescriptor  $beanDescriptor
141
+	 * @param string          $className       The name of the class
142
+	 * @param string          $baseClassName   The name of the base class which will be extended (name only, no directory)
143
+	 * @param Table           $table           The table
144
+	 * @param ClassNameMapper $classNameMapper
145
+	 *
146
+	 * @throws TDBMException
147
+	 */
148
+	public function generateBean(BeanDescriptor $beanDescriptor, $className, $baseClassName, Table $table, ClassNameMapper $classNameMapper)
149
+	{
150
+		$beannamespace = $this->configuration->getBeanNamespace();
151
+		$str = $beanDescriptor->generatePhpCode($beannamespace);
152
+
153
+		$possibleBaseFileNames = $classNameMapper->getPossibleFileNames($beannamespace.'\\Generated\\'.$baseClassName);
154
+		if (empty($possibleBaseFileNames)) {
155
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$beannamespace.'\\'.$baseClassName.'" is not autoloadable.');
156
+		}
157
+		$possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0];
158
+
159
+		$this->ensureDirectoryExist($possibleBaseFileName);
160
+		file_put_contents($possibleBaseFileName, $str);
161
+		@chmod($possibleBaseFileName, 0664);
162
+
163
+		$possibleFileNames = $classNameMapper->getPossibleFileNames($beannamespace.'\\'.$className);
164
+		if (empty($possibleFileNames)) {
165
+			// @codeCoverageIgnoreStart
166
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$beannamespace.'\\'.$className.'" is not autoloadable.');
167
+			// @codeCoverageIgnoreEnd
168
+		}
169
+		$possibleFileName = $this->rootPath.$possibleFileNames[0];
170
+		if (!file_exists($possibleFileName)) {
171
+			$tableName = $table->getName();
172
+			$str = "<?php
173 173
 /*
174 174
  * This file has been automatically generated by TDBM.
175 175
  * You can edit this file as it will not be overwritten.
@@ -186,76 +186,76 @@  discard block
 block discarded – undo
186 186
 {
187 187
 }
188 188
 ";
189
-            $this->ensureDirectoryExist($possibleFileName);
190
-            file_put_contents($possibleFileName, $str);
191
-            @chmod($possibleFileName, 0664);
192
-        }
193
-    }
194
-
195
-    /**
196
-     * Tries to find a @defaultSort annotation in one of the columns.
197
-     *
198
-     * @param Table $table
199
-     *
200
-     * @return array First item: column name, Second item: column order (asc/desc)
201
-     */
202
-    private function getDefaultSortColumnFromAnnotation(Table $table)
203
-    {
204
-        $defaultSort = null;
205
-        $defaultSortDirection = null;
206
-        foreach ($table->getColumns() as $column) {
207
-            $comments = $column->getComment();
208
-            $matches = [];
209
-            if (preg_match('/@defaultSort(\((desc|asc)\))*/', $comments, $matches) != 0) {
210
-                $defaultSort = $column->getName();
211
-                if (count($matches) === 3) {
212
-                    $defaultSortDirection = $matches[2];
213
-                } else {
214
-                    $defaultSortDirection = 'ASC';
215
-                }
216
-            }
217
-        }
218
-
219
-        return [$defaultSort, $defaultSortDirection];
220
-    }
221
-
222
-    /**
223
-     * Writes the PHP bean DAO with simple functions to create/get/save objects.
224
-     *
225
-     * @param BeanDescriptor  $beanDescriptor
226
-     * @param string          $className       The name of the class
227
-     * @param string          $baseClassName
228
-     * @param string          $beanClassName
229
-     * @param Table           $table
230
-     * @param ClassNameMapper $classNameMapper
231
-     *
232
-     * @throws TDBMException
233
-     */
234
-    private function generateDao(BeanDescriptor $beanDescriptor, string $className, string $baseClassName, string $beanClassName, Table $table, ClassNameMapper $classNameMapper)
235
-    {
236
-        $daonamespace = $this->configuration->getDaoNamespace();
237
-        $beannamespace = $this->configuration->getBeanNamespace();
238
-        $tableName = $table->getName();
239
-        $primaryKeyColumns = $table->getPrimaryKeyColumns();
240
-
241
-        list($defaultSort, $defaultSortDirection) = $this->getDefaultSortColumnFromAnnotation($table);
242
-
243
-        // FIXME: lowercase tables with _ in the name should work!
244
-        $tableCamel = self::toSingular(self::toCamelCase($tableName));
245
-
246
-        $beanClassWithoutNameSpace = $beanClassName;
247
-        $beanClassName = $beannamespace.'\\'.$beanClassName;
248
-
249
-        list($usedBeans, $findByDaoCode) = $beanDescriptor->generateFindByDaoCode($beannamespace, $beanClassWithoutNameSpace);
250
-
251
-        $usedBeans[] = $beanClassName;
252
-        // Let's suppress duplicates in used beans (if any)
253
-        $usedBeans = array_flip(array_flip($usedBeans));
254
-        $useStatements = array_map(function ($usedBean) {
255
-            return "use $usedBean;\n";
256
-        }, $usedBeans);
257
-
258
-        $str = "<?php
189
+			$this->ensureDirectoryExist($possibleFileName);
190
+			file_put_contents($possibleFileName, $str);
191
+			@chmod($possibleFileName, 0664);
192
+		}
193
+	}
194
+
195
+	/**
196
+	 * Tries to find a @defaultSort annotation in one of the columns.
197
+	 *
198
+	 * @param Table $table
199
+	 *
200
+	 * @return array First item: column name, Second item: column order (asc/desc)
201
+	 */
202
+	private function getDefaultSortColumnFromAnnotation(Table $table)
203
+	{
204
+		$defaultSort = null;
205
+		$defaultSortDirection = null;
206
+		foreach ($table->getColumns() as $column) {
207
+			$comments = $column->getComment();
208
+			$matches = [];
209
+			if (preg_match('/@defaultSort(\((desc|asc)\))*/', $comments, $matches) != 0) {
210
+				$defaultSort = $column->getName();
211
+				if (count($matches) === 3) {
212
+					$defaultSortDirection = $matches[2];
213
+				} else {
214
+					$defaultSortDirection = 'ASC';
215
+				}
216
+			}
217
+		}
218
+
219
+		return [$defaultSort, $defaultSortDirection];
220
+	}
221
+
222
+	/**
223
+	 * Writes the PHP bean DAO with simple functions to create/get/save objects.
224
+	 *
225
+	 * @param BeanDescriptor  $beanDescriptor
226
+	 * @param string          $className       The name of the class
227
+	 * @param string          $baseClassName
228
+	 * @param string          $beanClassName
229
+	 * @param Table           $table
230
+	 * @param ClassNameMapper $classNameMapper
231
+	 *
232
+	 * @throws TDBMException
233
+	 */
234
+	private function generateDao(BeanDescriptor $beanDescriptor, string $className, string $baseClassName, string $beanClassName, Table $table, ClassNameMapper $classNameMapper)
235
+	{
236
+		$daonamespace = $this->configuration->getDaoNamespace();
237
+		$beannamespace = $this->configuration->getBeanNamespace();
238
+		$tableName = $table->getName();
239
+		$primaryKeyColumns = $table->getPrimaryKeyColumns();
240
+
241
+		list($defaultSort, $defaultSortDirection) = $this->getDefaultSortColumnFromAnnotation($table);
242
+
243
+		// FIXME: lowercase tables with _ in the name should work!
244
+		$tableCamel = self::toSingular(self::toCamelCase($tableName));
245
+
246
+		$beanClassWithoutNameSpace = $beanClassName;
247
+		$beanClassName = $beannamespace.'\\'.$beanClassName;
248
+
249
+		list($usedBeans, $findByDaoCode) = $beanDescriptor->generateFindByDaoCode($beannamespace, $beanClassWithoutNameSpace);
250
+
251
+		$usedBeans[] = $beanClassName;
252
+		// Let's suppress duplicates in used beans (if any)
253
+		$usedBeans = array_flip(array_flip($usedBeans));
254
+		$useStatements = array_map(function ($usedBean) {
255
+			return "use $usedBean;\n";
256
+		}, $usedBeans);
257
+
258
+		$str = "<?php
259 259
 
260 260
 /*
261 261
  * This file has been automatically generated by TDBM.
@@ -331,10 +331,10 @@  discard block
 block discarded – undo
331 331
     }
332 332
     ";
333 333
 
334
-        if (count($primaryKeyColumns) === 1) {
335
-            $primaryKeyColumn = $primaryKeyColumns[0];
336
-            $primaryKeyPhpType = self::dbalTypeToPhpType($table->getColumn($primaryKeyColumn)->getType());
337
-            $str .= "
334
+		if (count($primaryKeyColumns) === 1) {
335
+			$primaryKeyColumn = $primaryKeyColumns[0];
336
+			$primaryKeyPhpType = self::dbalTypeToPhpType($table->getColumn($primaryKeyColumn)->getType());
337
+			$str .= "
338 338
     /**
339 339
      * Get $beanClassWithoutNameSpace specified by its ID (its primary key)
340 340
      * If the primary key does not exist, an exception is thrown.
@@ -349,8 +349,8 @@  discard block
 block discarded – undo
349 349
         return \$this->tdbmService->findObjectByPk('$tableName', ['$primaryKeyColumn' => \$id], [], \$lazyLoading);
350 350
     }
351 351
     ";
352
-        }
353
-        $str .= "
352
+		}
353
+		$str .= "
354 354
     /**
355 355
      * Deletes the $beanClassWithoutNameSpace passed in parameter.
356 356
      *
@@ -450,33 +450,33 @@  discard block
 block discarded – undo
450 450
     }
451 451
 ";
452 452
 
453
-        $str .= $findByDaoCode;
454
-        $str .= '}
453
+		$str .= $findByDaoCode;
454
+		$str .= '}
455 455
 ';
456 456
 
457
-        $possibleBaseFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\Generated\\'.$baseClassName);
458
-        if (empty($possibleBaseFileNames)) {
459
-            // @codeCoverageIgnoreStart
460
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$daonamespace.'\\Generated\\'.$baseClassName.'" is not autoloadable.');
461
-            // @codeCoverageIgnoreEnd
462
-        }
463
-        $possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0];
464
-
465
-        $this->ensureDirectoryExist($possibleBaseFileName);
466
-        file_put_contents($possibleBaseFileName, $str);
467
-        @chmod($possibleBaseFileName, 0664);
468
-
469
-        $possibleFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\'.$className);
470
-        if (empty($possibleFileNames)) {
471
-            // @codeCoverageIgnoreStart
472
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$daonamespace.'\\'.$className.'" is not autoloadable.');
473
-            // @codeCoverageIgnoreEnd
474
-        }
475
-        $possibleFileName = $this->rootPath.$possibleFileNames[0];
476
-
477
-        // Now, let's generate the "editable" class
478
-        if (!file_exists($possibleFileName)) {
479
-            $str = "<?php
457
+		$possibleBaseFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\Generated\\'.$baseClassName);
458
+		if (empty($possibleBaseFileNames)) {
459
+			// @codeCoverageIgnoreStart
460
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$daonamespace.'\\Generated\\'.$baseClassName.'" is not autoloadable.');
461
+			// @codeCoverageIgnoreEnd
462
+		}
463
+		$possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0];
464
+
465
+		$this->ensureDirectoryExist($possibleBaseFileName);
466
+		file_put_contents($possibleBaseFileName, $str);
467
+		@chmod($possibleBaseFileName, 0664);
468
+
469
+		$possibleFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\'.$className);
470
+		if (empty($possibleFileNames)) {
471
+			// @codeCoverageIgnoreStart
472
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$daonamespace.'\\'.$className.'" is not autoloadable.');
473
+			// @codeCoverageIgnoreEnd
474
+		}
475
+		$possibleFileName = $this->rootPath.$possibleFileNames[0];
476
+
477
+		// Now, let's generate the "editable" class
478
+		if (!file_exists($possibleFileName)) {
479
+			$str = "<?php
480 480
 
481 481
 /*
482 482
  * This file has been automatically generated by TDBM.
@@ -494,27 +494,27 @@  discard block
 block discarded – undo
494 494
 {
495 495
 }
496 496
 ";
497
-            $this->ensureDirectoryExist($possibleFileName);
498
-            file_put_contents($possibleFileName, $str);
499
-            @chmod($possibleFileName, 0664);
500
-        }
501
-    }
502
-
503
-    /**
504
-     * Generates the factory bean.
505
-     *
506
-     * @param Table[] $tableList
507
-     * @param ClassNameMapper $classNameMapper
508
-     * @throws TDBMException
509
-     */
510
-    private function generateFactory(array $tableList, ClassNameMapper $classNameMapper) : void
511
-    {
512
-        $daoNamespace = $this->configuration->getDaoNamespace();
513
-        $daoFactoryClassName = $this->namingStrategy->getDaoFactoryClassName();
514
-
515
-        // For each table, let's write a property.
516
-
517
-        $str = "<?php
497
+			$this->ensureDirectoryExist($possibleFileName);
498
+			file_put_contents($possibleFileName, $str);
499
+			@chmod($possibleFileName, 0664);
500
+		}
501
+	}
502
+
503
+	/**
504
+	 * Generates the factory bean.
505
+	 *
506
+	 * @param Table[] $tableList
507
+	 * @param ClassNameMapper $classNameMapper
508
+	 * @throws TDBMException
509
+	 */
510
+	private function generateFactory(array $tableList, ClassNameMapper $classNameMapper) : void
511
+	{
512
+		$daoNamespace = $this->configuration->getDaoNamespace();
513
+		$daoFactoryClassName = $this->namingStrategy->getDaoFactoryClassName();
514
+
515
+		// For each table, let's write a property.
516
+
517
+		$str = "<?php
518 518
 
519 519
 /*
520 520
  * This file has been automatically generated by TDBM.
@@ -524,13 +524,13 @@  discard block
 block discarded – undo
524 524
 namespace {$daoNamespace}\\Generated;
525 525
 
526 526
 ";
527
-        foreach ($tableList as $table) {
528
-            $tableName = $table->getName();
529
-            $daoClassName = $this->namingStrategy->getDaoClassName($tableName);
530
-            $str .= "use {$daoNamespace}\\".$daoClassName.";\n";
531
-        }
527
+		foreach ($tableList as $table) {
528
+			$tableName = $table->getName();
529
+			$daoClassName = $this->namingStrategy->getDaoClassName($tableName);
530
+			$str .= "use {$daoNamespace}\\".$daoClassName.";\n";
531
+		}
532 532
 
533
-        $str .= "
533
+		$str .= "
534 534
 /**
535 535
  * The $daoFactoryClassName provides an easy access to all DAOs generated by TDBM.
536 536
  *
@@ -539,12 +539,12 @@  discard block
 block discarded – undo
539 539
 {
540 540
 ";
541 541
 
542
-        foreach ($tableList as $table) {
543
-            $tableName = $table->getName();
544
-            $daoClassName = $this->namingStrategy->getDaoClassName($tableName);
545
-            $daoInstanceName = self::toVariableName($daoClassName);
542
+		foreach ($tableList as $table) {
543
+			$tableName = $table->getName();
544
+			$daoClassName = $this->namingStrategy->getDaoClassName($tableName);
545
+			$daoInstanceName = self::toVariableName($daoClassName);
546 546
 
547
-            $str .= '    /**
547
+			$str .= '    /**
548 548
      * @var '.$daoClassName.'
549 549
      */
550 550
     private $'.$daoInstanceName.';
@@ -568,140 +568,140 @@  discard block
 block discarded – undo
568 568
     {
569 569
         $this->'.$daoInstanceName.' = $'.$daoInstanceName.';
570 570
     }';
571
-        }
571
+		}
572 572
 
573
-        $str .= '
573
+		$str .= '
574 574
 }
575 575
 ';
576 576
 
577
-        $possibleFileNames = $classNameMapper->getPossibleFileNames($daoNamespace.'\\Generated\\'.$daoFactoryClassName);
578
-        if (empty($possibleFileNames)) {
579
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$daoNamespace.'\\'.$daoFactoryClassName.'" is not autoloadable.');
580
-        }
581
-        $possibleFileName = $this->rootPath.$possibleFileNames[0];
582
-
583
-        $this->ensureDirectoryExist($possibleFileName);
584
-        file_put_contents($possibleFileName, $str);
585
-        @chmod($possibleFileName, 0664);
586
-    }
587
-
588
-    /**
589
-     * Transforms a string to camelCase (except the first letter will be uppercase too).
590
-     * Underscores and spaces are removed and the first letter after the underscore is uppercased.
591
-     *
592
-     * @param $str string
593
-     *
594
-     * @return string
595
-     */
596
-    public static function toCamelCase($str)
597
-    {
598
-        $str = strtoupper(substr($str, 0, 1)).substr($str, 1);
599
-        while (true) {
600
-            if (strpos($str, '_') === false && strpos($str, ' ') === false) {
601
-                break;
602
-            }
603
-
604
-            $pos = strpos($str, '_');
605
-            if ($pos === false) {
606
-                $pos = strpos($str, ' ');
607
-            }
608
-            $before = substr($str, 0, $pos);
609
-            $after = substr($str, $pos + 1);
610
-            $str = $before.strtoupper(substr($after, 0, 1)).substr($after, 1);
611
-        }
612
-
613
-        return $str;
614
-    }
615
-
616
-    /**
617
-     * Tries to put string to the singular form (if it is plural).
618
-     * We assume the table names are in english.
619
-     *
620
-     * @param $str string
621
-     *
622
-     * @return string
623
-     */
624
-    public static function toSingular($str)
625
-    {
626
-        return Inflector::singularize($str);
627
-    }
628
-
629
-    /**
630
-     * Put the first letter of the string in lower case.
631
-     * Very useful to transform a class name into a variable name.
632
-     *
633
-     * @param $str string
634
-     *
635
-     * @return string
636
-     */
637
-    public static function toVariableName($str)
638
-    {
639
-        return strtolower(substr($str, 0, 1)).substr($str, 1);
640
-    }
641
-
642
-    /**
643
-     * Ensures the file passed in parameter can be written in its directory.
644
-     *
645
-     * @param string $fileName
646
-     *
647
-     * @throws TDBMException
648
-     */
649
-    private function ensureDirectoryExist($fileName)
650
-    {
651
-        $dirName = dirname($fileName);
652
-        if (!file_exists($dirName)) {
653
-            $old = umask(0);
654
-            $result = mkdir($dirName, 0775, true);
655
-            umask($old);
656
-            if ($result === false) {
657
-                throw new TDBMException("Unable to create directory: '".$dirName."'.");
658
-            }
659
-        }
660
-    }
661
-
662
-    /**
663
-     * Absolute path to composer json file.
664
-     *
665
-     * @param string $composerFile
666
-     */
667
-    public function setComposerFile($composerFile)
668
-    {
669
-        $this->rootPath = dirname($composerFile).'/';
670
-        $this->composerFile = basename($composerFile);
671
-    }
672
-
673
-    /**
674
-     * Transforms a DBAL type into a PHP type (for PHPDoc purpose).
675
-     *
676
-     * @param Type $type The DBAL type
677
-     *
678
-     * @return string The PHP type
679
-     */
680
-    public static function dbalTypeToPhpType(Type $type)
681
-    {
682
-        $map = [
683
-            Type::TARRAY => 'array',
684
-            Type::SIMPLE_ARRAY => 'array',
685
-            'json' => 'array',  // 'json' is supported from Doctrine DBAL 2.6 only.
686
-            Type::JSON_ARRAY => 'array',
687
-            Type::BIGINT => 'string',
688
-            Type::BOOLEAN => 'bool',
689
-            Type::DATETIME => '\DateTimeInterface',
690
-            Type::DATETIMETZ => '\DateTimeInterface',
691
-            Type::DATE => '\DateTimeInterface',
692
-            Type::TIME => '\DateTimeInterface',
693
-            Type::DECIMAL => 'float',
694
-            Type::INTEGER => 'int',
695
-            Type::OBJECT => 'string',
696
-            Type::SMALLINT => 'int',
697
-            Type::STRING => 'string',
698
-            Type::TEXT => 'string',
699
-            Type::BINARY => 'string',
700
-            Type::BLOB => 'string',
701
-            Type::FLOAT => 'float',
702
-            Type::GUID => 'string',
703
-        ];
704
-
705
-        return isset($map[$type->getName()]) ? $map[$type->getName()] : $type->getName();
706
-    }
577
+		$possibleFileNames = $classNameMapper->getPossibleFileNames($daoNamespace.'\\Generated\\'.$daoFactoryClassName);
578
+		if (empty($possibleFileNames)) {
579
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$daoNamespace.'\\'.$daoFactoryClassName.'" is not autoloadable.');
580
+		}
581
+		$possibleFileName = $this->rootPath.$possibleFileNames[0];
582
+
583
+		$this->ensureDirectoryExist($possibleFileName);
584
+		file_put_contents($possibleFileName, $str);
585
+		@chmod($possibleFileName, 0664);
586
+	}
587
+
588
+	/**
589
+	 * Transforms a string to camelCase (except the first letter will be uppercase too).
590
+	 * Underscores and spaces are removed and the first letter after the underscore is uppercased.
591
+	 *
592
+	 * @param $str string
593
+	 *
594
+	 * @return string
595
+	 */
596
+	public static function toCamelCase($str)
597
+	{
598
+		$str = strtoupper(substr($str, 0, 1)).substr($str, 1);
599
+		while (true) {
600
+			if (strpos($str, '_') === false && strpos($str, ' ') === false) {
601
+				break;
602
+			}
603
+
604
+			$pos = strpos($str, '_');
605
+			if ($pos === false) {
606
+				$pos = strpos($str, ' ');
607
+			}
608
+			$before = substr($str, 0, $pos);
609
+			$after = substr($str, $pos + 1);
610
+			$str = $before.strtoupper(substr($after, 0, 1)).substr($after, 1);
611
+		}
612
+
613
+		return $str;
614
+	}
615
+
616
+	/**
617
+	 * Tries to put string to the singular form (if it is plural).
618
+	 * We assume the table names are in english.
619
+	 *
620
+	 * @param $str string
621
+	 *
622
+	 * @return string
623
+	 */
624
+	public static function toSingular($str)
625
+	{
626
+		return Inflector::singularize($str);
627
+	}
628
+
629
+	/**
630
+	 * Put the first letter of the string in lower case.
631
+	 * Very useful to transform a class name into a variable name.
632
+	 *
633
+	 * @param $str string
634
+	 *
635
+	 * @return string
636
+	 */
637
+	public static function toVariableName($str)
638
+	{
639
+		return strtolower(substr($str, 0, 1)).substr($str, 1);
640
+	}
641
+
642
+	/**
643
+	 * Ensures the file passed in parameter can be written in its directory.
644
+	 *
645
+	 * @param string $fileName
646
+	 *
647
+	 * @throws TDBMException
648
+	 */
649
+	private function ensureDirectoryExist($fileName)
650
+	{
651
+		$dirName = dirname($fileName);
652
+		if (!file_exists($dirName)) {
653
+			$old = umask(0);
654
+			$result = mkdir($dirName, 0775, true);
655
+			umask($old);
656
+			if ($result === false) {
657
+				throw new TDBMException("Unable to create directory: '".$dirName."'.");
658
+			}
659
+		}
660
+	}
661
+
662
+	/**
663
+	 * Absolute path to composer json file.
664
+	 *
665
+	 * @param string $composerFile
666
+	 */
667
+	public function setComposerFile($composerFile)
668
+	{
669
+		$this->rootPath = dirname($composerFile).'/';
670
+		$this->composerFile = basename($composerFile);
671
+	}
672
+
673
+	/**
674
+	 * Transforms a DBAL type into a PHP type (for PHPDoc purpose).
675
+	 *
676
+	 * @param Type $type The DBAL type
677
+	 *
678
+	 * @return string The PHP type
679
+	 */
680
+	public static function dbalTypeToPhpType(Type $type)
681
+	{
682
+		$map = [
683
+			Type::TARRAY => 'array',
684
+			Type::SIMPLE_ARRAY => 'array',
685
+			'json' => 'array',  // 'json' is supported from Doctrine DBAL 2.6 only.
686
+			Type::JSON_ARRAY => 'array',
687
+			Type::BIGINT => 'string',
688
+			Type::BOOLEAN => 'bool',
689
+			Type::DATETIME => '\DateTimeInterface',
690
+			Type::DATETIMETZ => '\DateTimeInterface',
691
+			Type::DATE => '\DateTimeInterface',
692
+			Type::TIME => '\DateTimeInterface',
693
+			Type::DECIMAL => 'float',
694
+			Type::INTEGER => 'int',
695
+			Type::OBJECT => 'string',
696
+			Type::SMALLINT => 'int',
697
+			Type::STRING => 'string',
698
+			Type::TEXT => 'string',
699
+			Type::BINARY => 'string',
700
+			Type::BLOB => 'string',
701
+			Type::FLOAT => 'float',
702
+			Type::GUID => 'string',
703
+		];
704
+
705
+		return isset($map[$type->getName()]) ? $map[$type->getName()] : $type->getName();
706
+	}
707 707
 }
Please login to merge, or discard this patch.