Test Failed
Pull Request — 4.2 (#140)
by David
12:30
created
src/Mouf/Database/TDBM/Controllers/TdbmController.php 1 patch
Indentation   +125 added lines, -125 removed lines patch added patch discarded remove patch
@@ -18,129 +18,129 @@
 block discarded – undo
18 18
  */
19 19
 class TdbmController extends AbstractMoufInstanceController
20 20
 {
21
-    /**
22
-     * @var HtmlBlock
23
-     */
24
-    public $content;
25
-
26
-    protected $daoNamespace;
27
-    protected $beanNamespace;
28
-    protected $daoFactoryInstanceName;
29
-    protected $autoloadDetected;
30
-    ///protected $storeInUtc;
31
-    protected $useCustomComposer;
32
-    protected $composerFile;
33
-
34
-    /**
35
-     * Admin page used to display the DAO generation form.
36
-     *
37
-     * @Action
38
-     */
39
-    public function defaultAction($name, $selfedit = 'false')
40
-    {
41
-        $this->initController($name, $selfedit);
42
-
43
-        // Fill variables
44
-        $this->daoNamespace = self::getFromConfiguration($this->moufManager, $name, 'daoNamespace');
45
-        $this->beanNamespace = self::getFromConfiguration($this->moufManager, $name, 'beanNamespace');
46
-        $this->daoFactoryInstanceName = self::getFromConfiguration($this->moufManager, $name, 'daoFactoryInstanceName');
47
-        //$this->storeInUtc = self::getFromConfiguration($this->moufManager, $name, 'storeInUtc');
48
-        $this->composerFile = self::getFromConfiguration($this->moufManager, $name, 'customComposerFile');
49
-        $this->useCustomComposer = $this->composerFile ? true : false;
50
-
51
-        if ($this->daoNamespace == null && $this->beanNamespace == null) {
52
-            $classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../../../composer.json');
53
-
54
-            $autoloadNamespaces = $classNameMapper->getManagedNamespaces();
55
-            if ($autoloadNamespaces) {
56
-                $this->autoloadDetected = true;
57
-                $rootNamespace = $autoloadNamespaces[0];
58
-                $this->daoNamespace = $rootNamespace.'Dao';
59
-                $this->beanNamespace = $rootNamespace.'Dao\\Bean';
60
-            } else {
61
-                $this->autoloadDetected = false;
62
-                $this->daoNamespace = 'YourApplication\\Dao';
63
-                $this->beanNamespace = 'YourApplication\\Dao\\Bean';
64
-            }
65
-        } else {
66
-            $this->autoloadDetected = true;
67
-        }
68
-
69
-        $this->content->addFile(__DIR__.'/../../../../views/tdbmGenerate.php', $this);
70
-        $this->template->toHtml();
71
-    }
72
-
73
-    /**
74
-     * This action generates the DAOs and Beans for the TDBM service passed in parameter.
75
-     *
76
-     * @Action
77
-     *
78
-     * @param string $name
79
-     * @param bool   $selfedit
80
-     */
81
-    public function generate($name, $daonamespace, $beannamespace, $daofactoryinstancename, /*$storeInUtc = 0,*/ $selfedit = 'false', $useCustomComposer = false, $composerFile = '')
82
-    {
83
-        $this->initController($name, $selfedit);
84
-
85
-        self::generateDaos($this->moufManager, $name, $daonamespace, $beannamespace, $daofactoryinstancename, $selfedit, /*$storeInUtc,*/ $useCustomComposer, $composerFile);
86
-
87
-        // TODO: better: we should redirect to a screen that list the number of DAOs generated, etc...
88
-        header('Location: '.ROOT_URL.'ajaxinstance/?name='.urlencode($name).'&selfedit='.$selfedit);
89
-    }
90
-
91
-    /**
92
-     * This function generates the DAOs and Beans for the TDBM service passed in parameter.
93
-     *
94
-     * @param MoufManager $moufManager
95
-     * @param string      $name
96
-     * @param string      $daonamespace
97
-     * @param string      $beannamespace
98
-     * @param string      $daofactoryclassname
99
-     * @param string      $daofactoryinstancename
100
-     * @param string      $selfedit
101
-     *
102
-     * @throws \Mouf\MoufException
103
-     */
104
-    public static function generateDaos(MoufManager $moufManager, $name, $daonamespace, $beannamespace, $daofactoryinstancename, $selfedit = 'false', /*$storeInUtc = null,*/ $useCustomComposer = null, $composerFile = null)
105
-    {
106
-        self::setInConfiguration($moufManager, $name, 'daoNamespace', $daonamespace);
107
-        self::setInConfiguration($moufManager, $name, 'beanNamespace', $beannamespace);
108
-        self::setInConfiguration($moufManager, $name, 'daoFactoryInstanceName', $daofactoryinstancename);
109
-        //self::setInConfiguration($moufManager, $name, 'storeInUtc', $storeInUtc);
110
-        if ($useCustomComposer) {
111
-            self::setInConfiguration($moufManager, $name, 'customComposerFile', $composerFile);
112
-        } else {
113
-            self::setInConfiguration($moufManager, $name, 'customComposerFile', null);
114
-        }
115
-        // Let's rewrite before calling the DAO generator
116
-        $moufManager->rewriteMouf();
117
-
118
-
119
-        $tdbmService = new InstanceProxy($name);
120
-        /* @var $tdbmService TDBMService */
121
-        $tdbmService->generateAllDaosAndBeans(($useCustomComposer ? $composerFile : null));
122
-    }
123
-
124
-    private static function getConfigurationDescriptor(MoufManager $moufManager, string $tdbmInstanceName)
125
-    {
126
-        return $moufManager->getInstanceDescriptor($tdbmInstanceName)->getConstructorArgumentProperty('configuration')->getValue();
127
-    }
128
-
129
-    private static function getFromConfiguration(MoufManager $moufManager, string $tdbmInstanceName, string $property)
130
-    {
131
-        $configuration = self::getConfigurationDescriptor($moufManager, $tdbmInstanceName);
132
-        if ($configuration === null) {
133
-            throw new \RuntimeException('Unable to find the configuration object linked to TDBMService.');
134
-        }
135
-        return $configuration->getProperty($property)->getValue();
136
-    }
137
-
138
-    private static function setInConfiguration(MoufManager $moufManager, string $tdbmInstanceName, string $property, ?string $value)
139
-    {
140
-        $configuration = self::getConfigurationDescriptor($moufManager, $tdbmInstanceName);
141
-        if ($configuration === null) {
142
-            throw new \RuntimeException('Unable to find the configuration object linked to TDBMService.');
143
-        }
144
-        $configuration->getProperty($property)->setValue($value);
145
-    }
21
+	/**
22
+	 * @var HtmlBlock
23
+	 */
24
+	public $content;
25
+
26
+	protected $daoNamespace;
27
+	protected $beanNamespace;
28
+	protected $daoFactoryInstanceName;
29
+	protected $autoloadDetected;
30
+	///protected $storeInUtc;
31
+	protected $useCustomComposer;
32
+	protected $composerFile;
33
+
34
+	/**
35
+	 * Admin page used to display the DAO generation form.
36
+	 *
37
+	 * @Action
38
+	 */
39
+	public function defaultAction($name, $selfedit = 'false')
40
+	{
41
+		$this->initController($name, $selfedit);
42
+
43
+		// Fill variables
44
+		$this->daoNamespace = self::getFromConfiguration($this->moufManager, $name, 'daoNamespace');
45
+		$this->beanNamespace = self::getFromConfiguration($this->moufManager, $name, 'beanNamespace');
46
+		$this->daoFactoryInstanceName = self::getFromConfiguration($this->moufManager, $name, 'daoFactoryInstanceName');
47
+		//$this->storeInUtc = self::getFromConfiguration($this->moufManager, $name, 'storeInUtc');
48
+		$this->composerFile = self::getFromConfiguration($this->moufManager, $name, 'customComposerFile');
49
+		$this->useCustomComposer = $this->composerFile ? true : false;
50
+
51
+		if ($this->daoNamespace == null && $this->beanNamespace == null) {
52
+			$classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../../../composer.json');
53
+
54
+			$autoloadNamespaces = $classNameMapper->getManagedNamespaces();
55
+			if ($autoloadNamespaces) {
56
+				$this->autoloadDetected = true;
57
+				$rootNamespace = $autoloadNamespaces[0];
58
+				$this->daoNamespace = $rootNamespace.'Dao';
59
+				$this->beanNamespace = $rootNamespace.'Dao\\Bean';
60
+			} else {
61
+				$this->autoloadDetected = false;
62
+				$this->daoNamespace = 'YourApplication\\Dao';
63
+				$this->beanNamespace = 'YourApplication\\Dao\\Bean';
64
+			}
65
+		} else {
66
+			$this->autoloadDetected = true;
67
+		}
68
+
69
+		$this->content->addFile(__DIR__.'/../../../../views/tdbmGenerate.php', $this);
70
+		$this->template->toHtml();
71
+	}
72
+
73
+	/**
74
+	 * This action generates the DAOs and Beans for the TDBM service passed in parameter.
75
+	 *
76
+	 * @Action
77
+	 *
78
+	 * @param string $name
79
+	 * @param bool   $selfedit
80
+	 */
81
+	public function generate($name, $daonamespace, $beannamespace, $daofactoryinstancename, /*$storeInUtc = 0,*/ $selfedit = 'false', $useCustomComposer = false, $composerFile = '')
82
+	{
83
+		$this->initController($name, $selfedit);
84
+
85
+		self::generateDaos($this->moufManager, $name, $daonamespace, $beannamespace, $daofactoryinstancename, $selfedit, /*$storeInUtc,*/ $useCustomComposer, $composerFile);
86
+
87
+		// TODO: better: we should redirect to a screen that list the number of DAOs generated, etc...
88
+		header('Location: '.ROOT_URL.'ajaxinstance/?name='.urlencode($name).'&selfedit='.$selfedit);
89
+	}
90
+
91
+	/**
92
+	 * This function generates the DAOs and Beans for the TDBM service passed in parameter.
93
+	 *
94
+	 * @param MoufManager $moufManager
95
+	 * @param string      $name
96
+	 * @param string      $daonamespace
97
+	 * @param string      $beannamespace
98
+	 * @param string      $daofactoryclassname
99
+	 * @param string      $daofactoryinstancename
100
+	 * @param string      $selfedit
101
+	 *
102
+	 * @throws \Mouf\MoufException
103
+	 */
104
+	public static function generateDaos(MoufManager $moufManager, $name, $daonamespace, $beannamespace, $daofactoryinstancename, $selfedit = 'false', /*$storeInUtc = null,*/ $useCustomComposer = null, $composerFile = null)
105
+	{
106
+		self::setInConfiguration($moufManager, $name, 'daoNamespace', $daonamespace);
107
+		self::setInConfiguration($moufManager, $name, 'beanNamespace', $beannamespace);
108
+		self::setInConfiguration($moufManager, $name, 'daoFactoryInstanceName', $daofactoryinstancename);
109
+		//self::setInConfiguration($moufManager, $name, 'storeInUtc', $storeInUtc);
110
+		if ($useCustomComposer) {
111
+			self::setInConfiguration($moufManager, $name, 'customComposerFile', $composerFile);
112
+		} else {
113
+			self::setInConfiguration($moufManager, $name, 'customComposerFile', null);
114
+		}
115
+		// Let's rewrite before calling the DAO generator
116
+		$moufManager->rewriteMouf();
117
+
118
+
119
+		$tdbmService = new InstanceProxy($name);
120
+		/* @var $tdbmService TDBMService */
121
+		$tdbmService->generateAllDaosAndBeans(($useCustomComposer ? $composerFile : null));
122
+	}
123
+
124
+	private static function getConfigurationDescriptor(MoufManager $moufManager, string $tdbmInstanceName)
125
+	{
126
+		return $moufManager->getInstanceDescriptor($tdbmInstanceName)->getConstructorArgumentProperty('configuration')->getValue();
127
+	}
128
+
129
+	private static function getFromConfiguration(MoufManager $moufManager, string $tdbmInstanceName, string $property)
130
+	{
131
+		$configuration = self::getConfigurationDescriptor($moufManager, $tdbmInstanceName);
132
+		if ($configuration === null) {
133
+			throw new \RuntimeException('Unable to find the configuration object linked to TDBMService.');
134
+		}
135
+		return $configuration->getProperty($property)->getValue();
136
+	}
137
+
138
+	private static function setInConfiguration(MoufManager $moufManager, string $tdbmInstanceName, string $property, ?string $value)
139
+	{
140
+		$configuration = self::getConfigurationDescriptor($moufManager, $tdbmInstanceName);
141
+		if ($configuration === null) {
142
+			throw new \RuntimeException('Unable to find the configuration object linked to TDBMService.');
143
+		}
144
+		$configuration->getProperty($property)->setValue($value);
145
+	}
146 146
 }
Please login to merge, or discard this patch.
src/views/installStep2.php 1 patch
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -8,7 +8,7 @@
 block discarded – undo
8 8
 <input type="hidden" id="selfedit" name="selfedit" value="<?php echo plainstring_to_htmlprotected($this->selfedit) ?>" />
9 9
 
10 10
 <?php if (!$this->autoloadDetected) {
11
-    ?>
11
+	?>
12 12
 <div class="alert">Warning! TDBM could not detect the autoload section of your composer.json file.
13 13
 Unless you are developing your own autoload system, you should configure <strong>composer.json</strong> to <a href="http://getcomposer.org/doc/01-basic-usage.md#autoloading" target="_blank">define a source directory and a root namespace using PSR-0</a>.</div>
14 14
 <?php
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/MoufDiListener.php 1 patch
Indentation   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -11,58 +11,58 @@
 block discarded – undo
11 11
 class MoufDiListener implements GeneratorListenerInterface
12 12
 {
13 13
 
14
-    /**
15
-     * @param ConfigurationInterface $configuration
16
-     * @param BeanDescriptorInterface[] $beanDescriptors
17
-     */
18
-    public function onGenerate(ConfigurationInterface $configuration, array $beanDescriptors): void
19
-    {
20
-        // Let's generate the needed instance in Mouf.
21
-        $moufManager = MoufManager::getMoufManager();
14
+	/**
15
+	 * @param ConfigurationInterface $configuration
16
+	 * @param BeanDescriptorInterface[] $beanDescriptors
17
+	 */
18
+	public function onGenerate(ConfigurationInterface $configuration, array $beanDescriptors): void
19
+	{
20
+		// Let's generate the needed instance in Mouf.
21
+		$moufManager = MoufManager::getMoufManager();
22 22
 
23
-        $daoFactoryInstanceName = null;
24
-        if ($configuration instanceof MoufConfiguration) {
25
-            $daoFactoryInstanceName = $configuration->getDaoFactoryInstanceName();
26
-            $daoFactoryClassName = $configuration->getDaoNamespace().'\\Generated\\'.$configuration->getNamingStrategy()->getDaoFactoryClassName();
27
-            $moufManager->declareComponent($daoFactoryInstanceName, $daoFactoryClassName, false, MoufManager::DECLARE_ON_EXIST_KEEP_INCOMING_LINKS);
28
-        }
23
+		$daoFactoryInstanceName = null;
24
+		if ($configuration instanceof MoufConfiguration) {
25
+			$daoFactoryInstanceName = $configuration->getDaoFactoryInstanceName();
26
+			$daoFactoryClassName = $configuration->getDaoNamespace().'\\Generated\\'.$configuration->getNamingStrategy()->getDaoFactoryClassName();
27
+			$moufManager->declareComponent($daoFactoryInstanceName, $daoFactoryClassName, false, MoufManager::DECLARE_ON_EXIST_KEEP_INCOMING_LINKS);
28
+		}
29 29
 
30
-        $tdbmServiceInstanceName = $this->getTdbmInstanceName($configuration);
30
+		$tdbmServiceInstanceName = $this->getTdbmInstanceName($configuration);
31 31
 
32
-        foreach ($beanDescriptors as $beanDescriptor) {
33
-            $daoName = $beanDescriptor->getDaoClassName();
32
+		foreach ($beanDescriptors as $beanDescriptor) {
33
+			$daoName = $beanDescriptor->getDaoClassName();
34 34
 
35
-            $instanceName = TDBMDaoGenerator::toVariableName($daoName);
36
-            if (!$moufManager->instanceExists($instanceName)) {
37
-                $moufManager->declareComponent($instanceName, $configuration->getDaoNamespace().'\\'.$daoName);
38
-            }
39
-            $moufManager->setParameterViaConstructor($instanceName, 0, $tdbmServiceInstanceName, 'object');
40
-            if ($daoFactoryInstanceName !== null) {
41
-                $moufManager->bindComponentViaSetter($daoFactoryInstanceName, 'set'.$daoName, $instanceName);
42
-            }
43
-        }
35
+			$instanceName = TDBMDaoGenerator::toVariableName($daoName);
36
+			if (!$moufManager->instanceExists($instanceName)) {
37
+				$moufManager->declareComponent($instanceName, $configuration->getDaoNamespace().'\\'.$daoName);
38
+			}
39
+			$moufManager->setParameterViaConstructor($instanceName, 0, $tdbmServiceInstanceName, 'object');
40
+			if ($daoFactoryInstanceName !== null) {
41
+				$moufManager->bindComponentViaSetter($daoFactoryInstanceName, 'set'.$daoName, $instanceName);
42
+			}
43
+		}
44 44
 
45
-        $moufManager->rewriteMouf();
46
-    }
45
+		$moufManager->rewriteMouf();
46
+	}
47 47
 
48
-    private function getTdbmInstanceName(ConfigurationInterface $configuration) : string
49
-    {
50
-        $moufManager = MoufManager::getMoufManager();
48
+	private function getTdbmInstanceName(ConfigurationInterface $configuration) : string
49
+	{
50
+		$moufManager = MoufManager::getMoufManager();
51 51
 
52
-        $configurationInstanceName = $moufManager->findInstanceName($configuration);
53
-        if (!$configurationInstanceName) {
54
-            throw new \TDBMException('Could not find TDBM instance for configuration object.');
55
-        }
52
+		$configurationInstanceName = $moufManager->findInstanceName($configuration);
53
+		if (!$configurationInstanceName) {
54
+			throw new \TDBMException('Could not find TDBM instance for configuration object.');
55
+		}
56 56
 
57
-        // Let's find the configuration
58
-        $tdbmServicesNames = $moufManager->findInstances(TDBMService::class);
57
+		// Let's find the configuration
58
+		$tdbmServicesNames = $moufManager->findInstances(TDBMService::class);
59 59
 
60
-        foreach ($tdbmServicesNames as $name) {
61
-            if ($moufManager->getInstanceDescriptor($name)->getConstructorArgumentProperty('configuration')->getValue()->getName() === $configurationInstanceName) {
62
-                return $name;
63
-            }
64
-        }
60
+		foreach ($tdbmServicesNames as $name) {
61
+			if ($moufManager->getInstanceDescriptor($name)->getConstructorArgumentProperty('configuration')->getValue()->getName() === $configurationInstanceName) {
62
+				return $name;
63
+			}
64
+		}
65 65
 
66
-        throw new \TDBMException('Could not find TDBMService instance.');
67
-    }
66
+		throw new \TDBMException('Could not find TDBMService instance.');
67
+	}
68 68
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/DefaultNamingStrategy.php 1 patch
Indentation   +164 added lines, -164 removed lines patch added patch discarded remove patch
@@ -7,168 +7,168 @@
 block discarded – undo
7 7
 
8 8
 class DefaultNamingStrategy implements NamingStrategyInterface
9 9
 {
10
-    private $beanPrefix = '';
11
-    private $beanSuffix = '';
12
-    private $baseBeanPrefix = 'Abstract';
13
-    private $baseBeanSuffix = '';
14
-    private $daoPrefix = '';
15
-    private $daoSuffix = 'Dao';
16
-    private $baseDaoPrefix = 'Abstract';
17
-    private $baseDaoSuffix = 'Dao';
18
-
19
-    /**
20
-     * Sets the string prefix to any bean class name.
21
-     *
22
-     * @param string $beanPrefix
23
-     */
24
-    public function setBeanPrefix(string $beanPrefix)
25
-    {
26
-        $this->beanPrefix = $beanPrefix;
27
-    }
28
-
29
-    /**
30
-     * Sets the string suffix to any bean class name.
31
-     *
32
-     * @param string $beanSuffix
33
-     */
34
-    public function setBeanSuffix(string $beanSuffix)
35
-    {
36
-        $this->beanSuffix = $beanSuffix;
37
-    }
38
-
39
-    /**
40
-     * Sets the string prefix to any base bean class name.
41
-     *
42
-     * @param string $baseBeanPrefix
43
-     */
44
-    public function setBaseBeanPrefix(string $baseBeanPrefix)
45
-    {
46
-        $this->baseBeanPrefix = $baseBeanPrefix;
47
-    }
48
-
49
-    /**
50
-     * Sets the string suffix to any base bean class name.
51
-     *
52
-     * @param string $baseBeanSuffix
53
-     */
54
-    public function setBaseBeanSuffix(string $baseBeanSuffix)
55
-    {
56
-        $this->baseBeanSuffix = $baseBeanSuffix;
57
-    }
58
-
59
-    /**
60
-     * Sets the string prefix to any DAO class name.
61
-     *
62
-     * @param string $daoPrefix
63
-     */
64
-    public function setDaoPrefix(string $daoPrefix)
65
-    {
66
-        $this->daoPrefix = $daoPrefix;
67
-    }
68
-
69
-    /**
70
-     * Sets the string suffix to any DAO class name.
71
-     *
72
-     * @param string $daoSuffix
73
-     */
74
-    public function setDaoSuffix(string $daoSuffix)
75
-    {
76
-        $this->daoSuffix = $daoSuffix;
77
-    }
78
-
79
-    /**
80
-     * Sets the string prefix to any base DAO class name.
81
-     *
82
-     * @param string $baseDaoPrefix
83
-     */
84
-    public function setBaseDaoPrefix(string $baseDaoPrefix)
85
-    {
86
-        $this->baseDaoPrefix = $baseDaoPrefix;
87
-    }
88
-
89
-    /**
90
-     * Sets the string suffix to any base DAO class name.
91
-     *
92
-     * @param string $baseDaoSuffix
93
-     */
94
-    public function setBaseDaoSuffix(string $baseDaoSuffix)
95
-    {
96
-        $this->baseDaoSuffix = $baseDaoSuffix;
97
-    }
98
-
99
-
100
-    /**
101
-     * Returns the bean class name from the table name (excluding the namespace).
102
-     *
103
-     * @param string $tableName
104
-     * @return string
105
-     */
106
-    public function getBeanClassName(string $tableName): string
107
-    {
108
-        return $this->beanPrefix.self::toSingularCamelCase($tableName).$this->beanSuffix;
109
-    }
110
-
111
-    /**
112
-     * Returns the base bean class name from the table name (excluding the namespace).
113
-     *
114
-     * @param string $tableName
115
-     * @return string
116
-     */
117
-    public function getBaseBeanClassName(string $tableName): string
118
-    {
119
-        return $this->baseBeanPrefix.self::toSingularCamelCase($tableName).$this->baseBeanSuffix;
120
-    }
121
-
122
-    /**
123
-     * Returns the name of the DAO class from the table name (excluding the namespace).
124
-     *
125
-     * @param string $tableName
126
-     * @return string
127
-     */
128
-    public function getDaoClassName(string $tableName): string
129
-    {
130
-        return $this->daoPrefix.self::toSingularCamelCase($tableName).$this->daoSuffix;
131
-    }
132
-
133
-    /**
134
-     * Returns the name of the base DAO class from the table name (excluding the namespace).
135
-     *
136
-     * @param string $tableName
137
-     * @return string
138
-     */
139
-    public function getBaseDaoClassName(string $tableName): string
140
-    {
141
-        return $this->baseDaoPrefix.self::toSingularCamelCase($tableName).$this->baseDaoSuffix;
142
-    }
143
-
144
-    /**
145
-     * Tries to put string to the singular form (if it is plural) and camel case form.
146
-     * We assume the table names are in english.
147
-     *
148
-     * @param $str string
149
-     *
150
-     * @return string
151
-     */
152
-    private static function toSingularCamelCase(string $str): string
153
-    {
154
-        $tokens = preg_split("/[_ ]+/", $str);
155
-        $tokens = array_map([Inflector::class, 'singularize'], $tokens);
156
-
157
-        $str = '';
158
-        foreach ($tokens as $token) {
159
-            $str .= ucfirst(Inflector::singularize($token));
160
-        }
161
-
162
-        return $str;
163
-    }
164
-
165
-    /**
166
-     * Returns the class name for the DAO factory.
167
-     *
168
-     * @return string
169
-     */
170
-    public function getDaoFactoryClassName(): string
171
-    {
172
-        return 'DaoFactory';
173
-    }
10
+	private $beanPrefix = '';
11
+	private $beanSuffix = '';
12
+	private $baseBeanPrefix = 'Abstract';
13
+	private $baseBeanSuffix = '';
14
+	private $daoPrefix = '';
15
+	private $daoSuffix = 'Dao';
16
+	private $baseDaoPrefix = 'Abstract';
17
+	private $baseDaoSuffix = 'Dao';
18
+
19
+	/**
20
+	 * Sets the string prefix to any bean class name.
21
+	 *
22
+	 * @param string $beanPrefix
23
+	 */
24
+	public function setBeanPrefix(string $beanPrefix)
25
+	{
26
+		$this->beanPrefix = $beanPrefix;
27
+	}
28
+
29
+	/**
30
+	 * Sets the string suffix to any bean class name.
31
+	 *
32
+	 * @param string $beanSuffix
33
+	 */
34
+	public function setBeanSuffix(string $beanSuffix)
35
+	{
36
+		$this->beanSuffix = $beanSuffix;
37
+	}
38
+
39
+	/**
40
+	 * Sets the string prefix to any base bean class name.
41
+	 *
42
+	 * @param string $baseBeanPrefix
43
+	 */
44
+	public function setBaseBeanPrefix(string $baseBeanPrefix)
45
+	{
46
+		$this->baseBeanPrefix = $baseBeanPrefix;
47
+	}
48
+
49
+	/**
50
+	 * Sets the string suffix to any base bean class name.
51
+	 *
52
+	 * @param string $baseBeanSuffix
53
+	 */
54
+	public function setBaseBeanSuffix(string $baseBeanSuffix)
55
+	{
56
+		$this->baseBeanSuffix = $baseBeanSuffix;
57
+	}
58
+
59
+	/**
60
+	 * Sets the string prefix to any DAO class name.
61
+	 *
62
+	 * @param string $daoPrefix
63
+	 */
64
+	public function setDaoPrefix(string $daoPrefix)
65
+	{
66
+		$this->daoPrefix = $daoPrefix;
67
+	}
68
+
69
+	/**
70
+	 * Sets the string suffix to any DAO class name.
71
+	 *
72
+	 * @param string $daoSuffix
73
+	 */
74
+	public function setDaoSuffix(string $daoSuffix)
75
+	{
76
+		$this->daoSuffix = $daoSuffix;
77
+	}
78
+
79
+	/**
80
+	 * Sets the string prefix to any base DAO class name.
81
+	 *
82
+	 * @param string $baseDaoPrefix
83
+	 */
84
+	public function setBaseDaoPrefix(string $baseDaoPrefix)
85
+	{
86
+		$this->baseDaoPrefix = $baseDaoPrefix;
87
+	}
88
+
89
+	/**
90
+	 * Sets the string suffix to any base DAO class name.
91
+	 *
92
+	 * @param string $baseDaoSuffix
93
+	 */
94
+	public function setBaseDaoSuffix(string $baseDaoSuffix)
95
+	{
96
+		$this->baseDaoSuffix = $baseDaoSuffix;
97
+	}
98
+
99
+
100
+	/**
101
+	 * Returns the bean class name from the table name (excluding the namespace).
102
+	 *
103
+	 * @param string $tableName
104
+	 * @return string
105
+	 */
106
+	public function getBeanClassName(string $tableName): string
107
+	{
108
+		return $this->beanPrefix.self::toSingularCamelCase($tableName).$this->beanSuffix;
109
+	}
110
+
111
+	/**
112
+	 * Returns the base bean class name from the table name (excluding the namespace).
113
+	 *
114
+	 * @param string $tableName
115
+	 * @return string
116
+	 */
117
+	public function getBaseBeanClassName(string $tableName): string
118
+	{
119
+		return $this->baseBeanPrefix.self::toSingularCamelCase($tableName).$this->baseBeanSuffix;
120
+	}
121
+
122
+	/**
123
+	 * Returns the name of the DAO class from the table name (excluding the namespace).
124
+	 *
125
+	 * @param string $tableName
126
+	 * @return string
127
+	 */
128
+	public function getDaoClassName(string $tableName): string
129
+	{
130
+		return $this->daoPrefix.self::toSingularCamelCase($tableName).$this->daoSuffix;
131
+	}
132
+
133
+	/**
134
+	 * Returns the name of the base DAO class from the table name (excluding the namespace).
135
+	 *
136
+	 * @param string $tableName
137
+	 * @return string
138
+	 */
139
+	public function getBaseDaoClassName(string $tableName): string
140
+	{
141
+		return $this->baseDaoPrefix.self::toSingularCamelCase($tableName).$this->baseDaoSuffix;
142
+	}
143
+
144
+	/**
145
+	 * Tries to put string to the singular form (if it is plural) and camel case form.
146
+	 * We assume the table names are in english.
147
+	 *
148
+	 * @param $str string
149
+	 *
150
+	 * @return string
151
+	 */
152
+	private static function toSingularCamelCase(string $str): string
153
+	{
154
+		$tokens = preg_split("/[_ ]+/", $str);
155
+		$tokens = array_map([Inflector::class, 'singularize'], $tokens);
156
+
157
+		$str = '';
158
+		foreach ($tokens as $token) {
159
+			$str .= ucfirst(Inflector::singularize($token));
160
+		}
161
+
162
+		return $str;
163
+	}
164
+
165
+	/**
166
+	 * Returns the class name for the DAO factory.
167
+	 *
168
+	 * @return string
169
+	 */
170
+	public function getDaoFactoryClassName(): string
171
+	{
172
+		return 'DaoFactory';
173
+	}
174 174
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Commands/GenerateCommand.php 1 patch
Indentation   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -8,29 +8,29 @@
 block discarded – undo
8 8
 class GenerateCommand extends Command
9 9
 {
10 10
 
11
-    /**
12
-     * @var TDBMService
13
-     */
14
-    private $tdbmService;
15
-
16
-    public function __construct(TDBMService $tdbmService)
17
-    {
18
-        $this->tdbmService = $tdbmService;
19
-    }
20
-
21
-    protected function configure()
22
-    {
23
-        $this->setName('tdbm:generate')
24
-            ->setDescription('Generates DAOs and beans.')
25
-            ->setHelp('Use this command to generate or regenerate the DAOs and beans for your project.')
26
-        ;
27
-    }
28
-
29
-    protected function execute(InputInterface $input, OutputInterface $output)
30
-    {
31
-        // TODO: wrap MultiLogger in configuration.
32
-        // TODO: externalize composer.json file for autoloading (no more parameters for generateAllDaosAndBeans)
33
-
34
-        $this->tdbmService->generateAllDaosAndBeans();
35
-    }
11
+	/**
12
+	 * @var TDBMService
13
+	 */
14
+	private $tdbmService;
15
+
16
+	public function __construct(TDBMService $tdbmService)
17
+	{
18
+		$this->tdbmService = $tdbmService;
19
+	}
20
+
21
+	protected function configure()
22
+	{
23
+		$this->setName('tdbm:generate')
24
+			->setDescription('Generates DAOs and beans.')
25
+			->setHelp('Use this command to generate or regenerate the DAOs and beans for your project.')
26
+		;
27
+	}
28
+
29
+	protected function execute(InputInterface $input, OutputInterface $output)
30
+	{
31
+		// TODO: wrap MultiLogger in configuration.
32
+		// TODO: externalize composer.json file for autoloading (no more parameters for generateAllDaosAndBeans)
33
+
34
+		$this->tdbmService->generateAllDaosAndBeans();
35
+	}
36 36
 }
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 = 'composer.json';
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 = 'composer.json';
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.