diff --git a/Makefile b/Makefile
deleted file mode 100644
index fe473d61..00000000
--- a/Makefile
+++ /dev/null
@@ -1,10 +0,0 @@
-clean:
- rm -rf tests/Fixtures/*/build
- rm -f tests/Fixtures/fixtures_built
-
-tests: clean
- phpunit
-
-tests-debug: clean
- phpunit --stop-on-failure
-
diff --git a/circle.yml b/circle.yml
deleted file mode 100644
index 6e8c8e7f..00000000
--- a/circle.yml
+++ /dev/null
@@ -1,23 +0,0 @@
-machine:
- environment:
- DB_USER: ubuntu
- DB_NAME: circle_test
- php:
- version: 5.5.9
-dependencies:
- pre:
- - sed -i 's/^;//' ~/.phpenv/versions/$(phpenv global)/etc/conf.d/xdebug.ini
- - echo "memory_limit=520M" > ~/.phpenv/versions/$(phpenv global)/etc/conf.d/memlimit.ini
- - if [ "$CIRCLE_NODE_INDEX" = "1" ]; then ./tests/bin/setup.mysql.sh; fi
- - if [ "$CIRCLE_NODE_INDEX" = "2" ]; then ./tests/bin/setup.pgsql.sh; fi
-
-notify:
- webhooks:
- # A list of hook hashes, containing the url field
- - url: http://propel.jarves.io/build.php
- - url: https://webhooks.gitter.im/e/206efe76e183f9ade489
-
-test:
- override:
- - ./tests/bin/circleci.sh:
- parallel: true
\ No newline at end of file
diff --git a/composer.json b/composer.json
index 7264a044..ad2e118d 100644
--- a/composer.json
+++ b/composer.json
@@ -16,33 +16,30 @@
}
],
"require": {
- "php": ">=7.2",
+ "php": ">=7.4",
"ext-pdo": "*",
"ext-sqlite3": "*",
- "symfony/yaml": "^3.0|^4.0",
- "symfony/console": "^3.0|^4.0",
- "symfony/finder": "^3.0|^4.0",
- "symfony/filesystem": "^3.0|^4.0",
- "symfony/event-dispatcher": "^3.0|^4.0",
- "symfony/config": "^3.0|^4.0",
+ "symfony/yaml": "^5.0",
+ "symfony/console": "^5.0",
+ "symfony/finder": "^5.0",
+ "symfony/filesystem": "^5.0",
+ "symfony/event-dispatcher": "^5.0",
+ "symfony/config": "^5.0",
"psr/log": "^1.0",
- "gossi/php-code-generator": "0.5",
- "mustache/mustache": "^2.6",
- "marcj/topsort": "1.1.0",
- "bramus/monolog-colored-line-formatter": "^2.0",
- "phootwork/lang": "^0.9.0",
- "phootwork/file": "^0.2.0",
- "phootwork/collection": "^1.6",
- "phootwork/json": "^1.2"
+ "marcj/topsort": "^1.1",
+ "phootwork/lang": "^2.0",
+ "phootwork/collection": "^2.0",
+ "phootwork/json": "^2.0",
+ "phootwork/file": "^2.0",
+ "susina/psr2-code-generator": "^3.0",
+ "monolog/monolog": "^2.0",
+ "bramus/monolog-colored-line-formatter": "^3.0"
},
"require-dev" : {
- "monolog/monolog" : "~1.3",
- "phpunit/phpunit" : "^6.0|^7.0",
- "behat/behat" : "^3.3",
- "mikey179/vfsstream": "^1.6"
- },
- "suggest" : {
- "monolog/monolog" : "The recommended logging library to use with Propel."
+ "mikey179/vfsstream": "^1.6",
+ "behat/behat": "^3.6",
+ "phpunit/phpunit": "^9.1",
+ "susina/coding-standard": "^1.2"
},
"autoload" : {
"psr-4" : {
diff --git a/pom.xml.dist b/pom.xml.dist
deleted file mode 100644
index 35b152f4..00000000
--- a/pom.xml.dist
+++ /dev/null
@@ -1,54 +0,0 @@
-
- 4.0.0
- com.propelorm.propel2
- Propel2
- The Propel2 PHP ORM
- 2.0.0-DEV
- pom
-
-
- src
- tests
-
-
-
-
-
-
- php
-
-
-
-
-
-
- true
-
- true
-
- true
- false
-
- true
-
- false
- true
-
-
- true
- tests
-
-
-
\ No newline at end of file
diff --git a/src/Common/Collection/ArrayList.php b/src/Common/Collection/ArrayList.php
deleted file mode 100644
index ccd3961c..00000000
--- a/src/Common/Collection/ArrayList.php
+++ /dev/null
@@ -1,24 +0,0 @@
-checkClass($element);
- parent::add($element, $index);
- }
-}
diff --git a/src/Common/Collection/CollectionTrait.php b/src/Common/Collection/CollectionTrait.php
deleted file mode 100644
index 447f52f0..00000000
--- a/src/Common/Collection/CollectionTrait.php
+++ /dev/null
@@ -1,82 +0,0 @@
-class = $className;
- foreach ($collection as $object) {
- $this->checkClass($object);
- }
- }
-
- parent::__construct($collection);
- }
-
- /**
- * If it's an object collection, clone this objects, too.
- */
- public function __clone()
- {
- $clonedCollection = [];
- foreach ($this->collection as $key => $element) {
- if (is_object($element)) {
- $clonedCollection[$key] = clone $element;
- continue;
- }
- $clonedCollection[$key] = $element;
- }
- $this->collection = $clonedCollection;
- }
-
- public function hasClass(): bool
- {
- return (null !== $this->class);
- }
-
- public function checkClass($object)
- {
- if ($this->hasClass()) {
- if (!($object instanceof $this->class)) {
- throw new CollectionException("The given objects should be an instance of {$this->class}");
- }
- }
- }
-}
diff --git a/src/Common/Collection/Exception/CollectionException.php b/src/Common/Collection/Exception/CollectionException.php
deleted file mode 100644
index 90501e9c..00000000
--- a/src/Common/Collection/Exception/CollectionException.php
+++ /dev/null
@@ -1,16 +0,0 @@
-checkClass($element);
- parent::set($key, $element);
- }
-
- public function get($key, $default = null)
- {
- if (null !== $default) {
- $this->checkClass($default);
- }
-
- return parent::get($key, $default);
- }
-}
diff --git a/src/Common/Collection/Set.php b/src/Common/Collection/Set.php
deleted file mode 100644
index 3add99fd..00000000
--- a/src/Common/Collection/Set.php
+++ /dev/null
@@ -1,24 +0,0 @@
-checkClass($element);
- parent::add($element);
- }
-}
diff --git a/src/Common/Collection/UniqueList.php b/src/Common/Collection/UniqueList.php
deleted file mode 100644
index 107e3203..00000000
--- a/src/Common/Collection/UniqueList.php
+++ /dev/null
@@ -1,41 +0,0 @@
-checkClass($element);
-
- if (!in_array($element, $this->collection, true)) {
- if ($index === null) {
- $this->collection[$this->size()] = $element;
- } else {
- array_splice($this->collection, $index, 0, $element);
- }
- }
-
- return $this;
- }
-}
diff --git a/src/Common/Config/ConfigurationManager.php b/src/Common/Config/ConfigurationManager.php
index 4bcaa97e..c4c527ce 100644
--- a/src/Common/Config/ConfigurationManager.php
+++ b/src/Common/Config/ConfigurationManager.php
@@ -1,5 +1,4 @@
process();
}
- /**
- * Return the whole configuration array
- *
- * @return array
- */
- public function get(): array
- {
- return $this->config;
- }
-
- /**
- * Return a specific section of the configuration array.
- * It ca be useful to get, in example, only 'buildtime' values.
- *
- * @param string $section the section to be returned
- * @return array
- */
- public function getSection(string $section): array
- {
- if (!array_key_exists($section, $this->config)) {
- return null;
- }
-
- return $this->config[$section];
- }
-
/**
* Return a specific configuration property.
* The name of the requested property must be given as a string, representing its hierarchy in the configuration
@@ -82,15 +57,20 @@ public function getSection(string $section): array
* $config['database']['adapter']['mysql']['tableType']
* is expressed by:
* 'database.adapter.mysql.tableType'
+ * If nothing has passed, return the whole configuration array.
*
* @param string $name The name of property, expressed as a dot separated level hierarchy
- * @throws \Propel\Common\Config\Exception\InvalidArgumentException
- * @return mixed The configuration property
+ * @throws InvalidArgumentException
+ * @return mixed The configuration property or null if the property does not exist
*/
- public function getConfigProperty(string $name)
+ public function get(string $name = '')
{
+ if ('' === $name) {
+ return $this->config;
+ }
+
$keys = explode('.', $name);
- $output = $this->get();
+ $output = $this->config;
foreach ($keys as $key) {
if (!array_key_exists($key, $output)) {
return null;
@@ -108,7 +88,7 @@ public function getConfigProperty(string $name)
* @param string $section `runtime` or `generator` section
* @return array|null
*/
- public function getConnectionParametersArray(string $section = 'runtime'):? array
+ public function getConnectionParametersArray(string $section = 'runtime'): ?array
{
if (!in_array($section, ['runtime', 'generator'])) {
return null;
@@ -130,10 +110,12 @@ public function getConnectionParametersArray(string $section = 'runtime'):? arra
* Only one configuration file is supposed to be found.
* This method also looks for a '.dist' configuration file and loads it.
*
- * @param string $fileName Configuration file name or directory in which resides the configuration file.
- * @param array $extraConf Array of configuration properties, to be merged with those loaded from file.
+ * @param string $fileName Configuration file name or directory in which resides the configuration file.
+ * @param array $extraConf Array of configuration properties, to be merged with those loaded from file.
+ *
+ * @throws \Exception if something went wrong
*/
- protected function load(string $fileName = '', array $extraConf): void
+ protected function load(string $fileName = '', array $extraConf = []): void
{
$currentDir = getcwd();
@@ -146,10 +128,6 @@ protected function load(string $fileName = '', array $extraConf): void
$fileName = 'propel';
}
- if (null === $extraConf) {
- $extraConf = [];
- }
-
if ('propel' === $fileName) {
$dirs[] = $currentDir;
if (is_dir($currentDir . '/conf')) {
diff --git a/src/Common/Config/Exception/ExceptionInterface.php b/src/Common/Config/Exception/ExceptionInterface.php
index 9ec2759d..ab51898d 100644
--- a/src/Common/Config/Exception/ExceptionInterface.php
+++ b/src/Common/Config/Exception/ExceptionInterface.php
@@ -1,5 +1,4 @@
getValue($property_key, null, $found);
+ $ret = $this->getValue($property_key, $found);
if (false === $found) {
throw new InvalidArgumentException("Parameter '$property_key' not found in configuration file.");
@@ -230,9 +225,9 @@ private function get($property_key)
* @param boolean $found if the key was found
* @return mixed The value or null if not found
*/
- private function getValue($property_key, $config = null, &$found)
+ private function getValue(string $property_key, bool &$found, array $config = [])
{
- if (null === $config) {
+ if ([] === $config) {
$config = $this->config;
}
@@ -243,7 +238,7 @@ private function getValue($property_key, $config = null, &$found)
return $value;
}
if (is_array($value)) {
- $ret = $this->getValue($property_key, $value, $found);
+ $ret = $this->getValue($property_key, $found, $value);
if (null !== $ret) {
return $ret;
@@ -260,7 +255,7 @@ private function getValue($property_key, $config = null, &$found)
* @param string $value The value to parse
*
* @return string|null
- * @throws \Propel\Common\Config\Exception\InvalidArgumentException if the environment variable is not set
+ * @throws InvalidArgumentException if the environment variable is not set
*/
private function parseEnvironmentParams(string $value): ?string
{
diff --git a/src/Common/Config/Loader/IniFileLoader.php b/src/Common/Config/Loader/IniFileLoader.php
index 52f890dd..4fcd9370 100644
--- a/src/Common/Config/Loader/IniFileLoader.php
+++ b/src/Common/Config/Loader/IniFileLoader.php
@@ -1,5 +1,4 @@
endsWith('.ini') || $resource->endsWith('.properties') || $resource->endsWith('.ini.dist') ||
+ $resource->endsWith('.properties.dist')
+ );
}
/**
* Loads a resource, merge it with the default configuration array and resolve its parameters.
*
- * @param mixed $file The resource
- * @param string $type The resource type
+ * @param mixed $file The resource
+ * @param string $type The resource type
+ *
* @return array The configuration array
*
- * @throws \InvalidArgumentException If configuration file not found
- * @throws \Propel\Common\Config\Exception\InvalidArgumentException When ini file is not valid
- * @throws \Propel\Common\Config\Exception\InputOutputException If configuration file is not readable
+ * @throws \InvalidArgumentException If configuration file not found
+ * @throws InvalidArgumentException When ini file is not valid
+ * @throws FileException If configuration file is not readable
*/
- public function load($file, $type = null): array
+ public function load($file, string $type = null): array
{
- $path = $this->locator->locate($file);
-
- if (!is_readable($path)) {
- throw new InputOutputException("You don't have permissions to access configuration file $file.");
- }
+ $file = new File($this->locator->locate($file));
- $ini = parse_ini_file($path, true);
+ $ini = parse_ini_string($file->read()->toString(), true);
if (false === $ini) {
throw new InvalidArgumentException("The configuration file '$file' has invalid content.");
}
$ini = $this->parse($ini); //Parse for nested sections
- $ini = $this->resolveParams($ini); //Resolve parameter placeholders (%name%)
- return $ini;
+ return $this->resolveParams($ini);
}
/**
@@ -153,7 +147,7 @@ private function parseSection(array $section): array
* @param string $value
* @param array $config
*
- * @throws \Propel\Common\Config\Exception\IniParseException
+ * @throws IniParseException
*/
private function parseKey(string $key, $value, array &$config)
{
diff --git a/src/Common/Config/Loader/JsonFileLoader.php b/src/Common/Config/Loader/JsonFileLoader.php
index b5ea47ae..01f6821c 100644
--- a/src/Common/Config/Loader/JsonFileLoader.php
+++ b/src/Common/Config/Loader/JsonFileLoader.php
@@ -1,5 +1,4 @@
locator->locate($file);
-
- if (!is_readable($path)) {
- throw new InputOutputException("You don't have permissions to access configuration file $file.");
- }
-
- $json = file_get_contents($path);
-
- if (false === $json) {
- throw new InvalidArgumentException('Error while reading configuration file');
- }
+ $file = new File($this->locator->locate($file));
+ $json = $file->read();
if ('' === $json) {
return [];
}
- $content = $this->resolveParams(Json::decode($json)); //Resolve parameter placeholders (%name%)
-
- return $content;
+ return $json->isEmpty() ? [] : $this->resolveParams(Json::decode((string) $json));
}
/**
@@ -64,15 +54,10 @@ public function load($file, $type = null): array
*
* @return Boolean true if this class supports the given resource, false otherwise
*/
- public function supports($resource, $type = null): bool
+ public function supports($resource, ?string $type = null): bool
{
- $info = pathinfo($resource);
- $extension = $info['extension'];
-
- if ('dist' === $extension) {
- $extension = pathinfo($info['filename'], PATHINFO_EXTENSION);
- }
+ $resource = new Text($resource);
- return is_string($resource) && ('json' === $extension);
+ return $resource->endsWith('.json') || $resource->endsWith('json.dist');
}
}
diff --git a/src/Common/Config/Loader/LoaderResolver.php b/src/Common/Config/Loader/LoaderResolver.php
index e4cb7582..066b89d7 100644
--- a/src/Common/Config/Loader/LoaderResolver.php
+++ b/src/Common/Config/Loader/LoaderResolver.php
@@ -1,5 +1,4 @@
locator->locate($file);
@@ -58,9 +58,7 @@ public function load($file, $type = null)
throw new InvalidArgumentException("The configuration file '$file' has invalid content.");
}
- $content = $this->resolveParams($content); //Resolve parameter placeholders (%name%)
-
- return $content;
+ return $this->resolveParams($content);
}
/**
@@ -72,15 +70,11 @@ public function load($file, $type = null)
*
* @return Boolean true if this class supports the given resource, false otherwise
*/
- public function supports($resource, $type = null): bool
+ public function supports($resource, ?string $type = null): bool
{
- $info = pathinfo($resource);
- $extension = $info['extension'];
-
- if ('dist' === $extension) {
- $extension = pathinfo($info['filename'], PATHINFO_EXTENSION);
- }
+ $resource = new Text($resource);
- return is_string($resource) && ('php' === $extension || 'inc' === $extension);
+ return $resource->endsWith('.php') || $resource->endsWith('.php.dist') || $resource->endsWith('.inc') ||
+ $resource->endsWith('.inc.dist');
}
}
diff --git a/src/Common/Config/Loader/XmlFileLoader.php b/src/Common/Config/Loader/XmlFileLoader.php
index 8cdedbb9..a7d7b7ea 100644
--- a/src/Common/Config/Loader/XmlFileLoader.php
+++ b/src/Common/Config/Loader/XmlFileLoader.php
@@ -1,5 +1,4 @@
locator->locate($file);
-
- if (!is_readable($path)) {
- throw new InputOutputException("You don't have permissions to access configuration file $file.");
- }
+ $file = new File($this->locator->locate($file));
+ $content = XmlToArrayConverter::convert($file->read());
- $content = XmlToArrayConverter::convert($path);
- $content = $this->resolveParams($content); //Resolve parameter placeholders (%name%)
-
- return $content;
+ return $this->resolveParams($content);
}
/**
@@ -54,15 +52,10 @@ public function load($file, $type = null): array
*
* @return Boolean true if this class supports the given resource, false otherwise
*/
- public function supports($resource, $type = null): bool
+ public function supports($resource, ?string $type = null): bool
{
- $info = pathinfo($resource);
- $extension = $info['extension'];
-
- if ('dist' === $extension) {
- $extension = pathinfo($info['filename'], PATHINFO_EXTENSION);
- }
+ $resource = new Text($resource);
- return is_string($resource) && ('xml' === $extension);
+ return $resource->endsWith('.xml') || $resource->endsWith('.xml.dist');
}
}
diff --git a/src/Common/Config/Loader/YamlFileLoader.php b/src/Common/Config/Loader/YamlFileLoader.php
index dad048d1..53777625 100644
--- a/src/Common/Config/Loader/YamlFileLoader.php
+++ b/src/Common/Config/Loader/YamlFileLoader.php
@@ -1,5 +1,4 @@
locator->locate($file);
-
- if (!is_readable($path)) {
- throw new InputOutputException("You don't have permissions to access configuration file $file.");
- }
-
- $content = Yaml::parse(file_get_contents($path));
+ $file = new File($this->locator->locate($file));
+ $content = Yaml::parse($file->read()->toString());
//config file is empty
- if (null === $content) {
- $content = [];
- }
+ $content = $content ?? [];
//Invalid yaml content (e.g. text only) return a string
if (!is_array($content)) {
throw new ParseException('The content is not valid yaml.');
}
- $content = $this->resolveParams($content); //Resolve parameter placeholders (%name%)
-
- return $content;
+ return $this->resolveParams($content);
}
/**
@@ -66,15 +61,12 @@ public function load($file, $type = null)
*
* @return Boolean true if this class supports the given resource, false otherwise
*/
- public function supports($resource, $type = null): bool
+ public function supports($resource, ?string $type = null): bool
{
- $info = pathinfo($resource);
- $extension = $info['extension'];
-
- if ('dist' === $extension) {
- $extension = pathinfo($info['filename'], PATHINFO_EXTENSION);
- }
+ $resource = new Text($resource);
- return is_string($resource) && ('yml' === $extension || 'yaml' === $extension);
+ return $resource->endsWith('.yml') || $resource->endsWith('.yml.dist') || $resource->endsWith('.yaml') ||
+ $resource->endsWith('.yaml.dist')
+ ;
}
}
diff --git a/src/Common/Config/PropelConfiguration.php b/src/Common/Config/PropelConfiguration.php
index fabf70e1..4924b1d9 100644
--- a/src/Common/Config/PropelConfiguration.php
+++ b/src/Common/Config/PropelConfiguration.php
@@ -1,5 +1,4 @@
root('propel');
+ $treeBuilder = new TreeBuilder('propel');
+ $rootNode = $treeBuilder->getRootNode();
- $this->addGeneralSection($rootNode);
- $this->addPathsSection($rootNode);
- $this->addDatabaseSection($rootNode);
- $this->addMigrationsSection($rootNode);
- $this->addReverseSection($rootNode);
- $this->addRuntimeSection($rootNode);
- $this->addGeneratorSection($rootNode);
- $this->addFieldTypesSection($rootNode);
+ $rootNode
+ ->append($this->addGeneralSection())
+ ->append($this->addPathsSection())
+ ->append($this->addDatabaseSection())
+ ->append($this->addMigrationsSection())
+ ->append($this->addReverseSection())
+ ->append($this->addRuntimeSection())
+ ->append($this->addGeneratorSection())
+ ->append($this->addFieldTypesSection())
+ ;
return $treeBuilder;
}
- protected function addFieldTypesSection(ArrayNodeDefinition $node)
+ protected function addFieldTypesSection(): NodeDefinition
{
- $node
+ $treeBuilder = new TreeBuilder('types');
+
+ return $treeBuilder->getRootNode()
+ ->addDefaultsIfNotSet()
->children()
- ->arrayNode('types')
- ->addDefaultsIfNotSet()
-// ->useAttributeAsKey('name')
-// ->prototype('scalar')
-// ->beforeNormalization()
-// ->always(function ($v) {
-// var_dump($v);
-// exit;
-// })
-// ->end()
-// ->end()
- ->children()
- ->scalarNode('varchar')->defaultValue(VarcharType::class)->end()
- ->scalarNode('char')->defaultValue(VarcharType::class)->end()
- ->scalarNode('longvarchar')->defaultValue(VarcharType::class)->end()
- ->scalarNode('boolean')->defaultValue(BooleanType::class)->end()
+ ->scalarNode('varchar')->defaultValue(VarcharType::class)->end()
+ ->scalarNode('char')->defaultValue(VarcharType::class)->end()
+ ->scalarNode('longvarchar')->defaultValue(VarcharType::class)->end()
+ ->scalarNode('boolean')->defaultValue(BooleanType::class)->end()
- ->scalarNode('integer')->defaultValue(IntegerType::class)->end()
- ->scalarNode('bigint')->defaultValue(IntegerType::class)->end()
- ->scalarNode('decimal')->defaultValue(IntegerType::class)->end()
- ->scalarNode('tinyint')->defaultValue(IntegerType::class)->end()
+ ->scalarNode('integer')->defaultValue(IntegerType::class)->end()
+ ->scalarNode('bigint')->defaultValue(IntegerType::class)->end()
+ ->scalarNode('decimal')->defaultValue(IntegerType::class)->end()
+ ->scalarNode('tinyint')->defaultValue(IntegerType::class)->end()
- ->scalarNode('double')->defaultValue(DoubleType::class)->end()
- ->scalarNode('float')->defaultValue(DoubleType::class)->end()
+ ->scalarNode('double')->defaultValue(DoubleType::class)->end()
+ ->scalarNode('float')->defaultValue(DoubleType::class)->end()
- ->scalarNode('datetime')->defaultValue(DateTimeType::class)->end()
- ->scalarNode('date')->defaultValue(DateTimeType::class)->end()
- ->scalarNode('time')->defaultValue(DateTimeType::class)->end()
- ->scalarNode('timestamp')->defaultValue(DateTimeType::class)->end()
+ ->scalarNode('datetime')->defaultValue(DateTimeType::class)->end()
+ ->scalarNode('date')->defaultValue(DateTimeType::class)->end()
+ ->scalarNode('time')->defaultValue(DateTimeType::class)->end()
+ ->scalarNode('timestamp')->defaultValue(DateTimeType::class)->end()
- ->scalarNode('lob')->defaultValue(LobType::class)->end()
- ->scalarNode('clob')->defaultValue(LobType::class)->end()
- ->scalarNode('blob')->defaultValue(LobType::class)->end()
+ ->scalarNode('lob')->defaultValue(LobType::class)->end()
+ ->scalarNode('clob')->defaultValue(LobType::class)->end()
+ ->scalarNode('blob')->defaultValue(LobType::class)->end()
- ->scalarNode('object')->defaultValue(ObjectType::class)->end()
- ->scalarNode('array')->defaultValue(ArrayType::class)->end()
- ->scalarNode('enum')->defaultValue(EnumType::class)->end()
- ->end()
- ->end()
+ ->scalarNode('object')->defaultValue(ObjectType::class)->end()
+ ->scalarNode('array')->defaultValue(ArrayType::class)->end()
+ ->scalarNode('enum')->defaultValue(EnumType::class)->end()
->end()
;
}
- protected function addGeneralSection(ArrayNodeDefinition $node)
+ protected function addGeneralSection(): NodeDefinition
{
- $node
+ $treeBuilder = new TreeBuilder('general');
+
+ return $treeBuilder->getRootNode()
+ ->addDefaultsIfNotSet()
->children()
- ->arrayNode('general')
- ->addDefaultsIfNotSet()
- ->children()
- ->scalarNode('project')->defaultValue('')->end()
- ->scalarNode('version')->defaultValue('3.0.0-dev')->end()
- ->end()
- ->end()
+ ->scalarNode('project')->defaultValue('')->end()
+ ->scalarNode('version')->defaultValue('3.0.0-dev')->end()
->end()
- ;
+ ;
}
- protected function addPathsSection(ArrayNodeDefinition $node)
+ protected function addPathsSection(): NodeDefinition
{
- $node
+ $treeBuilder = new TreeBuilder('paths');
+
+ return $treeBuilder->getRootNode()
+ ->addDefaultsIfNotSet()
->children()
- ->arrayNode('paths')
- ->addDefaultsIfNotSet()
- ->children()
- ->scalarNode('projectDir')->defaultValue(getcwd())->end()
- ->scalarNode('schemaDir')->defaultValue(getcwd())->end()
- ->scalarNode('outputDir')->defaultValue(getcwd())->end()
- ->scalarNode('phpDir')->defaultValue(getcwd() . '/generated-classes')->end()
- ->scalarNode('phpConfDir')->defaultValue(getcwd() . '/generated-conf')->end()
- ->scalarNode('sqlDir')->defaultValue(getcwd() . '/generated-sql')->end()
- ->scalarNode('migrationDir')->defaultValue(getcwd() . '/generated-migrations')->end()
- ->scalarNode('composerDir')->defaultNull()->end()
- ->end()
- ->end()
+ ->scalarNode('projectDir')->defaultValue(getcwd())->end()
+ ->scalarNode('schemaDir')->defaultValue('%projectDir%')->end()
+ ->scalarNode('outputDir')->defaultValue('%projectDir%')->end()
+ ->scalarNode('phpDir')->defaultValue('%projectDir%/generated-classes')->end()
+ ->scalarNode('phpConfDir')->defaultValue('%projectDir%/generated-conf')->end()
+ ->scalarNode('sqlDir')->defaultValue('%projectDir%/generated-sql')->end()
+ ->scalarNode('migrationDir')->defaultValue('%projectDir%/generated-migrations')->end()
+ ->scalarNode('composerDir')->defaultNull()->end()
->end()
;
}
- protected function addDatabaseSection(ArrayNodeDefinition $node)
+ protected function addDatabaseSection(): NodeDefinition
{
- $node
+ $treeBuilder = new TreeBuilder('database');
+
+ return $treeBuilder->getRootNode()
+ ->addDefaultsIfNotSet()
->children()
- ->arrayNode('database')
- ->addDefaultsIfNotSet()
- ->children()
- ->arrayNode('connections')
- ->isRequired()
- ->validate()
- ->always()
- ->then(function ($connections) {
- foreach ($connections as $name => $connection) {
- if (strpos($name, '.') !== false) {
- throw new \InvalidArgumentException('Dots are not allowed in connection names');
- }
- }
+ ->arrayNode('connections')
+ ->isRequired()
+ ->validate()
+ ->always()
+ ->then(function ($connections) {
+ foreach ($connections as $name => $connection) {
+ if (strpos($name, '.') !== false) {
+ throw new \InvalidArgumentException('Dots are not allowed in connection names');
+ }
+ }
- return $connections;
- })
+ return $connections;
+ })
+ ->end()
+ ->requiresAtLeastOneElement()
+ ->normalizeKeys(false)
+ ->prototype('array')
+ ->fixXmlConfig('slave')
+ ->children()
+ ->scalarNode('classname')->defaultValue('\Propel\Runtime\Connection\ConnectionWrapper')->end()
+ ->enumNode('adapter')
+ ->isRequired()
+ ->cannotBeEmpty()
+ ->values(['mysql', 'pgsql', 'sqlite', 'mssql', 'sqlsrv', 'oracle'])
->end()
- ->requiresAtLeastOneElement()
- ->normalizeKeys(false)
- ->prototype('array')
- ->fixXmlConfig('slave')
+ ->scalarNode('dsn')->isRequired()->cannotBeEmpty()->end()
+ ->scalarNode('user')->isRequired()->end()
+ ->scalarNode('password')->isRequired()->treatNullLike('')->end()
+ ->arrayNode('options')
->children()
- ->scalarNode('classname')->defaultValue('\Propel\Runtime\Connection\ConnectionWrapper')->end()
- ->enumNode('adapter')
- ->isRequired()
- ->cannotBeEmpty()
- ->values(['mysql', 'pgsql', 'sqlite', 'mssql', 'sqlsrv', 'oracle'])
- ->end()
- ->scalarNode('dsn')->isRequired()->cannotBeEmpty()->end()
- ->scalarNode('user')->isRequired()->end()
- ->scalarNode('password')->isRequired()->treatNullLike('')->end()
- ->arrayNode('options')
- ->children()
- ->booleanNode('ATTR_PERSISTENT')->defaultFalse()->end()
- ->scalarNode('MYSQL_ATTR_SSL_CA')->end()
- ->scalarNode('MYSQL_ATTR_SSL_CERT')->end()
- ->scalarNode('MYSQL_ATTR_SSL_KEY')->end()
- ->scalarNode('MYSQL_ATTR_MAX_BUFFER_SIZE')->end()
- ->end()
- ->end()
- ->arrayNode('attributes')
- ->children()
- ->booleanNode('ATTR_EMULATE_PREPARES')->defaultFalse()->end()
- ->end()
- ->end()
- ->arrayNode('settings')
- ->fixXmlConfig('query', 'queries')
- ->children()
- ->scalarNode('charset')->defaultValue('utf8')->end()
- ->arrayNode('queries')
- ->prototype('scalar')->end()
- ->end()
- ->end()
- ->end()
- ->arrayNode('slaves')
- ->prototype('array')
- ->children()
- ->scalarNode('dsn')->end()
- ->end()
- ->end()
- ->end()
+ ->booleanNode('ATTR_PERSISTENT')->defaultFalse()->end()
+ ->scalarNode('MYSQL_ATTR_SSL_CA')->end()
+ ->scalarNode('MYSQL_ATTR_SSL_CERT')->end()
+ ->scalarNode('MYSQL_ATTR_SSL_KEY')->end()
+ ->scalarNode('MYSQL_ATTR_MAX_BUFFER_SIZE')->end()
->end()
->end()
- ->end()
- ->arrayNode('adapters')
- ->addDefaultsIfNotSet()
- ->children()
- ->arrayNode('mysql')
- ->addDefaultsIfNotSet()
- ->children()
- ->scalarNode('tableType')->defaultValue('InnoDB')->treatNullLike('InnoDB')->end()
- ->scalarNode('tableEngineKeyword')->defaultValue('ENGINE')->end()
- ->end()
+ ->arrayNode('attributes')
+ ->children()
+ ->booleanNode('ATTR_EMULATE_PREPARES')->defaultFalse()->end()
->end()
- ->arrayNode('sqlite')
- ->addDefaultsIfNotSet()
- ->children()
- ->scalarNode('foreignKey')->end()
- ->scalarNode('tableAlteringWorkaround')->end()
+ ->end()
+ ->arrayNode('settings')
+ ->fixXmlConfig('query', 'queries')
+ ->children()
+ ->scalarNode('charset')->defaultValue('utf8')->end()
+ ->arrayNode('queries')
+ ->prototype('scalar')->end()
->end()
->end()
- ->arrayNode('oracle')
- ->addDefaultsIfNotSet()
+ ->end()
+ ->arrayNode('slaves')
+ ->prototype('array')
->children()
- ->scalarNode('autoincrementSequencePattern')->defaultValue('${table}_SEQ')->end()
+ ->scalarNode('dsn')->end()
->end()
->end()
->end()
- ->end() //adapters
+ ->end()
->end()
- ->end() //database
+ ->end()
+ ->arrayNode('adapters')
+ ->addDefaultsIfNotSet()
+ ->children()
+ ->arrayNode('mysql')
+ ->addDefaultsIfNotSet()
+ ->children()
+ ->scalarNode('tableType')->defaultValue('InnoDB')->treatNullLike('InnoDB')->end()
+ ->scalarNode('tableEngineKeyword')->defaultValue('ENGINE')->end()
+ ->end()
+ ->end()
+ ->arrayNode('sqlite')
+ ->addDefaultsIfNotSet()
+ ->children()
+ ->scalarNode('foreignKey')->end()
+ ->scalarNode('tableAlteringWorkaround')->end()
+ ->end()
+ ->end()
+ ->arrayNode('oracle')
+ ->addDefaultsIfNotSet()
+ ->children()
+ ->scalarNode('autoincrementSequencePattern')->defaultValue('${table}_SEQ')->end()
+ ->end()
+ ->end()
+ ->end()
+ ->end() //adapters
->end()
;
}
- protected function addMigrationsSection(ArrayNodeDefinition $node)
+ protected function addMigrationsSection(): NodeDefinition
{
- $node
+ $treeBuilder = new TreeBuilder('migrations');
+
+ return $treeBuilder->getRootNode()
+ ->addDefaultsIfNotSet()
->children()
- ->arrayNode('migrations')
- ->addDefaultsIfNotSet()
- ->children()
- ->booleanNode('samePhpName')->defaultFalse()->end()
- ->booleanNode('addVendorInfo')->defaultFalse()->end()
- ->scalarNode('tableName')->defaultValue('propel_migration')->end()
- ->scalarNode('parserClass')->defaultNull()->end()
- ->end()
- ->end() //migrations
+ ->booleanNode('samePhpName')->defaultFalse()->end()
+ ->booleanNode('addVendorInfo')->defaultFalse()->end()
+ ->scalarNode('tableName')->defaultValue('propel_migration')->end()
+ ->scalarNode('parserClass')->defaultNull()->end()
->end()
;
}
- protected function addReverseSection(ArrayNodeDefinition $node)
+ protected function addReverseSection(): NodeDefinition
{
- $node
+ $treeBuilder = new TreeBuilder('reverse');
+
+ return $treeBuilder->getRootNode()
->children()
- ->arrayNode('reverse')
- ->children()
- ->scalarNode('connection')->end()
- ->scalarNode('parserClass')->end()
- ->end()
- ->end() //reverse
+ ->scalarNode('connection')->end()
+ ->scalarNode('parserClass')->end()
->end()
;
}
- protected function addRuntimeSection(ArrayNodeDefinition $node)
+ protected function addRuntimeSection(): NodeDefinition
{
- $node
+ $treeBuilder = new TreeBuilder('runtime');
+
+ return $treeBuilder->getRootNode()
+ ->addDefaultsIfNotSet()
+ ->fixXmlConfig('connection')
->children()
- ->arrayNode('runtime')
- ->addDefaultsIfNotSet()
- ->fixXmlConfig('connection')
- ->children()
- ->scalarNode('defaultConnection')->defaultValue('default')->end()
- ->arrayNode('connections')
- ->prototype('scalar')->end()
- ->end()
- ->arrayNode('log')
- ->useAttributeAsKey('name')
- ->prototype('array')
- ->children()
- ->scalarNode('type')->end()
- ->scalarNode('path')->end()
- ->enumNode('level')->values([100, 200, 250, 300, 400, 500, 550, 600])->end()
- ->end()
- ->end()
+ ->scalarNode('defaultConnection')->defaultValue('default')->end()
+ ->arrayNode('connections')
+ ->prototype('scalar')->end()
+ ->end()
+ ->arrayNode('log')
+ ->useAttributeAsKey('name')
+ ->prototype('array')
+ ->children()
+ ->scalarNode('type')->end()
+ ->scalarNode('path')->end()
+ ->enumNode('level')->values([100, 200, 250, 300, 400, 500, 550, 600])->end()
->end()
- ->arrayNode('profiler')
+ ->end()
+ ->end()
+ ->arrayNode('profiler')
+ ->children()
+ ->scalarNode('classname')->defaultValue('\Propel\Runtime\Util\Profiler')->end()
+ ->floatNode('slowTreshold')->defaultValue(0.1)->end()
+ ->arrayNode('details')
->children()
- ->scalarNode('classname')->defaultValue('\Propel\Runtime\Util\Profiler')->end()
- ->floatNode('slowTreshold')->defaultValue(0.1)->end()
- ->arrayNode('details')
+ ->arrayNode('time')
+ ->addDefaultsIfNotSet()
+ ->children()
+ ->integerNode('precision')->min(0)->defaultValue(3)->end()
+ ->integerNode('pad')->min(0)->defaultValue(8)->end()
+ ->end()
+ ->end()
+ ->arrayNode('memory')
+ ->addDefaultsIfNotSet()
+ ->children()
+ ->integerNode('precision')->min(0)->defaultValue(3)->end()
+ ->integerNode('pad')->min(0)->defaultValue(8)->end()
+ ->end()
+ ->end()
+ ->arrayNode('memDelta')
+ ->addDefaultsIfNotSet()
->children()
- ->arrayNode('time')
- ->addDefaultsIfNotSet()
- ->children()
- ->integerNode('precision')->min(0)->defaultValue(3)->end()
- ->integerNode('pad')->min(0)->defaultValue(8)->end()
- ->end()
- ->end()
- ->arrayNode('memory')
- ->addDefaultsIfNotSet()
- ->children()
- ->integerNode('precision')->min(0)->defaultValue(3)->end()
- ->integerNode('pad')->min(0)->defaultValue(8)->end()
- ->end()
- ->end()
- ->arrayNode('memDelta')
- ->addDefaultsIfNotSet()
- ->children()
- ->integerNode('precision')->min(0)->defaultValue(3)->end()
- ->integerNode('pad')->min(0)->defaultValue(8)->end()
- ->end()
- ->end()
- ->arrayNode('memPeak')
- ->addDefaultsIfNotSet()
- ->children()
- ->integerNode('precision')->min(0)->defaultValue(3)->end()
- ->integerNode('pad')->min(0)->defaultValue(8)->end()
- ->end()
- ->end()
+ ->integerNode('precision')->min(0)->defaultValue(3)->end()
+ ->integerNode('pad')->min(0)->defaultValue(8)->end()
+ ->end()
+ ->end()
+ ->arrayNode('memPeak')
+ ->addDefaultsIfNotSet()
+ ->children()
+ ->integerNode('precision')->min(0)->defaultValue(3)->end()
+ ->integerNode('pad')->min(0)->defaultValue(8)->end()
->end()
->end()
- ->scalarNode('innerGlue')->defaultValue(':')->end()
- ->scalarNode('outerGlue')->defaultValue('|')->end()
->end()
->end()
+ ->scalarNode('innerGlue')->defaultValue(':')->end()
+ ->scalarNode('outerGlue')->defaultValue('|')->end()
->end()
- ->end() //runtime
+ ->end()
->end()
;
}
- protected function addGeneratorSection(ArrayNodeDefinition $node)
+ protected function addGeneratorSection(): NodeDefinition
{
- $node
+ $treeBuilder= new TreeBuilder('generator');
+
+ return $treeBuilder->getRootNode()
+ ->addDefaultsIfNotSet()
+ ->fixXmlConfig('connection')
->children()
- ->arrayNode('generator')
+ ->scalarNode('defaultConnection')->isRequired()->end()
+ ->arrayNode('connections')
+ ->prototype('scalar')->end()
+ ->end()
+ ->arrayNode('schema')
->addDefaultsIfNotSet()
- ->fixXmlConfig('connection')
->children()
- ->scalarNode('defaultConnection')->isRequired()->end()
- ->arrayNode('connections')
- ->prototype('scalar')->end()
- ->end()
- ->arrayNode('schema')
- ->addDefaultsIfNotSet()
- ->children()
- ->scalarNode('basename')->defaultValue('schema')->end()
- ->booleanNode('autoNamespace')->defaultFalse()->end()
- ->booleanNode('transform')->defaultFalse()->end()
- ->end()
- ->end() //schema
- ->arrayNode('dateTime')
+ ->scalarNode('basename')->defaultValue('schema')->end()
+ ->booleanNode('autoNamespace')->defaultFalse()->end()
+ ->booleanNode('transform')->defaultFalse()->end()
+ ->end()
+ ->end() //schema
+ ->arrayNode('dateTime')
+ ->addDefaultsIfNotSet()
+ ->children()
+ ->booleanNode('useDateTimeClass')->defaultTrue()->end()
+ ->scalarNode('dateTimeClass')->defaultValue('DateTime')->end()
+ ->scalarNode('defaultTimeStampFormat')->end()
+ ->scalarNode('defaultTimeFormat')->end()
+ ->scalarNode('defaultDateFormat')->end()
+ ->end()
+ ->end()
+ ->arrayNode('objectModel')
+ ->addDefaultsIfNotSet()
+ ->children()
+ ->booleanNode('addGenericAccessors')->defaultTrue()->end()
+ ->booleanNode('addGenericMutators')->defaultTrue()->end()
+ ->booleanNode('emulateForeignKeyConstraints')->defaultFalse()->end()
+ ->booleanNode('addClassLevelComment')->defaultTrue()->end()
+ ->scalarNode('defaultKeyType')->defaultValue('fieldName')->end()
+ ->booleanNode('addSaveMethod')->defaultTrue()->end()
+ ->scalarNode('namespaceMap')->defaultValue('Map')->end()
+ ->booleanNode('addTimeStamp')->defaultFalse()->end()
+ ->booleanNode('addHooks')->defaultTrue()->end()
+ ->scalarNode('classPrefix')->defaultNull()->end()
+ ->booleanNode('useLeftJoinsInDoJoinMethods')->defaultTrue()->end()
+ ->arrayNode('builders')
->addDefaultsIfNotSet()
->children()
- ->booleanNode('useDateTimeClass')->defaultTrue()->end()
- ->scalarNode('dateTimeClass')->defaultValue('DateTime')->end()
- ->scalarNode('defaultTimeStampFormat')->end()
- ->scalarNode('defaultTimeFormat')->end()
- ->scalarNode('defaultDateFormat')->end()
+ ->scalarNode('object')->cannotBeEmpty()->defaultValue('\Propel\Generator\Builder\Om\ObjectBuilder')->end()
+ ->scalarNode('activerecordtrait')->cannotBeEmpty()->defaultValue('\Propel\Generator\Builder\Om\ActiveRecordTraitBuilder')->end()
+ ->scalarNode('objectmultiextend')->cannotBeEmpty()->defaultValue('\Propel\Generator\Builder\Om\MultiExtendObjectBuilder')->end()
+ ->scalarNode('repository')->cannotBeEmpty()->defaultValue('\Propel\Generator\Builder\Om\RepositoryBuilder')->end()
+ ->scalarNode('repositorystub')->cannotBeEmpty()->defaultValue('\Propel\Generator\Builder\Om\StubRepositoryBuilder')->end()
+ ->scalarNode('query')->cannotBeEmpty()->defaultValue('\Propel\Generator\Builder\Om\QueryBuilder')->end()
+ ->scalarNode('proxy')->cannotBeEmpty()->defaultValue('\Propel\Generator\Builder\Om\ProxyBuilder')->end()
+ ->scalarNode('querystub')->cannotBeEmpty()->defaultValue('\Propel\Generator\Builder\Om\StubQueryBuilder')->end()
+ ->scalarNode('queryinheritance')->cannotBeEmpty()->defaultValue('\Propel\Generator\Builder\Om\QueryInheritanceBuilder')->end()
+ ->scalarNode('queryinheritancestub')->cannotBeEmpty()->defaultValue('\Propel\Generator\Builder\Om\StubQueryInheritanceBuilder')->end()
+ ->scalarNode('inheritanceentitymap')->cannotBeEmpty()->defaultValue('\Propel\Generator\Builder\Om\EntityMapInheritanceBuilder')->end()
+ ->scalarNode('entitymap')->cannotBeEmpty()->defaultValue('\Propel\Generator\Builder\Om\EntityMapBuilder')->end()
+ ->scalarNode('datasql')->cannotBeEmpty()->end()
->end()
->end()
- ->arrayNode('objectModel')
- ->addDefaultsIfNotSet()
- ->children()
- ->booleanNode('addGenericAccessors')->defaultTrue()->end()
- ->booleanNode('addGenericMutators')->defaultTrue()->end()
- ->booleanNode('emulateForeignKeyConstraints')->defaultFalse()->end()
- ->booleanNode('addClassLevelComment')->defaultTrue()->end()
- ->scalarNode('defaultKeyType')->defaultValue('fieldName')->end()
- ->booleanNode('addSaveMethod')->defaultTrue()->end()
- ->scalarNode('namespaceMap')->defaultValue('Map')->end()
- ->booleanNode('addTimeStamp')->defaultFalse()->end()
- ->booleanNode('addHooks')->defaultTrue()->end()
- ->scalarNode('classPrefix')->defaultNull()->end()
- ->booleanNode('useLeftJoinsInDoJoinMethods')->defaultTrue()->end()
- ->scalarNode('pluralizerClass')->defaultValue('\Propel\Common\Pluralizer\StandardEnglishPluralizer')->end()
- ->arrayNode('builders')
- ->addDefaultsIfNotSet()
- ->children()
- ->scalarNode('object')->cannotBeEmpty()->defaultValue('\Propel\Generator\Builder\Om\ObjectBuilder')->end()
- ->scalarNode('activerecordtrait')->cannotBeEmpty()->defaultValue('\Propel\Generator\Builder\Om\ActiveRecordTraitBuilder')->end()
- ->scalarNode('objectmultiextend')->cannotBeEmpty()->defaultValue('\Propel\Generator\Builder\Om\MultiExtendObjectBuilder')->end()
- ->scalarNode('repository')->cannotBeEmpty()->defaultValue('\Propel\Generator\Builder\Om\RepositoryBuilder')->end()
- ->scalarNode('repositorystub')->cannotBeEmpty()->defaultValue('\Propel\Generator\Builder\Om\StubRepositoryBuilder')->end()
- ->scalarNode('query')->cannotBeEmpty()->defaultValue('\Propel\Generator\Builder\Om\QueryBuilder')->end()
- ->scalarNode('proxy')->cannotBeEmpty()->defaultValue('\Propel\Generator\Builder\Om\ProxyBuilder')->end()
- ->scalarNode('querystub')->cannotBeEmpty()->defaultValue('\Propel\Generator\Builder\Om\StubQueryBuilder')->end()
- ->scalarNode('queryinheritance')->cannotBeEmpty()->defaultValue('\Propel\Generator\Builder\Om\QueryInheritanceBuilder')->end()
- ->scalarNode('queryinheritancestub')->cannotBeEmpty()->defaultValue('\Propel\Generator\Builder\Om\StubQueryInheritanceBuilder')->end()
- ->scalarNode('inheritanceentitymap')->cannotBeEmpty()->defaultValue('\Propel\Generator\Builder\Om\EntityMapInheritanceBuilder')->end()
- ->scalarNode('entitymap')->cannotBeEmpty()->defaultValue('\Propel\Generator\Builder\Om\EntityMapBuilder')->end()
- ->scalarNode('datasql')->cannotBeEmpty()->end()
- ->end()
- ->end()
- ->end()
- ->end() //objectModel
->end()
- ->end() //generator
+ ->end() //objectModel
->end()
;
}
diff --git a/src/Common/Config/XmlToArrayConverter.php b/src/Common/Config/XmlToArrayConverter.php
index 37786282..f3916235 100644
--- a/src/Common/Config/XmlToArrayConverter.php
+++ b/src/Common/Config/XmlToArrayConverter.php
@@ -1,5 +1,4 @@
exists()) {
+ $xmlToParse = $file->read();
}
//Empty xml file returns empty array
- if ('' === $xmlToParse) {
+ if ($xmlToParse->isEmpty()) {
return [];
}
- if ($xmlToParse[0] !== '<') {
+ if (!$xmlToParse->startsWith('<')) {
throw new InvalidArgumentException('Invalid xml content');
}
$currentEntityLoader = libxml_disable_entity_loader(true);
$currentInternalErrors = libxml_use_internal_errors(true);
- $xml = simplexml_load_string($xmlToParse);
+ $xml = simplexml_load_string($xmlToParse->toString());
$errors = libxml_get_errors();
libxml_clear_errors();
@@ -62,9 +62,7 @@ public static function convert(string $xmlToParse): array
throw new XmlParseException($errors);
}
- $conf = self::simpleXmlToArray($xml);
-
- return $conf;
+ return self::simpleXmlToArray($xml);
}
/**
diff --git a/src/Common/Pluralizer/PluralizerInterface.php b/src/Common/Pluralizer/PluralizerInterface.php
deleted file mode 100644
index 08bbd0f9..00000000
--- a/src/Common/Pluralizer/PluralizerInterface.php
+++ /dev/null
@@ -1,27 +0,0 @@
-
- */
-interface PluralizerInterface
-{
- /**
- * Generate a plural name based on the passed in root.
- *
- * @param string $root The root that needs to be pluralized (e.g. Author)
- * @return string The plural form of $root.
- */
- public function getPluralForm(string $root): string;
-}
diff --git a/src/Common/Pluralizer/SimpleEnglishPluralizer.php b/src/Common/Pluralizer/SimpleEnglishPluralizer.php
deleted file mode 100644
index cd634071..00000000
--- a/src/Common/Pluralizer/SimpleEnglishPluralizer.php
+++ /dev/null
@@ -1,31 +0,0 @@
-
- */
-class SimpleEnglishPluralizer implements PluralizerInterface
-{
- /**
- * Generate a plural name based on the passed in root.
- *
- * @param string $root The root that needs to be pluralized (e.g. Author)
- * @return string The plural form of $root (e.g. Authors).
- */
- public function getPluralForm(string $root): string
- {
- return $root . 's';
- }
-}
diff --git a/src/Common/Pluralizer/StandardEnglishPluralizer.php b/src/Common/Pluralizer/StandardEnglishPluralizer.php
deleted file mode 100644
index f894e2bd..00000000
--- a/src/Common/Pluralizer/StandardEnglishPluralizer.php
+++ /dev/null
@@ -1,152 +0,0 @@
- '\1ices',
- '(alumn|bacill|cact|foc|fung|nucle|radi|stimul|syllab|termin|vir)us' => '\1i',
- '(buffal|tomat)o' => '\1oes',
-
- 'x' => 'xes',
- 'ch' => 'ches',
- 'sh' => 'shes',
- 'ss' => 'sses',
-
- 'ay' => 'ays',
- 'ey' => 'eys',
- 'iy' => 'iys',
- 'oy' => 'oys',
- 'uy' => 'uys',
- 'y' => 'ies',
-
- 'ao' => 'aos',
- 'eo' => 'eos',
- 'io' => 'ios',
- 'oo' => 'oos',
- 'uo' => 'uos',
- 'o' => 'os',
-
- 'us' => 'uses',
-
- 'cis' => 'ces',
- 'sis' => 'ses',
- 'xis' => 'xes',
-
- 'zoon' => 'zoa',
-
- 'itis' => 'itis',
- 'ois' => 'ois',
- 'pox' => 'pox',
- 'ox' => 'oxes',
-
- 'foot' => 'feet',
- 'goose' => 'geese',
- 'tooth' => 'teeth',
- 'quiz' => 'quizzes',
- 'alias' => 'aliases',
-
- 'alf' => 'alves',
- 'elf' => 'elves',
- 'olf' => 'olves',
- 'arf' => 'arves',
- 'nife' => 'nives',
- 'life' => 'lives'
- ];
-
- protected $irregular = [
- 'leaf' => 'leaves',
- 'loaf' => 'loaves',
- 'move' => 'moves',
- 'foot' => 'feet',
- 'goose' => 'geese',
- 'genus' => 'genera',
- 'sex' => 'sexes',
- 'ox' => 'oxen',
- 'child' => 'children',
- 'man' => 'men',
- 'tooth' => 'teeth',
- 'person' => 'people',
- 'wife' => 'wives',
- 'mythos' => 'mythoi',
- 'testis' => 'testes',
- 'numen' => 'numina',
- 'quiz' => 'quizzes',
- 'alias' => 'aliases',
- ];
-
- protected $uncountable = [
- 'sheep',
- 'fish',
- 'deer',
- 'series',
- 'species',
- 'money',
- 'rice',
- 'information',
- 'equipment',
- 'news',
- 'people',
- ];
-
- /**
- * Generate a plural name based on the passed in root.
- *
- * @param string $root The root that needs to be pluralized (e.g. Author)
- * @return string The plural form of $root (e.g. Authors).
- */
- public function getPluralForm(string $root): string
- {
- // save some time in the case that singular and plural are the same
- if (in_array(strtolower($root), $this->uncountable)) {
- return $root;
- }
-
- // check for irregular singular words
- foreach ($this->irregular as $pattern => $result) {
- $searchPattern = '/' . $pattern . '$/i';
- if (preg_match($searchPattern, $root)) {
- $replacement = preg_replace($searchPattern, $result, $root);
- // look at the first char and see if it's upper case
- // I know it won't handle more than one upper case char here (but I'm OK with that)
- if (preg_match('/^[A-Z]/', $root)) {
- $replacement = ucfirst($replacement);
- }
-
- return $replacement;
- }
- }
-
- // check for irregular singular suffixes
- foreach ($this->plural as $pattern => $result) {
- $searchPattern = '/' . $pattern . '$/i';
- if (preg_match($searchPattern, $root)) {
- return preg_replace($searchPattern, $result, $root);
- }
- }
-
- // fallback to naive pluralization
- return $root . 's';
- }
-}
diff --git a/src/Common/Types/AbstractType.php b/src/Common/Types/AbstractType.php
index 405f6851..4fa09ba9 100644
--- a/src/Common/Types/AbstractType.php
+++ b/src/Common/Types/AbstractType.php
@@ -1,5 +1,4 @@
getValueSet() as $valueSet) {
- $constName = strtoupper($field->getName() . '_type_' . $valueSet);
- $constName = preg_replace('/[^a-zA-z0-9_]+/', '_', $constName);
+ $constName = $field->getName()->append("_type_$valueSet")->toSnakeCase()->toUpperCase();
$types[] = 'self::' . $constName;
- $constant = PhpConstant::create($constName, $valueSet);
+ $constant = PhpConstant::create((string) $constName, $valueSet);
$constant->setType('string');
$builder->getDefinition()->setConstant($constant);
}
- $all = '[' . implode(', ', $types) . ']';
- $allConstName = strtoupper($field->getName() . '_types');
- $constant = PhpConstant::create($allConstName, $all, true);
+ $allConstName = $field->getName()->append('_types')->toUpperCase();
+ $constant = PhpConstant::create((string) $allConstName, $types->join(', ')->ensureEnd(']')->ensureStart('[')->toString(), true);
$constant->setType('array|string[]');
$builder->getDefinition()->setConstant($constant);
}
diff --git a/src/Common/Types/SQL/IntegerType.php b/src/Common/Types/SQL/IntegerType.php
index a6ce70fb..2162ea6a 100644
--- a/src/Common/Types/SQL/IntegerType.php
+++ b/src/Common/Types/SQL/IntegerType.php
@@ -1,5 +1,4 @@
null,
'expression' => null,
'condition' => null,
diff --git a/src/Generator/Behavior/AggregateField/AggregateFieldRelationBehavior.php b/src/Generator/Behavior/AggregateField/AggregateFieldRelationBehavior.php
index c4dc24d7..c5477492 100644
--- a/src/Generator/Behavior/AggregateField/AggregateFieldRelationBehavior.php
+++ b/src/Generator/Behavior/AggregateField/AggregateFieldRelationBehavior.php
@@ -29,7 +29,7 @@ class AggregateFieldRelationBehavior extends Behavior
use ComponentTrait;
// default parameters value
- protected $defaultParameters = [
+ protected array $defaultParameters = [
'foreign_entity' => '',
'update_method' => '',
'aggregate_name' => '',
diff --git a/src/Generator/Behavior/Archivable/ArchivableBehavior.php b/src/Generator/Behavior/Archivable/ArchivableBehavior.php
index 78e6499a..4e4e42da 100644
--- a/src/Generator/Behavior/Archivable/ArchivableBehavior.php
+++ b/src/Generator/Behavior/Archivable/ArchivableBehavior.php
@@ -32,7 +32,7 @@ class ArchivableBehavior extends Behavior
use ComponentTrait;
// default parameters value
- protected $defaultParameters = [
+ protected array $defaultParameters = [
'archive_entity' => '',
'archive_table' => null,
'log_archived_at' => true,
@@ -49,7 +49,7 @@ class ArchivableBehavior extends Behavior
protected $objectBuilderModifier;
protected $queryBuilderModifier;
- public function modifyDatabase()
+ public function modifyDatabase(): void
{
foreach ($this->getDatabase()->getEntities() as $entity) {
if ($entity->hasBehavior($this->getId())) {
diff --git a/src/Generator/Behavior/AutoAddPk/AutoAddPkBehavior.php b/src/Generator/Behavior/AutoAddPk/AutoAddPkBehavior.php
index fe7e382f..4dbb1765 100644
--- a/src/Generator/Behavior/AutoAddPk/AutoAddPkBehavior.php
+++ b/src/Generator/Behavior/AutoAddPk/AutoAddPkBehavior.php
@@ -21,7 +21,7 @@
class AutoAddPkBehavior extends Behavior
{
// default parameters value
- protected $defaultParameters = [
+ protected array $defaultParameters = [
'name' => 'id',
'autoIncrement' => true,
'type' => 'INTEGER'
@@ -31,7 +31,7 @@ class AutoAddPkBehavior extends Behavior
* Copy the behavior to the database entities
* Only for entities that have no Pk
*/
- public function modifyDatabase()
+ public function modifyDatabase(): void
{
foreach ($this->getDatabase()->getEntities() as $entity) {
if (!$entity->hasPrimaryKey()) {
diff --git a/src/Generator/Behavior/ConcreteInheritance/ConcreteInheritanceBehavior.php b/src/Generator/Behavior/ConcreteInheritance/ConcreteInheritanceBehavior.php
index 303d914c..8d7e566a 100644
--- a/src/Generator/Behavior/ConcreteInheritance/ConcreteInheritanceBehavior.php
+++ b/src/Generator/Behavior/ConcreteInheritance/ConcreteInheritanceBehavior.php
@@ -33,7 +33,7 @@ class ConcreteInheritanceBehavior extends Behavior
use ComponentTrait;
// default parameters value
- protected $defaultParameters = [
+ protected array $defaultParameters = [
'extends' => '',
'copy_data_to_parent' => true,
'descendant_field' => 'descendantClass',
diff --git a/src/Generator/Behavior/ConcreteInheritance/ConcreteInheritanceParentBehavior.php b/src/Generator/Behavior/ConcreteInheritance/ConcreteInheritanceParentBehavior.php
index 8bc419de..b3d766ff 100644
--- a/src/Generator/Behavior/ConcreteInheritance/ConcreteInheritanceParentBehavior.php
+++ b/src/Generator/Behavior/ConcreteInheritance/ConcreteInheritanceParentBehavior.php
@@ -27,7 +27,7 @@
class ConcreteInheritanceParentBehavior extends Behavior
{
// default parameters value
- protected $defaultParameters = [
+ protected array $defaultParameters = [
'descendant_field' => 'descendantClass'
];
diff --git a/src/Generator/Behavior/Delegate/DelegateBehavior.php b/src/Generator/Behavior/Delegate/DelegateBehavior.php
index 7ea985f9..93207803 100644
--- a/src/Generator/Behavior/Delegate/DelegateBehavior.php
+++ b/src/Generator/Behavior/Delegate/DelegateBehavior.php
@@ -28,7 +28,7 @@ class DelegateBehavior extends Behavior
const MANY_TO_ONE = 2;
// default parameters value
- protected $defaultParameters = [
+ protected array $defaultParameters = [
'to' => ''
];
diff --git a/src/Generator/Behavior/I18n/I18nBehavior.php b/src/Generator/Behavior/I18n/I18nBehavior.php
index 474a13ab..42ba4ecd 100644
--- a/src/Generator/Behavior/I18n/I18nBehavior.php
+++ b/src/Generator/Behavior/I18n/I18nBehavior.php
@@ -35,7 +35,7 @@ class I18nBehavior extends Behavior
const DEFAULT_LOCALE = 'en_US';
// default parameters value
- protected $defaultParameters = [
+ protected array $defaultParameters = [
'i18n_entity' => '%ENTITYNAME%I18n',
'i18n_fields' => '',
'i18n_relation_field' => null,
@@ -52,7 +52,7 @@ class I18nBehavior extends Behavior
*/
protected $i18nEntity;
- public function modifyDatabase()
+ public function modifyDatabase(): void
{
foreach ($this->getDatabase()->getEntities() as $entity) {
if ($entity->hasBehavior('i18n') && !$entity->getBehavior('i18n')->getParameter('default_locale')) {
diff --git a/src/Generator/Behavior/NestedSet/NestedSetBehavior.php b/src/Generator/Behavior/NestedSet/NestedSetBehavior.php
index 93330949..bcccc656 100644
--- a/src/Generator/Behavior/NestedSet/NestedSetBehavior.php
+++ b/src/Generator/Behavior/NestedSet/NestedSetBehavior.php
@@ -29,7 +29,7 @@ class NestedSetBehavior extends Behavior
use ComponentTrait;
// default parameters value
- protected $defaultParameters = [
+ protected array $defaultParameters = [
'left_field' => 'tree_left',
'right_field' => 'tree_right',
'level_field' => 'tree_level',
diff --git a/src/Generator/Behavior/QueryCache/QueryCacheBehavior.php b/src/Generator/Behavior/QueryCache/QueryCacheBehavior.php
index 71cd1434..1f7ae604 100644
--- a/src/Generator/Behavior/QueryCache/QueryCacheBehavior.php
+++ b/src/Generator/Behavior/QueryCache/QueryCacheBehavior.php
@@ -24,7 +24,7 @@ class QueryCacheBehavior extends Behavior
use ComponentTrait;
// default parameters value
- protected $defaultParameters = [
+ protected array $defaultParameters = [
'backend' => 'apc',
'lifetime' => 3600,
];
diff --git a/src/Generator/Behavior/Sluggable/SluggableBehavior.php b/src/Generator/Behavior/Sluggable/SluggableBehavior.php
index 33923785..b02b7b40 100644
--- a/src/Generator/Behavior/Sluggable/SluggableBehavior.php
+++ b/src/Generator/Behavior/Sluggable/SluggableBehavior.php
@@ -30,7 +30,7 @@ class SluggableBehavior extends Behavior
{
use ComponentTrait;
- protected $defaultParameters = [
+ protected array $defaultParameters = [
'slug_field' => 'slug',
'slug_pattern' => '',
'replace_pattern' => '/\W+/',
@@ -54,7 +54,7 @@ public function modifyEntity()
throw new BuildException('Sluggable behavior requires the entity has one primary string at least when no slug_pattern is set, to calculate the slug.');
}
- if (!$entity->hasField($this->getParameter('slug_field'))) {
+ if (!$entity->hasFieldByName($this->getParameter('slug_field'))) {
$entity->addField($modelFactory->createField(
[
'name' => $this->getParameter('slug_field'),
@@ -70,9 +70,9 @@ public function modifyEntity()
$unique->setName(
($entity->getSchemaName() ? "{$entity->getSchemaName()}_" : '') . $entity->getTableName() . '_slug'
);
- $unique->addField($entity->getField($this->getParameter('slug_field')));
+ $unique->addField($entity->getFieldByName($this->getParameter('slug_field')));
if ($this->getParameter('scope_field')) {
- $unique->addField($entity->getField($this->getParameter('scope_field')));
+ $unique->addField($entity->getFieldByName($this->getParameter('scope_field')));
}
$entity->addUnique($unique);
}
diff --git a/src/Generator/Behavior/Sortable/SortableBehavior.php b/src/Generator/Behavior/Sortable/SortableBehavior.php
index 76a8194a..492ab092 100644
--- a/src/Generator/Behavior/Sortable/SortableBehavior.php
+++ b/src/Generator/Behavior/Sortable/SortableBehavior.php
@@ -32,7 +32,7 @@ class SortableBehavior extends Behavior
use ComponentTrait;
// default parameters value
- protected $defaultParameters = [
+ protected array $defaultParameters = [
'rank_field' => 'sortable_rank',
'use_scope' => false,
'scope_field' => '',
@@ -235,15 +235,13 @@ public function generateScopePhp(): array
/**
* {@inheritdoc}
*/
- public function addParameter(array $parameter): Behavior
+ public function addParameter(array $parameter): void
{
if ('scope_field' === $parameter['name']) {
$this->parameters['scope_field'] .= ($this->parameters['scope_field'] ? ',' : '') . $parameter['value'];
} else {
parent::addParameter($parameter);
}
-
- return $this;
}
/**
diff --git a/src/Generator/Behavior/Timestampable/TimestampableBehavior.php b/src/Generator/Behavior/Timestampable/TimestampableBehavior.php
index 4582525e..ce6c50e5 100644
--- a/src/Generator/Behavior/Timestampable/TimestampableBehavior.php
+++ b/src/Generator/Behavior/Timestampable/TimestampableBehavior.php
@@ -55,13 +55,13 @@ public function modifyEntity(): void
{
$entity = $this->getEntity();
- if ($this->withCreatedAt() && !$entity->hasField($this->getParameter('create_field'))) {
+ if ($this->withCreatedAt() && !$entity->hasFieldByName($this->getParameter('create_field'))) {
$createField = new Field();
$createField->setName($this->getParameter('create_field'));
$createField->setType('TIMESTAMP');
$entity->addField($createField);
}
- if ($this->withUpdatedAt() && !$entity->hasField($this->getParameter('update_field'))) {
+ if ($this->withUpdatedAt() && !$entity->hasFieldByName($this->getParameter('update_field'))) {
$updateField = new Field();
$updateField->setName($this->getParameter('update_field'));
$updateField->setType('TIMESTAMP');
@@ -72,7 +72,7 @@ public function modifyEntity(): void
public function preUpdate(RepositoryBuilder $repositoryBuilder): string
{
if ($this->withUpdatedAt()) {
- $field = $this->getEntity()->getField($this->getParameter('update_field'))->getName();
+ $field = $this->getEntity()->getFieldByName($this->getParameter('update_field'))->getName();
return "
\$writer = \$this->getEntityMap()->getPropWriter();
@@ -95,7 +95,7 @@ public function preInsert(RepositoryBuilder $repositoryBuilder): string
if ($this->withCreatedAt()) {
- $createdAtField = $this->getEntity()->getField($this->getParameter('create_field'))->getName();
+ $createdAtField = $this->getEntity()->getFieldByName($this->getParameter('create_field'))->getName();
$script .= "
if (!\$this->getEntityMap()->isFieldModified(\$entity, '$createdAtField')) {
\$writer(\$entity, '$createdAtField', \\Propel\\Runtime\\Util\\PropelDateTime::createHighPrecision());
@@ -103,7 +103,7 @@ public function preInsert(RepositoryBuilder $repositoryBuilder): string
}
if ($this->withUpdatedAt()) {
- $updatedAtField = $this->getEntity()->getField($this->getParameter('update_field'))->getName();
+ $updatedAtField = $this->getEntity()->getFieldByName($this->getParameter('update_field'))->getName();
$script .= "
if (!\$this->getEntityMap()->isFieldModified(\$entity, '$updatedAtField')) {
\$writer(\$entity, '$updatedAtField', \\Propel\\Runtime\\Util\\PropelDateTime::createHighPrecision());
diff --git a/src/Generator/Builder/DataModelBuilder.php b/src/Generator/Builder/DataModelBuilder.php
index 5f2bd631..5a91c15d 100644
--- a/src/Generator/Builder/DataModelBuilder.php
+++ b/src/Generator/Builder/DataModelBuilder.php
@@ -508,7 +508,7 @@ public function getGeneratorConfig(): GeneratorConfigInterface
public function getBuildProperty(string $name)
{
if ($this->getGeneratorConfig()) {
- return $this->getGeneratorConfig()->getConfigProperty($name);
+ return $this->getGeneratorConfig()->get($name);
}
return null;
diff --git a/src/Generator/Builder/Om/Component/BuildComponent.php b/src/Generator/Builder/Om/Component/BuildComponent.php
index a8f4fa70..c4ecbcea 100644
--- a/src/Generator/Builder/Om/Component/BuildComponent.php
+++ b/src/Generator/Builder/Om/Component/BuildComponent.php
@@ -73,7 +73,7 @@ protected function getEntity()
/**
* @return PlatformInterface
*/
- protected function getPlatform()
+ protected function getPlatform(): PlatformInterface
{
return $this->builder->getPlatform();
}
diff --git a/src/Generator/Command/ConfigConvertCommand.php b/src/Generator/Command/ConfigConvertCommand.php
index f5e87d97..f8bb3a5d 100644
--- a/src/Generator/Command/ConfigConvertCommand.php
+++ b/src/Generator/Command/ConfigConvertCommand.php
@@ -59,9 +59,9 @@ protected function execute(InputInterface $input, OutputInterface $output)
//Create the options array to pass to ArrayToPhpConverter
$options['connections'] = $configManager->getConnectionParametersArray();
- $options['defaultConnection'] = $configManager->getSection('runtime')['defaultConnection'];
- $options['log'] = $configManager->getSection('runtime')['log'];
- $options['profiler'] = $configManager->getConfigProperty('runtime.profiler');
+ $options['defaultConnection'] = $configManager->get('runtime.defaultConnection');
+ $options['log'] = $configManager->get('runtime.log');
+ $options['profiler'] = $configManager->get('runtime.profiler');
$schemas = $this->getSchemas($input->getOption('input-dir'));
if ($schemas) {
diff --git a/src/Generator/Command/MigrationDiffCommand.php b/src/Generator/Command/MigrationDiffCommand.php
index 2a958652..5d5ec4b9 100644
--- a/src/Generator/Command/MigrationDiffCommand.php
+++ b/src/Generator/Command/MigrationDiffCommand.php
@@ -99,8 +99,8 @@ protected function execute(InputInterface $input, OutputInterface $output)
}
$manager->setConnections($connections);
- $manager->setMigrationTable($generatorConfig->getConfigProperty('migrations.tableName'));
- $manager->setWorkingDirectory($generatorConfig->getSection('paths')['migrationDir']);
+ $manager->setMigrationTable($generatorConfig->get('migrations.tableName'));
+ $manager->setWorkingDirectory($generatorConfig->get('paths.migrationDir'));
if ($manager->hasPendingMigrations()) {
throw new RuntimeException('Uncommitted migrations have been found ; you should either execute or delete them before rerunning the \'diff\' task');
diff --git a/src/Generator/Config/GeneratorConfig.php b/src/Generator/Config/GeneratorConfig.php
index c3ef3264..9abca071 100644
--- a/src/Generator/Config/GeneratorConfig.php
+++ b/src/Generator/Config/GeneratorConfig.php
@@ -176,7 +176,7 @@ public function getFieldType(string $name)
*/
public function getConfiguredBuilder(Entity $entity, string $type): AbstractBuilder
{
- $className = $this->getConfigProperty('generator.objectModel.builders.' . $type);
+ $className = $this->get("generator.objectModel.builders.$type");
if (null === $className || !class_exists($className)) {
throw new InvalidArgumentException(sprintf('Builder for `%s` not found.', $type));
@@ -189,18 +189,6 @@ public function getConfiguredBuilder(Entity $entity, string $type): AbstractBuil
return $builder;
}
- /**
- * Returns a configured Pluralizer class.
- *
- * @return PluralizerInterface
- */
- public function getConfiguredPluralizer(): PluralizerInterface
- {
- $classname = $this->get()['generator']['objectModel']['pluralizerClass'];
-
- return $this->getInstance($classname, null, '\\Propel\\Common\\Pluralizer\\PluralizerInterface');
- }
-
/**
* Return an array of all configured connection properties, from `generator` and `reverse`
* sections of the configuration.
@@ -212,13 +200,13 @@ public function getBuildConnections(): array
if (null === $this->buildConnections) {
$connectionNames = $this->get()['generator']['connections'];
- $reverseConnection = $this->getConfigProperty('reverse.connection');
+ $reverseConnection = $this->get('reverse.connection');
if (null !== $reverseConnection && !in_array($reverseConnection, $connectionNames)) {
$connectionNames[] = $reverseConnection;
}
foreach ($connectionNames as $name) {
- if ($definition = $this->getConfigProperty('database.connections.' . $name)) {
+ if ($definition = $this->get('database.connections.' . $name)) {
$this->buildConnections[$name] = $definition;
}
}
diff --git a/src/Generator/Config/GeneratorConfigInterface.php b/src/Generator/Config/GeneratorConfigInterface.php
index 8ecbc4de..1fee3a31 100644
--- a/src/Generator/Config/GeneratorConfigInterface.php
+++ b/src/Generator/Config/GeneratorConfigInterface.php
@@ -12,6 +12,7 @@
namespace Propel\Generator\Config;
+use Propel\Common\Config\Exception\InvalidArgumentException;
use Propel\Common\Pluralizer\PluralizerInterface;
use Propel\Common\Types\BuildableFieldTypeInterface;
use Propel\Common\Types\FieldTypeInterface;
@@ -34,13 +35,6 @@ interface GeneratorConfigInterface
*/
public function getConfiguredBuilder(Entity $entity, string $type): AbstractBuilder;
- /**
- * Returns a configured Pluralizer class.
- *
- * @return PluralizerInterface
- */
- public function getConfiguredPluralizer(): PluralizerInterface;
-
/**
* Creates and configures a new Platform class.
*
@@ -83,8 +77,8 @@ public function getFieldType(string $name);
*
* @param string $name The name of property, expressed as a dot separated level hierarchy
*
- * @throws \Propel\Common\Config\Exception\InvalidArgumentException
+ * @throws InvalidArgumentException
* @return mixed The configuration property
*/
- public function getConfigProperty(string $name);
+ public function get(string $name);
}
diff --git a/src/Generator/Config/QuickGeneratorConfig.php b/src/Generator/Config/QuickGeneratorConfig.php
index fb78e4c0..6af639f1 100644
--- a/src/Generator/Config/QuickGeneratorConfig.php
+++ b/src/Generator/Config/QuickGeneratorConfig.php
@@ -80,7 +80,7 @@ public function __construct(array $extraConf = [])
*/
public function getConfiguredBuilder(Entity $entity, string $type): AbstractBuilder
{
- $class = $this->getConfigProperty('generator.objectModel.builders.' . $type);
+ $class = $this->get("generator.objectModel.builders.$type");
if (null === $class) {
throw new InvalidArgumentException("Invalid data model builder type `$type`");
diff --git a/src/Generator/Manager/BehaviorManager.php b/src/Generator/Manager/BehaviorManager.php
index 5e4c78db..61546884 100644
--- a/src/Generator/Manager/BehaviorManager.php
+++ b/src/Generator/Manager/BehaviorManager.php
@@ -1,4 +1,4 @@
-setGeneratorConfig($config);
- }
-
- /**
- * Sets the generator config
- *
- * @param GeneratorConfigInterface $config build config
- */
- public function setGeneratorConfig(GeneratorConfigInterface $config = null)
- {
- $this->generatorConfig = $config;
- $this->composerDir = null;
- $this->behaviors = null;
-
- if (null !== $config) {
- $this->composerDir = $config->get()['paths']['composerDir'];
+ if ($config !== null) {
+ $this->composerDir = $config->get('paths.composerDir') ?? '';
}
+ $this->behaviors =new Map();
}
-
+
/**
* Instantiates a behavior from a given name
*
* @param string $name
- * @throws BuildException
+ *
* @return Behavior
+ * @throws JsonException
+ * @throws BuildException
*/
public function create(string $name): Behavior
{
@@ -85,16 +65,18 @@ public function create(string $name): Behavior
}
return $behavior;
}
-
+
/**
* Searches a composer file
*
+ * @param string $fileName
+ *
* @return SplFileInfo the found composer file or null if composer file isn't found
*/
- private function findComposerFile($fileName)
+ private function findComposerFile(string $fileName): ?SplFileInfo
{
- if (null !== $this->composerDir) {
- $filePath = $this->composerDir . '/' . $fileName;
+ if ('' !== $this->composerDir) {
+ $filePath = "{$this->composerDir}/$fileName";
if (file_exists($filePath)) {
return new SplFileInfo($filePath, dirname($filePath), dirname($filePath));
@@ -147,21 +129,20 @@ private function getSearchDirs()
__DIR__ . '/../../../../' // propel development environment
];
}
-
+
/**
* Returns the loaded behaviors and loads them if not done before
*
- * @return array behaviors
+ * @return Map behaviors
+ * @throws JsonException
*/
- public function getBehaviors()
+ public function getBehaviors(): Map
{
- if (null === $this->behaviors) {
+ if (!isset($this->behaviors)) {
// find behaviors in composer.lock file
$lock = $this->findComposerLock();
- if (null === $lock) {
- $this->behaviors = [];
- } else {
+ if (null !== $lock) {
$this->behaviors = $this->loadBehaviors($lock);
}
@@ -184,10 +165,10 @@ public function getBehaviors()
* Returns the class name for a given behavior name
*
* @param string $name The behavior name (e.g. timetampable)
- * @throws BehaviorNotFoundException when the behavior cannot be found
+ * @throws BehaviorNotFoundException|JsonException when the behavior cannot be found
* @return string the class name
*/
- public function getClassname($name)
+ public function getClassname(string $name): string
{
if (false !== strpos($name, '\\')) {
$class = $name;
@@ -196,7 +177,7 @@ public function getClassname($name)
if (!class_exists($class)) {
$behaviors = $this->getBehaviors();
- if (array_key_exists($name, $behaviors)) {
+ if ($behaviors->has($name)) {
$class = $behaviors[$name]['class'];
}
}
@@ -216,9 +197,9 @@ public function getClassname($name)
* @param string $name The behavior name (ie: timestampable)
* @return string The behavior fully qualified class name
*/
- private function getCoreBehavior($name)
+ private function getCoreBehavior(string $name): string
{
- $phpName = NamingTool::toStudlyCase($name);
+ $phpName = Text::create($name)->toStudlyCase()->toString();
return sprintf('\\Propel\\Generator\\Behavior\\%s\\%sBehavior', $phpName, $phpName);
}
@@ -227,25 +208,22 @@ private function getCoreBehavior($name)
* Finds all behaviors by parsing composer.lock file
*
* @param SplFileInfo $composerLock
- * @return array
+ * @return Map
* @throws JsonException
*/
- private function loadBehaviors($composerLock): array
+ private function loadBehaviors(SplFileInfo $composerLock = null): Map
{
- $behaviors = [];
-
- if (null === $composerLock) {
- return $behaviors;
- }
-
- $json = Json::decode($composerLock->getContents(), true);
-
- if (isset($json['packages'])) {
- foreach ($json['packages'] as $package) {
- $behavior = $this->loadBehavior($package);
-
- if (null !== $behavior) {
- $behaviors[$behavior['name']] = $behavior;
+ $behaviors =new Map();
+ if (null !== $composerLock) {
+ $json = Json::decode($composerLock->getContents());
+
+ if (isset($json['packages'])) {
+ foreach ($json['packages'] as $package) {
+ $behavior = $this->loadBehavior($package);
+
+ if (null !== $behavior) {
+ $behaviors->set($behavior['name'], $behavior);
+ }
}
}
}
@@ -260,7 +238,7 @@ private function loadBehaviors($composerLock): array
* @throws BuildException
* @return array behavior data
*/
- private function loadBehavior($package)
+ private function loadBehavior(array $package): array
{
if (isset($package['type']) && $package['type'] == self::BEHAVIOR_PACKAGE_TYPE) {
@@ -280,6 +258,6 @@ private function loadBehavior($package)
}
}
- return null;
+ return [];
}
}
diff --git a/src/Generator/Manager/ReverseManager.php b/src/Generator/Manager/ReverseManager.php
index 27ce0dc7..d37515e2 100644
--- a/src/Generator/Manager/ReverseManager.php
+++ b/src/Generator/Manager/ReverseManager.php
@@ -205,7 +205,7 @@ protected function buildModel()
protected function getConnection()
{
$generatorConfig = $this->getGeneratorConfig();
- $database = $generatorConfig->getConfigProperty('reverse.connection');
+ $database = $generatorConfig->get('reverse.connection');
if (null === $database) {
throw new BuildException('No configured connection. Please add a connection to your configuration file
diff --git a/src/Generator/Model/Behavior.php b/src/Generator/Model/Behavior.php
index 8e0ed25e..10d5b3b1 100644
--- a/src/Generator/Model/Behavior.php
+++ b/src/Generator/Model/Behavior.php
@@ -1,5 +1,4 @@
-id === null) {
+ if (!isset($this->id)) {
$this->setId($name);
}
- $this->name = $name;
-
- return $this;
+ $this->namePartSetName($name);
}
/**
* Sets the id of the Behavior
*
* @param string $id The id of the behavior
- * @return $this
*/
- public function setId(string $id): Behavior
+ public function setId(string $id): void
{
$this->id = $id;
-
- return $this;
}
/**
@@ -149,16 +133,13 @@ public function allowMultiple(): bool
*
* @param string $name
* @param mixed $value
- * @return $this
*/
- public function setParameter(string $name, $value): Behavior
+ public function setParameter(string $name, $value): void
{
//Don't want override a default parameter with a null value
if (null !== $value) {
$this->parameters->set(strtolower($name), $value);
}
-
- return $this;
}
/**
@@ -168,13 +149,10 @@ public function setParameter(string $name, $value): Behavior
* ['name' => 'foo', 'value' => 'bar']
*
* @param array $parameter
- * @return $this
*/
- public function addParameter(array $parameter): Behavior
+ public function addParameter(array $parameter): void
{
$this->parameters->set(strtolower($parameter['name']), $parameter['value']);
-
- return $this;
}
/**
@@ -183,14 +161,11 @@ public function addParameter(array $parameter): Behavior
* Expects an associative array looking like [ 'foo' => 'bar' ].
*
* @param array $parameters
- * @return $this
*/
- public function setParameters(array $parameters): Behavior
+ public function setParameters(array $parameters): void
{
$this->parameters->clear();
$this->parameters->setAll($parameters);
-
- return $this;
}
/**
@@ -219,11 +194,11 @@ public function getParameter(string $name)
/**
* Returns the associative array of parameters.
*
- * @return array
+ * @return Map
*/
- public function getParameters(): array
+ public function getParameters(): Map
{
- return $this->parameters->toArray();
+ return $this->parameters;
}
/**
@@ -234,13 +209,10 @@ public function getParameters(): array
* Default is 50.
*
* @param integer $entityModificationOrder
- * @return $this
*/
- public function setEntityModificationOrder(int $entityModificationOrder): Behavior
+ public function setEntityModificationOrder(int $entityModificationOrder): void
{
$this->entityModificationOrder = $entityModificationOrder;
-
- return $this;
}
/**
@@ -264,14 +236,14 @@ public function getEntityModificationOrder(): int
* Propagates the behavior to the entities of the database and override this
* method to have a database behavior do something special.
*/
- public function modifyDatabase()
+ public function modifyDatabase(): void
{
foreach ($this->getEntities() as $entity) {
if ($entity->hasBehavior($this->getId())) {
// don't add the same behavior twice
continue;
}
- $behavior = clone $this;
+ $behavior = deep_copy($this);
$entity->addBehavior($behavior);
}
}
@@ -279,9 +251,9 @@ public function modifyDatabase()
/**
* Returns the list of all entities in the same database.
*
- * @return Entity[] A collection of Entity instance
+ * @return Set A collection of Entity instance
*/
- protected function getEntities(): array
+ protected function getEntities(): Set
{
return $this->database->getEntities();
}
@@ -299,12 +271,10 @@ public function modifyEntity()
* Sets whether or not the entity has been modified.
*
* @param bool $modified
- * @return $this
*/
- public function setEntityModified(bool $modified): Behavior
+ public function setEntityModified(bool $modified): void
{
$this->isEntityModified = $modified;
- return $this;
}
/**
@@ -326,7 +296,7 @@ public function isEntityModified(): bool
*/
public function getFieldForParameter(string $name): Field
{
- return $this->entity->getField($this->getParameter($name));
+ return $this->entity->getFieldByName($this->getParameter($name));
}
/**
diff --git a/src/Generator/Model/CrossRelation.php b/src/Generator/Model/CrossRelation.php
index 07137e7f..cc2fa4d9 100644
--- a/src/Generator/Model/CrossRelation.php
+++ b/src/Generator/Model/CrossRelation.php
@@ -1,5 +1,4 @@
-setName($name);
- }
+ $this->setName($name);
if (null !== $platform) {
$this->setPlatform($platform);
@@ -82,8 +72,8 @@ public function __construct(?string $name = null, ?PlatformInterface $platform =
// init
$this->sequences = new ArrayList();
- $this->domains = new Map([], Domain::class);
- $this->entities = new Set([], Entity::class);
+ $this->domains = new Map();
+ $this->entities = new Set();
$this->initBehaviors();
$this->initSql();
$this->initVendor();
@@ -93,43 +83,22 @@ public function __construct(?string $name = null, ?PlatformInterface $platform =
$this->identifierQuoting = false;
}
- public function __clone()
- {
- $this->domains = clone $this->domains;
- $this->entities = clone $this->entities;
- $this->sequences = clone $this->sequences;
- if (null !== $this->generatorConfig) {
- $this->generatorConfig = clone $this->generatorConfig;
- }
- if (null !== $this->platform) {
- $this->platform = clone $this->platform;
- }
- $this->idMethodParameters = clone $this->idMethodParameters;
- $this->behaviors = clone $this->behaviors;
- if (null !== $this->schema) {
- $this->schema = clone $this->schema;
- }
- if (null !== $this->vendor) {
- $this->vendor = clone $this->vendor;
- }
- }
-
/**
* @return Schema
*/
protected function getSuperordinate(): ?Schema
{
- return $this->schema;
+ return $this->getSchema();
}
/**
* Return the list of all entities.
*
- * @return Entity[]
+ * @return Set
*/
- public function getEntities(): array
+ public function getEntities(): Set
{
- return $this->entities->toArray();
+ return $this->entities;
}
/**
@@ -137,7 +106,7 @@ public function getEntities(): array
*
* @return int
*/
- public function getEntitySize()
+ public function getEntitySize(): int
{
return $this->entities->size();
}
@@ -151,26 +120,17 @@ public function getEntitySize()
*/
public function countEntities(): int
{
- $count = 0;
- foreach ($this->entities as $entity) {
- if (!$entity->isReadOnly()) {
- $count++;
- }
- }
-
- return $count;
+ return $this->entities->findAll(fn(Entity $element) => !$element->isReadOnly())->count();
}
/**
* Returns the list of all entities that have a SQL representation.
*
- * @return Entity[]
+ * @return Set
*/
- public function getEntitiesForSql(): array
+ public function getEntitiesForSql(): Set
{
- return $this->entities->filter(function (Entity $entity) {
- return !$entity->isSkipSql();
- })->toArray();
+ return $this->entities->filter(fn(Entity $entity) => !$entity->isSkipSql());
}
/**
@@ -189,11 +149,11 @@ public function hasEntity(Entity $entity): bool
*
* @return bool
*/
- public function hasEntityByName($name): bool
+ public function hasEntityByName(string $name): bool
{
- return $this->entities->search($name, function (Entity $entity, $query) {
- return $entity->getName() === $query;
- });
+ return $this->entities->search($name,
+ fn(Entity $entity, string $query): bool => $entity->getName()->toString() === $query
+ );
}
/**
@@ -201,11 +161,11 @@ public function hasEntityByName($name): bool
*
* @return Entity
*/
- public function getEntityByName($name): ?Entity
+ public function getEntityByName(string $name): ?Entity
{
- return $this->entities->find($name, function (Entity $entity, $query) {
- return $entity->getName() === $query;
- });
+ return $this->entities->find($name,
+ fn(Entity $entity, string $query): bool => $entity->getName()->toString() === $query
+ );
}
/**
@@ -213,11 +173,11 @@ public function getEntityByName($name): ?Entity
*
* @return bool
*/
- public function hasEntityByFullName($fullName): bool
+ public function hasEntityByFullName(string $fullName): bool
{
- return $this->entities->search($fullName, function (Entity $entity, $query) {
- return $entity->getFullName() === $query;
- });
+ return $this->entities->search($fullName,
+ fn(Entity $entity, string $query): bool => $entity->getFullName()->toString() === $query
+ );
}
/**
@@ -225,11 +185,11 @@ public function hasEntityByFullName($fullName): bool
*
* @return Entity
*/
- public function getEntityByFullName($fullName): ?Entity
+ public function getEntityByFullName(string $fullName): ?Entity
{
- return $this->entities->find($fullName, function (Entity $entity, $query) {
- return $entity->getFullName() === $query;
- });
+ return $this->entities->find($fullName,
+ fn(Entity $entity, string $query): bool => $entity->getFullName()->toString() === $query
+ );
}
/**
@@ -237,11 +197,11 @@ public function getEntityByFullName($fullName): ?Entity
*
* @return bool
*/
- public function hasEntityByTableName($tableName): bool
+ public function hasEntityByTableName(string $tableName): bool
{
- return (bool) $this->entities->find($tableName, function (Entity $entity, $query) {
- return $entity->getTableName() === $query;
- });
+ return $this->entities->search($tableName,
+ fn(Entity $entity, string $query): bool => $entity->getTableName()->toString() === $query
+ );
}
/**
@@ -249,11 +209,11 @@ public function hasEntityByTableName($tableName): bool
*
* @return Entity
*/
- public function getEntityByTableName($tableName): ?Entity
+ public function getEntityByTableName(string $tableName): ?Entity
{
- return $this->entities->find($tableName, function (Entity $entity, $query) {
- return $entity->getTableName() === $query;
- });
+ return $this->entities->find($tableName,
+ fn(Entity $entity, string $query): bool => $entity->getTableName()->toString() === $query
+ );
}
/**
@@ -261,11 +221,11 @@ public function getEntityByTableName($tableName): ?Entity
*
* @return bool
*/
- public function hasEntityByFullTableName($tableName): bool
+ public function hasEntityByFullTableName(string $tableName): bool
{
- return (bool) $this->entities->find($tableName, function (Entity $entity, $query) {
- return $entity->getFullTableName() === $query;
- });
+ return $this->entities->search($tableName,
+ fn(Entity $entity, string $query): bool => $entity->getFullTableName()->toString() === $query
+ );
}
/**
@@ -275,105 +235,73 @@ public function hasEntityByFullTableName($tableName): bool
*/
public function getEntityByFullTableName($tableName): ?Entity
{
- return $this->entities->find($tableName, function (Entity $entity, $query) {
- return $entity->getFullTableName() === $query;
- });
+ return $this->entities->find($tableName,
+ fn(Entity $entity, string $query): bool => $entity->getFullTableName()->toString() === $query
+ );
}
/**
- * @TODO is this needed? -> array_map($db->getEntities(), fn {....});
- * @return string[]
+ * @return Text[]
*/
public function getEntityNames(): array
{
- return $this->entities->map(function (Entity $entity) {
- return $entity->getName();
- })->toArray();
+ return $this->entities->map(fn(Entity $entity): Text => $entity->getName())->toArray();
}
/**
* Adds a new entity to this database.
*
* @param Entity $entity
- * @return $this
*/
- public function addEntity(Entity $entity): Database
+ public function addEntity(Entity $entity): void
{
- if (!$this->entities->contains($entity)) {
- $this->entities->add($entity);
+ if ($entity->getDatabase() !== $this) {
$entity->setDatabase($this);
}
-
- return $this;
+ $this->entities->add($entity);
}
- public function removeEntity(Entity $entity): Database
+ public function removeEntity(Entity $entity): void
{
$this->entities->remove($entity);
-
- return $this;
}
/**
* Adds several entities at once.
*
* @param Entity[] $entities An array of Entity instances
- * @return $this
*/
- public function addEntities(array $entities): Database
+ public function addEntities(array $entities): void
{
foreach ($entities as $entity) {
$this->addEntity($entity);
}
- return $this;
}
- /**
- * @param string[] $sequences
- * @return $this
- */
- public function setSequences(array $sequences): Database
+ public function setSequences(array $sequences): void
{
$this->sequences->clear();
- $this->sequences->addAll($sequences);
- return $this;
+ $this->sequences->add(...$sequences);
}
- /**
- * @return string[]
- */
- public function getSequences(): array
+ public function getSequences(): ArrayList
{
- return $this->sequences->toArray();
+ return $this->sequences;
}
- /**
- * @param string $sequence
- * @return $this
- */
- public function addSequence(string $sequence): Database
+ public function addSequence(string $sequence): void
{
$this->sequences->add($sequence);
- return $this;
}
- /**
- * @param string $sequence
- * @return bool
- */
public function hasSequence(string $sequence): bool
{
return $this->sequences->contains($sequence);
}
- /**
- * @param string $sequence
- * @return $this
- */
- public function removeSequence(string $sequence): Database
+ public function removeSequence(string $sequence): void
{
$this->sequences->remove($sequence);
- return $this;
}
// /**
@@ -441,7 +369,7 @@ public function removeSequence(string $sequence): Database
*
* @param Schema $schema The parent schema
*/
- protected function registerSchema(Schema $schema)
+ protected function registerSchema(Schema $schema): void
{
$schema->addDatabase($this);
}
@@ -460,15 +388,13 @@ protected function unregisterSchema(Schema $schema)
* Adds a domain object to this database.
*
* @param Domain $domain
- * @return $this
*/
- public function addDomain(Domain $domain): Database
+ public function addDomain(Domain $domain): void
{
if (!$this->domains->contains($domain)) {
$domain->setDatabase($this);
$this->domains->set($domain->getName(), $domain);
}
- return $this;
}
/**
@@ -488,7 +414,7 @@ public function getDomain(string $name): ?Domain
*
* @return Behavior
*/
- public function getNextEntityBehavior()
+ public function getNextEntityBehavior(): ?Behavior
{
// order the behaviors according to Behavior::$entityModificationOrder
$behaviors = [];
@@ -511,7 +437,7 @@ public function getNextEntityBehavior()
/**
* @param Behavior $behavior
*/
- protected function registerBehavior(Behavior $behavior)
+ protected function registerBehavior(Behavior $behavior): void
{
$behavior->setDatabase($this);
}
@@ -519,7 +445,7 @@ protected function registerBehavior(Behavior $behavior)
/**
* @param Behavior $behavior
*/
- protected function unregisterBehavior(Behavior $behavior)
+ protected function unregisterBehavior(Behavior $behavior): void
{
$behavior->setDatabase(null);
}
@@ -529,6 +455,8 @@ public function __toString(): string
return $this->toSql();
}
+
+ //@todo remove: use a template to render this inside the function that need it
/**
* @return string
*/
diff --git a/src/Generator/Model/Diff/DatabaseComparator.php b/src/Generator/Model/Diff/DatabaseComparator.php
index f456a68e..37499b57 100644
--- a/src/Generator/Model/Diff/DatabaseComparator.php
+++ b/src/Generator/Model/Diff/DatabaseComparator.php
@@ -1,5 +1,4 @@
-databaseDiff = (null === $databaseDiff) ? new DatabaseDiff() : $databaseDiff;
+ $this->databaseDiff = $databaseDiff ?? new DatabaseDiff();
$this->excludedEntities = new Set();
}
@@ -76,17 +54,6 @@ public function setFromDatabase(Database $fromDatabase): void
$this->fromDatabase = $fromDatabase;
}
- //@todo never used: remove?
- /**
- * Returns the fromDatabase property.
- *
- * @return Database
- */
-// public function getFromDatabase(): Database
-// {
-// return $this->fromDatabase;
-// }
-
/**
* Sets the toDatabase property.
*
@@ -97,17 +64,6 @@ public function setToDatabase(Database $toDatabase): void
$this->toDatabase = $toDatabase;
}
- //@todo never used: remove?
- /**
- * Returns the toDatabase property.
- *
- * @return Database
- */
-// public function getToDatabase(): Database
-// {
-// return $this->toDatabase;
-// }
-
/**
* Set true to handle removed tables or false to ignore them
*
@@ -129,15 +85,12 @@ public function getRemoveEntity(): bool
/**
* Set the list of tables excluded from the comparison
*
- * @param Set $excludedEntities set the list of table name
+ * @param array $excludedEntities set the list of table name
*/
- public function setExcludedEntities(?Set $excludedEntities): void
+ public function addExcludedEntities(?array $excludedEntities = null): void
{
- if (null === $excludedEntities) {
- $excludedEntities = [];
- }
- $this->excludedEntities->clear();
- $this->excludedEntities->addAll($excludedEntities);
+ $excludedEntities = $excludedEntities ?? [];
+ $this->excludedEntities->add(...$excludedEntities);
}
/**
@@ -153,11 +106,11 @@ public function getExcludedEntities(): Set
/**
* Returns the computed difference between two database objects.
*
- * @param Database $fromDatabase
- * @param Database $toDatabase
- * @param bool $withRenaming
- * @param bool $removeEntity
- * @param Set $excludedEntities Entities to exclude from the difference computation
+ * @param Database $fromDatabase
+ * @param Database $toDatabase
+ * @param bool $withRenaming
+ * @param bool $removeEntity
+ * @param array $excludedEntities Entities to exclude from the difference computation
*
* @return DatabaseDiff
*/
@@ -166,16 +119,16 @@ public static function computeDiff(
Database $toDatabase,
bool $withRenaming = false,
bool $removeEntity = true,
- ?Set $excludedEntities = null): ?DatabaseDiff
+ ?array $excludedEntities = null): ?DatabaseDiff
{
$databaseComparator = new self();
$databaseComparator->setFromDatabase($fromDatabase);
$databaseComparator->setToDatabase($toDatabase);
$databaseComparator->setWithRenaming($withRenaming);
$databaseComparator->setRemoveEntity($removeEntity);
- $databaseComparator->setExcludedEntities($excludedEntities);
+ $databaseComparator->addExcludedEntities($excludedEntities);
- $platform = $toDatabase->getPlatform() ?: $fromDatabase->getPlatform();
+ $platform = $toDatabase->getPlatform() ?? $fromDatabase->getPlatform();
if ($platform) {
foreach ($fromDatabase->getEntities() as $table) {
@@ -224,11 +177,11 @@ public function compareEntities(): int
// check for new tables in $toDatabase
foreach ($toDatabaseEntities as $table) {
- if ($this->excludedEntities->contains($table->getName())) {
+ if ($this->excludedEntities->contains($table->getName()->toString())) {
continue;
}
- if (!$this->fromDatabase->hasEntityByName($table->getName()) && !$table->isSkipSql()) {
- $this->databaseDiff->getAddedEntities()->set($table->getName(), $table);
+ if (!$this->fromDatabase->hasEntityByName($table->getName()->toString()) && !$table->isSkipSql()) {
+ $this->databaseDiff->getAddedEntities()->set($table->getName()->toString(), $table);
$databaseDifferences++;
}
}
@@ -236,11 +189,11 @@ public function compareEntities(): int
// check for removed tables in $toDatabase
if ($this->getRemoveEntity()) {
foreach ($fromDatabaseEntities as $table) {
- if ($this->excludedEntities->contains($table->getName())) {
+ if ($this->excludedEntities->contains($table->getName()->toString())) {
continue;
}
- if (!$this->toDatabase->hasEntityByName($table->getName()) && !$table->isSkipSql()) {
- $this->databaseDiff->getRemovedEntities()->set($table->getName(), $table);
+ if (!$this->toDatabase->hasEntityByName($table->getName()->toString()) && !$table->isSkipSql()) {
+ $this->databaseDiff->getRemovedEntities()->set($table->getName()->toString(), $table);
$databaseDifferences++;
}
}
@@ -248,14 +201,14 @@ public function compareEntities(): int
// check for table differences
foreach ($fromDatabaseEntities as $fromEntity) {
- if ($this->excludedEntities->contains($fromEntity->getName())) {
+ if ($this->excludedEntities->contains($fromEntity->getName()->toString())) {
continue;
}
- if ($this->toDatabase->hasEntityByName($fromEntity->getName())) {
- $toEntity = $this->toDatabase->getEntityByName($fromEntity->getName());
+ if ($this->toDatabase->hasEntityByName($fromEntity->getName()->toString())) {
+ $toEntity = $this->toDatabase->getEntityByName($fromEntity->getName()->toString());
$databaseDiff = EntityComparator::computeDiff($fromEntity, $toEntity);
if (null !== $databaseDiff) {
- $this->databaseDiff->getModifiedEntities()->set($fromEntity->getName(), $databaseDiff);
+ $this->databaseDiff->getModifiedEntities()->set($fromEntity->getName()->toString(), $databaseDiff);
$databaseDifferences++;
}
}
diff --git a/src/Generator/Model/Diff/DatabaseDiff.php b/src/Generator/Model/Diff/DatabaseDiff.php
index 76e93173..5e1dd0d2 100644
--- a/src/Generator/Model/Diff/DatabaseDiff.php
+++ b/src/Generator/Model/Diff/DatabaseDiff.php
@@ -1,5 +1,4 @@
-addedEntities = new Map();
- $this->removedEntities = new Map();
+ $this->addedEntities = new Map();
+ $this->removedEntities = new Map();
$this->modifiedEntities = new Map();
- $this->renamedEntities = new Map();
- $this->possibleRenamedEntities = new Map();
+ $this->renamedEntities = new Map();
+ $this->possibleRenamedEntities = new Map();
}
- /**
- * @return Map
- */
public function getPossibleRenamedEntities(): Map
{
return $this->possibleRenamedEntities;
diff --git a/src/Generator/Model/Diff/EntityComparator.php b/src/Generator/Model/Diff/EntityComparator.php
index 3a9c680a..4aa1d1f0 100644
--- a/src/Generator/Model/Diff/EntityComparator.php
+++ b/src/Generator/Model/Diff/EntityComparator.php
@@ -1,5 +1,4 @@
-tableDiff = (null === $tableDiff) ? new EntityDiff() : $tableDiff;
+ $this->tableDiff = $tableDiff ?? new EntityDiff();
}
/**
@@ -127,27 +122,27 @@ public function compareFields(): int
// check for new columns in $toEntity
foreach ($toEntityFields as $column) {
- if (!$this->getFromEntity()->hasField($column->getName())) {
- $this->tableDiff->getAddedFields()->set($column->getName(), $column);
+ if (!$this->getFromEntity()->hasFieldByName($column->getName()->toString())) {
+ $this->tableDiff->getAddedFields()->set($column->getName()->toString(), $column);
$columnDifferences++;
}
}
// check for removed columns in $toEntity
foreach ($fromEntityFields as $column) {
- if (!$this->getToEntity()->hasField($column->getName())) {
- $this->tableDiff->getRemovedFields()->set($column->getName(), $column);
+ if (!$this->getToEntity()->hasFieldByName($column->getName()->toString())) {
+ $this->tableDiff->getRemovedFields()->set($column->getName()->toString(), $column);
$columnDifferences++;
}
}
// check for column differences
foreach ($fromEntityFields as $fromField) {
- if ($this->getToEntity()->hasField($fromField->getName())) {
- $toField = $this->getToEntity()->getField($fromField->getName());
+ if ($this->getToEntity()->hasFieldByName($fromField->getName()->toString())) {
+ $toField = $this->getToEntity()->getFieldByName($fromField->getName()->toString());
$columnDiff = FieldComparator::computeDiff($fromField, $toField);
if (null !== $columnDiff) {
- $this->tableDiff->getModifiedFields()->set($fromField->getName(), $columnDiff);
+ $this->tableDiff->getModifiedFields()->set($fromField->getName()->toString(), $columnDiff);
$columnDifferences++;
}
}
@@ -187,8 +182,8 @@ public function comparePrimaryKeys(): int
// check for new pk columns in $toEntity
foreach ($toEntityPk as $column) {
- if (!$this->getFromEntity()->hasField($column->getName()) ||
- !$this->getFromEntity()->getField($column->getName())->isPrimaryKey()) {
+ if (!$this->getFromEntity()->hasFieldByName($column->getName()->toString()) ||
+ !$this->getFromEntity()->getFieldByName($column->getName()->toString())->isPrimaryKey()) {
$this->tableDiff->getAddedPkFields()->set($column->getName(), $column);
$pkDifferences++;
}
@@ -196,8 +191,8 @@ public function comparePrimaryKeys(): int
// check for removed pk columns in $toEntity
foreach ($fromEntityPk as $column) {
- if (!$this->getToEntity()->hasField($column->getName()) ||
- !$this->getToEntity()->getField($column->getName())->isPrimaryKey()) {
+ if (!$this->getToEntity()->hasFieldByName($column->getName()->toString()) ||
+ !$this->getToEntity()->getFieldByName($column->getName()->toString())->isPrimaryKey()) {
$this->tableDiff->getRemovedPkFields()->set($column->getName(), $column);
$pkDifferences++;
}
@@ -232,14 +227,14 @@ public function comparePrimaryKeys(): int
public function compareIndices(): int
{
$indexDifferences = 0;
- $fromEntityIndices = array_merge($this->getFromEntity()->getIndices(), $this->getFromEntity()->getUnices());
- $toEntityIndices = array_merge($this->getToEntity()->getIndices(), $this->getToEntity()->getUnices());
+ $fromEntityIndices = array_merge($this->getFromEntity()->getIndices()->toArray(), $this->getFromEntity()->getUnices()->toArray());
+ $toEntityIndices = array_merge($this->getToEntity()->getIndices()->toArray(), $this->getToEntity()->getUnices()->toArray());
/** @var Index $fromEntityIndex */
foreach ($fromEntityIndices as $fromEntityIndexPos => $fromEntityIndex) {
/** @var Index $toEntityIndex */
foreach ($toEntityIndices as $toEntityIndexPos => $toEntityIndex) {
- if ($fromEntityIndex->getName() === $toEntityIndex->getName()) {
+ if ($fromEntityIndex->getName()->compare($toEntityIndex->getName()) === 0) {
if (false === IndexComparator::computeDiff($fromEntityIndex, $toEntityIndex)) {
//no changes
unset($fromEntityIndices[$fromEntityIndexPos]);
@@ -282,17 +277,17 @@ public function compareRelations(): int
$fromEntityFks = $this->getFromEntity()->getRelations();
$toEntityFks = $this->getToEntity()->getRelations();
- foreach ($fromEntityFks as $fromEntityFkPos => $fromEntityFk) {
- foreach ($toEntityFks as $toEntityFkPos => $toEntityFk) {
- if ($fromEntityFk->getName() === $toEntityFk->getName()) {
+ foreach ($fromEntityFks as $fromEntityFk) {
+ foreach ($toEntityFks as $toEntityFk) {
+ if ($fromEntityFk->getName()->compare($toEntityFk->getName()) === 0) {
if (false === RelationComparator::computeDiff($fromEntityFk, $toEntityFk)) {
- unset($fromEntityFks[$fromEntityFkPos]);
- unset($toEntityFks[$toEntityFkPos]);
+ $fromEntityFks->remove($fromEntityFk);
+ $toEntityFks->remove($toEntityFk);
} else {
// same name, but different columns
$this->tableDiff->getModifiedFks()->set($fromEntityFk->getName(), [$fromEntityFk, $toEntityFk]);
- unset($fromEntityFks[$fromEntityFkPos]);
- unset($toEntityFks[$toEntityFkPos]);
+ $fromEntityFks->remove($fromEntityFk);
+ $toEntityFks->remove($toEntityFk);
$fkDifferences++;
}
}
@@ -300,14 +295,14 @@ public function compareRelations(): int
}
foreach ($fromEntityFks as $fromEntityFk) {
- if (!$fromEntityFk->isSkipSql() && !in_array($fromEntityFk, $toEntityFks)) {
+ if (!$fromEntityFk->isSkipSql() && !$toEntityFks->contains($fromEntityFk)) {
$this->tableDiff->getRemovedFks()->set($fromEntityFk->getName(), $fromEntityFk);
$fkDifferences++;
}
}
foreach ($toEntityFks as $toEntityFk) {
- if (!$toEntityFk->isSkipSql() && !in_array($toEntityFk, $fromEntityFks)) {
+ if (!$toEntityFk->isSkipSql() && !$fromEntityFks->contains($toEntityFk)) {
$this->tableDiff->getAddedFks()->set($toEntityFk->getName(), $toEntityFk);
$fkDifferences++;
}
diff --git a/src/Generator/Model/Diff/EntityDiff.php b/src/Generator/Model/Diff/EntityDiff.php
index ea9d82b7..62d0e0da 100644
--- a/src/Generator/Model/Diff/EntityDiff.php
+++ b/src/Generator/Model/Diff/EntityDiff.php
@@ -1,5 +1,4 @@
-hasRenamedFields()) {
$renamedFields = [];
foreach ($this->renamedFields as $columnRenaming) {
- $renamedFields[$columnRenaming[1]->getName()] = array_reverse($columnRenaming);
+ $renamedFields[$columnRenaming[1]->getName()->toString()] = array_reverse($columnRenaming);
}
$diff->setRenamedFields(new Map($renamedFields));
}
@@ -728,7 +721,7 @@ public function getReverseDiff(): EntityDiff
if ($this->hasRenamedPkFields()) {
$renamedPkFields = [];
foreach ($this->renamedPkFields as $columnRenaming) {
- $renamedPkFields[$columnRenaming[1]->getName()] = array_reverse($columnRenaming);
+ $renamedPkFields[$columnRenaming[1]->getName()->toString()] = array_reverse($columnRenaming);
}
$diff->setRenamedPkFields(new Map($renamedPkFields));
}
@@ -814,7 +807,7 @@ public function __toString(): string
if ($renamedFields = $this->getRenamedFields()) {
$ret .= " renamedFields:\n";
foreach ($renamedFields as $columnRenaming) {
- list($fromField, $toField) = $columnRenaming;
+ [$fromField, $toField] = $columnRenaming;
$ret .= sprintf(" %s: %s\n", $fromField->getName(), $toField->getName());
}
}
@@ -856,7 +849,7 @@ public function __toString(): string
* @var Relation $fromFk
* @var Relation $toFk
*/
- list($fromFk, $toFk) = $fkFromTo;
+ [$fromFk, $toFk] = $fkFromTo;
$fromLocalFields = Json::encode($fromFk->getLocalFields()->toArray());
$toLocalFields = Json::encode($toFk->getLocalFields()->toArray());
diff --git a/src/Generator/Model/Diff/FieldComparator.php b/src/Generator/Model/Diff/FieldComparator.php
index 623346a0..5669a1da 100644
--- a/src/Generator/Model/Diff/FieldComparator.php
+++ b/src/Generator/Model/Diff/FieldComparator.php
@@ -1,5 +1,4 @@
-fromField->getFullName());
$ret .= " modifiedProperties:\n";
foreach ($this->changedProperties as $key => $value) {
- $ret .= sprintf(" %s: %s\n", $key, json_encode($value));
+ $ret .= sprintf(" %s: %s\n", $key, Json::encode($value));
}
return $ret;
diff --git a/src/Generator/Model/Diff/IndexComparator.php b/src/Generator/Model/Diff/IndexComparator.php
index e78f1b31..af3c0c12 100644
--- a/src/Generator/Model/Diff/IndexComparator.php
+++ b/src/Generator/Model/Diff/IndexComparator.php
@@ -1,5 +1,4 @@
-getFields();
$i = 0;
foreach ($fromIndexFields as $indexField) {
- if (!$toIndex->hasFieldAtPosition($i, $indexField->getName(), $indexField->getSize())) {
+ if (!$toIndex->hasFieldAtPosition($i, (string) $indexField->getName(), $indexField->getSize())) {
return true;
}
$i++;
@@ -44,7 +41,7 @@ public static function computeDiff(Index $fromIndex, Index $toIndex): bool
$toIndexFields = $toIndex->getFields();
$i = 0;
foreach ($toIndexFields as $indexField) {
- if (!$fromIndex->hasFieldAtPosition($i, $indexField->getName(), $indexField->getSize())) {
+ if (!$fromIndex->hasFieldAtPosition($i, (string) $indexField->getName(), $indexField->getSize())) {
return true;
}
$i++;
diff --git a/src/Generator/Model/Diff/RelationComparator.php b/src/Generator/Model/Diff/RelationComparator.php
index 94a5de15..dc33e419 100644
--- a/src/Generator/Model/Diff/RelationComparator.php
+++ b/src/Generator/Model/Diff/RelationComparator.php
@@ -1,5 +1,4 @@
-getEntityName() !== $toFk->getEntityName()) {
+ if ($fromFk->getEntityName()->compare($toFk->getEntityName()) !== 0) {
return true;
}
@@ -41,37 +38,17 @@ public static function computeDiff(Relation $fromFk, Relation $toFk): bool
}
// compare columns
- $fromFkLocalFields = $fromFk->getLocalFields();
- $fromFkLocalFields = $fromFkLocalFields->sort();
- $toFkLocalFields = $toFk->getLocalFields();
- $toFkLocalFields = $toFkLocalFields->sort();
- //Why case insensitive comparison?
- $fromFkLocalFields = $fromFkLocalFields->map(function(string $element){
- return strtolower($element);
- });
- $toFkLocalFields = $toFkLocalFields->map(function(string $element){
- return strtolower($element);
- });
+ $fromFkLocalFields = $fromFk->getLocalFields()->sort()->map("strtolower");
+ $toFkLocalFields = $toFk->getLocalFields()->sort()->map("strtolower");
- if ($fromFkLocalFields != $toFkLocalFields) {
+ if ($fromFkLocalFields->toArray() !== $toFkLocalFields->toArray()) {
return true;
}
- $fromFkForeignFields = $fromFk->getForeignFields();
- $fromFkForeignFields = $fromFkForeignFields->sort();
- $toFkForeignFields = $toFk->getForeignFields();
- $toFkForeignFields = $toFkForeignFields->sort();
- //Why case insensitive comparison?
- $fromFkForeignFields = $fromFkForeignFields->map(function(string $element){
- return strtolower($element);
- });
- $toFkForeignFields = $toFkForeignFields->map(function(string $element){
- return strtolower($element);
- });
-
-
+ $fromFkForeignFields = $fromFk->getForeignFields()->sort()->map("strtolower");
+ $toFkForeignFields = $toFk->getForeignFields()->sort()->map("strtolower");
- if ($fromFkForeignFields != $toFkForeignFields) {
+ if ($fromFkForeignFields->toArray() !== $toFkForeignFields->toArray()) {
return true;
}
diff --git a/src/Generator/Model/Domain.php b/src/Generator/Model/Domain.php
index a4fa418e..f8a4be89 100644
--- a/src/Generator/Model/Domain.php
+++ b/src/Generator/Model/Domain.php
@@ -1,4 +1,4 @@
-defaultValue = $domain->getDefaultValue();
$this->description = $domain->getDescription();
$this->name = $domain->getName();
- $this->scale = $domain->getScale();
- $this->size = $domain->getSize();
$this->sqlType = $domain->getSqlType();
$this->mappingType = $domain->getType();
+ if (null !== $scale = $domain->getScale()) {
+ $this->scale = $scale;
+ }
+ if (null !== $size = $domain->getSize()) {
+ $this->size = $size;
+ }
}
/**
@@ -99,7 +96,7 @@ public function copy(Domain $domain)
*
* @return string
*/
- public function getDescription(): ?string
+ public function getDescription(): string
{
return $this->description;
}
@@ -109,7 +106,7 @@ public function getDescription(): ?string
*
* @param string $description
*/
- public function setDescription(string $description)
+ public function setDescription(string $description): void
{
$this->description = $description;
}
@@ -121,7 +118,7 @@ public function setDescription(string $description)
*/
public function getScale(): ?int
{
- return $this->scale;
+ return $this->scale ?? null;
}
/**
@@ -129,7 +126,7 @@ public function getScale(): ?int
*
* @param integer $scale
*/
- public function setScale(int $scale)
+ public function setScale(int $scale): void
{
$this->scale = $scale;
}
@@ -139,7 +136,7 @@ public function setScale(int $scale)
*
* @param integer $scale
*/
- public function replaceScale(int $scale)
+ public function replaceScale(int $scale): void
{
$this->setScale($scale);
}
@@ -151,7 +148,7 @@ public function replaceScale(int $scale)
*/
public function getSize(): ?int
{
- return $this->size;
+ return $this->size ?? null;
}
/**
@@ -159,7 +156,7 @@ public function getSize(): ?int
*
* @param integer $size
*/
- public function setSize(int $size)
+ public function setSize(int $size): void
{
$this->size = $size;
}
@@ -179,7 +176,7 @@ public function getType(): string
*
* @param string $mappingType
*/
- public function setType(string $mappingType)
+ public function setType(string $mappingType): void
{
$this->mappingType = $mappingType;
}
@@ -191,7 +188,7 @@ public function setType(string $mappingType)
*/
public function getDefaultValue(): ?FieldDefaultValue
{
- return $this->defaultValue;
+ return $this->defaultValue ?? null;
}
/**
@@ -225,7 +222,7 @@ public function getPhpDefaultValue()
*
* @param FieldDefaultValue $value
*/
- public function setDefaultValue(FieldDefaultValue $value)
+ public function setDefaultValue(FieldDefaultValue $value): void
{
$this->defaultValue = $value;
}
@@ -235,9 +232,9 @@ public function setDefaultValue(FieldDefaultValue $value)
*
* @return string
*/
- public function getSqlType(): ?string
+ public function getSqlType(): string
{
- if (null === $this->sqlType) {
+ if ('' === $this->sqlType) {
return $this->getType();
}
@@ -249,7 +246,7 @@ public function getSqlType(): ?string
*
* @param string $sqlType
*/
- public function setSqlType(string $sqlType)
+ public function setSqlType(string $sqlType): void
{
$this->sqlType = $sqlType;
}
@@ -259,7 +256,7 @@ public function setSqlType(string $sqlType)
*
* @param string $sqlType
*/
- public function replaceSqlType(string $sqlType)
+ public function replaceSqlType(string $sqlType): void
{
$this->setSqlType($sqlType);
$this->replaced = true;
@@ -272,11 +269,11 @@ public function replaceSqlType(string $sqlType)
*/
public function getSizeDefinition(): string
{
- if (null === $this->size) {
+ if (!isset($this->size)) {
return '';
}
- if (null !== $this->scale) {
+ if (isset($this->scale)) {
return sprintf('(%u,%u)', $this->size, $this->scale);
}
@@ -288,31 +285,12 @@ public function isReplaced(): bool
return $this->replaced;
}
- public function __clone()
- {
- if ($this->defaultValue) {
- $this->defaultValue = clone $this->defaultValue;
- }
- }
-
- protected function getDefaultValueForArray(?string $stringValue): ?string
+ protected function getDefaultValueForArray(string $stringValue): ?Text
{
$stringValue = trim($stringValue);
+ $stringValue = $stringValue === '|' ? '' : $stringValue;
+ $textValues = Text::create($stringValue)->split(',')->map('trim')->join(' | ');
- if (empty($stringValue)) {
- return null;
- }
-
- $values = [];
- foreach (explode(',', $stringValue) as $v) {
- $values[] = trim($v);
- }
-
- $value = implode($values, ' | ');
- if (empty($value) || '|' === trim($value)) {
- return null;
- }
-
- return sprintf('||%s||', $value);
+ return $textValues->isEmpty() ? null : $textValues->ensureStart('||')->ensureEnd('||');
}
}
diff --git a/src/Generator/Model/Entity.php b/src/Generator/Model/Entity.php
index 06b58fca..74be6be6 100644
--- a/src/Generator/Model/Entity.php
+++ b/src/Generator/Model/Entity.php
@@ -1,5 +1,4 @@
- (Torque)
* @author Hugo Hamon (Propel)
* @author Thomas Gossmann
+ * @author Cristiano Cinotti
*/
class Entity
{
- use SuperordinatePart;
- use PlatformAccessorPart;
- use ActiveRecordPart;
- use ScopePart;
- use BehaviorPart;
- use NamespacePart;
- use SchemaNamePart;
- use SqlPart;
- use GeneratorPart;
- use VendorPart;
- use DatabasePart;
- use DescriptionPart;
- use FieldsPart;
+ use ActiveRecordPart, BehaviorPart, DatabasePart, DescriptionPart, FieldsPart, GeneratorPart, NamespacePart,
+ PlatformAccessorPart, SchemaNamePart, ScopePart, SqlPart, SuperordinatePart, VendorPart;
//
// Model properties
// ------------------------------------------------------------
- /** @var string */
- private $tableName;
-
- /** @var string */
- private $alias;
-
-
+ private Text $tableName;
+ private Text $alias;
//
// References to other models
// ------------------------------------------------------------
/** @var bool|string */
- private $repository;
-
- /** @var Field */
- private $inheritanceField;
-
-
+ private string $repository;
+ private Field $inheritanceField;
//
// Collections to other models
// ------------------------------------------------------------
-
- /** @var Set */
- private $relations;
-
- /** @var Set */
- private $referrers;
-
- /** @var Set */
- private $foreignEntityNames;
-
- /** @var Set */
- private $indices;
-
- /** @var Set */
- private $unices;
-
-
+ private Set $relations;
+ private Set $referrers;
+ private Set $indices;
+ private Set $unices;
//
// Database related options/properties
// ------------------------------------------------------------
-
- /** @var bool */
- private $allowPkInsert;
-
- /** @var bool */
- private $containsForeignPK = false;
+ private bool $allowPkInsert = false;
+ private bool $containsForeignPK = false;
/**
* Whether this entity is an implementation detail. Implementation details are entities that are only
* relevant in the current persister api, like implicit pivot tables in n-n relations, or foreign key columns.
* @var bool
*/
- private $implementationDetail = false;
-
- /** @var bool */
- private $needsTransactionInPostgres;
-
- /** @var bool */
- private $forReferenceOnly;
-
- /** @var bool */
- private $reloadOnInsert;
-
- /** @var bool */
- private $reloadOnUpdate;
-
+ private bool $implementationDetail = false;
+ private bool $needsTransactionInPostgres = false;
+ private bool $forReferenceOnly = false;
+ private bool $reloadOnInsert = false;
+ private bool $reloadOnUpdate = false;
//
// Generator options
// ------------------------------------------------------------
-
- /** @var bool */
- private $readOnly;
-
- /** @var bool */
- private $isAbstract;
-
- /** @var bool */
- private $skipSql;
+ private bool $readOnly = false;
+ private bool $isAbstract = false;
+ private bool $skipSql = false;
/**
* @TODO maybe move this to database related options/props section ;)
*
* @var bool
*/
- private $isCrossRef;
+ private bool $isCrossRef = false;
/**
@@ -159,63 +106,32 @@ class Entity
*
* @param string $name entity name
*/
- public function __construct($name = null)
+ public function __construct(string $name = null)
{
if ($name) {
$this->setName($name);
}
// init
- $this->relations = new Set([], Relation::class);
- $this->foreignEntityNames = new Set();
- $this->indices = new Set([], Index::class);
- $this->referrers = new Set([], Relation::class);
- $this->unices = new Set([], Unique::class);
+ $this->alias = new Text();
+ $this->relations = new Set();
+ $this->indices = new Set();
+ $this->referrers = new Set();
+ $this->tableName = new Text();
+ $this->unices = new Set();
$this->initFields();
$this->initBehaviors();
$this->initSql();
$this->initVendor();
-
- // default values
- $this->allowPkInsert = false;
- $this->isAbstract = false;
- $this->isCrossRef = false;
- $this->readOnly = false;
- $this->reloadOnInsert = false;
- $this->reloadOnUpdate = false;
- $this->skipSql = false;
- $this->forReferenceOnly = false;
- }
-
- public function __clone()
- {
- $this->fields = clone $this->fields;
- $this->behaviors = clone $this->behaviors;
- $this->idMethodParameters = clone $this->idMethodParameters;
- $this->vendor = clone $this->vendor;
- //Circular reference. Which strategy? Leave the reference to the original database
- //or set it to null?
- //$this->database = clone $this->database;
- $this->relations = clone $this->relations;
- $this->referrers = clone $this->referrers;
- $this->foreignEntityNames = clone $this->foreignEntityNames;
- $this->indices = clone $this->indices;
- $this->unices = clone $this->unices;
- foreach ($this->fields as $field) {
- if ($field->isInheritance()) {
- $this->inheritanceField = $field;
- break;
- }
- }
}
/**
* @inheritdoc
- * @return Database
+ * @return Database|null
*/
protected function getSuperordinate(): ?Database
{
- return $this->database;
+ return $this->getDatabase();
}
//
@@ -223,58 +139,56 @@ protected function getSuperordinate(): ?Database
// ------------------------------------------------------------
/**
- * @param string $tableName
- * @return $this
+ * @param string|Text $tableName
*/
- public function setTableName(string $tableName): Entity
+ public function setTableName($tableName): void
{
- $this->tableName = $tableName;
- return $this;
+ $this->tableName = new Text($tableName);
}
/**
* Returns the blank table name.
*
- * @return string
+ * @return Text
*/
- public function getTableName(): string
+ public function getTableName(): Text
{
- $tableName = !$this->tableName ? NamingTool::toSnakeCase($this->name) : $this->tableName;
+ if ($this->tableName->isEmpty()) {
+ $this->setTableName($this->getName()->toSnakeCase());
+ }
- return $tableName;
+ return $this->tableName;
}
/**
* The table name with database scope.
*
- * @return string
+ * @return Text
*/
- public function getScopedTableName(): string
+ public function getScopedTableName(): Text
{
- $tableName = !$this->tableName ? NamingTool::toSnakeCase($this->name) : $this->tableName;
- $scope = $this->getScope();
-
- if ($scope) {
- $tableName = $scope . $tableName;
- }
-
- return $tableName;
+ return $this->getTableName()->prepend($this->getScope());
}
/**
* Returns the scoped table name with possible schema.
*
- * @return string
+ * @return Text
*/
- public function getFullTableName(): string
+ public function getFullTableName(): Text
{
- $fqTableName = $this->getScopedTableName();
+ $delimiter = $this->getPlatform()->getSchemaDelimiter();
- if (null !== $schemaName = $this->getSchemaName()) {
- $fqTableName = "$schemaName{$this->getPlatform()->getSchemaDelimiter()}$fqTableName";
- }
+ return $this->getScopedTableName()
+ ->prepend($delimiter)
+ ->prepend($this->getSchemaName())
+ ->trimStart($delimiter) //if the schemaName is '', the delimiter is the first character and must be removed
+ ;
+ }
- return $fqTableName;
+ protected function getEntity(): self
+ {
+ return $this;
}
//
@@ -282,17 +196,17 @@ public function getFullTableName(): string
// ------------------------------------------------------------
/**
- * @param bool|string $repository
+ * @param string $repository
*/
- public function setRepository($repository)
+ public function setRepository(string $repository): void
{
$this->repository = $repository;
}
/**
- * @return bool|string
+ * @return string
*/
- public function getRepository()
+ public function getRepository(): string
{
return $this->repository;
}
@@ -301,17 +215,14 @@ public function getRepository()
* Set the database that contains this entity.
*
* @param Database $database
- * @return $this
*/
- public function setDatabase(Database $database): Entity
+ public function setDatabase(Database $database): void
{
- if ($this->database !== null && $this->database !== $database) {
+ if (isset($this->database) && $this->database !== $database) {
$this->database->removeEntity($this);
}
$this->database = $database;
$this->database->addEntity($this);
-
- return $this;
}
/**
@@ -321,18 +232,18 @@ public function setDatabase(Database $database): Entity
*/
public function getPlatform(): ?PlatformInterface
{
- return $this->database ? $this->database->getPlatform() : null;
+ return isset($this->database) ? $this->database->getPlatform() : null;
}
/**
* Returns the field that subclasses the class representing this
* entity can be produced from.
*
- * @return null|Field
+ * @return Field
*/
public function getChildrenField(): ?Field
{
- return $this->inheritanceField;
+ return $this->inheritanceField ?? null;
}
/**
@@ -342,7 +253,7 @@ public function getChildrenField(): ?Field
*/
public function getChildrenNames(): array
{
- if (null === $this->inheritanceField || !$this->inheritanceField->isEnumeratedClasses()) {
+ if (!isset($this->inheritanceField) || !$this->inheritanceField->isEnumeratedClasses()) {
return [];
}
@@ -354,38 +265,19 @@ public function getChildrenNames(): array
return $names;
}
-
-
//
// Collections to other models
// ------------------------------------------------------------
-
// behaviors
// -----------------------------------------
- /**
- * @TODO can it be externalized?
- *
- * Executes behavior entity modifiers.
- * This is only for testing purposes. Model\Database calls already `modifyEntity` on each behavior.
- */
- public function applyBehaviors()
- {
- foreach ($this->behaviors as $behavior) {
- if (!$behavior->isEntityModified()) {
- $behavior->getEntityModifier()->modifyEntity();
- $behavior->setEntityModified(true);
- }
- }
- }
-
- protected function registerBehavior(Behavior $behavior)
+ protected function registerBehavior(Behavior $behavior): void
{
$behavior->setEntity($this);
}
- protected function unregisterBehavior(Behavior $behavior)
+ protected function unregisterBehavior(Behavior $behavior): void
{
$behavior->setEntity(null);
}
@@ -400,13 +292,12 @@ protected function unregisterBehavior(Behavior $behavior)
* @param Field $field
*
* @throws EngineException
- * @return $this
*/
- public function addField(Field $field): Entity
+ public function addField(Field $field): void
{
//The field must be unique
- if (null !== $this->getFieldByName($field->getName())) {
- throw new EngineException(sprintf('Field "%s" declared twice in entity "%s"', $field->getName(), $this->getName()));
+ if ($this->hasFieldByName($field->getName()->toString())) {
+ throw new EngineException("Field `{$field->getName()}` declared twice in entity `{$this->getName()}`");
}
$field->setEntity($this);
@@ -421,41 +312,48 @@ public function addField(Field $field): Entity
if ($field->isInheritance()) {
$this->inheritanceField = $field;
}
-
- return $this;
}
/**
- * @TODO check consistency with naming size/num/count methods
- *
* Returns the number of fields in this entity.
*
* @return int
*/
- public function getNumFields(): int
+ public function countFields(): int
{
return $this->fields->size();
}
/**
- * @TODO check consistency with naming size/num/count methods
- *
+ * @deprecated Use `Entity::countFields()` instead
+ * @return int
+ */
+ public function getNumFields(): int
+ {
+ return $this->countFields();
+ }
+
+
+ /**
* Returns the number of lazy loaded fields in this entity.
*
* @return int
*/
- public function getNumLazyLoadFields(): int
+ public function countLazyLoadFields(): int
{
- $count = 0;
- foreach ($this->fields as $col) {
- if ($col->isLazyLoad()) {
- $count++;
- }
- }
+ return $this->fields->findAll(fn(Field $element): bool => $element->isLazyLoad())->count();
+ }
- return $count;
+ /**
+ * @deprecated Use `Entity::countLazyLoadFields()` instead
+ * @return int
+ */
+ public function getNumLazyLoadFields(): int
+ {
+ return $this->countLazyLoadFields();
}
+
/**
* Returns whether or not one of the fields is of type ENUM.
*
@@ -463,13 +361,7 @@ public function getNumLazyLoadFields(): int
*/
public function hasEnumFields(): bool
{
- foreach ($this->fields as $col) {
- if ($col->isEnumType()) {
- return true;
- }
- }
-
- return false;
+ return $this->fields->search(fn(Field $element): bool => $element->isEnumType());
}
// relations
@@ -479,17 +371,11 @@ public function hasEnumFields(): bool
* Adds a new relation to this entity.
*
* @param Relation $relation The relation
- *
- * @return $this
*/
- public function addRelation(Relation $relation): Entity
+ public function addRelation(Relation $relation): void
{
$relation->setEntity($this);
-
$this->relations->add($relation);
- $this->foreignEntityNames->add($relation->getForeignEntityName());
-
- return $this;
}
/**
@@ -521,7 +407,7 @@ public function hasRelations(): bool
*/
public function hasCrossRelations(): bool
{
- return count($this->getCrossRelations()) > 0;
+ return $this->getCrossRelations()->count() > 0;
}
/**
@@ -531,19 +417,19 @@ public function hasCrossRelations(): bool
*/
public function getRelation(string $fieldName): Relation
{
- return $this->relations->find($fieldName, function(Relation $element, string $query) {
- return $element->getName() === $query;
- });
+ return $this->relations->find($fieldName,
+ fn(Relation $element, string $query): bool => $element->getName()->toString() === $query
+ );
}
/**
* Returns the list of all foreign keys.
*
- * @return Relation[]
+ * @return Set
*/
- public function getRelations(): array
+ public function getRelations(): Set
{
- return $this->relations->toArray();
+ return $this->relations;
}
/**
@@ -552,13 +438,13 @@ public function getRelations(): array
*
* @param string $entityName
*
- * @return Relation[]
+ * @return Set
*/
- public function getRelationsReferencingEntity(string $entityName): array
+ public function getRelationsReferencingEntity(string $entityName): Set
{
- return $this->relations->filter(function (Relation $relation) use ($entityName) {
- return $relation->getForeignEntityName() === $entityName;
- })->toArray();
+ return $this->relations->findAll($entityName,
+ fn(Relation $relation, string $query): bool => $relation->getForeignEntityName() === $entityName
+ );
}
/**
@@ -570,40 +456,35 @@ public function getRelationsReferencingEntity(string $entityName): array
*
* @param string $fieldName Name of the field
*
- * @return Relation[]
+ * @return Set
*/
- public function getFieldRelations(string $fieldName): array
+ public function getFieldRelations(string $fieldName): Set
{
- return $this->relations->filter(function (Relation $relation) use ($fieldName) {
- return in_array($fieldName, $relation->getLocalFields()->toArray());
- })->toArray();
+ return $this->relations->findAll($fieldName,
+ fn(Relation $relation, string $query): bool => $relation->getLocalFields()->contains($fieldName)
+ );
}
/**
* Returns the list of cross relations.
- *
- * @return CrossRelation[]
*/
- public function getCrossRelations()
+ public function getCrossRelations(): Set
{
- $crossFks = [];
- foreach ($this->referrers as $refRelation) {
- if ($refRelation->getEntity()->isCrossRef()) {
+ return $this->referrers
+ ->filter(fn(Relation $element): bool => $element->getEntity()->isCrossRef())
+ ->map(function(Relation $refRelation): CrossRelation {
$crossRelation = new CrossRelation($refRelation, $this);
- /** @var Relation $relation */
foreach ($refRelation->getOtherFks() as $relation) {
if ($relation->isAtLeastOneLocalPrimaryKeyIsRequired() &&
$crossRelation->isAtLeastOneLocalPrimaryKeyNotCovered($relation)) {
$crossRelation->addRelation($relation);
}
}
- if ($crossRelation->hasRelations()) {
- $crossFks[] = $crossRelation;
- }
- }
- }
- return $crossFks;
+ return $crossRelation;
+ })
+ ->filter(fn(CrossRelation $element): bool => $element->hasRelations())
+ ;
}
/**
@@ -613,7 +494,7 @@ public function getCrossRelations()
*/
public function getForeignEntityNames(): Set
{
- return $this->foreignEntityNames;
+ return $this->relations->map(fn(Relation $element): string => $element->getForeignEntityName());
}
@@ -624,22 +505,20 @@ public function getForeignEntityNames(): Set
* Adds the foreign key from another entity that refers to this entity.
*
* @param Relation $relation
- * @return $this
*/
- public function addReferrer(Relation $relation): Entity
+ public function addReferrer(Relation $relation): void
{
$this->referrers->add($relation);
- return $this;
}
/**
* Returns the list of references to this entity.
*
- * @return Relation[]
+ * @return Set
*/
- public function getReferrers(): array
+ public function getReferrers(): Set
{
- return $this->referrers->toArray();
+ return $this->referrers;
}
@@ -671,12 +550,10 @@ public function createIndex(string $name, array $fields): Index
* @param Index $index
*
* @throw InvalidArgumentException
- *
- * @return $this
*/
- public function addIndex(Index $index): Entity
+ public function addIndex(Index $index): void
{
- if ($this->hasIndex($index->getName())) {
+ if ($this->hasIndex($index->getName()->toString())) {
throw new \InvalidArgumentException(sprintf('Index "%s" already exist.', $index->getName()));
}
@@ -686,10 +563,8 @@ public function addIndex(Index $index): Entity
$index->setEntity($this);
// @TODO $index->getName() ? we can do better here. Under investigation
-// $index->getName();
+ $index->getName(); // we call this method so that the name is created now if it doesn't already exist.
$this->indices->add($index);
-
- return $this;
}
/**
@@ -699,15 +574,9 @@ public function addIndex(Index $index): Entity
*
* @return bool
*/
- public function hasIndex($name): bool
+ public function hasIndex(string $name): bool
{
- foreach ($this->indices as $idx) {
- if ($idx->getName() == $name) {
- return true;
- }
- }
-
- return false;
+ return $this->indices->search($name, fn(Index $elem, string $query): bool => $elem->getName()->toString() === $name);
}
/**
@@ -718,11 +587,12 @@ public function hasIndex($name): bool
*/
public function isIndex(array $keys): bool
{
+ /** @var Index $index */
foreach ($this->indices as $index) {
if (count($keys) === $index->getFields()->size()) {
$allAvailable = true;
foreach ($keys as $key) {
- if (!$index->hasField($key instanceof Field ? $key->getName() : $key)) {
+ if (!$index->hasFieldByName($key instanceof Field ? $key->getName()->toString() : $key)) {
$allAvailable = false;
break;
}
@@ -739,33 +609,30 @@ public function isIndex(array $keys): bool
/**
* Returns the list of all indices of this entity.
*
- * @return Index[]
+ * @return Set
*/
- public function getIndices(): array
+ public function getIndices(): Set
{
- return $this->indices->toArray();
+ return $this->indices;
}
/**
* Removes an index off this entity
*
* @param Index|string $index
- * @return $this
*/
- public function removeIndex($index): Entity
+ public function removeIndex($index): void
{
if (is_string($index)) {
- $index = $this->indices->find($index, function (Index $index, string $query) {
- return $index->getName() === $query;
- });
+ $index = $this->indices->find($index,
+ fn(Index $index, string $query): bool => $index->getName()->toString() === $query
+ );
}
if ($index instanceof Index && $index->getEntity() === $this) {
$index->setEntity(null);
$this->indices->remove($index);
}
-
- return $this;
}
@@ -777,17 +644,13 @@ public function removeIndex($index): Entity
* parent entity of the field to the current entity.
*
* @param Unique $unique
- *
- * @return $this
*/
- public function addUnique(Unique $unique): Entity
+ public function addUnique(Unique $unique): void
{
$unique->setEntity($this);
$unique->getName(); // we call this method so that the name is created now if it doesn't already exist.
$this->unices->add($unique);
-
- return $this;
}
/**
@@ -801,7 +664,7 @@ public function addUnique(Unique $unique): Entity
public function isUnique(array $keys): bool
{
if (1 === count($keys)) {
- $field = $keys[0] instanceof Field ? $keys[0] : $this->getField($keys[0]);
+ $field = $keys[0] instanceof Field ? $keys[0] : $this->getFieldByName($keys[0]);
if ($field) {
if ($field->isUnique()) {
return true;
@@ -816,15 +679,14 @@ public function isUnique(array $keys): bool
// check if pk == $keys
if (count($this->getPrimaryKey()) === count($keys)) {
$allPk = true;
- $stringArray = is_string($keys[0]);
foreach ($this->getPrimaryKey() as $pk) {
- if ($stringArray) {
- if (!in_array($pk->getName(), $keys)) {
+ if (is_string($keys[0])) {
+ if (!in_array((string) $pk->getName(), $keys)) {
$allPk = false;
break;
}
} else {
- if (!in_array($pk, $keys)) {
+ if (!in_array($pk, $keys, true)) {
$allPk = false;
break;
}
@@ -841,7 +703,7 @@ public function isUnique(array $keys): bool
if (count($unique->getFields()->toArray()) === count($keys)) {
$allAvailable = true;
foreach ($keys as $key) {
- if (!$unique->hasField($key instanceof Field ? $key->getName() : $key)) {
+ if (!$unique->hasFieldByName($key instanceof Field ? (string) $key->getName() : $key)) {
$allAvailable = false;
break;
}
@@ -860,37 +722,32 @@ public function isUnique(array $keys): bool
/**
* Returns the list of all unique indices of this entity.
*
- * @return Unique[]
+ * @return Set
*/
- public function getUnices(): array
+ public function getUnices(): Set
{
- return $this->unices->toArray();
+ return $this->unices;
}
/**
* Removes an unique index off this entity
*
* @param Unique|string $unique
- * @return $this
*/
- public function removeUnique($unique): Entity
+ public function removeUnique($unique): void
{
if (is_string($unique)) {
- $unique = $this->unices->find($unique, function (Unique $index, string $query) {
- return $index->getName() == $query;
- });
+ $unique = $this->unices->find($unique,
+ fn(Unique $index, string $query): bool => $index->getName()->toString() === $query
+ );
}
if ($unique instanceof Unique && $unique->getEntity() === $this) {
$unique->setEntity(null);
$this->unices->remove($unique);
}
-
- return $this;
}
-
-
//
// Database related options/properties
// ------------------------------------------------------------
@@ -906,7 +763,7 @@ public function isImplementationDetail(): bool
/**
* @param bool $implementationDetail
*/
- public function setImplementationDetail(bool $implementationDetail)
+ public function setImplementationDetail(bool $implementationDetail): void
{
$this->implementationDetail = $implementationDetail;
}
@@ -921,31 +778,7 @@ public function requiresTransactionInPostgres(): bool
return $this->needsTransactionInPostgres;
}
- /**
- * @param bool $identifierQuoting
- * @return $this
- */
- public function setIdentifierQuoting(bool $identifierQuoting): Entity
- {
- $this->identifierQuoting = $identifierQuoting;
- return $this;
- }
-
- /**
- * Checks if identifierQuoting is enabled. Looks up to its database->isIdentifierQuotingEnabled
- * if identifierQuoting is null hence undefined.
- *
- * Use getIdentifierQuoting() if you need the raw value.
- *
- * @return bool
- */
- public function isIdentifierQuotingEnabled(): bool
- {
- return (null !== $this->identifierQuoting || !$this->database)
- ? $this->identifierQuoting
- : $this->database->isIdentifierQuotingEnabled();
- }
-
+ //@todo useful?
/**
* Quotes a identifier depending on identifierQuotingEnabled.
*
@@ -970,24 +803,14 @@ public function quoteIdentifier(string $text): string
return $text;
}
- /**
- * @return bool|null
- */
- public function getIdentifierQuoting(): ?bool
- {
- return $this->identifierQuoting;
- }
-
/**
* Makes this database reload on insert statement.
*
* @param bool $flag True by default
- * @return $this
*/
- public function setReloadOnInsert(bool $flag = true): Entity
+ public function setReloadOnInsert(bool $flag = true): void
{
$this->reloadOnInsert = $flag;
- return $this;
}
/**
@@ -1004,13 +827,10 @@ public function isReloadOnInsert(): bool
* Makes this database reload on update statement.
*
* @param bool $flag True by default
- * @return $this
*/
- public function setReloadOnUpdate(bool $flag = true): Entity
+ public function setReloadOnUpdate(bool $flag = true): void
{
$this->reloadOnUpdate = $flag;
-
- return $this;
}
/**
@@ -1028,12 +848,10 @@ public function isReloadOnUpdate(): bool
* Entity will be skipped, if set to true.
*
* @param bool $flag
- * @return $this
*/
- public function setForReferenceOnly(bool $flag = true): Entity
+ public function setForReferenceOnly(bool $flag = true): void
{
$this->forReferenceOnly = $flag;
- return $this;
}
/**
@@ -1074,12 +892,10 @@ public function isSkipSql(): bool
* Sets whether or not this entity should have its SQL DDL code generated.
*
* @param bool $skip
- * @return $this
*/
- public function setSkipSql(bool $skip): Entity
+ public function setSkipSql(bool $skip): void
{
$this->skipSql = $skip;
- return $this;
}
@@ -1094,9 +910,7 @@ public function setSkipSql(bool $skip): Entity
*/
public function getPrimaryKey(): array
{
- return $this->fields->filter(function (Field $field) {
- return $field->isPrimaryKey();
- })->toArray();
+ return $this->fields->filter(fn(Field $field): bool => $field->isPrimaryKey())->toArray();
}
/**
@@ -1122,29 +936,21 @@ public function hasCompositePrimaryKey(): bool
/**
* Returns the first primary key field.
*
- * Useful for entitys with a PK using a single field.
+ * Useful for entities with a PK using a single field.
*
* @return Field
*/
public function getFirstPrimaryKeyField(): ?Field
{
- foreach ($this->fields as $field) {
- if ($field->isPrimaryKey()) {
- return $field;
- }
- }
-
- return null;
+ return $this->fields->find(fn(Field $elem): bool => $elem->isPrimaryKey());
}
/**
* Sets whether or not this entity contains a foreign primary key.
*
* @param $containsForeignPK
- *
- * @return bool
*/
- public function setContainsForeignPK(bool $containsForeignPK)
+ public function setContainsForeignPK(bool $containsForeignPK): void
{
$this->containsForeignPK = $containsForeignPK;
}
@@ -1190,19 +996,12 @@ public function hasAutoIncrementPrimaryKey(): bool
return null !== $this->getAutoIncrementPrimaryKey();
}
- /**
- * @return string[]
- */
- public function getAutoIncrementFieldNames(): array
+ public function getAutoIncrementFieldNames(): Set
{
- $names = [];
- foreach ($this->getFields() as $field) {
- if ($field->isAutoIncrement()) {
- $names[] = $field->getName();
- }
- }
-
- return $names;
+ return $this->fields
+ ->filter(fn(Field $elem): bool => $elem->isAutoIncrement())
+ ->map(fn(Field $elem): Text => $elem->getName())
+ ;
}
/**
@@ -1230,17 +1029,9 @@ public function getAutoIncrementPrimaryKey(): ?Field
*/
public function hasAutoIncrement(): bool
{
- foreach ($this->getFields() as $field) {
- if ($field->isAutoIncrement()) {
- return true;
- }
- }
-
- return false;
+ return $this->fields->search(fn(Field $elem): bool => $elem->isAutoIncrement());
}
-
-
//
// Generator options
// ------------------------------------------------------------
@@ -1260,12 +1051,10 @@ public function isReadOnly(): bool
* Makes this database in read-only mode.
*
* @param bool $flag True by default
- * @return $this
*/
- public function setReadOnly(bool $flag = true): Entity
+ public function setReadOnly(bool $flag = true): void
{
$this->readOnly = $flag;
- return $this;
}
@@ -1289,24 +1078,20 @@ public function isAbstract(): bool
* declared abstract. This helps support class hierarchies
*
* @param bool $flag
- * @return $this
*/
- public function setAbstract(bool $flag = true): Entity
+ public function setAbstract(bool $flag = true): void
{
$this->isAbstract = $flag;
- return $this;
}
/**
* Sets a cross reference status for this foreign key.
*
* @param bool $flag
- * @return $this
*/
- public function setCrossRef(bool $flag = true): Entity
+ public function setCrossRef(bool $flag = true): void
{
$this->isCrossRef = $flag;
- return $this;
}
/**
@@ -1327,13 +1112,7 @@ public function isCrossRef(): bool
*/
public function hasAdditionalBuilders(): bool
{
- foreach ($this->behaviors as $behavior) {
- if ($behavior->hasAdditionalBuilders()) {
- return true;
- }
- }
-
- return false;
+ return $this->behaviors->search(fn(Behavior $elem): bool => $elem->hasAdditionalBuilders());
}
/**
@@ -1357,10 +1136,10 @@ public function getAdditionalBuilders(): array
/**
* Returns the schema name from this entity or from its database.
- *
- * @return string
+ * @deprecated Use `getSchemaName()` instead
+ * @return Text
*/
- public function guessSchemaName(): string
+ public function guessSchemaName(): Text
{
if (null === $this->schemaName) {
return $this->database->getSchema()->getName();
@@ -1376,8 +1155,8 @@ public function guessSchemaName(): string
*/
public function hasSchema(): bool
{
- return $this->database
- && ($this->database->getSchema() ?: $this->database->getSchema())
+ return $this->getDatabase()
+ && $this->database->getSchema()
&& ($platform = $this->getPlatform())
&& $platform->supportsSchemas();
}
@@ -1385,9 +1164,9 @@ public function hasSchema(): bool
/**
* Returns the PHP name of an active record object this entry references.
*
- * @return string
+ * @return Text
*/
- public function getAlias(): ?string
+ public function getAlias(): Text
{
return $this->alias;
}
@@ -1400,19 +1179,17 @@ public function getAlias(): ?string
*/
public function isAlias(): bool
{
- return null !== $this->alias;
+ return !$this->alias->isEmpty();
}
/**
* Sets whether or not this entity is specified in the schema or if there is
* just a foreign key reference to it.
*
- * @param string $alias
- * @return $this
+ * @param string|Text $alias
*/
- public function setAlias(string $alias): Entity
+ public function setAlias($alias): void
{
- $this->alias = $alias;
- return $this;
+ $this->alias = new Text($alias);
}
}
diff --git a/src/Generator/Model/Field.php b/src/Generator/Model/Field.php
index 656487d7..194e278b 100644
--- a/src/Generator/Model/Field.php
+++ b/src/Generator/Model/Field.php
@@ -1,5 +1,4 @@
- (Torque)
* @author Bernd Goldschmidt
* @author Hugo Hamon (Propel)
+ * @author Cristiano Cinotti
*/
class Field
{
- use DomainPart, NamePart, GeneratorPart, EntityPart, PlatformAccessorPart, DescriptionPart, VendorPart;
+ use DescriptionPart, DomainPart, EntityPart, GeneratorPart, NamePart, PlatformAccessorPart, VendorPart;
const CONSTANT_PREFIX = 'FIELD_';
@@ -50,44 +48,24 @@ class Field
// ---------------------------------
/**
- * @var string The name of the mapped column
+ * @var Text The name of the mapped column
*/
- private $columnName;
-
- /** @var string */
- private $singularName;
-
- /** @var bool */
- private $isNotNull;
+ private Text $columnName;
+ private Text $singularName;
+ private bool $isNotNull = false;
/**
* Native PHP type (scalar or class name)
* @var string "string", "boolean", "int", "double"
*/
- private $phpType;
-
- /** @var int */
- private $position;
-
- /** @var bool */
- private $isPrimaryKey;
-
- /** @var bool */
- private $isUnique;
-
- /** @var bool */
- private $isAutoIncrement;
-
- /** @var bool */
- private $skipCodeGeneration = false;
-
- /** @var bool */
- private $isLazyLoad;
-
- /**
- * @var bool
- */
- private $isPrimaryString;
+ private string $phpType;
+ private int $position;
+ private bool $isPrimaryKey = false;
+ private bool $isUnique = false;
+ private bool $isAutoIncrement = false;
+ private bool $skipCodeGeneration = false;
+ private bool $isLazyLoad = false;
+ private bool $isPrimaryString = false;
// only one type is supported currently, which assumes the
// column either contains the classnames or a key to
@@ -95,33 +73,16 @@ class Field
// supported later.
/** @var string 'single' or 'false' are accepted values */
- private $inheritanceType;
-
- /** @var bool */
- private $isEnumeratedClasses;
-
- /**
- * @var Map
- */
- private $inheritanceList;
-
- /**
- * @var bool
- */
- private $implementationDetail = false;
+ private string $inheritanceType = '';
+ private bool $isEnumeratedClasses = false;
+ private Set $inheritanceList;
+ private bool $implementationDetail = false;
// maybe this can be retrieved from vendor specific information
- private $needsTransactionInPostgres;
+ private bool $needsTransactionInPostgres = false;
- /**
- * @var Set
- */
- protected $valueSet;
-
- /**
- * @var Set
- */
- protected $referrers;
+ protected Set $valueSet;
+ protected Set $referrers;
/**
* Creates a new column and set the name.
@@ -143,20 +104,14 @@ public function __construct(string $name = null, string $type = PropelTypes::VAR
$this->setSize($size);
}
- $this->isAutoIncrement = false;
- $this->isEnumeratedClasses = false;
- $this->isLazyLoad = false;
- $this->isNotNull = false;
- $this->isPrimaryKey = false;
- $this->isPrimaryString = false;
- $this->isUnique = false;
- $this->needsTransactionInPostgres = false;
$this->valueSet = new Set();
$this->inheritanceList = new Set();
$this->referrers = new Set();
- $this->vendor = new Map([], Vendor::class);
+ $this->vendor = new Map();
$this->mutatorVisibility = Model::VISIBILITY_PUBLIC;
$this->accessorVisibility = Model::VISIBILITY_PUBLIC;
+ $this->columnName = new Text();
+ $this->singularName = new Text();
}
/**
@@ -165,50 +120,44 @@ public function __construct(string $name = null, string $type = PropelTypes::VAR
*/
protected function getSuperordinate(): ?Entity
{
- return $this->entity;
+ return $this->getEntity();
}
/**
* Returns the fully qualified column name (table.column).
*
- * @return string
+ * @return Text
*/
- public function getFullName(): string
+ public function getFullName(): Text
{
- return $this->getEntity()->getName() . '.' . strtoupper($this->getName());
+ return $this->getName()->toUpperCase()->prepend('.')->prepend($this->getEntity()->getName());
}
- /**
- * @return string
- */
- public function getMethodName(): string
+ public function getMethodName(): Text
{
- return NamingTool::toStudlyCase($this->getName());
+ return $this->getName()->toStudlyCase();
}
- /**
- * @return mixed
- */
- public function getColumnName(): string
+ public function getColumnName(): Text
{
- if (null == $this->columnName) {
- return NamingTool::toSnakeCase($this->getName());
+ if ($this->columnName->isEmpty()) {
+ $this->columnName = $this->getName()->toSnakeCase();
}
return $this->columnName;
}
/**
- * @param string $columnName
+ * @param string|Text $columnName
*/
- public function setColumnName(string $columnName)
+ public function setColumnName($columnName): void
{
- $this->columnName = $columnName;
+ $this->columnName = new Text($columnName);
}
- public function setPhpType(string $phptype)
+ public function setPhpType(string $phpType): void
{
- $this->phpType = $phptype;
+ $this->phpType = $phpType;
}
/**
@@ -218,52 +167,45 @@ public function setPhpType(string $phptype)
*/
public function isNamePlural(): bool
{
- return $this->getSingularName() !== $this->name;
+ return $this->getSingularName()->compare($this->getName()) !== 0;
}
/**
* Returns the column singular name.
*
- * @return string
+ * @return Text
*/
- public function getSingularName(): string
+ public function getSingularName(): Text
{
- if ($this->singularName) {
- return $this->singularName;
- }
-
- return rtrim($this->name, 's');
+ return $this->singularName->isEmpty() ? $this->getName()->toSingular() : $this->singularName;
}
/**
- * @param string $singularName
+ * @param string|Text $singularName
*/
- public function setSingularName(string $singularName)
+ public function setSingularName($singularName): void
{
- $this->singularName = $singularName;
+ $this->singularName = new Text($singularName);
}
/**
* Returns the full column constant name (e.g. EntityMapName::FIELD_COLUMN_NAME).
*
- * @return string A column constant name for insertion into PHP code
+ * @return Text A column constant name for insertion into PHP code
*/
- public function getFullConstantName(): string
+ public function getFullConstantName(): Text
{
- $classname = $this->getEntity()->getName() . 'EntityMap';
- $const = $this->getConstantName();
-
- return $classname.'::'.$const;
+ return $this->getEntity()->getName()->append('EntityMap::')->append($this->getConstantName());
}
/**
* Returns the column constant name.
*
- * @return string
+ * @return Text
*/
- public function getConstantName(): string
+ public function getConstantName(): Text
{
- return self::CONSTANT_PREFIX . strtoupper(NamingTool::toSnakeCase($this->getName()));
+ return $this->getName()->toSnakeCase()->toUpperCase()->prepend(self::CONSTANT_PREFIX);
}
/**
@@ -275,7 +217,7 @@ public function getConstantName(): string
*/
public function getPhpType(): string
{
- return $this->phpType ? $this->phpType : PropelTypes::getPhpNative($this->getType());
+ return $this->phpType ?? PropelTypes::getPhpNative($this->getType());
}
/**
@@ -293,9 +235,9 @@ public function getPosition(): int
*
* @param integer $position
*/
- public function setPosition(int $position)
+ public function setPosition(int $position): void
{
- $this->position = (int) $position;
+ $this->position = $position;
}
/**
@@ -303,15 +245,12 @@ public function setPosition(int $position)
* parent column of the inheritance to the current column.
*
* @param Inheritance $inheritance
- * @return Inheritance
*/
- public function addInheritance(Inheritance $inheritance): Inheritance
+ public function addInheritance(Inheritance $inheritance): void
{
$inheritance->setField($this);
$this->inheritanceList->add($inheritance);
$this->isEnumeratedClasses = true;
-
- return $inheritance;
}
/**
@@ -333,6 +272,8 @@ public function setInheritanceType(string $type): void
* Returns the inheritance list.
*
* @return Set
+ *
+ * @deprecated Use `getChildren()` instead
*/
public function getInheritanceList(): Set
{
@@ -430,7 +371,7 @@ public function isPrimaryString(): bool
*
* @param boolean $flag
*/
- public function setPrimaryKey(bool $flag = true)
+ public function setPrimaryKey(bool $flag = true): void
{
$this->isPrimaryKey = $flag;
@@ -477,7 +418,7 @@ public function requiresTransactionInPostgres(): bool
*/
public function isRelation(): bool
{
- return count($this->getRelations()) > 0;
+ return !$this->getRelations()->isEmpty();
}
/**
@@ -487,7 +428,7 @@ public function isRelation(): bool
*/
public function hasMultipleFK(): bool
{
- return count($this->getRelations()) > 1;
+ return $this->getRelations()->count() > 1;
}
/**
@@ -495,11 +436,11 @@ public function hasMultipleFK(): bool
*
* Only if it is a foreign key or part of a foreign key.
*
- * @return Relation[]
+ * @return Set
*/
- public function getRelations(): array
+ public function getRelations(): Set
{
- return $this->getEntity()->getFieldRelations($this->name);
+ return $this->getEntity()->getFieldRelations($this->getName()->toString());
}
/**
@@ -524,7 +465,7 @@ public function isImplementationDetail(): bool
/**
* @param boolean $implementationDetail
*/
- public function setImplementationDetail(bool $implementationDetail)
+ public function setImplementationDetail(bool $implementationDetail): void
{
$this->implementationDetail = $implementationDetail;
}
@@ -534,7 +475,7 @@ public function setImplementationDetail(bool $implementationDetail)
*
* @param Relation $fk
*/
- public function addReferrer(Relation $fk)
+ public function addReferrer(Relation $fk): void
{
$this->referrers->add($fk);
}
@@ -567,7 +508,7 @@ public function hasReferrers(): bool
* @param Relation $fk
* @return boolean
*/
- public function hasReferrer(Relation $fk)
+ public function hasReferrer(Relation $fk): bool
{
return $this->getReferrers()->contains($fk);
}
@@ -576,7 +517,7 @@ public function hasReferrer(Relation $fk)
* Clears all referrers.
*
*/
- public function clearReferrers()
+ public function clearReferrers(): void
{
$this->getReferrers()->clear();
}
@@ -585,9 +526,9 @@ public function clearReferrers()
* Clears all inheritance children.
*
*/
- public function clearInheritanceList()
+ public function clearInheritanceList(): void
{
- $this->getInheritanceList()->clear();
+ $this->getChildren()->clear();
}
/**
@@ -598,7 +539,7 @@ public function clearInheritanceList()
*
* @param string $mappingType
*/
- public function setDomainForType(string $mappingType)
+ public function setDomainForType(string $mappingType): void
{
$this->getDomain()->copy($this->getPlatform()->getDomainForType($mappingType));
}
@@ -609,7 +550,7 @@ public function setDomainForType(string $mappingType)
* @param string $mappingType
* @see Domain::setType()
*/
- public function setType(string $mappingType)
+ public function setType(string $mappingType): void
{
$this->getDomain()->setType($mappingType);
@@ -739,9 +680,9 @@ public function isFloatingPointNumber(): bool
/**
* Sets the list of possible values for an ENUM column.
*
- * @param Set
+ * @param Set|array|string
*/
- public function setValueSet($valueSet)
+ public function setValueSet($valueSet): void
{
if (is_string($valueSet)) {
$valueSet = explode(',', $valueSet);
@@ -772,7 +713,7 @@ public function getValueSet(): Set
*/
public function getSize(): ?int
{
- return $this->domain->getSize();
+ return $this->getDomain()->getSize();
}
/**
@@ -780,9 +721,9 @@ public function getSize(): ?int
*
* @param integer $size
*/
- public function setSize(int $size)
+ public function setSize(int $size): void
{
- $this->domain->setSize($size);
+ $this->getDomain()->setSize($size);
}
/**
@@ -792,7 +733,7 @@ public function setSize(int $size)
*/
public function getScale(): int
{
- return $this->domain->getScale();
+ return $this->getDomain()->getScale();
}
/**
@@ -800,9 +741,9 @@ public function getScale(): int
*
* @param integer $scale
*/
- public function setScale(int $scale)
+ public function setScale(int $scale): void
{
- $this->domain->setScale($scale);
+ $this->getDomain()->setScale($scale);
}
/**
@@ -814,7 +755,7 @@ public function setScale(int $scale)
*/
public function getSizeDefinition(): string
{
- return $this->domain->getSizeDefinition();
+ return $this->getDomain()->getSizeDefinition();
}
/**
@@ -861,13 +802,13 @@ public function getDefaultValueString(): string
*
* @param FieldDefaultValue|mixed $defaultValue The column's default value
*/
- public function setDefaultValue($defaultValue)
+ public function setDefaultValue($defaultValue): void
{
if (!$defaultValue instanceof FieldDefaultValue) {
$defaultValue = new FieldDefaultValue($defaultValue, FieldDefaultValue::TYPE_VALUE);
}
- $this->domain->setDefaultValue($defaultValue);
+ $this->getDomain()->setDefaultValue($defaultValue);
}
/**
@@ -875,13 +816,13 @@ public function setDefaultValue($defaultValue)
*
* @param FieldDefaultValue|string $defaultExpression The column's default value
*/
- public function setDefaultExpression($defaultExpression)
+ public function setDefaultExpression($defaultExpression): void
{
if (!$defaultExpression instanceof FieldDefaultValue) {
$defaultExpression = new FieldDefaultValue($defaultExpression, FieldDefaultValue::TYPE_EXPR);
}
- $this->domain->setDefaultValue($defaultExpression);
+ $this->getDomain()->setDefaultValue($defaultExpression);
}
/**
@@ -892,7 +833,7 @@ public function setDefaultExpression($defaultExpression)
*/
public function getDefaultValue(): ?FieldDefaultValue
{
- return $this->domain->getDefaultValue();
+ return $this->getDomain()->getDefaultValue();
}
/**
@@ -903,7 +844,7 @@ public function getDefaultValue(): ?FieldDefaultValue
*/
public function getPhpDefaultValue()
{
- return $this->domain->getPhpDefaultValue();
+ return $this->getDomain()->getPhpDefaultValue();
}
/**
@@ -931,7 +872,7 @@ public function isLazyLoad(): bool
return $this->isLazyLoad;
}
- public function setLazyLoad(bool $lazyLoad = false)
+ public function setLazyLoad(bool $lazyLoad = false): void
{
$this->isLazyLoad = $lazyLoad;
}
@@ -949,8 +890,8 @@ public function getAutoIncrementString(): string
if ($this->isAutoIncrement()) {
throw new EngineException(sprintf(
- 'You have specified autoIncrement for column "%s", but you have not specified idMethod="native" for table "%s".',
- $this->name,
+ 'You have specified autoIncrement for column "%s", but you have not specified idMethod="native" for entity "%s".',
+ $this->getName(),
$this->getEntity()->getName()
));
}
@@ -967,7 +908,7 @@ public function getAutoIncrementString(): string
*/
public function setAutoIncrement(bool $flag = true): void
{
- $this->isAutoIncrement = (Boolean) $flag;
+ $this->isAutoIncrement = $flag;
}
/**
@@ -981,7 +922,7 @@ public function isSkipCodeGeneration(): bool
/**
* @param boolean $skipCodeGeneration
*/
- public function setSkipCodeGeneration(bool $skipCodeGeneration)
+ public function setSkipCodeGeneration(bool $skipCodeGeneration): void
{
$this->skipCodeGeneration = $skipCodeGeneration;
}
@@ -1037,31 +978,8 @@ public function isPhpObjectType(): bool
return PropelTypes::isPhpObjectType($this->getPhpType());
}
- public function setSqlType(string $sqlType)
+ public function setSqlType(string $sqlType): void
{
$this->getDomain()->replaceSqlType($sqlType);
}
-
- /**
- * Clones the current object.
- *
- */
- public function __clone()
- {
- if ($this->referrers) {
- $this->referrers = clone $this->referrers;
- }
- if ($this->valueSet) {
- $this->valueSet = clone $this->valueSet;
- }
- if ($this->inheritanceList) {
- $this->inheritanceList = clone $this->inheritanceList;
- }
- if ($this->vendor) {
- $this->vendor = clone $this->vendor;
- }
- if ($this->domain) {
- $this->domain = clone $this->domain;
- }
- }
}
diff --git a/src/Generator/Model/FieldDefaultValue.php b/src/Generator/Model/FieldDefaultValue.php
index a430af11..9fd99087 100644
--- a/src/Generator/Model/FieldDefaultValue.php
+++ b/src/Generator/Model/FieldDefaultValue.php
@@ -1,5 +1,4 @@
setValue($value);
- if (null !== $type) {
+ if ('' !== $type) {
$this->setType($type);
}
}
@@ -57,7 +56,7 @@ public function getType(): string
/**
* @param string $type The type of default value (DefaultValue::TYPE_VALUE or DefaultValue::TYPE_EXPR)
*/
- public function setType($type)
+ public function setType(string $type): void
{
$this->type = $type;
}
@@ -83,7 +82,7 @@ public function getValue()
/**
* @param mixed $value The value, as specified in the schema.
*/
- public function setValue($value)
+ public function setValue($value): void
{
$this->value = $value;
}
diff --git a/src/Generator/Model/IdMethodParameter.php b/src/Generator/Model/IdMethodParameter.php
index 666792b6..691df28b 100644
--- a/src/Generator/Model/IdMethodParameter.php
+++ b/src/Generator/Model/IdMethodParameter.php
@@ -1,5 +1,4 @@
-value = $value;
}
diff --git a/src/Generator/Model/Index.php b/src/Generator/Model/Index.php
index f7050fee..25dfa557 100644
--- a/src/Generator/Model/Index.php
+++ b/src/Generator/Model/Index.php
@@ -1,5 +1,4 @@
size` to use for indexes creation.
*/
- protected $fieldSizes;
+ protected Map $fieldSizes;
/**
* Creates a new Index instance.
*
* @param string $name Name of the index
*/
- public function __construct(string $name = null)
+ public function __construct(string $name = '')
{
$this->initFields();
$this->initVendor();
$this->fieldSizes = new Map();
-
- if (null !== $name) {
- $this->setName($name);
- }
+ $this->setName($name);
}
/**
@@ -77,14 +71,14 @@ public function isUnique(): bool
/**
* Returns the index name.
*
- * @return string
+ * @return Text
*/
- public function getName(): string
+ public function getName(): Text
{
$this->doNaming();
- if ($this->entity && $database = $this->entity->getDatabase()) {
- return substr($this->name, 0, $database->getPlatform()->getMaxFieldNameLength());
+ if (isset($this->entity) && $database = $this->entity->getDatabase()) {
+ return $this->name->substring(0, $database->getPlatform()->getMaxFieldNameLength());
}
return $this->name;
@@ -92,7 +86,7 @@ public function getName(): string
protected function doNaming(): void
{
- if (!$this->name || $this->autoNaming) {
+ if ($this->name->isEmpty() || $this->autoNaming) {
$newName = sprintf('%s_', $this instanceof Unique ? 'u' : 'i');
if (!$this->fields->isEmpty()) {
@@ -109,11 +103,11 @@ protected function doNaming(): void
$newName .= 'no_fields';
}
- if ($this->entity) {
- $newName = $this->getEntity()->getTableName() . '_' . $newName;
+ if ($this->getEntity()) {
+ $newName = $this->getEntity()->getTableName()->append("_$newName");
}
- $this->name = $newName;
+ $this->name = new Text($newName);
$this->autoNaming = true;
}
}
@@ -137,7 +131,7 @@ public function hasFieldAtPosition(int $pos, string $name, int $size = null): bo
/** @var Field $field */
$field = $fieldsArray[$pos];
- if ($field->getName() !== $name) {
+ if ($field->getName()->compare($name) !== 0) {
return false;
}
diff --git a/src/Generator/Model/Inheritance.php b/src/Generator/Model/Inheritance.php
index 75672fe0..8811e1ca 100644
--- a/src/Generator/Model/Inheritance.php
+++ b/src/Generator/Model/Inheritance.php
@@ -1,5 +1,4 @@
- [
+ private array $database = ['map' => [
'name' => 'setName',
'baseClass' => 'setBaseClass',
'defaultIdMethod' => 'setDefaultIdMethod',
@@ -37,7 +34,7 @@ class ModelFactory
]];
- private $entity = ['map' => [
+ private array $entity = ['map' => [
'name' => 'setName',
'description' => 'setDescription',
'tableName' => 'setTableName',
@@ -59,7 +56,7 @@ class ModelFactory
'namespace' => 'setNamespace'
]];
- private $field = ['map' => [
+ private array $field = ['map' => [
'name' => 'setName',
'required' => 'setNotNull',
'primaryKey' => 'setPrimaryKey',
@@ -80,18 +77,18 @@ class ModelFactory
'inheritance' => 'setInheritanceType'
]];
- private $vendor = ['map' => [
+ private array $vendor = ['map' => [
'type' => 'setType',
'parameters' => 'setParameters'
]];
- private $inheritance = ['map' => [
+ private array $inheritance = ['map' => [
'key' => 'setKey',
'class' => 'setClassName',
'extends' => 'setAncestor'
]];
- private $relation = ['map'=> [
+ private array $relation = ['map'=> [
'target' => 'setForeignEntityName',
'field' => 'setField',
'name' => 'setName',
@@ -104,11 +101,8 @@ class ModelFactory
'foreignSchema' => 'setForeignSchema'
]];
- /** @var GeneratorConfigInterface */
- private $config;
-
- /** @var BehaviorManager */
- private $behaviorManager;
+ private ?GeneratorConfigInterface $config;
+ private BehaviorManager $behaviorManager;
/**
* ModelFactory constructor.
@@ -266,11 +260,7 @@ public function createBehavior(array $attributes): Behavior
*/
protected function getBehaviorManager(): BehaviorManager
{
- if (null === $this->behaviorManager) {
- $this->behaviorManager = new BehaviorManager($this->config);
- }
-
- return $this->behaviorManager;
+ return $this->behaviorManager ?? $this->behaviorManager = new BehaviorManager($this->config);
}
/**
diff --git a/src/Generator/Model/Parts/ActiveRecordPart.php b/src/Generator/Model/Parts/ActiveRecordPart.php
index fc528543..f6ea540b 100644
--- a/src/Generator/Model/Parts/ActiveRecordPart.php
+++ b/src/Generator/Model/Parts/ActiveRecordPart.php
@@ -18,29 +18,20 @@ trait ActiveRecordPart
{
use SuperordinatePart;
- /**
- * @var bool|null
- */
- private $activeRecord;
+ private bool $activeRecord;
- /**
- * @param bool $activeRecord
- * @return $this
- */
- public function setActiveRecord(bool $activeRecord): object
+ public function setActiveRecord(bool $activeRecord): void
{
$this->activeRecord = $activeRecord;
-
- return $this;
}
/**
* @return bool
*/
- public function getActiveRecord(): bool
+ public function isActiveRecord(): bool
{
- if (null !== $this->activeRecord) {
+ if (isset($this->activeRecord)) {
return $this->activeRecord;
}
@@ -52,10 +43,11 @@ public function getActiveRecord(): bool
}
/**
+ * @deprecated use isActiveRecord
* @return bool
*/
- public function isActiveRecord(): bool
+ public function getActiveRecord(): bool
{
- return $this->getActiveRecord();
+ return $this->isActiveRecord();
}
}
diff --git a/src/Generator/Model/Parts/AttributesPart.php b/src/Generator/Model/Parts/AttributesPart.php
index 87af0f74..03cd1297 100644
--- a/src/Generator/Model/Parts/AttributesPart.php
+++ b/src/Generator/Model/Parts/AttributesPart.php
@@ -9,7 +9,7 @@
namespace Propel\Generator\Model\Parts;
-use Propel\Common\Collection\Map;
+use phootwork\collection\Map;
/**
* Trait Attributes part.
@@ -19,10 +19,7 @@
*/
trait AttributesPart
{
- /**
- * @var Map
- */
- protected $attributes;
+ protected Map $attributes;
/**
* Returns all definition attributes.
@@ -38,7 +35,7 @@ public function getAttributes(): Map
* Sets an element with the given key.
*
* @param string $key
- * @param $element
+ * @param mixed $element
*/
public function setAttribute(string $key, $element)
{
@@ -55,8 +52,8 @@ public function setAttribute(string $key, $element)
* @param mixed $default
* @return mixed
*/
- public function getAttribute($name, $default = null)
+ public function getAttribute(string $name, $default = null)
{
- return $this->attributes->get($name, $default);
+ return $this->attributes->get($name) ?? $default;
}
}
diff --git a/src/Generator/Model/Parts/BehaviorPart.php b/src/Generator/Model/Parts/BehaviorPart.php
index eadb16a3..293688fd 100644
--- a/src/Generator/Model/Parts/BehaviorPart.php
+++ b/src/Generator/Model/Parts/BehaviorPart.php
@@ -9,22 +9,27 @@
namespace Propel\Generator\Model\Parts;
+use phootwork\collection\Map;
use Propel\Generator\Exception\BuildException;
use Propel\Generator\Model\Behavior;
-use Propel\Common\Collection\Map;
-/**
- * BehaviorableTrait use it on every model that can hold behaviors
- *
- */
trait BehaviorPart
{
- /** @var Map */
- protected $behaviors;
+ protected Map $behaviors;
+
+ /**
+ * @param Behavior $behavior
+ */
+ abstract protected function registerBehavior(Behavior $behavior): void;
+
+ /**
+ * @param Behavior $behavior
+ */
+ abstract protected function unregisterBehavior(Behavior $behavior): void;
protected function initBehaviors()
{
- $this->behaviors = new Map([], Behavior::class);
+ $this->behaviors = new Map();
}
/**
@@ -32,10 +37,8 @@ protected function initBehaviors()
*
* @param Behavior $behavior
* @throws BuildException when the added behavior is not an instance of \Propel\Generator\Model\Behavior
-
- * @return $this
*/
- public function addBehavior(Behavior $behavior)
+ public function addBehavior(Behavior $behavior): void
{
// the new behavior is already registered
if ($this->hasBehavior($behavior->getId()) && $behavior->allowMultiple()) {
@@ -56,33 +59,18 @@ public function addBehavior(Behavior $behavior)
$this->registerBehavior($behavior);
$this->behaviors->set($behavior->getId(), $behavior);
-
- return $this;
}
- /**
- * @param Behavior $behavior
- */
- abstract protected function registerBehavior(Behavior $behavior);
-
/**
* Removes the behavior
* @param Behavior $behavior
- * @return $this
*/
- public function removeBehavior(Behavior $behavior)
+ public function removeBehavior(Behavior $behavior): void
{
$this->unregisterBehavior($behavior);
$this->behaviors->remove($behavior->getId());
-
- return $this;
}
- /**
- * @param Behavior $behavior
- */
- abstract protected function unregisterBehavior(Behavior $behavior);
-
/**
* Returns the list of behaviors.
*
@@ -99,7 +87,7 @@ public function getBehaviors(): array
* @param string $id the behavior id
* @return bool True if the behavior exists
*/
- public function hasBehavior($id): bool
+ public function hasBehavior(string $id): bool
{
return $this->behaviors->has($id);
}
@@ -112,10 +100,6 @@ public function hasBehavior($id): bool
*/
public function getBehavior($id): ?Behavior
{
- if ($this->hasBehavior($id)) {
- return $this->behaviors->get($id);
- }
-
- return null;
+ return $this->behaviors->get($id);
}
}
diff --git a/src/Generator/Model/Parts/DatabasePart.php b/src/Generator/Model/Parts/DatabasePart.php
index 3925fc83..dfa98be3 100644
--- a/src/Generator/Model/Parts/DatabasePart.php
+++ b/src/Generator/Model/Parts/DatabasePart.php
@@ -1,5 +1,4 @@
database = $database;
-
- return $this;
}
/**
@@ -44,6 +36,6 @@ public function setDatabase(Database $database)
*/
public function getDatabase(): ?Database
{
- return $this->database;
+ return $this->database ?? null;
}
}
diff --git a/src/Generator/Model/Parts/DescriptionPart.php b/src/Generator/Model/Parts/DescriptionPart.php
index a5b928d7..6c0ef492 100644
--- a/src/Generator/Model/Parts/DescriptionPart.php
+++ b/src/Generator/Model/Parts/DescriptionPart.php
@@ -1,5 +1,4 @@
-description)) {
+ $this->description = new Text();
+ }
+
return $this->description;
}
/**
- * @param string $description
- * @return $this
+ * @param string|Text $description
*/
- public function setDescription(string $description)
+ public function setDescription($description): void
{
- $this->description = $description;
-
- return $this;
+ $this->description = new Text($description);
}
/**
@@ -50,6 +44,6 @@ public function setDescription(string $description)
*/
public function hasDescription(): bool
{
- return !empty($this->description);
+ return !$this->getDescription()->isEmpty();
}
}
diff --git a/src/Generator/Model/Parts/DomainPart.php b/src/Generator/Model/Parts/DomainPart.php
index 40b06bbd..293c1896 100644
--- a/src/Generator/Model/Parts/DomainPart.php
+++ b/src/Generator/Model/Parts/DomainPart.php
@@ -1,5 +1,4 @@
domain = $domain;
-
- return $this;
}
- /**
- * @return Domain
- */
public function getDomain(): Domain
{
return $this->domain;
diff --git a/src/Generator/Model/Parts/EntityPart.php b/src/Generator/Model/Parts/EntityPart.php
index 91e30b72..797d14f2 100644
--- a/src/Generator/Model/Parts/EntityPart.php
+++ b/src/Generator/Model/Parts/EntityPart.php
@@ -1,5 +1,4 @@
-entity = $entity;
-
- return $this;
}
- /**
- * @return Entity
- */
public function getEntity(): ?Entity
{
- return $this->entity;
+ return $this->entity ?? null;
}
}
diff --git a/src/Generator/Model/Parts/FieldsPart.php b/src/Generator/Model/Parts/FieldsPart.php
index 78277169..b9969f82 100644
--- a/src/Generator/Model/Parts/FieldsPart.php
+++ b/src/Generator/Model/Parts/FieldsPart.php
@@ -9,7 +9,8 @@
namespace Propel\Generator\Model\Parts;
-use Propel\Common\Collection\Set;
+use phootwork\collection\Set;
+use phootwork\lang\Text;
use Propel\Generator\Exception\EngineException;
use Propel\Generator\Model\Entity;
use Propel\Generator\Model\Field;
@@ -22,14 +23,13 @@
*/
trait FieldsPart
{
- /**
- * @var Set
- */
- protected $fields;
+ protected Set $fields;
+
+ abstract protected function getEntity(): ?Entity;
- public function initFields()
+ public function initFields(): void
{
- $this->fields =new Set([], Field::class);
+ $this->fields = new Set();
}
/**
@@ -41,9 +41,7 @@ public function initFields()
*/
public function getFieldByName(string $name): ?Field
{
- return $this->fields->find(function(Field $element) use ($name){
- return $element->getName() === $name;
- });
+ return $this->fields->find($name, fn(Field $element, string $query): bool => $element->getName()->toString() === $query);
}
/**
@@ -55,9 +53,8 @@ public function getFieldByName(string $name): ?Field
*/
public function getFieldByLowercaseName(string $name): ?Field
{
- return $this->fields->find(function(Field $element) use ($name){
- return strtolower($element->getName()) === strtolower($name);
- });
+ return $this->fields->find($name,
+ fn(Field $element, string $query): bool => $element->getName()->toLowerCase() === strtolower($query));
}
/**
@@ -68,7 +65,7 @@ public function getFieldByLowercaseName(string $name): ?Field
*
* @throws EngineException If the field is already added
*/
- public function addField(Field $field)
+ public function addField(Field $field): void
{
if (null !== $this->getEntity()) {
$field->setEntity($this->getEntity());
@@ -81,55 +78,38 @@ public function addField(Field $field)
*
* @param Field[] $fields An array of Field instance
*/
- public function addFields(array $fields)
+ public function addFields(array $fields): void
{
- foreach ($fields as $field) {
- $this->addField($field);
+ if (null !== $this->getEntity()) {
+ foreach ($fields as $field) {
+ $field->setEntity($this->getEntity());
+ }
}
+ $this->fields->add(...$fields);
}
/**
* Returns whether or not the entity has a field.
*
- * @param Field|string $field The Field object or its name
+ * @param Field $field The Field object or its name
*
* @return bool
*/
- public function hasField($field): bool
+ public function hasField(Field $field): bool
{
- if ($field instanceof Field) {
- return $this->fields->contains($field);
- }
-
- return (bool) $this->getFieldByName($field);
+ return $this->fields->contains($field);
}
/**
- * Returns the Field object with the specified name.
+ * Returns whether or not the entity has a field.
*
- * @param string $name The name of the field (e.g. 'my_field')
+ * @param string $field The Field object or its name
*
- * @return Field
+ * @return bool
*/
- public function getField(string $name): Field
+ public function hasFieldByName(string $field): bool
{
- if (!$this->hasField($name)) {
- $fieldsList = '';
- $this->fields->each(function (Field $element) use ($fieldsList) {
- $fieldsList .= $element->getName() . ', ';
- });
- $fieldsList = substr($fieldsList, 0, -2);
-
- throw new \InvalidArgumentException(sprintf(
- "Field `%s` not found in %s `%s` [%s]",
- $name,
- get_class($this),
- $this->getName(),
- $fieldsList)
- );
- }
-
- return $this->getFieldByName($name);
+ return $this->getFieldByName($field) !== null;
}
/**
@@ -145,17 +125,13 @@ public function getFields(): Set
/**
* Removes a field from the fields collection.
*
- * @param Field|string $field The Field or its name
+ * @param Field $field The Field or its name
*
* @throws EngineException
*/
- public function removeField($field)
+ public function removeField(Field $field): void
{
- if (is_string($field)) {
- $field = $this->getField($field);
- }
-
- if (null === $field || !$this->fields->contains($field)) {
+ if (!$this->fields->contains($field)) {
throw new EngineException(sprintf('No field named %s found in entity %s.', $field->getName(), $this->getName()));
}
@@ -171,4 +147,14 @@ public function removeField($field)
// @FIXME: also remove indexes on this field?
}
}
+
+ public function removeFieldByName(string $name): void
+ {
+ $field = $this->getFieldByName($name);
+ if (null === $field) {
+ throw new EngineException(sprintf('No field named %s found in entity %s.', $name, $this->getName()));
+ }
+
+ $this->removeField($field);
+ }
}
diff --git a/src/Generator/Model/Parts/GeneratorPart.php b/src/Generator/Model/Parts/GeneratorPart.php
index 3682a18f..08caedc3 100644
--- a/src/Generator/Model/Parts/GeneratorPart.php
+++ b/src/Generator/Model/Parts/GeneratorPart.php
@@ -1,4 +1,4 @@
-mutatorVisibility = $visibility;
-
- return $this;
}
/**
@@ -64,32 +59,27 @@ public function setMutatorVisibility(string $visibility)
*/
public function getMutatorVisibility(): string
{
- if (null !== $this->mutatorVisibility) {
- return $this->mutatorVisibility;
- }
-
- if ($this->getSuperordinate() && method_exists($this->getSuperordinate(), 'getMutatorVisibility')) {
- return $this->getSuperordinate()->getMutatorVisibility();
+ if ($this->mutatorVisibility === Model::DEFAULT_MUTATOR_ACCESSIBILITY) {
+ if ($this->getSuperordinate() && method_exists($this->getSuperordinate(), 'getMutatorVisibility')) {
+ return $this->getSuperordinate()->getMutatorVisibility();
+ }
}
- return Model::DEFAULT_MUTATOR_ACCESSIBILITY;
+ return $this->mutatorVisibility;
}
/**
* Sets the visibility for accessors
*
* @param string $visibility
- * @return $this
*/
- public function setAccessorVisibility(string $visibility)
+ public function setAccessorVisibility(string $visibility): void
{
if (!in_array($visibility, [Model::VISIBILITY_PUBLIC, Model::VISIBILITY_PRIVATE, Model::VISIBILITY_PROTECTED])) {
$visibility = Model::VISIBILITY_PUBLIC;
}
$this->accessorVisibility = $visibility;
-
- return $this;
}
/**
@@ -98,14 +88,12 @@ public function setAccessorVisibility(string $visibility)
*/
public function getAccessorVisibility(): string
{
- if (null !== $this->accessorVisibility) {
- return $this->accessorVisibility;
- }
-
- if ($this->getSuperordinate() && method_exists($this->getSuperordinate(), 'getAccessorVisibility')) {
- return $this->getSuperordinate()->getAccessorVisibility();
+ if ($this->accessorVisibility === Model::DEFAULT_ACCESSOR_ACCESSIBILITY) {
+ if ($this->getSuperordinate() && method_exists($this->getSuperordinate(), 'getAccessorVisibility')) {
+ return $this->getSuperordinate()->getAccessorVisibility();
+ }
}
- return Model::DEFAULT_ACCESSOR_ACCESSIBILITY;
+ return $this->accessorVisibility;
}
}
diff --git a/src/Generator/Model/Parts/NamePart.php b/src/Generator/Model/Parts/NamePart.php
index bc52652b..e1dc01fc 100644
--- a/src/Generator/Model/Parts/NamePart.php
+++ b/src/Generator/Model/Parts/NamePart.php
@@ -9,6 +9,8 @@
namespace Propel\Generator\Model\Parts;
+use phootwork\lang\Text;
+
/**
* Trait NamePart
*
@@ -16,29 +18,21 @@
*/
trait NamePart
{
- /**
- * @var string
- */
- protected $name = '';
+ protected Text $name;
/**
* Returns the class name without namespace.
- *
- * @return string
*/
- public function getName(): string
+ public function getName(): Text
{
- return $this->name;
+ return $this->name ?? $this->name = new Text();
}
/**
- * @param string $name
- * @return $this
+ * @param string|Text $name
*/
- public function setName(string $name)
+ public function setName($name): void
{
- $this->name = $name;
-
- return $this;
+ $this->name = new Text($name);
}
}
diff --git a/src/Generator/Model/Parts/NamespacePart.php b/src/Generator/Model/Parts/NamespacePart.php
index 21d51816..44c185f2 100644
--- a/src/Generator/Model/Parts/NamespacePart.php
+++ b/src/Generator/Model/Parts/NamespacePart.php
@@ -10,86 +10,79 @@
namespace Propel\Generator\Model\Parts;
+use phootwork\lang\Text;
+
/**
* Trait NamespacePart
*
* @author Thomas Gossmann
+ * @author Cristiano Cinotti
*/
trait NamespacePart
{
- use NamePart;
use SuperordinatePart;
- /** @var string */
- protected $namespace;
+ protected Text $namespace;
+ protected Text $name;
/**
- * @param string $name
- *
- * @return $this
+ * @param string|Text $name
*/
- public function setName(string $name): object
+ public function setName($name): void
{
- if (false !== strpos($name, '\\')) {
- $namespace = explode('\\', trim($name, '\\'));
- $this->name = array_pop($namespace);
- $this->namespace = implode('\\', $namespace);
+ $name = new Text($name);
+
+ if ($name->contains('\\')) {
+ $this->namespace = $name->substring(0, $name->lastIndexOf('\\'));
+ $this->name = $name->substring($name->lastIndexOf('\\') + 1);
} else {
$this->name = $name;
}
- return $this;
}
/**
* Sets the namespace
*
- * @param string $namespace
- * @return $this
+ * @param string|Text $namespace
*/
- public function setNamespace(?string $namespace): object
+ public function setNamespace($namespace): void
{
- if (null !== $namespace) {
- $namespace = rtrim($namespace, '\\');
- }
- $this->namespace = $namespace;
-
- return $this;
+ $namespace = new Text($namespace);
+ $this->namespace = $namespace->trimEnd('\\');
}
/**
* Returns the namespace
*
- * @return string
+ * @return Text
*/
- public function getNamespace(): string
+ public function getNamespace(): Text
{
- $namespace = $this->namespace;
+ $namespace = $this->namespace ?? $this->namespace = new Text();
- if (null === $namespace && $this->getSuperordinate() && method_exists($this->getSuperordinate(), 'getNamespace')) {
+ if ($namespace->isEmpty() && $this->getSuperordinate() && method_exists($this->getSuperordinate(), 'getNamespace')) {
$namespace = $this->getSuperordinate()->getNamespace();
}
- if (null === $namespace) {
- $namespace = '';
- }
-
return $namespace;
}
/**
* Returns the class name with namespace.
*
- * @return string
+ * @return Text
*/
- public function getFullName(): string
+ public function getFullName(): Text
{
- $name = $this->getName();
- $namespace = $this->getNamespace();
-
- if ($namespace) {
- return $namespace . '\\' . $name;
- } else {
- return $name;
+ if (!isset($this->namespace) || $this->namespace->isEmpty()) {
+ return $this->name;
}
+
+ return $this->namespace->ensureEnd('\\')->append($this->name);
+ }
+
+ public function getName(): Text
+ {
+ return $this->name ?? $this->name = new Text();
}
}
diff --git a/src/Generator/Model/Parts/PlatformAccessorPart.php b/src/Generator/Model/Parts/PlatformAccessorPart.php
index 35aff45d..20870881 100644
--- a/src/Generator/Model/Parts/PlatformAccessorPart.php
+++ b/src/Generator/Model/Parts/PlatformAccessorPart.php
@@ -21,11 +21,9 @@ trait PlatformAccessorPart
{
use SuperordinatePart;
- /** @var GeneratorConfigInterface */
- protected $generatorConfig;
+ protected GeneratorConfigInterface $generatorConfig;
- /** @var PlatformInterface */
- protected $platform;
+ protected PlatformInterface $platform;
/**
* Retrieves the configuration object.
@@ -34,7 +32,7 @@ trait PlatformAccessorPart
*/
public function getGeneratorConfig(): ?GeneratorConfigInterface
{
- if (null !== $this->generatorConfig) {
+ if (isset($this->generatorConfig)) {
return $this->generatorConfig;
}
@@ -50,7 +48,7 @@ public function getGeneratorConfig(): ?GeneratorConfigInterface
*/
public function getPlatform(): ?PlatformInterface
{
- if (null !== $this->platform) {
+ if (isset($this->platform)) {
return $this->platform;
}
diff --git a/src/Generator/Model/Parts/PlatformMutatorPart.php b/src/Generator/Model/Parts/PlatformMutatorPart.php
index ff9ff80c..1871dc28 100644
--- a/src/Generator/Model/Parts/PlatformMutatorPart.php
+++ b/src/Generator/Model/Parts/PlatformMutatorPart.php
@@ -1,4 +1,4 @@
-generatorConfig = $generatorConfig;
- if (!$this->platform) {
+ if (!isset($this->platform)) {
$this->platform = $generatorConfig->createPlatformForDatabase();
}
-
- return $this;
}
/**
* @param PlatformInterface $platform
- * @return $this
*/
- public function setPlatform(PlatformInterface $platform)
+ public function setPlatform(PlatformInterface $platform): void
{
$this->platform = $platform;
- return $this;
}
}
diff --git a/src/Generator/Model/Parts/SchemaNamePart.php b/src/Generator/Model/Parts/SchemaNamePart.php
index 4320d821..89949628 100644
--- a/src/Generator/Model/Parts/SchemaNamePart.php
+++ b/src/Generator/Model/Parts/SchemaNamePart.php
@@ -9,6 +9,8 @@
namespace Propel\Generator\Model\Parts;
+use phootwork\lang\Text;
+
/**
* Trait SchemaNamePart
*
@@ -16,38 +18,31 @@
*/
trait SchemaNamePart
{
- /**
- * @var string
- */
- protected $schemaName;
+ protected Text $schemaName;
/**
* Returns the schema name.
*
- * @return string|null
+ * @return Text
*/
- public function getSchemaName(): ?string
+ public function getSchemaName(): Text
{
- if (null === $this->schemaName) {
+ if (!isset($this->schemaName)) {
if ($this->getSuperordinate() && method_exists($this->getSuperordinate(), 'getSchemaName')) {
return $this->getSuperordinate()->getSchemaName();
}
}
- return $this->schemaName;
+ return $this->schemaName ?? new Text();
}
/**
* Sets the schema name.
*
- * @param string $schemaName
+ * @param string|Text $schemaName
*/
- public function setSchemaName(string $schemaName): void
+ public function setSchemaName($schemaName): void
{
- if ($schemaName === $this->schemaName) {
- return;
- }
-
- $this->schemaName = $schemaName;
+ $this->schemaName = new Text($schemaName);
}
}
diff --git a/src/Generator/Model/Parts/SchemaPart.php b/src/Generator/Model/Parts/SchemaPart.php
index 86eb4096..1bd9c326 100644
--- a/src/Generator/Model/Parts/SchemaPart.php
+++ b/src/Generator/Model/Parts/SchemaPart.php
@@ -1,4 +1,4 @@
-schema = $schema;
- if ($schema) {
- $this->registerSchema($schema);
- } else {
- $this->unregisterSchema($schema);
- }
-
- return $this;
+ $this->registerSchema($schema);
}
/**
@@ -62,6 +43,6 @@ public function setSchema(Schema $schema)
*/
public function getSchema(): ?Schema
{
- return $this->schema;
+ return $this->schema ?? null;
}
}
diff --git a/src/Generator/Model/Parts/ScopePart.php b/src/Generator/Model/Parts/ScopePart.php
index 73fecbf8..0b24599b 100644
--- a/src/Generator/Model/Parts/ScopePart.php
+++ b/src/Generator/Model/Parts/ScopePart.php
@@ -1,5 +1,4 @@
scope = $scope;
-
- return $this;
+ $this->scope = new Text($scope);
}
/**
* Returns scope
*
- * @return string
+ * @return Text
*/
- public function getScope(): string
+ public function getScope(): Text
{
- $scope = $this->scope;
+ if (!isset($this->scope)) {
+ $this->scope = new Text();
+ }
- if (null === $scope && $this->getSuperordinate() && method_exists($this->getSuperordinate(), 'getScope')) {
- $scope = $this->getSuperordinate()->getScope();
+ if ($this->scope->isEmpty() && $this->getSuperordinate() && method_exists($this->getSuperordinate(), 'getScope')) {
+ return $this->getSuperordinate()->getScope();
}
- return null === $scope ? '' : $scope;
+ return $this->scope;
}
}
diff --git a/src/Generator/Model/Parts/SqlPart.php b/src/Generator/Model/Parts/SqlPart.php
index c4f3ba81..eab239ce 100644
--- a/src/Generator/Model/Parts/SqlPart.php
+++ b/src/Generator/Model/Parts/SqlPart.php
@@ -1,5 +1,4 @@
idMethodParameters = new Set([], IdMethodParameter::class);
+ $this->idMethodParameters = new Set();
}
/**
@@ -53,13 +43,10 @@ abstract public function getPlatform(): ?PlatformInterface;
* Sets the method strategy for generating primary keys.
*
* @param string $idMethod
- * @return $this
*/
- public function setIdMethod(string $idMethod)
+ public function setIdMethod(string $idMethod): void
{
$this->idMethod = $idMethod;
-
- return $this;
}
/**
@@ -67,12 +54,10 @@ public function setIdMethod(string $idMethod)
*
* [HL] changing behavior so that Database default method is returned
* if no method has been specified for the entity.
- *
- * @return string
*/
public function getIdMethod(): string
{
- if (null !== $this->idMethod) {
+ if ('' !== $this->idMethod) {
return $this->idMethod;
}
@@ -87,14 +72,11 @@ public function getIdMethod(): string
* Adds a new parameter for the strategy that generates primary keys.
*
* @param IdMethodParameter $idMethodParameter
- * @return $this
*/
- public function addIdMethodParameter(IdMethodParameter $idMethodParameter)
+ public function addIdMethodParameter(IdMethodParameter $idMethodParameter): void
{
$idMethodParameter->setEntity($this);
$this->idMethodParameters->add($idMethodParameter);
-
- return $this;
}
/**
@@ -112,30 +94,21 @@ public function getIdMethodParameters(): array
* Removes a parameter for the strategy that generates primary keys.
*
* @param IdMethodParameter $idMethodParameter
- * @return $this
*/
- public function removeIdMethodParameter(IdMethodParameter $idMethodParameter)
+ public function removeIdMethodParameter(IdMethodParameter $idMethodParameter): void
{
$idMethodParameter->setEntity(null);
$this->idMethodParameters->remove($idMethodParameter);
-
- return $this;
}
/**
* Sets heavy indexing
*
* @param bool $heavyIndexing
- * @return $this
*/
- public function setHeavyIndexing(?bool $heavyIndexing = null)
+ public function setHeavyIndexing(bool $heavyIndexing = null): void
{
- if (null === $heavyIndexing) {
- $heavyIndexing = true;
- }
- $this->heavyIndexing = $heavyIndexing;
-
- return $this;
+ $this->heavyIndexing = $heavyIndexing ?? true;
}
/**
@@ -143,7 +116,7 @@ public function setHeavyIndexing(?bool $heavyIndexing = null)
*/
public function isHeavyIndexing(): bool
{
- if (null !== $this->heavyIndexing) {
+ if (isset($this->heavyIndexing)) {
return $this->heavyIndexing;
}
@@ -156,13 +129,10 @@ public function isHeavyIndexing(): bool
/**
* @param bool $identifierQuoting
- * @return $this
*/
- public function setIdentifierQuoting(bool $identifierQuoting)
+ public function setIdentifierQuoting(bool $identifierQuoting): void
{
$this->identifierQuoting = $identifierQuoting;
-
- return $this;
}
/**
@@ -175,7 +145,7 @@ public function setIdentifierQuoting(bool $identifierQuoting)
*/
public function isIdentifierQuotingEnabled(): bool
{
- if (null !== $this->identifierQuoting) {
+ if (isset($this->identifierQuoting)) {
return $this->identifierQuoting;
}
@@ -187,9 +157,9 @@ public function isIdentifierQuotingEnabled(): bool
/**
* @return bool|null
*/
- public function getIdentifierQuoting()
+ public function getIdentifierQuoting(): ?bool
{
- return $this->identifierQuoting;
+ return $this->identifierQuoting ?? null;
}
/**
@@ -225,9 +195,8 @@ public function quoteIdentifier(string $text): string
* @param string $format
*
* @throws \InvalidArgumentException
- * @return $this
*/
- public function setStringFormat(string $format)
+ public function setStringFormat(string $format): void
{
$formats = Model::SUPPORTED_STRING_FORMATS;
$format = strtoupper($format);
@@ -243,8 +212,6 @@ public function setStringFormat(string $format)
}
$this->stringFormat = $format;
-
- return $this;
}
/**
@@ -255,7 +222,7 @@ public function setStringFormat(string $format)
*/
public function getStringFormat(): string
{
- if (null !== $this->stringFormat) {
+ if (isset($this->stringFormat)) {
return $this->stringFormat;
}
diff --git a/src/Generator/Model/Parts/VendorPart.php b/src/Generator/Model/Parts/VendorPart.php
index 0cb00415..073f9ea0 100644
--- a/src/Generator/Model/Parts/VendorPart.php
+++ b/src/Generator/Model/Parts/VendorPart.php
@@ -1,5 +1,4 @@
vendor = new Map([], Vendor::class);
+ $this->vendor = new Map();
}
/**
* Adds vendor information to the current model
*
* @param Vendor $vendor
- * @return $this
*/
- public function addVendor(Vendor $vendor)
+ public function addVendor(Vendor $vendor): void
{
$this->vendor->set($vendor->getType(), $vendor);
-
- return $this;
}
/**
diff --git a/src/Generator/Model/PropelTypes.php b/src/Generator/Model/PropelTypes.php
index f66f8731..2759bbf3 100644
--- a/src/Generator/Model/PropelTypes.php
+++ b/src/Generator/Model/PropelTypes.php
@@ -1,5 +1,4 @@
- self::CHAR_NATIVE_TYPE,
self::VARCHAR => self::VARCHAR_NATIVE_TYPE,
self::LONGVARCHAR => self::LONGVARCHAR_NATIVE_TYPE,
@@ -158,7 +155,7 @@ class PropelTypes
*
* @var array
*/
- private static $mappingTypeToPDOTypeMap = [
+ private static array $mappingTypeToPDOTypeMap = [
self::CHAR => \PDO::PARAM_STR,
self::VARCHAR => \PDO::PARAM_STR,
self::LONGVARCHAR => \PDO::PARAM_STR,
@@ -180,8 +177,6 @@ class PropelTypes
self::DATE => \PDO::PARAM_STR,
self::TIME => \PDO::PARAM_STR,
self::TIMESTAMP => \PDO::PARAM_STR,
- self::BU_DATE => \PDO::PARAM_STR,
- self::BU_TIMESTAMP => \PDO::PARAM_STR,
self::BOOLEAN => \PDO::PARAM_BOOL,
self::BOOLEAN_EMU => \PDO::PARAM_INT,
self::OBJECT => \PDO::PARAM_STR,
@@ -195,7 +190,7 @@ class PropelTypes
self::BU_TIMESTAMP => \PDO::PARAM_STR,
];
- private static $pdoTypeNames = [
+ private static array $pdoTypeNames = [
\PDO::PARAM_BOOL => '\\PDO::PARAM_BOOL',
\PDO::PARAM_NULL => '\\PDO::PARAM_NULL',
\PDO::PARAM_INT => '\\PDO::PARAM_INT',
@@ -218,6 +213,8 @@ public static function getPhpNative(string $mappingType): string
/**
* Returns the PDO type (PDO::PARAM_* constant) value.
*
+ * @param string $type
+ *
* @return integer
*/
public static function getPDOType(string $type): int
@@ -228,6 +225,8 @@ public static function getPDOType(string $type): int
/**
* Returns the PDO type ('PDO::PARAM_*' constant) name.
*
+ * @param string $type
+ *
* @return string
*/
public static function getPdoTypeString(string $type): string
diff --git a/src/Generator/Model/Relation.php b/src/Generator/Model/Relation.php
index 71c3f74a..bee8f310 100644
--- a/src/Generator/Model/Relation.php
+++ b/src/Generator/Model/Relation.php
@@ -1,5 +1,4 @@
-setName($name);
- }
+ $this->setName($name);
- $this->onUpdate = Model::RELATION_NONE;
- $this->onDelete = Model::RELATION_NONE;
- $this->defaultJoin = 'INNER JOIN';
- $this->localFields = new UniqueList();
+ $this->localFields = new ArrayList();
$this->foreignFields = new ArrayList();
$this->initVendor();
}
@@ -134,23 +79,15 @@ public function getSuperordinate(): Entity
/**
* @return string
*/
- public function getField(): ?string
+ public function getField(): string
{
- $field = $this->field;
-
- if (!$field) {
- if ($this->hasName()) {
- $field = $this->name;
- }
- }
-
- return $field;
+ return $this->field ?? $this->getName()->toString();
}
/**
* @param string $field
*/
- public function setField(string $field)
+ public function setField(string $field): void
{
$this->field = $field;
}
@@ -160,13 +97,13 @@ public function setField(string $field)
*/
public function getRefField(): ?string
{
- return $this->refField;
+ return $this->refField ?? null;
}
/**
* @param string $refField
*/
- public function setRefField(string $refField)
+ public function setRefField(string $refField): void
{
$this->refField = $refField;
}
@@ -242,10 +179,10 @@ public function setSkipCodeGeneration(bool $skipCodeGeneration)
*/
public function hasLocalField(Field $field): bool
{
- if ($field = $this->getEntity()->getField($field->getName())) {
- return $this->localFields->search($field->getName(), function($element, $query) {
- return $element === $query;
- });
+ if ($field = $this->getEntity()->getFieldByName($field->getName()->toString())) {
+ return $this->localFields->search($field->getName()->toString(),
+ fn(string $element, string $query): bool => $element === $query
+ );
}
return false;
@@ -294,9 +231,9 @@ public function setOnUpdate(string $behavior)
/**
* Returns the foreign key name.
*
- * @return string
+ * @return Text
*/
- public function getName(): string
+ public function getName(): Text
{
$this->doNaming();
@@ -308,7 +245,7 @@ public function getName(): string
*/
public function hasName(): bool
{
- return !!$this->name && !$this->autoNaming;
+ return !$this->getName()->isEmpty() && !$this->autoNaming;
}
/**
@@ -316,20 +253,20 @@ public function hasName(): bool
*
* @param string $name
*/
- public function setName(string $name)
+ public function setName(string $name = '')
{
- $this->autoNaming = !$name; //if no name we activate autoNaming
- $this->name = $name;
+ $this->autoNaming = ($name === ''); //if no name we activate autoNaming
+ $this->name = new Text($name);
}
protected function doNaming()
{
- if (!$this->name || $this->autoNaming) {
+ if ($this->name->isEmpty() || $this->autoNaming) {
$newName = 'fk_';
$hash = [];
if ($this->getForeignEntity()) {
- $hash[] = $this->getForeignEntity()->getFullTableName();
+ $hash[] = $this->getForeignEntity()->getFullTableName()->toString();
}
$hash[] = implode(',', $this->localFields->toArray());
$hash[] = implode(',', $this->foreignFields->toArray());
@@ -337,7 +274,7 @@ protected function doNaming()
$newName .= substr(md5(strtolower(implode(':', $hash))), 0, 6);
if ($this->getEntity()) {
- $newName = $this->getEntity()->getTableName() . '_' . $newName;
+ $newName = $this->getEntity()->getTableName()->append("_$newName");
}
$this->name = $newName;
@@ -392,8 +329,8 @@ public function setDefaultJoin(string $join)
*/
public function getForeignEntityName(): ?string
{
- if (null === $this->foreignEntityName && null !== $this->foreignEntity) {
- $this->foreignEntityName = $this->foreignEntity->getFullName();
+ if ('' === $this->foreignEntityName && isset($this->foreignEntity)) {
+ $this->foreignEntityName = $this->foreignEntity->getFullName()->toString();
}
return $this->foreignEntityName;
@@ -418,7 +355,7 @@ public function getForeignEntityName(): ?string
/**
* @param string $foreignEntityName
*/
- public function setForeignEntityName(string $foreignEntityName)
+ public function setForeignEntityName(string $foreignEntityName): void
{
$this->foreignEntityName = $foreignEntityName;
}
@@ -430,7 +367,7 @@ public function setForeignEntityName(string $foreignEntityName)
*/
public function getForeignEntity(): ?Entity
{
- if (null !== $this->foreignEntity) {
+ if (isset($this->foreignEntity)) {
return $this->foreignEntity;
}
@@ -445,7 +382,7 @@ public function getForeignEntity(): ?Entity
/**
* @param null|Entity $foreignEntity
*/
- public function setForeignEntity(Entity $foreignEntity)
+ public function setForeignEntity(Entity $foreignEntity): void
{
$this->foreignEntity = $foreignEntity;
}
@@ -453,9 +390,9 @@ public function setForeignEntity(Entity $foreignEntity)
/**
* Returns the name of the table the foreign key is in.
*
- * @return string
+ * @return Text
*/
- public function getEntityName(): string
+ public function getEntityName(): Text
{
return $this->getEntity()->getName();
}
@@ -463,9 +400,9 @@ public function getEntityName(): string
/**
* Returns the name of the schema the foreign key is in.
*
- * @return string
+ * @return Text
*/
- public function getSchemaName(): string
+ public function getSchemaName(): Text
{
return $this->getEntity()->getSchemaName();
}
@@ -473,8 +410,8 @@ public function getSchemaName(): string
/**
* Adds a new reference entry to the foreign key.
*
- * @param mixed $ref1 A Field object or an associative array or a string
- * @param mixed $ref2 A Field object or a single string name
+ * @param Field|array|string $ref1 A Field object or an associative array or a string
+ * @param Field|string $ref2 A Field object or a single string name
*/
public function addReference($ref1, $ref2 = null)
{
@@ -495,11 +432,11 @@ public function addReference($ref1, $ref2 = null)
$local = null;
$foreign = null;
if ($ref1 instanceof Field) {
- $local = $ref1->getName();
+ $local = $ref1->getName()->toString();
}
if ($ref2 instanceof Field) {
- $foreign = $ref2->getName();
+ $foreign = $ref2->getName()->toString();
}
$this->localFields->add($local);
@@ -510,7 +447,7 @@ public function addReference($ref1, $ref2 = null)
* Clears the references of this foreign key.
*
*/
- public function clearReferences()
+ public function clearReferences(): void
{
$this->localFields->clear();
$this->foreignFields->clear();
@@ -519,9 +456,9 @@ public function clearReferences()
/**
* Returns an array of local field names.
*
- * @return UniqueList
+ * @return ArrayList
*/
- public function getLocalFields(): UniqueList
+ public function getLocalFields(): ArrayList
{
return $this->localFields;
}
@@ -529,26 +466,24 @@ public function getLocalFields(): UniqueList
/**
* Returns an array of local field objects.
*
- * @return Field[]
+ * @return ArrayList
*/
- public function getLocalFieldObjects(): array
+ public function getLocalFieldObjects(): ArrayList
{
- $fields = [];
- foreach ($this->getLocalFields() as $fieldName) {
- $field = $this->getEntity()->getField($fieldName);
+ return $this->getLocalFields()->map(function (string $fieldName): Field {
+ $field = $this->getEntity()->getFieldByName($fieldName);
if (null === $field) {
throw new BuildException(sprintf(
- 'Field `%s` in local reference of relation `%s` from `%s` to `%s` not found.',
- $fieldName,
- $this->getName(),
- $this->getEntity()->getName(),
- $this->getForeignEntity()->getName()
- ));
+ 'Field `%s` in local reference of relation `%s` from `%s` to `%s` not found.',
+ $fieldName,
+ $this->getName(),
+ $this->getEntity()->getName(),
+ $this->getForeignEntity()->getName()
+ ));
}
- $fields[] = $field;
- }
- return $fields;
+ return $field;
+ });
}
/**
@@ -560,7 +495,7 @@ public function getLocalFieldObjects(): array
*/
public function getLocalField(int $index = 0): Field
{
- return $this->getEntity()->getField($this->getLocalFields()->get($index));
+ return $this->getEntity()->getFieldByName($this->getLocalFields()->get($index));
}
/**
@@ -607,8 +542,8 @@ public function getFieldObjectsMapping(): array
$foreignFields = $this->getForeignFieldObjects();
for ($i = 0, $size = $this->localFields->size(); $i < $size; $i++) {
$mapping[] = [
- 'local' => $this->getEntity()->getField($this->localFields->get($i)),
- 'foreign' => $foreignFields[$i],
+ 'local' => $this->getEntity()->getFieldByName($this->localFields->get($i)),
+ 'foreign' => $foreignFields->get($i),
];
}
@@ -632,7 +567,7 @@ public function getFieldObjectsMapArray(): array
$mapping = [];
$foreignFields = $this->getForeignFieldObjects();
for ($i = 0, $size = $this->localFields->size(); $i < $size; $i++) {
- $mapping[] = [$this->getEntity()->getField($this->localFields->get($i)), $foreignFields[$i]];
+ $mapping[] = [$this->getEntity()->getFieldByName($this->localFields->get($i)), $foreignFields->get($i)];
}
return $mapping;
@@ -649,7 +584,7 @@ public function getMappedForeignField(string $local): ?string
{
$m = $this->getLocalForeignMapping();
- return isset($m[$local]) ? $m[$local] : null;
+ return $m[$local] ?? null;
}
/**
@@ -681,14 +616,14 @@ public function getForeignFields(): ArrayList
*
* @return Field[]
*/
- public function getForeignFieldObjects(): array
+ public function getForeignFieldObjects(): ArrayList
{
- $fields = [];
+ $fields = new ArrayList();
$foreignEntity = $this->getForeignEntity();
foreach ($this->foreignFields as $fieldName) {
$field = null;
if (false !== strpos($fieldName, '.')) {
- list($relationName, $foreignFieldName) = explode('.', $fieldName);
+ [$relationName, $foreignFieldName] = explode('.', $fieldName);
$foreignRelation = $this->getForeignEntity()->getRelation($relationName);
if (!$foreignRelation) {
throw new BuildException(sprintf(
@@ -713,7 +648,7 @@ public function getForeignFieldObjects(): array
// }
// }
} else {
- $field = $foreignEntity->getField($fieldName);
+ $field = $foreignEntity->getFieldByName($fieldName);
}
if (null === $field) {
@@ -725,7 +660,7 @@ public function getForeignFieldObjects(): array
$this->getForeignEntity()->getName()
));
}
- $fields[] = $field;
+ $fields->add($field);
}
return $fields;
@@ -740,7 +675,7 @@ public function getForeignFieldObjects(): array
*/
public function getForeignField(int $index = 0): Field
{
- return $this->getForeignEntity()->getField($this->foreignFields->get($index));
+ return $this->getForeignEntity()->getFieldByName($this->foreignFields->get($index));
}
/**
@@ -751,7 +686,7 @@ public function getForeignField(int $index = 0): Field
public function isLocalFieldsRequired(): bool
{
foreach ($this->localFields as $fieldName) {
- if (!$this->getEntity()->getField($fieldName)->isNotNull()) {
+ if (!$this->getEntity()->getFieldByName($fieldName)->isNotNull()) {
return false;
}
}
@@ -767,7 +702,7 @@ public function isLocalFieldsRequired(): bool
public function isAtLeastOneLocalFieldRequired(): bool
{
foreach ($this->localFields as $fieldName) {
- if ($this->getEntity()->getField($fieldName)->isNotNull()) {
+ if ($this->getEntity()->getFieldByName($fieldName)->isNotNull()) {
return true;
}
}
@@ -809,7 +744,7 @@ public function isForeignPrimaryKey(): bool
$foreignCols = [];
foreach ($this->localFields as $colName) {
- $foreignCols[] = $foreignEntity->getField($lfmap[$colName])->getName();
+ $foreignCols[] = $foreignEntity->getFieldByName($lfmap[$colName])->getName();
}
return ((count($foreignPKCols) === count($foreignCols))
@@ -849,7 +784,7 @@ public function isLocalPrimaryKey(): bool
*
* @param boolean $skip
*/
- public function setSkipSql(bool $skip)
+ public function setSkipSql(bool $skip): void
{
$this->skipSql = $skip;
}
@@ -877,7 +812,7 @@ public function isSkipSql(): bool
*/
public function isMatchedByInverseFK(): bool
{
- return (Boolean)$this->getInverseFK();
+ return $this->getInverseFK() !== null;
}
public function getInverseFK(): ?Relation
@@ -938,13 +873,13 @@ public function getForeignPrimaryKeys(): array
$foreignPKCols = [];
foreach ($foreignEntity->getPrimaryKey() as $fPKCol) {
- $foreignPKCols[$fPKCol->getName()] = true;
+ $foreignPKCols[$fPKCol->getName()->toString()] = true;
}
$foreignCols = [];
foreach ($this->getLocalField() as $colName) {
if ($foreignPKCols[$lfmap[$colName]]) {
- $foreignCols[] = $foreignEntity->getField($lfmap[$colName]);
+ $foreignCols[] = $foreignEntity->getFieldByName($lfmap[$colName]);
}
}
@@ -954,20 +889,11 @@ public function getForeignPrimaryKeys(): array
/**
* Returns all local fields which are also a primary key of the local table.
*
- * @return Field[]
+ * @return ArrayList
*/
- public function getLocalPrimaryKeys(): array
+ public function getLocalPrimaryKeys(): ArrayList
{
- $cols = [];
- $localCols = $this->getLocalFieldObjects();
-
- foreach ($localCols as $localCol) {
- if ($localCol->isPrimaryKey()) {
- $cols[] = $localCol;
- }
- }
-
- return $cols;
+ return $this->getForeignFieldObjects()->filter(fn(Field $elem): bool => $elem->isPrimaryKey());
}
/**
@@ -977,9 +903,7 @@ public function getLocalPrimaryKeys(): array
*/
public function isAtLeastOneLocalPrimaryKey(): bool
{
- $cols = $this->getLocalPrimaryKeys();
-
- return 0 !== count($cols);
+ return !$this->getLocalPrimaryKeys()->isEmpty();
}
public function setForeignSchema(string $foreignSchema): void
@@ -987,7 +911,7 @@ public function setForeignSchema(string $foreignSchema): void
$this->foreignSchema = $foreignSchema;
}
- public function getForeignSchema()
+ public function getForeignSchema(): string
{
return $this->foreignSchema;
}
diff --git a/src/Generator/Model/Schema.php b/src/Generator/Model/Schema.php
index f0279f16..9e1afbbc 100644
--- a/src/Generator/Model/Schema.php
+++ b/src/Generator/Model/Schema.php
@@ -1,5 +1,4 @@
-setPlatform($platform);
}
// init
- $this->databases = new ArrayList([], Database::class);
- $this->schemas = new Set([], Schema::class);
+ $this->databases = new ArrayList();
+ $this->schemas = new Set();
}
- protected function getSuperordinate()
+ protected function getSuperordinate(): Schema
{
return $this->schema;
}
@@ -71,12 +62,10 @@ protected function getSuperordinate()
* Sets the filename when reading this schema
*
* @param string $filename
- * @return $this
*/
- public function setFilename(string $filename): Schema
+ public function setFilename(string $filename): void
{
$this->filename = $filename;
- return $this;
}
/**
@@ -89,7 +78,7 @@ public function getFilename(): string
return $this->filename;
}
- protected function registerSchema(Schema $schema)
+ protected function registerSchema(Schema $schema): void
{
$schema->addExternalSchema($this);
}
@@ -98,15 +87,13 @@ protected function registerSchema(Schema $schema)
* Adds an external schema
*
* @param Schema $schema
- * @return $this
*/
- public function addExternalSchema(Schema $schema): Schema
+ public function addExternalSchema(Schema $schema): void
{
if (!$this->schemas->contains($schema)) {
$this->schemas->add($schema);
$schema->setSchema($this);
}
- return $this;
}
/**
@@ -116,17 +103,17 @@ public function addExternalSchema(Schema $schema): Schema
*/
public function isExternalSchema(): bool
{
- return null !== $this->schema;
+ return $this->getSchema() !== null;
}
/**
* Returns all external schema
*
- * @return Schema[]
+ * @return Set
*/
- public function getExternalSchemas(): array
+ public function getExternalSchemas(): Set
{
- return $this->schemas->toArray();
+ return $this->schemas;
}
/**
@@ -148,19 +135,17 @@ protected function unregisterSchema(Schema $schema)
* Removes an external schema (only relevant if this is an external schema)
*
* @param Schema $schema
- * @return $this
*/
- public function removeExternalSchema(Schema $schema): Schema
+ public function removeExternalSchema(Schema $schema): void
{
if ($this->schemas->contains($schema)) {
$schema->setSchema(null);
$this->schemas->remove($schema);
}
- return $this;
}
/**
- * Retuns the root schema
+ * Returns the root schema
*
* @return Schema
*/
@@ -178,12 +163,10 @@ public function getRootSchema(): Schema
* Set whether this schema is only for reference (only relevant if this is an external schema)
*
* @param bool $referenceOnly
- * @return $this
*/
- public function setReferenceOnly(bool $referenceOnly): Schema
+ public function setReferenceOnly(bool $referenceOnly): void
{
$this->referenceOnly = $referenceOnly;
- return $this;
}
/**
@@ -201,16 +184,13 @@ public function getReferenceOnly(): bool
* Schema.
*
* @param Database $database
- * @return $this
*/
- public function addDatabase(Database $database): Schema
+ public function addDatabase(Database $database): void
{
if (!$this->databases->contains($database)) {
$this->databases->add($database);
$database->setSchema($this);
}
-
- return $this;
}
/**
@@ -218,13 +198,12 @@ public function addDatabase(Database $database): Schema
* schema.
*
* @param string $name
- * @return boolean
*/
- public function hasDatabase($name): bool
+ public function hasDatabase(string $name): bool
{
- return $this->databases->search($name, function (Database $db, $query) {
- return $db->getName() === $query;
- });
+ return $this->databases->search($name,
+ fn(Database $db, string $query): bool => $db->getName()->toString() === $query
+ );
}
/**
@@ -245,30 +224,27 @@ public function hasMultipleDatabases(): bool
*/
public function getDatabase(?string $name = null): ?Database
{
- if ($this->databases->size() === 0) {
- return null;
- }
+// if ($this->databases->size() === 0) {
+// return null;
+// }
if (null === $name) {
return $this->databases->get(0);
}
return $this->databases->find($name, function (Database $db, $query) {
- return $db->getName() === $query;
+ return $db->getName()->toString() === $query;
});
}
/**
- * Returns an array of all databases.
+ * Returns an ArrayList of all databases.
*
- * The first boolean parameter tells whether or not to run the
- * final initialization process.
- *
- * @return Database[]
+ * @return ArrayList
*/
- public function getDatabases()
+ public function getDatabases(): ArrayList
{
- return $this->databases->toArray();
+ return $this->databases;
}
/**
@@ -285,20 +261,20 @@ public function getDatabaseSize(): int
* Removes the database from this schema
*
* @param Database $database
- * @return $this
*/
- public function removeDatabase(Database $database): Schema
+ public function removeDatabase(Database $database): void
{
if ($this->databases->contains($database)) {
$database->setSchema(null);
$this->databases->remove($database);
}
- return $this;
}
/**
* @TODO
* Merge other Schema objects together into this Schema object.
+ *
+ * @param array $schemas
*/
public function joinSchemas(array $schemas)
{
@@ -306,14 +282,14 @@ public function joinSchemas(array $schemas)
/** @var Database $addDb */
foreach ($schema->getDatabases() as $addDb) {
$addDbName = $addDb->getName();
- if ($this->hasDatabase($addDbName)) {
- $db = $this->getDatabase($addDbName);
+ if ($this->hasDatabase((string) $addDbName)) {
+ $db = $this->getDatabase((string) $addDbName);
// temporarily reset database namespace to avoid double namespace decoration (see ticket #1355)
$namespace = $db->getNamespace();
$db->setNamespace(null);
// join tables
foreach ($addDb->getEntities() as $addEntity) {
- if ($db->hasEntityByFullName($addEntity->getFullName())) {
+ if ($db->hasEntityByFullName($addEntity->getFullName()->toString())) {
throw new EngineException(sprintf('Duplicate entity found: %s.', $addEntity->getName()));
}
$db->addEntity($addEntity);
@@ -357,6 +333,7 @@ public function countEntities(): int
}
/**
+ * @todo externalize (in other formats, too)
* Creates a string representation of this Schema.
* The representation is given in xml format.
*
diff --git a/src/Generator/Model/Unique.php b/src/Generator/Model/Unique.php
index 0f4a0e05..82f5f59d 100644
--- a/src/Generator/Model/Unique.php
+++ b/src/Generator/Model/Unique.php
@@ -1,5 +1,4 @@
-parameters = new Map();
+ $this->parameters = new Map($parameters);
if (null !== $type) {
$this->setType($type);
}
-
- if ($parameters) {
- $this->setParameters($parameters);
- }
}
/**
* Sets the RDBMS type for this vendor specific information.
*
* @param string $type
- * @return $this
*/
- public function setType(string $type): Vendor
+ public function setType(string $type): void
{
$this->type = $type;
-
- return $this;
}
/**
@@ -108,13 +96,10 @@ public function getType(): string
*
* @param string $name The parameter name
* @param mixed $value The parameter value
- * @return $this
*/
- public function setParameter(string $name, $value): Vendor
+ public function setParameter(string $name, $value): void
{
$this->parameters->set($name, $value);
-
- return $this;
}
/**
@@ -154,11 +139,11 @@ public function setParameters(array $parameters = [])
* Returns an associative array of parameters for
* vendor specific information.
*
- * @return array
+ * @return Map
*/
- public function getParameters(): array
+ public function getParameters(): Map
{
- return $this->parameters->toArray();
+ return $this->parameters;
}
/**
@@ -179,7 +164,7 @@ public function isEmpty(): bool
*/
public function getMergedVendorInfo(Vendor $info): Vendor
{
- $params = array_merge($this->parameters->toArray(), $info->getParameters());
+ $params = array_merge($this->parameters->toArray(), $info->getParameters()->toArray());
$newInfo = new Vendor($this->type);
$newInfo->setParameters($params);
diff --git a/src/Generator/Platform/FinalizationTrait.php b/src/Generator/Platform/FinalizationTrait.php
index 77e82251..19cdc5c5 100644
--- a/src/Generator/Platform/FinalizationTrait.php
+++ b/src/Generator/Platform/FinalizationTrait.php
@@ -14,7 +14,6 @@
use Propel\Generator\Exception\BuildException;
use Propel\Generator\Model\Database;
-use Propel\Generator\Model\Domain;
use Propel\Generator\Model\Entity;
use Propel\Generator\Model\Field;
use Propel\Generator\Model\Index;
@@ -135,7 +134,7 @@ protected function setupReferrer(Relation $relation)
$entity->getDatabase()->getEntityByFullName($relation->getForeignEntityName())
;
$referrers = $foreignEntity->getReferrers();
- if (null === $referrers || !in_array($relation, $referrers, true)) {
+ if (null === $referrers || !$referrers->contains($relation)) {
$foreignEntity->addReferrer($relation);
}
diff --git a/src/Generator/Platform/MysqlPlatform.php b/src/Generator/Platform/MysqlPlatform.php
index 6af80e5c..83e4903c 100644
--- a/src/Generator/Platform/MysqlPlatform.php
+++ b/src/Generator/Platform/MysqlPlatform.php
@@ -62,8 +62,10 @@ protected function initialize()
* Adds extra indices for reverse foreign keys
* This is required for MySQL databases,
* and is called while performing the final initialization of the model.
+ *
+ * @param Entity $entity
*/
- protected function addExtraIndices(Entity $entity)
+ protected function addExtraIndices(Entity $entity): void
{
/**
* A collection of indexed columns. The keys is the column name
@@ -79,7 +81,7 @@ protected function addExtraIndices(Entity $entity)
$this->collectIndexedFields('PRIMARY', $entity->getPrimaryKey(), $indices);
/** @var Index[] $entityIndices */
- $entityIndices = array_merge($entity->getIndices(), $entity->getUnices());
+ $entityIndices = array_merge($entity->getIndices()->toArray(), $entity->getUnices()->toArray());
foreach ($entityIndices as $index) {
$this->collectIndexedFields($this->getName($index), $index->getFields()->toArray(), $indices);
}
@@ -89,7 +91,7 @@ protected function addExtraIndices(Entity $entity)
$counter = 0;
foreach ($entity->getReferrers() as $relation) {
$referencedFields = $relation->getForeignFieldObjects();
- $referencedFieldsHash = $this->getFieldList($referencedFields);
+ $referencedFieldsHash = $this->getFieldList($referencedFields->toArray());
if (empty($referencedFields) || isset($indices[$referencedFieldsHash])) {
continue;
}
@@ -109,9 +111,10 @@ protected function addExtraIndices(Entity $entity)
}
// we're adding indices for this entity foreign keys
+ /** @var Relation $relation */
foreach ($entity->getRelations() as $relation) {
$localFields = $relation->getLocalFieldObjects();
- $localFieldsHash = $this->getFieldList($localFields);
+ $localFieldsHash = $this->getFieldList($localFields->toArray());
if (empty($localFields) || isset($indices[$localFieldsHash])) {
continue;
}
@@ -120,7 +123,7 @@ protected function addExtraIndices(Entity $entity)
// MySQL needs indices on any columns that serve as foreign keys.
// These are not auto-created prior to 4.1.2.
- $name = substr_replace($relation->getName(), 'fi_', strrpos($relation->getName(), 'fk_'), 3);
+ $name = substr_replace($relation->getName()->toString(), 'fi_', strrpos($relation->getName()->toString(), 'fk_'), 3);
if ($entity->hasIndex($name)) {
// if we already have an index with this name, then it looks like the columns of this index have just
// been changed, so remove it and inject it again. This is the case if a referenced entity is handled
@@ -128,8 +131,8 @@ protected function addExtraIndices(Entity $entity)
$entity->removeIndex($name);
}
- $index = $entity->createIndex($name, $localFields);
- $this->collectIndexedFields($this->getName($index), $localFields, $indices);
+ $index = $entity->createIndex($name, $localFields->toArray());
+ $this->collectIndexedFields($this->getName($index), $localFields->toArray(), $indices);
}
}
@@ -892,13 +895,13 @@ public function getTimestampFormatter(): string
public function getMysqlEntityType(Entity $entity): string
{
$vendorSpecific = $entity->getVendorByType('mysql');
- if ([] === $vendorSpecific->getParameters()) {
+ if ($vendorSpecific->getParameters()->isEmpty()) {
$vendorSpecific = $entity->getDatabase()->getVendorByType('mysql');
}
+
if ($vendorSpecific->hasParameter('Type')) {
return $vendorSpecific->getParameter('Type');
}
-
if ($vendorSpecific->hasParameter('Engine')) {
return $vendorSpecific->getParameter('Engine');
}
diff --git a/src/Generator/Platform/SqlDefaultPlatform.php b/src/Generator/Platform/SqlDefaultPlatform.php
index 173a10d3..ae5394fd 100644
--- a/src/Generator/Platform/SqlDefaultPlatform.php
+++ b/src/Generator/Platform/SqlDefaultPlatform.php
@@ -82,11 +82,11 @@ public function __construct(ConnectionInterface $con = null)
public function getName($object): string
{
if ($object instanceof Entity) {
- return $object->getFullTableName();
+ return $object->getFullTableName()->toString();
} elseif ($object instanceof Field) {
- return $object->getColumnName();
+ return $object->getColumnName()->toString();
} else {
- return NamingTool::toSnakeCase($object->getName());
+ return $object->getName()->toSnakeCase()->toString();
}
}
@@ -197,7 +197,7 @@ public function getMaxFieldNameLength(): int
*/
public function getSchemaDelimiter(): string
{
- return '.';
+ return $this->supportsSchemas() ? '.' : '';
}
/**
diff --git a/src/Generator/Platform/SqlitePlatform.php b/src/Generator/Platform/SqlitePlatform.php
index 93135499..0d9feea1 100644
--- a/src/Generator/Platform/SqlitePlatform.php
+++ b/src/Generator/Platform/SqlitePlatform.php
@@ -96,11 +96,11 @@ public function setGeneratorConfig(GeneratorConfigInterface $generatorConfig)
{
parent::setGeneratorConfig($generatorConfig);
- if (null !== ($relationSupport = $generatorConfig->getConfigProperty('database.adapter.sqlite.relation'))) {
+ if (null !== ($relationSupport = $generatorConfig->get('database.adapter.sqlite.relation'))) {
$this->relationSupport = filter_var($relationSupport, FILTER_VALIDATE_BOOLEAN);
;
}
- if (null !== ($entityAlteringWorkaround = $generatorConfig->getConfigProperty('database.adapter.sqlite.entityAlteringWorkaround'))) {
+ if (null !== ($entityAlteringWorkaround = $generatorConfig->get('database.adapter.sqlite.entityAlteringWorkaround'))) {
$this->entityAlteringWorkaround = filter_var($entityAlteringWorkaround, FILTER_VALIDATE_BOOLEAN);
;
;
diff --git a/src/Generator/Reverse/AbstractSchemaParser.php b/src/Generator/Reverse/AbstractSchemaParser.php
index aaae8f02..c2d463ec 100644
--- a/src/Generator/Reverse/AbstractSchemaParser.php
+++ b/src/Generator/Reverse/AbstractSchemaParser.php
@@ -228,7 +228,7 @@ public function setPlatform($platform)
*
* @return \Propel\Generator\Platform\PlatformInterface
*/
- public function getPlatform()
+ public function getPlatform(): PlatformInterface
{
if (null === $this->platform) {
$this->platform = $this->getGeneratorConfig()->createPlatformForDatabase();
diff --git a/src/Generator/Reverse/SchemaParserInterface.php b/src/Generator/Reverse/SchemaParserInterface.php
index 9457e029..556c0a4e 100644
--- a/src/Generator/Reverse/SchemaParserInterface.php
+++ b/src/Generator/Reverse/SchemaParserInterface.php
@@ -51,7 +51,7 @@ public function getWarnings();
/**
* @return \Propel\Generator\Platform\PlatformInterface
*/
- public function getPlatform();
+ public function getPlatform(): PlatformInterface;
/**
* @param \Propel\Generator\Platform\PlatformInterface $platform
diff --git a/src/Generator/Schema/Dumper/DumperInterface.php b/src/Generator/Schema/Dumper/DumperInterface.php
index b4e3f794..8946780d 100644
--- a/src/Generator/Schema/Dumper/DumperInterface.php
+++ b/src/Generator/Schema/Dumper/DumperInterface.php
@@ -1,4 +1,12 @@
-appendDatabaseNode($database, $this->document);
@@ -72,7 +71,7 @@ public function dump(Database $database)
* @param Schema $schema The schema object
* @return string
*/
- public function dumpSchema(Schema $schema)
+ public function dumpSchema(Schema $schema): string
{
$rootNode = $this->document->createElement('app-data');
$this->document->appendChild($rootNode);
@@ -89,18 +88,18 @@ public function dumpSchema(Schema $schema)
* @param Database $database The Database model instance
* @param \DOMNode $parentNode The parent DOMNode object
*/
- private function appendDatabaseNode(Database $database, \DOMNode $parentNode)
+ private function appendDatabaseNode(Database $database, \DOMNode $parentNode): void
{
$databaseNode = $parentNode->appendChild($this->document->createElement('database'));
- $databaseNode->setAttribute('name', $database->getName());
+ $databaseNode->setAttribute('name', $database->getName()->toString());
$databaseNode->setAttribute('defaultIdMethod', $database->getIdMethod());
if ($schema = $database->getSchemaName()) {
- $databaseNode->setAttribute('schema', $schema);
+ $databaseNode->setAttribute('schema', $schema->toString());
}
if ($namespace = $database->getNamespace()) {
- $databaseNode->setAttribute('namespace', $namespace);
+ $databaseNode->setAttribute('namespace', $namespace->toString());
}
$defaultAccessorVisibility = $database->getAccessorVisibility();
@@ -146,10 +145,10 @@ private function appendDatabaseNode(Database $database, \DOMNode $parentNode)
* @param Vendor $vendorInfo The VendorInfo model instance
* @param \DOMNode $parentNode The parent DOMNode object
*/
- private function appendVendorInformationNode(Vendor $vendorInfo, \DOMNode $parentNode)
+ private function appendVendorInformationNode(Vendor $vendorInfo, \DOMNode $parentNode): void
{
//It's an empty Vendor created by VendorPart::getVendorByType method
- if ([] === $vendorInfo->getParameters()) {
+ if ($vendorInfo->getParameters()->isEmpty()) {
return;
}
@@ -170,10 +169,10 @@ private function appendVendorInformationNode(Vendor $vendorInfo, \DOMNode $paren
* @param Entity $entity The Entity model instance
* @param \DOMNode $parentNode The parent DOMNode object
*/
- private function appendEntityNode(Entity $entity, \DOMNode $parentNode)
+ private function appendEntityNode(Entity $entity, \DOMNode $parentNode): void
{
$entityNode = $parentNode->appendChild($this->document->createElement('entity'));
- $entityNode->setAttribute('name', $entity->getName());
+ $entityNode->setAttribute('name', $entity->getName()->toString());
$database = $entity->getDatabase();
$schema = $entity->getSchemaName();
@@ -186,11 +185,11 @@ private function appendEntityNode(Entity $entity, \DOMNode $parentNode)
}
if ($tableName = $entity->getTableName()) {
- $entityNode->setAttribute('tableName', $tableName);
+ $entityNode->setAttribute('tableName', $tableName->toString());
}
if ($namespace = $entity->getNamespace()) {
- $entityNode->setAttribute('namespace', $namespace);
+ $entityNode->setAttribute('namespace', $namespace->toString());
}
if ($entity->isSkipSql()) {
@@ -217,12 +216,12 @@ private function appendEntityNode(Entity $entity, \DOMNode $parentNode)
$entityNode->setAttribute('forReferenceOnly', $referenceOnly ? 'true' : 'false');
}
- if ($alias = $entity->getAlias()) {
- $entityNode->setAttribute('alias', $alias);
+ if (!$entity->getAlias()->isEmpty()) {
+ $entityNode->setAttribute('alias', $entity->getAlias()->toString());
}
- if ($description = $entity->getDescription()) {
- $entityNode->setAttribute('description', $description);
+ if ($entity->hasDescription()) {
+ $entityNode->setAttribute('description', $entity->getDescription()->toString());
}
$defaultStringFormat = $entity->getStringFormat();
@@ -275,10 +274,10 @@ private function appendEntityNode(Entity $entity, \DOMNode $parentNode)
* @param Behavior $behavior The Behavior model instance
* @param \DOMNode $parentNode The parent DOMNode object
*/
- private function appendBehaviorNode(Behavior $behavior, \DOMNode $parentNode)
+ private function appendBehaviorNode(Behavior $behavior, \DOMNode $parentNode): void
{
$behaviorNode = $parentNode->appendChild($this->document->createElement('behavior'));
- $behaviorNode->setAttribute('name', $behavior->getName());
+ $behaviorNode->setAttribute('name', $behavior->getName()->toString());
if ($behavior->allowMultiple()) {
$behaviorNode->setAttribute('id', $behavior->getId());
@@ -297,20 +296,20 @@ private function appendBehaviorNode(Behavior $behavior, \DOMNode $parentNode)
* @param Field $field The Field model instance
* @param \DOMNode $parentNode The parent DOMNode object
*/
- private function appendFieldNode(Field $field, \DOMNode $parentNode)
+ private function appendFieldNode(Field $field, \DOMNode $parentNode): void
{
$fieldNode = $parentNode->appendChild($this->document->createElement('field'));
- $fieldNode->setAttribute('name', $field->getName());
+ $fieldNode->setAttribute('name', $field->getName()->toString());
$fieldNode->setAttribute('type', $field->getType());
$domain = $field->getDomain();
if ($size = $domain->getSize()) {
- $fieldNode->setAttribute('size', $size);
+ $fieldNode->setAttribute('size', (string) $size);
}
if ($scale = $domain->getScale()) {
- $fieldNode->setAttribute('scale', $scale);
+ $fieldNode->setAttribute('scale', (string) $scale);
}
$platform = $field->getPlatform();
@@ -318,8 +317,8 @@ private function appendFieldNode(Field $field, \DOMNode $parentNode)
$fieldNode->setAttribute('sqlType', $platform->getDomainForType($field->getType())->getSqlType());
}
- if ($description = $field->getDescription()) {
- $fieldNode->setAttribute('description', $description);
+ if ($field->hasDescription()) {
+ $fieldNode->setAttribute('description', $field->getDescription()->toString());
}
if ($field->isPrimaryKey()) {
@@ -342,7 +341,7 @@ private function appendFieldNode(Field $field, \DOMNode $parentNode)
if ($field->isInheritance()) {
$fieldNode->setAttribute('inheritance', $field->getInheritanceType());
- foreach ($field->getInheritanceList() as $inheritance) {
+ foreach ($field->getChildren() as $inheritance) {
$this->appendInheritanceNode($inheritance, $fieldNode);
}
}
@@ -358,7 +357,7 @@ private function appendFieldNode(Field $field, \DOMNode $parentNode)
* @param Inheritance $inheritance The Inheritance model instance
* @param \DOMNode $parentNode The parent DOMNode object
*/
- private function appendInheritanceNode(Inheritance $inheritance, \DOMNode $parentNode)
+ private function appendInheritanceNode(Inheritance $inheritance, \DOMNode $parentNode): void
{
$inheritanceNode = $parentNode->appendChild($this->document->createElement('inheritance'));
$inheritanceNode->setAttribute('key', $inheritance->getKey());
@@ -375,13 +374,13 @@ private function appendInheritanceNode(Inheritance $inheritance, \DOMNode $paren
* @param Relation $relation The Relation model instance
* @param \DOMNode $parentNode The parent DOMNode object
*/
- private function appendRelationNode(Relation $relation, \DOMNode $parentNode)
+ private function appendRelationNode(Relation $relation, \DOMNode $parentNode): void
{
$relationNode = $parentNode->appendChild($this->document->createElement('relation'));
$relationNode->setAttribute('target', $relation->getForeignEntityName());
if ($relation->hasName()) {
- $relationNode->setAttribute('name', $relation->getName());
+ $relationNode->setAttribute('name', $relation->getName()->toString());
}
$relationNode->setAttribute('field', $relation->getField());
@@ -403,7 +402,7 @@ private function appendRelationNode(Relation $relation, \DOMNode $parentNode)
for ($i = 0, $size = $relation->getLocalFields()->size(); $i < $size; $i++) {
$refNode = $relationNode->appendChild($this->document->createElement('reference'));
- $refNode->setAttribute('local', $relation->getLocalField($i)->getName());
+ $refNode->setAttribute('local', $relation->getLocalField($i)->getName()->toString());
$refNode->setAttribute('foreign', $relation->getForeignFields()->get($i));
}
@@ -418,7 +417,7 @@ private function appendRelationNode(Relation $relation, \DOMNode $parentNode)
* @param IdMethodParameter $parameter The IdMethodParameter model instance
* @param \DOMNode $parentNode The parent DOMNode object
*/
- private function appendIdMethodParameterNode(IdMethodParameter $parameter, \DOMNode $parentNode)
+ private function appendIdMethodParameterNode(IdMethodParameter $parameter, \DOMNode $parentNode): void
{
$idMethodParameterNode = $parentNode->appendChild($this->document->createElement('id-method-parameter'));
$idMethodParameterNode->setAttribute('value', $parameter->getValue());
@@ -430,7 +429,7 @@ private function appendIdMethodParameterNode(IdMethodParameter $parameter, \DOMN
* @param Index $index The Index model instance
* @param \DOMNode $parentNode The parent DOMNode object
*/
- private function appendIndexNode(Index $index, \DOMNode $parentNode)
+ private function appendIndexNode(Index $index, \DOMNode $parentNode): void
{
$this->appendGenericIndexNode('index', $index, $parentNode);
}
@@ -441,7 +440,7 @@ private function appendIndexNode(Index $index, \DOMNode $parentNode)
* @param Unique $index The Unique model instance
* @param \DOMNode $parentNode The parent DOMNode object
*/
- private function appendUniqueIndexNode(Unique $index, \DOMNode $parentNode)
+ private function appendUniqueIndexNode(Unique $index, \DOMNode $parentNode): void
{
$this->appendGenericIndexNode('unique', $index, $parentNode);
}
@@ -453,17 +452,17 @@ private function appendUniqueIndexNode(Unique $index, \DOMNode $parentNode)
* @param Index $index The Index model instance
* @param \DOMNode $parentNode The parent DOMNode object
*/
- private function appendGenericIndexNode($nodeType, Index $index, \DOMNode $parentNode)
+ private function appendGenericIndexNode($nodeType, Index $index, \DOMNode $parentNode): void
{
$indexNode = $parentNode->appendChild($this->document->createElement($nodeType));
- $indexNode->setAttribute('name', $index->getName());
+ $indexNode->setAttribute('name', $index->getName()->toString());
foreach ($index->getFields() as $field) {
$indexFieldNode = $indexNode->appendChild($this->document->createElement($nodeType.'-field'));
- $indexFieldNode->setAttribute('name', $field->getName());
+ $indexFieldNode->setAttribute('name', $field->getName()->toString());
- if ($size = $index->getFieldSizes()->get($field->getName())) {
- $indexFieldNode->setAttribute('size', $size);
+ if ($size = $index->getFieldSizes()->get($field->getName()->toString())) {
+ $indexFieldNode->setAttribute('size', (string) $size);
}
}
diff --git a/src/Generator/Schema/Exception/InputOutputException.php b/src/Generator/Schema/Exception/InputOutputException.php
index 5cfdd5c0..5de857cd 100644
--- a/src/Generator/Schema/Exception/InputOutputException.php
+++ b/src/Generator/Schema/Exception/InputOutputException.php
@@ -1,4 +1,4 @@
-locator->locate($file));
- $content = Json::decode($file->read());
- return $content;
+ return Json::decode((string) $file->read());
}
/**
@@ -49,10 +50,8 @@ public function load($file, $type = null): array
*
* @return Boolean true if this class supports the given resource, false otherwise
*/
- public function supports($resource, $type = null): bool
+ public function supports($resource, string $type = null): bool
{
- $file = new File($resource);
-
- return 'json' === $file->getExtension();
+ return Text::create($resource)->endsWith('.json');
}
}
diff --git a/src/Generator/Schema/Loader/PhpSchemaLoader.php b/src/Generator/Schema/Loader/PhpSchemaLoader.php
index 448ef184..80c78302 100644
--- a/src/Generator/Schema/Loader/PhpSchemaLoader.php
+++ b/src/Generator/Schema/Loader/PhpSchemaLoader.php
@@ -1,4 +1,4 @@
-locator->locate($file);
@@ -73,11 +72,10 @@ public function load($file, $type = null)
*
* @return Boolean true if this class supports the given resource, false otherwise
*/
- public function supports($resource, $type = null): bool
+ public function supports($resource, string $type = null): bool
{
- $file = new File($resource);
- $extension = $file->getExtension();
+ $resource = new Text($resource);
- return ('php' === $extension) || ('inc') === $extension;
+ return $resource->endsWith('.php') || $resource->endsWith('.inc');
}
}
diff --git a/src/Generator/Schema/Loader/XmlSchemaLoader.php b/src/Generator/Schema/Loader/XmlSchemaLoader.php
index 1e210f2b..a88149d2 100644
--- a/src/Generator/Schema/Loader/XmlSchemaLoader.php
+++ b/src/Generator/Schema/Loader/XmlSchemaLoader.php
@@ -1,4 +1,4 @@
-locator->locate($file));
$content = XmlToArrayConverter::convert($this->normalize($file));
if ([] === $content) {
- throw new InvalidArgumentException("The schema file '{$file->getPathname()}' has invalid content.");
+ throw new InvalidArgumentException("The schema file `{$file->getPathname()}` has invalid content.");
}
return $content;
@@ -54,11 +54,9 @@ public function load($file, $type = null): array
*
* @return Boolean true if this class supports the given resource, false otherwise
*/
- public function supports($resource, $type = null): bool
+ public function supports($resource, string $type = null): bool
{
- $file = new File($resource);
-
- return 'xml' === $file->getExtension();
+ return Text::create($resource)->endsWith('.xml');
}
/**
@@ -67,15 +65,18 @@ public function supports($resource, $type = null): bool
* @param File $file
*
* @return string
- * @throws \phootwork\file\exception\FileException
+ * @throws FileException
*/
private function normalize(File $file): string
{
$xmlContent = $file->read();
- if ('' === $xmlContent || $xmlContent[0] !== '<') {
- throw new InvalidArgumentException("The schema file '{$file->getPathname()}' has invalid content.");
+ if ($xmlContent->isEmpty() || !$xmlContent->startsWith('<')) {
+ throw new InvalidArgumentException("The schema file `{$file->getPathname()}` has invalid content.");
}
- return '' . substr($xmlContent, strpos($xmlContent, '';
+ return $xmlContent->substring($xmlContent->indexOf('prepend('')
+ ->append('')
+ ->toString();
}
}
diff --git a/src/Generator/Schema/Loader/YamlSchemaLoader.php b/src/Generator/Schema/Loader/YamlSchemaLoader.php
index b40ebb98..9038de75 100644
--- a/src/Generator/Schema/Loader/YamlSchemaLoader.php
+++ b/src/Generator/Schema/Loader/YamlSchemaLoader.php
@@ -1,4 +1,4 @@
-locator->locate($file));
+ $file = new File($this->locator->locate($file));
- $content = Yaml::parse($file->read());
+ $content = Yaml::parse($file->read()->toString());
if (!is_array($content)) {
- throw new ParseException('The content is not valid yaml.');
+ throw new ParseException("The content of the schema file `{$file->getPathname()}` is not valid yaml.");
}
return $content;
@@ -56,11 +57,10 @@ public function load($file, $type = null): array
*
* @return Boolean true if this class supports the given resource, false otherwise
*/
- public function supports($resource, $type = null): bool
+ public function supports($resource, string $type = null): bool
{
- $file = new File($resource);
- $extension = $file->getExtension();
+ $resource = new Text($resource);
- return ('yaml' === $extension) || ('yml' === $extension);
+ return $resource->endsWith('.yaml') || $resource->endsWith('.yml');
}
}
diff --git a/src/Generator/Schema/SchemaConfiguration.php b/src/Generator/Schema/SchemaConfiguration.php
index 7df89083..83d71ae2 100644
--- a/src/Generator/Schema/SchemaConfiguration.php
+++ b/src/Generator/Schema/SchemaConfiguration.php
@@ -1,4 +1,4 @@
-root('database');
+ $treeBuilder = new TreeBuilder('database');
+ $rootNode = $treeBuilder->getRootNode();
$rootNode
->fixXmlConfig('entity', 'entities')
->fixXmlConfig('behavior')
@@ -52,58 +51,9 @@ public function getConfigTreeBuilder()
->booleanNode('heavyIndexing')->defaultFalse()->end()
->scalarNode('baseClass')->end()
->scalarNode('schema')->end()
- ->arrayNode('external-schemas')
- ->arrayPrototype()
- ->addDefaultsIfNotSet()
- ->children()
- ->scalarNode('filename')->end()
- ->booleanNode('referenceOnly')->defaultTrue()->end()
- ->end()
- ->end()
- ->end()
- ->arrayNode('behaviors')
- ->beforeNormalization()
- ->always(function($behaviors) {
- foreach ($behaviors as $key => $behavior) {
- if (!isset($behavior['id'])) {
- $behaviors[$key]['id'] = $behavior['name'];
- }
- }
-
- return $behaviors;
- })
- ->end()
- ->useAttributeAsKey('id')
- ->arrayPrototype()
- ->fixXmlConfig('parameter')
- ->children()
- ->scalarNode('name')->isRequired()->cannotBeEmpty()->end()
- ->arrayNode('parameters')
- ->useAttributeAsKey('name')
- ->arrayPrototype()
- ->children()
- ->scalarNode('name')->end()
- ->scalarNode('value')->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->arrayNode('vendor')
- ->fixXmlConfig('parameter')
- ->children()
- ->enumNode('type')->values(['mysql', 'MYSQL', 'oracle', 'ORACLE', 'pgsql', 'PGSQL'])->end()
- ->arrayNode('parameters')
- ->arrayPrototype()
- ->children()
- ->scalarNode('name')->end()
- ->scalarNode('value')->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->end()
+ ->append($this->getExternalSchemasNode())
+ ->append($this->getBehaviorNode())
+ ->append($this->getVendorNode())
->arrayNode('entities')
->requiresAtLeastOneElement()
->arrayPrototype()
@@ -118,9 +68,7 @@ public function getConfigTreeBuilder()
->isRequired()
->cannotBeEmpty()
->beforeNormalization()
- ->always(function($name) {
- return NamingTool::toStudlyCase($name);
- })
+ ->always(fn(string $name): string => Text::create($name)->toStudlyCase()->toString())
->end()
->end()
->scalarNode('tableName')->end()
@@ -142,248 +90,12 @@ public function getConfigTreeBuilder()
->booleanNode('allowPkInsert')->defaultFalse()->end()
->booleanNode('heavyIndexing')->end()
->scalarNode('defaultStringFormat')->end()
- ->arrayNode('fields')
- ->requiresAtLeastOneElement()
- ->fixXmlconfig('inheritance')
- ->arrayPrototype()
- ->addDefaultsIfNotSet()
- ->children()
- ->scalarNode('name')->isRequired()->cannotBeEmpty()->end()
- ->booleanNode('primaryKey')->defaultFalse()->end()
- ->booleanNode('required')->defaultFalse()->end()
- ->enumNode('type')
- ->beforeNormalization()->always(function ($variable) {
- return strtoupper($variable);
- })
- ->end()
- ->values(['BIT', 'TINYINT', 'SMALLINT', 'INTEGER', 'BIGINT', 'FLOAT',
- 'REAL', 'NUMERIC', 'DECIMAL', 'CHAR', 'VARCHAR', 'LONGVARCHAR',
- 'DATE', 'TIME', 'TIMESTAMP', 'BINARY', 'VARBINARY', 'LONGVARBINARY',
- 'NULL', 'OTHER', 'PHP_OBJECT', 'DISTINCT', 'STRUCT', 'ARRAY',
- 'BLOB', 'CLOB', 'REF', 'BOOLEANINT', 'BOOLEANCHAR', 'DOUBLE',
- 'BOOLEAN', 'OBJECT', 'ENUM'
- ])
- ->isRequired()
- ->cannotBeEmpty()
- ->defaultValue('VARCHAR')
- ->end()
- ->scalarNode('phpType')->end()
- ->scalarNode('sqlType')->end()
- ->integerNode('size')->end()
- ->integerNode('scale')->end()
- ->scalarNode('default')->end()
- ->scalarNode('defaultValue')->end()
- ->scalarNode('defaultExpr')->end()
- ->booleanNode('autoIncrement')->defaultFalse()->end()
- ->enumNode('inheritance')->values(['single', 'none'])->defaultValue('none')->end()
- ->scalarNode('description')->end()
- ->booleanNode('lazyLoad')->defaultFalse()->end()
- ->booleanNode('primaryString')->defaultFalse()->end()
- ->scalarNode('valueSet')->end()
- ->arrayNode('inheritances')
- ->arrayPrototype()
- ->children()
- ->scalarNode('key')->isRequired()->end()
- ->scalarNode('class')->isRequired()->end()
- ->scalarNode('extends')->end()
- ->end()
- ->end()
- ->end()
- ->arrayNode('vendor')
- ->fixXmlConfig('parameter')
- ->children()
- ->enumNode('type')
- ->values(['mysql', 'MYSQL', 'oracle', 'ORACLE', 'pgsql', 'PGSQL'])
- ->end()
- ->arrayNode('parameters')
- ->arrayPrototype()
- ->children()
- ->scalarNode('name')->end()
- ->scalarNode('value')->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->arrayNode('relations')
- ->arrayPrototype()
- ->fixXmlConfig('reference')
- ->children()
- ->scalarNode('target')
- ->isRequired()
- ->cannotBeEmpty()
- ->beforeNormalization()
- ->always(function($name) {
- return NamingTool::toStudlyCase($name);
- })
- ->end()
- ->end()
- ->scalarNode('field')->end()
- ->scalarNode('name')->end()
- ->scalarNode('refField')->end()
- ->scalarNode('refName')->end()
- ->scalarNode('foreignSchema')->end()
- ->enumNode('onUpdate')
- ->beforeNormalization()->always(function ($variable) {
- return strtoupper($variable);
- })
- ->end()
- ->values(['CASCADE', 'SETNULL', 'RESTRICT', 'NONE'])
- ->end()
- ->enumNode('onDelete')
- ->beforeNormalization()->always(function ($variable) {
- return strtoupper($variable);
- })
- ->end()
- ->values(['CASCADE', 'SETNULL', 'RESTRICT', 'NONE'])
- ->end()
- ->enumNode('defaultJoin')
- ->beforeNormalization()->always(function ($variable) {
- return strtoupper($variable);
- })
- ->end()
- ->values(['INNER JOIN', 'LEFT JOIN'])
- ->end()
- ->booleanNode('skipSql')->defaultFalse()->end()
- ->arrayNode('references')
- ->arrayPrototype()
- ->children()
- ->scalarNode('local')->isRequired()->cannotBeEmpty()->end()
- ->scalarNode('foreign')->isRequired()->cannotBeEmpty()->end()
- ->end()
- ->end()
- ->end()
- ->arrayNode('vendor')
- ->fixXmlConfig('parameter')
- ->children()
- ->enumNode('type')
- ->values(['mysql', 'MYSQL', 'oracle', 'ORACLE', 'pgsql', 'PGSQL'])
- ->end()
- ->arrayNode('parameters')
- ->arrayPrototype()
- ->children()
- ->scalarNode('name')->end()
- ->scalarNode('value')->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->arrayNode('indices')
- ->arrayPrototype()
- ->fixXmlConfig('index-field', 'index-fields')
- ->normalizeKeys(false)
- ->children()
- ->scalarNode('name')->end()
- ->arrayNode('index-fields')
- ->arrayPrototype()
- ->children()
- ->scalarNode('name')->isRequired()->end()
- ->integerNode('size')->end()
- ->end()
- ->end()
- ->end()
- ->arrayNode('vendor')
- ->fixXmlConfig('parameter')
- ->children()
- ->enumNode('type')
- ->values(['mysql', 'MYSQL', 'oracle', 'ORACLE', 'pgsql', 'PGSQL'])
- ->end()
- ->arrayNode('parameters')
- ->arrayPrototype()
- ->children()
- ->scalarNode('name')->end()
- ->scalarNode('value')->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->arrayNode('uniques')
- ->arrayPrototype()
- ->fixXmlConfig('unique-field', 'unique-fields')
- ->normalizeKeys(false)
- ->children()
- ->scalarNode('name')->end()
- ->arrayNode('unique-fields')
- ->arrayPrototype()
- ->children()
- ->scalarNode('name')->isRequired()->end()
- ->integerNode('size')->end()
- ->end()
- ->end()
- ->end()
- ->arrayNode('vendor')
- ->fixXmlConfig('parameter')
- ->children()
- ->enumNode('type')
- ->values(['mysql', 'MYSQL', 'oracle', 'ORACLE', 'pgsql', 'PGSQL'])
- ->end()
- ->arrayNode('parameters')
- ->arrayPrototype()
- ->children()
- ->scalarNode('name')->end()
- ->scalarNode('value')->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->arrayNode('behaviors')
- ->beforeNormalization()
- ->always(function($behaviors) {
- foreach ($behaviors as $key => $behavior) {
- if (!isset($behavior['id'])) {
- $behaviors[$key]['id'] = $behavior['name'];
- }
- }
-
- return $behaviors;
- })
- ->end()
- ->useAttributeAsKey('id')
- ->arrayPrototype()
- ->fixXmlConfig('parameter')
- ->children()
- ->scalarNode('name')->isRequired()->cannotBeEmpty()->end()
- ->arrayNode('parameters')
- ->useAttributeAsKey('name')
- ->arrayPrototype()
- ->children()
- ->scalarNode('name')->end()
- ->scalarNode('value')->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->arrayNode('vendor')
- ->fixXmlConfig('parameter')
- ->children()
- ->enumNode('type')->values(['mysql', 'MYSQL','oracle', 'ORACLE', 'pgsql', 'PGSQL'])->end()
- ->arrayNode('parameters')
- ->arrayPrototype()
- ->children()
- ->scalarNode('name')->end()
- ->scalarNode('value')->end()
- ->end()
- ->end()
- ->end()
- ->end()
- ->end()
+ ->append($this->getFieldsNode())
+ ->append($this->getRelationsNode())
+ ->append($this->getIndicesNode())
+ ->append($this->getUniquesNode())
+ ->append($this->getBehaviorNode())
+ ->append($this->getVendorNode())
->arrayNode('id_method_parameter')
->children()
->scalarNode('value')->end()
@@ -398,4 +110,236 @@ public function getConfigTreeBuilder()
return $treeBuilder;
}
+
+ private function getParametersNode(): NodeDefinition
+ {
+ $treeBuilder = new TreeBuilder('parameters');
+
+ return $treeBuilder->getRootNode()
+ ->useAttributeAsKey('name')
+ ->arrayPrototype()
+ ->children()
+ ->scalarNode('name')->end()
+ ->scalarNode('value')->end()
+ ->end()
+ ->end()
+ ;
+ }
+
+ private function getBehaviorNode(): NodeDefinition
+ {
+ $treeBuilder = new TreeBuilder('behaviors');
+
+ return $treeBuilder->getRootNode()
+ ->beforeNormalization()
+ ->always(function(array $behaviors): array {
+ foreach ($behaviors as $key => $behavior) {
+ if (!isset($behavior['id'])) {
+ $behaviors[$key]['id'] = $behavior['name'];
+ }
+ }
+
+ return $behaviors;
+ })
+ ->end()
+ ->useAttributeAsKey('id')
+ ->arrayPrototype()
+ ->fixXmlConfig('parameter')
+ ->children()
+ ->scalarNode('name')->isRequired()->cannotBeEmpty()->end()
+ ->append($this->getParametersNode())
+ ->end()
+ ->end()
+ ;
+ }
+
+ private function getVendorNode(): NodeDefinition
+ {
+ $treeBuilder = new TreeBuilder('vendor');
+
+ return $treeBuilder->getRootNode()
+ ->fixXmlConfig('parameter')
+ ->children()
+ ->enumNode('type')->values(['mysql', 'MYSQL','oracle', 'ORACLE', 'pgsql', 'PGSQL'])->end()
+ ->append($this->getParametersNode())
+ ->end()
+ ;
+ }
+
+ private function getExternalSchemasNode(): NodeDefinition
+ {
+ $treeBuilder = new TreeBuilder('external-schemas');
+
+ return $treeBuilder->getRootNode()
+ ->arrayPrototype()
+ ->addDefaultsIfNotSet()
+ ->children()
+ ->scalarNode('filename')->end()
+ ->booleanNode('referenceOnly')->defaultTrue()->end()
+ ->end()
+ ->end()
+ ;
+ }
+
+ private function getInheritancesNode(): NodeDefinition
+ {
+ $treeBuilder = new TreeBuilder('inheritances');
+
+ return $treeBuilder->getRootNode()
+ ->arrayPrototype()
+ ->children()
+ ->scalarNode('key')->isRequired()->end()
+ ->scalarNode('class')->isRequired()->end()
+ ->scalarNode('extends')->end()
+ ->end()
+ ->end()
+ ;
+ }
+
+ private function getFieldsNode(): NodeDefinition
+ {
+ $treeBuilder = new TreeBuilder('fields');
+
+ return $treeBuilder->getRootNode()
+ ->requiresAtLeastOneElement()
+ ->fixXmlConfig('inheritance')
+ ->arrayPrototype()
+ ->addDefaultsIfNotSet()
+ ->children()
+ ->scalarNode('name')->isRequired()->cannotBeEmpty()->end()
+ ->booleanNode('primaryKey')->defaultFalse()->end()
+ ->booleanNode('required')->defaultFalse()->end()
+ ->enumNode('type')
+ ->beforeNormalization()->always(fn(string $variable): string => strtoupper($variable))->end()
+ ->values(['BIT', 'TINYINT', 'SMALLINT', 'INTEGER', 'BIGINT', 'FLOAT',
+ 'REAL', 'NUMERIC', 'DECIMAL', 'CHAR', 'VARCHAR', 'LONGVARCHAR',
+ 'DATE', 'TIME', 'TIMESTAMP', 'BINARY', 'VARBINARY', 'LONGVARBINARY',
+ 'NULL', 'OTHER', 'PHP_OBJECT', 'DISTINCT', 'STRUCT', 'ARRAY',
+ 'BLOB', 'CLOB', 'REF', 'BOOLEANINT', 'BOOLEANCHAR', 'DOUBLE',
+ 'BOOLEAN', 'OBJECT', 'ENUM'
+ ])
+ ->isRequired()
+ ->cannotBeEmpty()
+ ->defaultValue('VARCHAR')
+ ->end()
+ ->scalarNode('phpType')->end()
+ ->scalarNode('sqlType')->end()
+ ->integerNode('size')->end()
+ ->integerNode('scale')->end()
+ ->scalarNode('default')->end()
+ ->scalarNode('defaultValue')->end()
+ ->scalarNode('defaultExpr')->end()
+ ->booleanNode('autoIncrement')->defaultFalse()->end()
+ ->enumNode('inheritance')->values(['single', 'none'])->defaultValue('none')->end()
+ ->scalarNode('description')->end()
+ ->booleanNode('lazyLoad')->defaultFalse()->end()
+ ->booleanNode('primaryString')->defaultFalse()->end()
+ ->scalarNode('valueSet')->end()
+ ->append($this->getInheritancesNode())
+ ->append($this->getVendorNode())
+ ->end()
+ ->end()
+ ;
+ }
+
+ private function getRelationsNode(): NodeDefinition
+ {
+ $treeBuilder = new TreeBuilder('relations');
+
+ return $treeBuilder->getRootNode()
+ ->arrayPrototype()
+ ->fixXmlConfig('reference')
+ ->children()
+ ->scalarNode('target')
+ ->isRequired()
+ ->cannotBeEmpty()
+ ->beforeNormalization()
+ ->always(fn(string $name): string => Text::create($name)->toStudlyCase()->toString())
+ ->end()
+ ->end()
+ ->scalarNode('field')->end()
+ ->scalarNode('name')->end()
+ ->scalarNode('refField')->end()
+ ->scalarNode('refName')->end()
+ ->scalarNode('foreignSchema')->end()
+ ->enumNode('onUpdate')
+ ->beforeNormalization()
+ ->always(fn(string $variable): string => strtoupper($variable))
+ ->end()
+ ->values(['CASCADE', 'SETNULL', 'RESTRICT', 'NONE'])
+ ->end()
+ ->enumNode('onDelete')
+ ->beforeNormalization()
+ ->always(fn(string $variable): string => strtoupper($variable))
+ ->end()
+ ->values(['CASCADE', 'SETNULL', 'RESTRICT', 'NONE'])
+ ->end()
+ ->enumNode('defaultJoin')
+ ->beforeNormalization()
+ ->always(fn(string $variable): string => strtoupper($variable))
+ ->end()
+ ->values(['INNER JOIN', 'LEFT JOIN'])
+ ->end()
+ ->booleanNode('skipSql')->defaultFalse()->end()
+ ->arrayNode('references')
+ ->arrayPrototype()
+ ->children()
+ ->scalarNode('local')->isRequired()->cannotBeEmpty()->end()
+ ->scalarNode('foreign')->isRequired()->cannotBeEmpty()->end()
+ ->end()
+ ->end()
+ ->end()
+ ->append($this->getVendorNode())
+ ->end()
+ ->end()
+ ;
+ }
+
+ private function getIndicesNode(): NodeDefinition
+ {
+ $treeBuilder = new TreeBuilder('indices');
+
+ return $treeBuilder->getRootNode()
+ ->arrayPrototype()
+ ->fixXmlConfig('index-field', 'index-fields')
+ ->normalizeKeys(false)
+ ->children()
+ ->scalarNode('name')->end()
+ ->arrayNode('index-fields')
+ ->arrayPrototype()
+ ->children()
+ ->scalarNode('name')->isRequired()->end()
+ ->integerNode('size')->end()
+ ->end()
+ ->end()
+ ->end()
+ ->append($this->getVendorNode())
+ ->end()
+ ->end()
+ ;
+ }
+
+ private function getUniquesNode(): NodeDefinition
+ {
+ $treeBuilder = new TreeBuilder('uniques');
+
+ return $treeBuilder->getRootNode()
+ ->arrayPrototype()
+ ->fixXmlConfig('unique-field', 'unique-fields')
+ ->normalizeKeys(false)
+ ->children()
+ ->scalarNode('name')->end()
+ ->arrayNode('unique-fields')
+ ->arrayPrototype()
+ ->children()
+ ->scalarNode('name')->isRequired()->end()
+ ->integerNode('size')->end()
+ ->end()
+ ->end()
+ ->end()
+ ->append($this->getVendorNode())
+ ->end()
+ ->end()
+ ;
+ }
}
diff --git a/src/Generator/Schema/SchemaParserTrait.php b/src/Generator/Schema/SchemaParserTrait.php
index 7bd3b313..d94cd280 100644
--- a/src/Generator/Schema/SchemaParserTrait.php
+++ b/src/Generator/Schema/SchemaParserTrait.php
@@ -1,13 +1,20 @@
-modelFactory) {
- $this->modelFactory = new ModelFactory($this->getGeneratorConfig());
- }
-
- return $this->modelFactory;
+ return $this->modelFactory ?? $this->modelFactory = new ModelFactory($this->getGeneratorConfig());
}
/**
@@ -126,7 +126,7 @@ private function addIndices(array $indices, Entity $entity): void
foreach ($indices as $index) {
$indexObj = $this->getModelFactory()->createIndex($index);
foreach ($index['index-fields'] as $indexField) {
- $field = $entity->getField($indexField['name']);
+ $field = $entity->getFieldByName($indexField['name']);
if (isset($indexField['size'])) {
$index->getFieldSizes()->set($field->getName(), $indexField['size']);
}
@@ -150,7 +150,7 @@ private function addUniques(array $uniques, Entity $entity): void
foreach ($uniques as $unique) {
$uniqueObj = $this->getModelFactory()->createUnique($unique);
foreach ($unique['unique-fields'] as $uniqueField) {
- $field = $entity->getField($uniqueField['name']);
+ $field = $entity->getFieldByName($uniqueField['name']);
if (isset($uniqueField['size'])) {
$field->setSize($uniqueField['size']);
}
@@ -259,6 +259,6 @@ private function getExternalFilename(string $filename, Schema $schema): string
return $schemaFile->getDirname() . DIRECTORY_SEPARATOR . $file->getPathname();
}
- return $file->getPathname();
+ return $file->getPathname()->toString();
}
}
diff --git a/src/Generator/Schema/SchemaReader.php b/src/Generator/Schema/SchemaReader.php
index 454384ff..e92b3984 100644
--- a/src/Generator/Schema/SchemaReader.php
+++ b/src/Generator/Schema/SchemaReader.php
@@ -1,5 +1,4 @@
-config = $config;
+ $this->config = $config ?? new QuickGeneratorConfig();
$this->parsedFiles = new Set();
}
@@ -59,9 +50,6 @@ public function getGeneratorConfig(): GeneratorConfigInterface
return $this->config;
}
- /**
- * @param GeneratorConfigInterface $config
- */
public function setGeneratorConfig(GeneratorConfigInterface $config): void
{
$this->config = $config;
@@ -76,7 +64,7 @@ public function setGeneratorConfig(GeneratorConfigInterface $config): void
* @return Schema
* @throws \Exception
*/
- public function parse(string $filename): Schema
+ public function parse(string $filename): ?Schema
{
// we don't want infinite recursion
if ($this->parsedFiles->contains($filename)) {
@@ -94,6 +82,7 @@ public function parse(string $filename): Schema
}
/**
+ * @todo move into something about tests, since Quickbuilder is for testing only
* Parse a string containing an xml schema.
* Useful only for Quickbuilder.
*
@@ -156,9 +145,8 @@ private function loadSchema(string $filename): array
new PhpSchemaLoader($fileLocator)
]);
$delegatingLoader = new DelegatingLoader($loaderResolver);
- $schemaArray = $delegatingLoader->load($file->toPath()->getFilename());
- return $schemaArray;
+ return $delegatingLoader->load((string) $file->toPath()->getFilename());
}
/**
diff --git a/tests/Common/Collection/ArrayListTest.php b/tests/Common/Collection/ArrayListTest.php
deleted file mode 100644
index 110685b5..00000000
--- a/tests/Common/Collection/ArrayListTest.php
+++ /dev/null
@@ -1,52 +0,0 @@
-setName('myDomain');
- $set = new ArrayList([$object], Domain::class);
-
- $this->assertTrue($set->search($object, function($element, $query){
- return $element === $query;
- }));
-
- $object1 = new Domain();
- $object1->setName('mySecondDomain');
-
- $set->add($object1);
-
- $this->assertEquals(2, $set->size());
- $this->assertTrue($set->search($object1, function($element, $query){
- return $element === $query;
- }));
- }
-
- /**
- * @expectedException \Propel\Common\Collection\Exception\CollectionException
- */
- public function testAddWrongObjectThrowsException()
- {
- $obj = new Domain();
- $obj->setName('myDomain');
- $set = new ArrayList([$obj], Domain::class);
- $wrong = new Vendor();
- $set->add($wrong);
- }
-}
diff --git a/tests/Common/Collection/MapTest.php b/tests/Common/Collection/MapTest.php
deleted file mode 100644
index ad3392bf..00000000
--- a/tests/Common/Collection/MapTest.php
+++ /dev/null
@@ -1,51 +0,0 @@
-setName('myDomain');
- $set = new Map(['obj' => $object], Domain::class);
-
- $this->assertTrue($set->search($object, function($element, $query){
- return $element === $query;
- }));
-
- $object1 = new Domain();
- $object1->setName('mySecondDomain');
-
- $set->set('obj1', $object1);
-
- $this->assertEquals(2, $set->size());
- $this->assertTrue($set->search($object1, function($element, $query){
- return $element === $query;
- }));
- }
-
- /**
- * @expectedException \Propel\Common\Collection\Exception\CollectionException
- */
- public function testAddWrongObjectThrowsException()
- {
- $obj = new Domain();
- $set = new Map(['obj' => $obj], Domain::class);
- $wrong = new Vendor();
- $set->set('wrong', $wrong);
- }
-}
diff --git a/tests/Common/Collection/SetTest.php b/tests/Common/Collection/SetTest.php
deleted file mode 100644
index 61f9483f..00000000
--- a/tests/Common/Collection/SetTest.php
+++ /dev/null
@@ -1,51 +0,0 @@
-setName('myDomain');
- $set = new Set([$object], Domain::class);
-
- $this->assertTrue($set->search($object, function($element, $query){
- return $element === $query;
- }));
-
- $object1 = new Domain();
- $object1->setName('mySecondDomain');
-
- $set->add($object1);
-
- $this->assertEquals(2, $set->size());
- $this->assertTrue($set->search($object1, function($element, $query){
- return $element === $query;
- }));
- }
-
- /**
- * @expectedException \Propel\Common\Collection\Exception\CollectionException
- */
- public function testAddWrongObjectThrowsException()
- {
- $obj = new Domain();
- $set = new Set([$obj], Domain::class);
- $wrong = new Vendor();
- $set->add($wrong);
- }
-}
diff --git a/tests/Common/Config/ConfigurationManagerTest.php b/tests/Common/Config/ConfigurationManagerTest.php
index 5be90a8a..e6d14d09 100644
--- a/tests/Common/Config/ConfigurationManagerTest.php
+++ b/tests/Common/Config/ConfigurationManagerTest.php
@@ -1,5 +1,4 @@
-assertEquals('baz', $actual['bar']);
}
- public function testLoadConfigFileInConfigSubdirectory()
+ public function testLoadConfigFileInConfigSubdirectory(): void
{
$yamlConf = <<assertEquals('baz', $actual['bar']);
}
- public function testLoadConfigFileInConfSubdirectory()
+ public function testLoadConfigFileInConfSubdirectory(): void
{
$yamlConf = <<assertEquals('baz', $actual['bar']);
}
- public function testNotExistingConfigFileLoadsDefaultSettingsAndDoesNotThrowExceptions()
+ public function testNotExistingConfigFileLoadsDefaultSettingsAndDoesNotThrowExceptions(): void
{
$yamlConf = <<assertArrayNotHasKey('baz', $actual);
}
- public function testUnsupportedExtensionsAreIgnored()
+ public function testUnsupportedExtensionsAreIgnored(): void
{
$yamlConf = <<assertArrayNotHasKey('baz', $actual);
}
- /**
- * @expectedException \Propel\Common\Config\Exception\InvalidArgumentException
- * @exceptionMessage Propel expects only one configuration file
- */
- public function testMoreThanOneConfigurationFileInSameDirectoryThrowsException()
+ public function testMoreThanOneConfigurationFileInSameDirectoryThrowsException(): void
{
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage("Propel expects only one configuration file");
+
$yamlConf = <<getRoot()->url());
}
- /**
- * @expectedException \Propel\Common\Config\Exception\InvalidArgumentException
- * @exceptionMessage Propel expects only one configuration file
- */
- public function testMoreThanOneConfigurationFileInDifferentDirectoriesThrowsException()
+ public function testMoreThanOneConfigurationFileInDifferentDirectoriesThrowsException(): void
{
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage("Propel expects only one configuration file");
$yamlConf = <<getRoot()->url());
}
- public function testGetSection()
+ public function testGetSection(): void
{
$yamlConf = <<newFile('propel.yaml', $yamlConf);
$manager = new TestableConfigurationManager($this->getRoot()->url());
- $actual = $manager->getSection('buildtime');
+ $actual = $manager->get('buildtime');
$this->assertEquals('bbar', $actual['bfoo']);
$this->assertEquals('bbaz', $actual['bbar']);
}
- public function testLoadGivenConfigFile()
+ public function testLoadGivenConfigFile(): void
{
$yamlConf = <<assertEquals(['foo' => 'bar', 'bar' => 'baz'], $actual);
}
- public function testLoadAlsoDistConfigFile()
+ public function testLoadAlsoDistConfigFile(): void
{
$yamlConf = <<assertEquals(['foo' => 'bar', 'bar' => 'baz'], $actual['runtime']);
}
- public function testLoadOnlyDistFile()
+ public function testLoadOnlyDistFile(): void
{
$yamlDistConf = <<assertEquals(['runtime' => ['foo' => 'bar', 'bar' => 'baz']], $actual);
}
- public function testLoadGivenFileAndDist()
+ public function testLoadGivenFileAndDist(): void
{
$yamlConf = <<assertEquals(['bfoo' => 'bbar', 'bbar' => 'bbaz'], $actual['buildtime']);
}
- public function testLoadDistGivenFileOnly()
+ public function testLoadDistGivenFileOnly(): void
{
$yamlDistConf = <<assertEquals(['runtime' => ['foo' => 'bar', 'bar' => 'baz']], $actual);
}
- public function testLoadInGivenDirectory()
+ public function testLoadInGivenDirectory(): void
{
$yamlConf = <<assertEquals(['bfoo' => 'bbar', 'bbar' => 'bbaz'], $actual['buildtime']);
}
- public function testMergeExtraProperties()
+ public function testMergeExtraProperties(): void
{
$extraConf = [
'buildtime' => [
@@ -316,12 +312,11 @@ public function testMergeExtraProperties()
$this->assertEquals($actual['extralevel'], ['extra1' => 'val1', 'extra2' => 'val2']);
}
- /**
- * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
- * @expectedExceptionMessage Unrecognized options "foo, bar" under "propel"
- */
- public function testInvalidHierarchyTrowsException()
+ public function testInvalidHierarchyTrowsException(): void
{
+ $this->expectException(InvalidConfigurationException::class);
+ $this->expectExceptionMessage("Unrecognized options \"foo, bar\" under \"propel\"");
+
$yamlConf = <<getRoot()->url());
}
- public function testNotDefineRuntimeAndGeneratorSectionUsesDefaultConnections()
+ public function testNotDefineRuntimeAndGeneratorSectionUsesDefaultConnections(): void
{
$yamlConf = <<assertArrayHasKey('runtime', $manager->get());
$this->assertArrayHasKey('generator', $manager->get());
- $this->assertArrayHasKey('connections', $manager->getSection('runtime'));
- $this->assertArrayHasKey('connections', $manager->getSection('generator'));
+ $this->assertArrayHasKey('connections', $manager->get('runtime'));
+ $this->assertArrayHasKey('connections', $manager->get('generator'));
$this->assertEquals(['default'], $manager->get()['runtime']['connections']);
$this->assertEquals(['default'], $manager->get()['generator']['connections']);
}
- /**
- * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
- * @expectedExceptionMessage Dots are not allowed in connection names
- */
- public function testDotInConnectionNamesArentAccepted()
+ public function testDotInConnectionNamesArentAccepted(): void
{
+ $this->expectException(InvalidConfigurationException::class);
+ $this->expectExceptionMessage("Dots are not allowed in connection names");
+
$yamlConf = <<getRoot()->url());
}
- public function testLoadValidConfigurationFile()
+ public function testLoadValidConfigurationFile(): void
{
$yamlConf = <<newFile('propel.yaml', $yamlConf);
$manager = new ConfigurationManager($this->getRoot()->url());
- $actual = $manager->getSection('runtime');
+ $actual = $manager->get('runtime');
$this->assertEquals($actual['defaultConnection'], 'mysource');
$this->assertEquals($actual['connections'], ['mysource', 'yoursource']);
}
- public function testSomeDeafults()
+ public function testSomeDeafults(): void
{
$yamlConf = <<get();
$this->assertEquals($actual['generator']['dateTime']['dateTimeClass'], 'DateTime');
- $this->assertEquals($actual['generator']['objectModel']['pluralizerClass'], '\Propel\Common\Pluralizer\StandardEnglishPluralizer');
}
- public function testGetConfigProperty()
+ public function testGetConfigProperty(): void
{
$yamlConf = <<newFile('propel.yaml', $yamlConf);
$manager = new ConfigurationManager($this->getRoot()->url());
- $this->assertEquals('mysource', $manager->getConfigProperty('runtime.defaultConnection'));
- $this->assertEquals('yoursource', $manager->getConfigProperty('runtime.connections.1'));
- $this->assertEquals('root', $manager->getConfigProperty('database.connections.mysource.user'));
+ $this->assertEquals('mysource', $manager->get('runtime.defaultConnection'));
+ $this->assertEquals('yoursource', $manager->get('runtime.connections.1'));
+ $this->assertEquals('root', $manager->get('database.connections.mysource.user'));
}
- public function testGetConfigPropertyBadName()
+ public function testGetConfigPropertyBadName(): void
{
$yamlConf = <<newFile('propel.yaml', $yamlConf);
$manager = new ConfigurationManager($this->getRoot()->url());
- $value = $manager->getConfigProperty('database.connections.adapter');
+ $value = $manager->get('database.connections.adapter');
$this->assertNull($value);
}
- public function testProcessWithParam()
+ public function testProcessWithParam(): void
{
$configs = [
'propel' => [
@@ -581,19 +574,19 @@ public function testProcessWithParam()
];
$manager = new NotLoadingConfigurationManager($configs);
- $actual = $manager->getSection('database')['connections'];
+ $actual = $manager->get('database.connections');
$this->assertEquals($configs['propel']['database']['connections'], $actual);
}
- public function testProcessWrongParameter()
+ public function testProcessWrongParameter(): void
{
$manager = new NotLoadingConfigurationManager(null);
$this->assertNotEmpty($manager->get());
}
- public function testGetConfigurationParametersArrayTest()
+ public function testGetConfigurationParametersArrayTest(): void
{
$yamlConf = <<loader = new TestableFileLoader();
}
@@ -100,12 +100,15 @@ public function resolveParamsProvider()
];
}
- public function testInitialResolveValueIsFalse()
+ public function testInitialResolveValueIsFalse(): void
{
- $this->assertAttributeEquals(false, 'resolved', $this->loader);
+ $prop = (new \ReflectionObject($this->loader))->getParentClass()->getProperty('resolved');
+ $prop->setAccessible(true);
+
+ $this->assertEquals(false, $prop->getValue($this->loader));
}
- public function testResolveParams()
+ public function testResolveParams(): void
{
putenv('host=127.0.0.1');
putenv('user=root');
@@ -157,7 +160,7 @@ public function testResolveValues($conf, $expected, $message)
$this->assertEquals($expected, $this->loader->resolveParams($conf), $message);
}
- public function testResolveReplaceWithoutCasting()
+ public function testResolveReplaceWithoutCasting(): void
{
$conf = $this->loader->resolveParams(['foo'=>true, 'expfoo' => '%foo%', 'bar' => null, 'expbar' => '%bar%']);
@@ -165,43 +168,39 @@ public function testResolveReplaceWithoutCasting()
$this->assertNull($conf['expbar'], '->resolve() replaces arguments that are just a placeholder by their value without casting them to strings');
}
- /**
- * @expectedException Propel\Common\Config\Exception\InvalidArgumentException
- * @expectedExceptionMessage Parameter 'baz' not found in configuration file.
- */
- public function testResolveThrowsExceptionIfInvalidPlaceholder()
+ public function testResolveThrowsExceptionIfInvalidPlaceholder(): void
{
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage("Parameter 'baz' not found in configuration file.");
+
$this->loader->resolveParams(['foo' => 'bar', '%baz%']);
}
- /**
- * @expectedException Propel\Common\Config\Exception\InvalidArgumentException
- * @expectedExceptionMessage Parameter 'foobar' not found in configuration file.
- */
- public function testResolveThrowsExceptionIfNonExistentParameter()
+ public function testResolveThrowsExceptionIfNonExistentParameter(): void
{
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage("Parameter 'foobar' not found in configuration file.");
+
$this->loader->resolveParams(['foo %foobar% bar']);
}
- /**
- * @expectedException Propel\Common\Config\Exception\RuntimeException
- * @expectedExceptionMessage Circular reference detected for parameter 'bar'.
- */
- public function testResolveThrowsRuntimeExceptionIfCircularReference()
+ public function testResolveThrowsRuntimeExceptionIfCircularReference(): void
{
+ $this->expectException(RuntimeException::class);
+ $this->expectExceptionMessage("Circular reference detected for parameter 'bar'.");
+
$this->loader->resolveParams(['foo' => '%bar%', 'bar' => '%foobar%', 'foobar' => '%foo%']);
}
- /**
- * @expectedException Propel\Common\Config\Exception\RuntimeException
- * @expectedExceptionMessage Circular reference detected for parameter 'bar'.
- */
- public function testResolveThrowsRuntimeExceptionIfCircularReferenceMixed()
+ public function testResolveThrowsRuntimeExceptionIfCircularReferenceMixed(): void
{
+ $this->expectException(RuntimeException::class);
+ $this->expectExceptionMessage("Circular reference detected for parameter 'bar'.");
+
$this->loader->resolveParams(['foo' => 'a %bar%', 'bar' => 'a %foobar%', 'foobar' => 'a %foo%']);
}
- public function testResolveEnvironmentVariable()
+ public function testResolveEnvironmentVariable(): void
{
putenv('home=myHome');
putenv('schema=mySchema');
diff --git a/tests/Common/Config/Loader/IniFileLoaderTest.php b/tests/Common/Config/Loader/IniFileLoaderTest.php
index f457055a..71e081ee 100644
--- a/tests/Common/Config/Loader/IniFileLoaderTest.php
+++ b/tests/Common/Config/Loader/IniFileLoaderTest.php
@@ -1,5 +1,4 @@
-loader = new IniFileLoader(new FileLocator([$this->getRoot()->url()]));
}
- public function testSupports()
+ public function testSupports(): void
{
$this->assertTrue($this->loader->supports('foo.ini'), '->supports() returns true if the resource is loadable');
$this->assertTrue($this->loader->supports('foo.properties'), '->supports() returns true if the resource is loadable');
@@ -38,7 +38,7 @@ public function testSupports()
$this->assertFalse($this->loader->supports('foo.foo.dist'), '->supports() returns true if the resource is loadable');
}
- public function testIniFileCanBeLoaded()
+ public function testIniFileCanBeLoaded(): void
{
$content = <<assertEquals('baz', $test['bar']);
}
- /**
- * @expectedException \InvalidArgumentException
- * @expectedExceptionMessage The file "inexistent.ini" does not exist (in:
- */
- public function testIniFileDoesNotExist()
+ public function testIniFileDoesNotExist(): void
{
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage("The file \"inexistent.ini\" does not exist (in:");
+
$this->loader->load('inexistent.ini');
}
- /**
- * @expectedException Propel\Common\Config\Exception\InvalidArgumentException
- * @expectedExceptionMessage The configuration file 'vfs://root/nonvalid.ini' has invalid content.
- */
- public function testIniFileHasInvalidContent()
+ public function testIniFileHasInvalidContent(): void
{
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage("The configuration file 'vfs://root/nonvalid.ini' has invalid content.");
+
$content = <<loader->load($file->url());
}
- public function testIniFileIsEmpty()
+ public function testIniFileIsEmpty(): void
{
$file = $this->newFile('empty.ini', '');
@@ -86,7 +84,7 @@ public function testIniFileIsEmpty()
$this->assertEquals([], $actual);
}
- public function testWithSections()
+ public function testWithSections(): void
{
$content = <<assertEquals('Minnie', $actual['Cartoons']['Mickey']['love']);
}
- public function testNestedSections()
+ public function testNestedSections(): void
{
$content = <<assertEquals('blabar', $actual['bla']['bar']);
}
- public function testMixedNestedSections()
+ public function testMixedNestedSections(): void
{
$content = <<assertEquals('foobaz2', $actual['bla']['foo']['baz'][1]);
}
- /**
- * @expectedException Propel\Common\Config\Exception\InputOutputException
- * @expectedExceptionMessage You don't have permissions to access configuration file vfs://root/notreadable.ini.
- */
- public function testIniFileNotReadableThrowsException()
+ public function testIniFileNotReadableThrowsException(): void
{
+ $this->expectException(FileException::class);
+ $this->expectExceptionMessage("You don't have permissions to access notreadable.ini file");
+
$content = <<loader = new JsonFileLoader(new FileLocator([$this->getRoot()->url()]));
}
- public function testSupports()
+ public function testSupports(): void
{
$this->assertTrue($this->loader->supports('foo.json'), '->supports() returns true if the resource is loadable');
$this->assertTrue($this->loader->supports('foo.json.dist'), '->supports() returns true if the resource is loadable');
@@ -36,7 +37,7 @@ public function testSupports()
$this->assertFalse($this->loader->supports('foo.bar.dist'), '->supports() returns true if the resource is loadable');
}
- public function testJsonFileCanBeLoaded()
+ public function testJsonFileCanBeLoaded(): void
{
$content = <<assertEquals('baz', $actual['bar']);
}
- /**
- * @expectedException \InvalidArgumentException
- * @expectedExceptionMessage The file "inexistent.json" does not exist (in:
- */
- public function testJsonFileDoesNotExist()
+ public function testJsonFileDoesNotExist(): void
{
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage("The file \"inexistent.json\" does not exist (in:");
+
$this->loader->load('inexistent.json');
}
- /**
- * @expectedException phootwork\json\JsonException
- */
- public function testJsonFileHasInvalidContent()
+ public function testJsonFileHasInvalidContent(): void
{
+ $this->expectException(JsonException::class);
+
$content = <<loader->load($file->url());
}
- public function testJsonFileIsEmpty()
+ public function testJsonFileIsEmpty(): void
{
$file = $this->newFile('empty.json', '');
@@ -84,12 +83,11 @@ public function testJsonFileIsEmpty()
$this->assertEquals([], $actual);
}
- /**
- * @expectedException Propel\Common\Config\Exception\InputOutputException
- * @expectedExceptionMessage You don't have permissions to access configuration file vfs://root/notreadable.json.
- */
- public function testJsonFileNotReadableThrowsException()
+ public function testJsonFileNotReadableThrowsException(): void
{
+ $this->expectException(FileException::class);
+ $this->expectExceptionMessage("You don't have permissions to access notreadable.json file")
+ ;
$content = <<loader = new PhpFileLoader(new FileLocator([$this->getRoot()->url()]));
}
- public function testSupports()
+ public function testSupports(): void
{
$this->assertTrue($this->loader->supports('foo.php'), '->supports() returns true if the resource is loadable');
$this->assertTrue($this->loader->supports('foo.inc'), '->supports() returns true if the resource is loadable');
@@ -39,7 +39,7 @@ public function testSupports()
$this->assertFalse($this->loader->supports('foo.foo.dist'), '->supports() returns true if the resource is loadable');
}
- public function testPhpFileCanBeLoaded()
+ public function testPhpFileCanBeLoaded(): void
{
$content = <<assertEquals('baz', $test['bar']);
}
- /**
- * @expectedException \InvalidArgumentException
- * @expectedExceptionMessage The file "inexistent.php" does not exist (in:
- */
public function testPhpFileDoesNotExist()
{
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage("The file \"inexistent.php\" does not exist (in:");
$this->loader->load('inexistent.php');
}
- /**
- * @expectedException Propel\Common\Config\Exception\InvalidArgumentException
- * @expectedExceptionMessage The configuration file 'vfs://root/nonvalid.php' has invalid content.
- */
- public function testPhpFileHasInvalidContent()
+ public function testPhpFileHasInvalidContent(): void
{
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage("The configuration file 'vfs://root/nonvalid.php' has invalid content.");
$content = <<loader->load($file->url());
}
- /**
- * @expectedException Propel\Common\Config\Exception\InvalidArgumentException
- * @expectedExceptionMessage The configuration file 'vfs://root/empty.php' has invalid content.
- */
- public function testPhpFileIsEmpty()
+ public function testPhpFileIsEmpty(): void
{
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage("The configuration file 'vfs://root/empty.php' has invalid content.");
+
$file = $this->newFile('empty.php', '');
$this->loader->load($file->url());
}
- /**
- * @expectedException Propel\Common\Config\Exception\InputOutputException
- * @expectedExceptionMessage You don't have permissions to access configuration file vfs://root/notreadable.php.
- */
- public function testConfigFileNotReadableThrowsException()
+ public function testConfigFileNotReadableThrowsException(): void
{
+ $this->expectException(InputOutputException::class);
+ $this->expectExceptionMessage("You don't have permissions to access configuration file vfs://root/notreadable.php.");
$content = <<loader = new XmlFileLoader(new FileLocator([$this->getRoot()->url()]));
}
- public function testSupports()
+ public function testSupports(): void
{
$this->assertTrue($this->loader->supports('foo.xml'), '->supports() returns true if the resource is loadable');
$this->assertTrue($this->loader->supports('foo.xml.dist'), '->supports() returns true if the resource is loadable');
@@ -54,21 +56,19 @@ public function testXmlFileCanBeLoaded()
$this->assertEquals('baz', $test['bar']);
}
- /**
- * @expectedException \InvalidArgumentException
- * @expectedExceptionMessage The file "inexistent.xml" does not exist (in:
- */
public function testXmlFileDoesNotExist()
{
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage("The file \"inexistent.xml\" does not exist (in:");
+
$this->loader->load('inexistent.xml');
}
- /**
- * @expectedException Propel\Common\Config\Exception\InvalidArgumentException
- * @expectedExceptionMessage Invalid xml content
- */
- public function testXmlFileHasInvalidContent()
+ public function testXmlFileHasInvalidContent(): void
{
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage("Invalid xml content");
+
$content = <<assertEquals([], $actual);
}
- /**
- * @expectedException Propel\Common\Config\Exception\InputOutputException
- * @expectedExceptionMessage You don't have permissions to access configuration file vfs://root/notreadable.xml.
- */
public function testXmlFileNotReadableThrowsException()
{
+ $this->expectException(FileException::class);
+ $this->expectExceptionMessage("You don't have permissions to access notreadable.xml file");
+
$content = <<< XML
diff --git a/tests/Common/Config/Loader/YamlFileLoaderTest.php b/tests/Common/Config/Loader/YamlFileLoaderTest.php
index 40b99c8e..d0c0c66b 100644
--- a/tests/Common/Config/Loader/YamlFileLoaderTest.php
+++ b/tests/Common/Config/Loader/YamlFileLoaderTest.php
@@ -1,4 +1,4 @@
-loader = new YamlFileLoader(new FileLocator([$this->getRoot()->url()]));
}
- public function testSupports()
+ public function testSupports(): void
{
$this->assertTrue($this->loader->supports('foo.yaml'), '->supports() returns true if the resource is loadable');
$this->assertTrue($this->loader->supports('foo.yml'), '->supports() returns true if the resource is loadable');
@@ -40,7 +41,7 @@ public function testSupports()
$this->assertFalse($this->loader->supports('foo.bar.dist'), '->supports() returns true if the resource is loadable');
}
- public function testYamlFileCanBeLoaded()
+ public function testYamlFileCanBeLoaded(): void
{
$content = <<assertEquals('baz', $test['bar']);
}
- /**
- * @expectedException \InvalidArgumentException
- * @expectedExceptionMessage The file "inexistent.yaml" does not exist (in:
- */
- public function testYamlFileDoesNotExist()
+ public function testYamlFileDoesNotExist(): void
{
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage("The file \"inexistent.yaml\" does not exist (in:");
+
$this->loader->load('inexistent.yaml');
}
- /**
- * @expectedException Symfony\Component\Yaml\Exception\ParseException
- * @expectedExceptionMessage The content is not valid yaml
- */
- public function testYamlFileHasInvalidContent()
+ public function testYamlFileHasInvalidContent(): void
{
+ $this->expectException(ParseException::class);
+ $this->expectExceptionMessage("The content is not valid yaml");
+
$content = <<loader->load($file->url());
}
- public function testYamlFileIsEmpty()
+ public function testYamlFileIsEmpty(): void
{
$file = $this->newFile('empty.yaml', '');
$actual = $this->loader->load($file->url());
@@ -87,12 +86,10 @@ public function testYamlFileIsEmpty()
$this->assertEquals([], $actual);
}
- /**
- * @expectedException Propel\Common\Config\Exception\InputOutputException
- * @expectedExceptionMessage You don't have permissions to access configuration file vfs://root/notreadable.yaml.
- */
- public function testYamlFileNotReadableThrowsException()
+ public function testYamlFileNotReadableThrowsException(): void
{
+ $this->expectException(FileException::class);
+ $this->expectExceptionMessage("You don't have permissions to access notreadable.yaml file");
$content = <<assertEquals($expected, $actual);
}
- /**
- * @expectedException \Propel\Common\Config\Exception\InvalidArgumentException
- * @expectedExceptionMessage Invalid xml content
- */
public function testInvalidFileNameThrowsException()
{
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage("Invalid xml content");
XmlToArrayConverter::convert(1);
}
- /**
- * @expectedException \Propel\Common\Config\Exception\InvalidArgumentException
- * @expectedExceptionMessage Invalid xml content
- */
public function testInexistentFileThrowsException()
{
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage("Invalid xml content");
+
XmlToArrayConverter::convert('nonexistent.xml');
}
- /**
- * @expectedException \Propel\Common\Config\Exception\InvalidArgumentException
- * @expectedExceptionMessage Invalid xml content
- */
public function testInvalidXmlThrowsException()
{
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage("Invalid xml content");
+
$invalidXml = <<< XML
No xml
only plain text
@@ -198,12 +196,11 @@ public function testInvalidXmlThrowsException()
XmlToArrayConverter::convert($invalidXml);
}
- /**
- * @expectedException \Propel\Common\Config\Exception\XmlParseException
- * @expectedExceptionMessage An error occurred while parsing XML configuration file:
- */
public function testErrorInXmlThrowsException()
{
+ $this->expectException(XmlParseException::class);
+ $this->expectExceptionMessage("An error occurred while parsing XML configuration file:");
+
$xmlWithError = <<< XML
@@ -218,15 +215,14 @@ public function testErrorInXmlThrowsException()
XmlToArrayConverter::convert($xmlWithError);
}
- /**
- * @expectedException \Propel\Common\Config\Exception\XmlParseException
- * @expectedExceptionMessage Some errors occurred while parsing XML configuration file:
- - Fatal Error 76: Opening and ending tag mismatch: titles line 4 and title
- - Fatal Error 73: expected '>'
- - Fatal Error 5: Extra content at the end of the document
- */
public function testMultipleErrorsInXmlThrowsException()
{
+ $this->expectException(XmlParseException::class);
+ $this->expectExceptionMessage("Some errors occurred while parsing XML configuration file:
+ - Fatal Error 76: Opening and ending tag mismatch: titles line 4 and title
+ - Fatal Error 76: Opening and ending tag mismatch: movies line 4 and moviess
+");
+
$xmlWithErrors = <<< XML
diff --git a/tests/Common/Pluralizer/EnglishPluralizerTest.php b/tests/Common/Pluralizer/EnglishPluralizerTest.php
deleted file mode 100644
index 39f9a773..00000000
--- a/tests/Common/Pluralizer/EnglishPluralizerTest.php
+++ /dev/null
@@ -1,112 +0,0 @@
-assertEquals($output, $pluralizer->getPluralForm($input));
- }
- /**
- * @dataProvider getPluralFormDataProvider
- */
- public function testSimplePluralForm($input)
- {
- $pluralizer = new SimpleEnglishPluralizer();
- $this->assertEquals($input.'s', $pluralizer->getPluralForm($input));
- }
-}
diff --git a/tests/Generator/Behavior/Archivable/ArchivableBehaviorObjectBuilderModifierTest.php b/tests/Generator/Behavior/Archivable/ArchivableBehaviorObjectBuilderModifierTest.php
index c969363a..9bcb23c3 100644
--- a/tests/Generator/Behavior/Archivable/ArchivableBehaviorObjectBuilderModifierTest.php
+++ b/tests/Generator/Behavior/Archivable/ArchivableBehaviorObjectBuilderModifierTest.php
@@ -1,4 +1,4 @@
-
@@ -77,20 +77,20 @@ public static function setUpBeforeClass()
QuickBuilder::buildSchema($schema);
}
- public function testHasGetArchiveMethod()
+ public function testHasGetArchiveMethod(): void
{
$this->assertTrue(method_exists('\Base\BaseArchivableTest10Repository', 'getArchive'));
}
- public function testGetArchiveReturnsNullOnNewObjects()
+ public function testGetArchiveReturnsNullOnNewObjects(): void
{
$repo = QuickBuilder::$configuration->getRepository('ArchivableTest10');
$a = new \ArchivableTest10();
$this->assertNull($repo->getArchive($a));
}
- public function testGetArchiveReturnsNullWhenNoArchiveIsFound()
+ public function testGetArchiveReturnsNullWhenNoArchiveIsFound(): void
{
$a = new \ArchivableTest10();
$a->setTitle('foo');
@@ -99,7 +99,7 @@ public function testGetArchiveReturnsNullWhenNoArchiveIsFound()
$this->assertNull($a->getArchive());
}
- public function testGetArchiveReturnsExistingArchive()
+ public function testGetArchiveReturnsExistingArchive(): void
{
$a = new \ArchivableTest10();
$a->setTitle('foo');
diff --git a/tests/Generator/Behavior/Archivable/ArchivableBehaviorTest.php b/tests/Generator/Behavior/Archivable/ArchivableBehaviorTest.php
index 8baa9a18..5987a46b 100644
--- a/tests/Generator/Behavior/Archivable/ArchivableBehaviorTest.php
+++ b/tests/Generator/Behavior/Archivable/ArchivableBehaviorTest.php
@@ -1,4 +1,4 @@
-clearEntityPool();
$this->clearEntityPool(true);
diff --git a/tests/Generator/Behavior/NestedSet/TestCase.php b/tests/Generator/Behavior/NestedSet/TestCase.php
index e84b1053..9435c440 100644
--- a/tests/Generator/Behavior/NestedSet/TestCase.php
+++ b/tests/Generator/Behavior/NestedSet/TestCase.php
@@ -1,4 +1,4 @@
-markTestSkipped('Polymorphic many-to-many relations will be supported soon.');
parent::setUp();
diff --git a/tests/Generator/Builder/Om/GeneratedObjectM2MRelationThreePKsTest.php b/tests/Generator/Builder/Om/GeneratedObjectM2MRelationThreePKsTest.php
index 9423dd78..d2d2f9d6 100644
--- a/tests/Generator/Builder/Om/GeneratedObjectM2MRelationThreePKsTest.php
+++ b/tests/Generator/Builder/Om/GeneratedObjectM2MRelationThreePKsTest.php
@@ -22,7 +22,7 @@ class GeneratedObjectM2MRelationThreePKsTest extends PlatformDatabaseBuildTimeBa
{
protected $databaseName = 'migration';
- public function setUp()
+ public function setUp(): void
{
$this->markTestSkipped('Polymorphic many-to-many relations will be supported soon.');
parent::setUp();
diff --git a/tests/Generator/Builder/Om/GeneratedObjectMoreRelationTest.php b/tests/Generator/Builder/Om/GeneratedObjectMoreRelationTest.php
index ed9eb794..a308707b 100644
--- a/tests/Generator/Builder/Om/GeneratedObjectMoreRelationTest.php
+++ b/tests/Generator/Builder/Om/GeneratedObjectMoreRelationTest.php
@@ -25,7 +25,7 @@ class GeneratedObjectMoreRelationTest extends TestCase
/**
* Setup schema und some default data
*/
- public function setUp()
+ public function setUp(): void
{
parent::setUp();
diff --git a/tests/Generator/Builder/Om/GeneratedObjectObjectColumnTypeTest.php b/tests/Generator/Builder/Om/GeneratedObjectObjectColumnTypeTest.php
index 8a8516c6..94a7494e 100644
--- a/tests/Generator/Builder/Om/GeneratedObjectObjectColumnTypeTest.php
+++ b/tests/Generator/Builder/Om/GeneratedObjectObjectColumnTypeTest.php
@@ -28,7 +28,7 @@ class GeneratedObjectObjectColumnTypeTest extends TestCase
*/
protected $configuration;
- public function setup()
+ public function setUp(): void
{
if (!class_exists('ComplexColumnTypeEntity1')) {
$schema = <<assertEquals('1702-02-02', $r->getBar1(null)->format('Y-m-d'));
}
- /**
- * @expectedException \Propel\Runtime\Exception\PropelException
- */
public function testInvalidValueThrowsPropelException()
{
+ $this->expectException(PropelException::class);
+
$r = new \ComplexColumnTypeEntity5();
$r->setBar1("Invalid Date");
}
diff --git a/tests/Generator/Builder/Om/GeneratedQueryArrayColumnTypeTest.php b/tests/Generator/Builder/Om/GeneratedQueryArrayColumnTypeTest.php
index f65dc33b..bb54ae93 100644
--- a/tests/Generator/Builder/Om/GeneratedQueryArrayColumnTypeTest.php
+++ b/tests/Generator/Builder/Om/GeneratedQueryArrayColumnTypeTest.php
@@ -23,7 +23,7 @@
*/
class GeneratedQueryArrayColumnTypeTest extends TestCase
{
- public function setUp()
+ public function setUp(): void
{
if (!class_exists('\ComplexColumnTypeEntity11')) {
$schema = <<markTestSkipped('not used anymore look if all tests are present in Query');
parent::setUp();
diff --git a/tests/Generator/Builder/Om/GeneratedQueryEnumColumnTypeTest.php b/tests/Generator/Builder/Om/GeneratedQueryEnumColumnTypeTest.php
index 495cda23..6962f49e 100644
--- a/tests/Generator/Builder/Om/GeneratedQueryEnumColumnTypeTest.php
+++ b/tests/Generator/Builder/Om/GeneratedQueryEnumColumnTypeTest.php
@@ -26,7 +26,7 @@
*/
class GeneratedQueryEnumColumnTypeTest extends TestCase
{
- public function setUp()
+ public function setUp(): void
{
if (!class_exists('\ComplexColumnTypeEntity13')) {
$schema = <<c1 = new FooColumnValue2();
$this->c1->bar = 1234;
diff --git a/tests/Generator/Builder/Om/PoisonedCacheBugTest.php b/tests/Generator/Builder/Om/PoisonedCacheBugTest.php
index 5473bcf9..d0818f88 100644
--- a/tests/Generator/Builder/Om/PoisonedCacheBugTest.php
+++ b/tests/Generator/Builder/Om/PoisonedCacheBugTest.php
@@ -35,7 +35,7 @@ class PoisonedCacheBugTest extends BookstoreTestBase
*/
private $books;
- public function setUp()
+ public function setUp(): void
{
parent::setUp();
diff --git a/tests/Generator/Builder/Om/QueryBuilderTest.php b/tests/Generator/Builder/Om/QueryBuilderTest.php
index ee7e3d4a..2675b122 100644
--- a/tests/Generator/Builder/Om/QueryBuilderTest.php
+++ b/tests/Generator/Builder/Om/QueryBuilderTest.php
@@ -51,7 +51,7 @@
*/
class QueryBuilderTest extends BookstoreTestBase
{
- protected function setUp()
+ protected function setUp(): void
{
parent::setUp();
include_once(__DIR__.'/QueryBuilderTestClasses.php');
diff --git a/tests/Generator/Builder/Om/TableMapBuilderTest.php b/tests/Generator/Builder/Om/TableMapBuilderTest.php
index de47cc0d..be5cbfe4 100644
--- a/tests/Generator/Builder/Om/TableMapBuilderTest.php
+++ b/tests/Generator/Builder/Om/TableMapBuilderTest.php
@@ -26,7 +26,7 @@ class TableMapBuilderTest extends BookstoreTestBase
{
protected $databaseMap;
- protected function setUp()
+ protected function setUp(): void
{
parent::setUp();
$this->databaseMap = Propel::getServiceContainer()->getDatabaseMap('bookstore');
diff --git a/tests/Generator/Command/AbstractCommandTest.php b/tests/Generator/Command/AbstractCommandTest.php
index 207b1410..579785d5 100644
--- a/tests/Generator/Command/AbstractCommandTest.php
+++ b/tests/Generator/Command/AbstractCommandTest.php
@@ -24,7 +24,7 @@ class AbstractCommandTest extends TestCase
{
protected $command;
- public function setUp()
+ public function setUp(): void
{
$this->command = new TestableAbstractCommand();
}
diff --git a/tests/Generator/Command/InitCommandTest.php b/tests/Generator/Command/InitCommandTest.php
index 6f7cf9c8..7199411f 100644
--- a/tests/Generator/Command/InitCommandTest.php
+++ b/tests/Generator/Command/InitCommandTest.php
@@ -33,7 +33,7 @@ class InitCommandTest extends TestCaseFixtures
/** @var Filesystem */
private $fileSystem;
- public function setUp()
+ public function setup(): void
{
parent::setUp();
@@ -45,7 +45,7 @@ public function setUp()
chdir($this->tempDir);
}
- public function tearDown()
+ public function tearDown(): void
{
chdir($this->currentDir);
parent::tearDown();
diff --git a/tests/Generator/Command/MigrationTest.php b/tests/Generator/Command/MigrationTest.php
index 05cfdda4..18ec56f4 100644
--- a/tests/Generator/Command/MigrationTest.php
+++ b/tests/Generator/Command/MigrationTest.php
@@ -21,7 +21,7 @@ class MigrationTest extends TestCaseFixturesDatabase
protected $inputDir;
protected $outputDir;
- public function setUp()
+ public function setUp(): void
{
parent::setUp();
$this->connectionOption = ['migration_command=' . $this->getConnectionDsn('bookstore', true)];
diff --git a/tests/Generator/Config/GeneratorConfigTest.php b/tests/Generator/Config/GeneratorConfigTest.php
index 0a244b63..bd92b201 100644
--- a/tests/Generator/Config/GeneratorConfigTest.php
+++ b/tests/Generator/Config/GeneratorConfigTest.php
@@ -11,6 +11,7 @@
namespace Propel\Tests\Generator\Config;
use Propel\Generator\Config\GeneratorConfig;
+use Propel\Generator\Exception\InvalidArgumentException;
use Propel\Tests\TestCase;
use Propel\Tests\VfsTrait;
@@ -36,7 +37,7 @@ public function setConfig($config)
$refProp->setValue($this->generatorConfig, $config);
}
- public function setUp()
+ public function setUp(): void
{
$php = "
assertInstanceOf('\\Propel\\Generator\\Platform\\PgsqlPlatform', $actual);
}
- /**
- * @expectedException Propel\Generator\Exception\InvalidArgumentException
- * @expectedExceptionMessage Invalid database name: no configured connection named `badsource`.
- */
public function testGetConfiguredPlatformGivenBadDatabaseNameThrowsException()
{
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage("Invalid database name: no configured connection named `badsource`.");
+
$this->generatorConfig->createPlatformForDatabase('badsource');
}
diff --git a/tests/Generator/Config/QuickGeneratorConfigTest.php b/tests/Generator/Config/QuickGeneratorConfigTest.php
index 525adaf1..eac375d8 100644
--- a/tests/Generator/Config/QuickGeneratorConfigTest.php
+++ b/tests/Generator/Config/QuickGeneratorConfigTest.php
@@ -10,6 +10,7 @@
namespace Propel\Tests\Generator\Config;
use Propel\Generator\Config\QuickGeneratorConfig;
+use Propel\Generator\Exception\InvalidArgumentException;
use Propel\Tests\TestCase;
class QuickGeneratorConfigTest extends TestCase
@@ -19,7 +20,7 @@ class QuickGeneratorConfigTest extends TestCase
*/
protected $generatorConfig;
- public function setUp()
+ public function setUp(): void
{
$this->generatorConfig = new QuickGeneratorConfig();
}
@@ -32,12 +33,11 @@ public function testGetConfiguredBuilder()
$this->assertInstanceOf('\\Propel\\Generator\\Builder\\Om\\QueryBuilder', $actual);
}
- /**
- * @expectedException Propel\Generator\Exception\InvalidArgumentException
- * @expectedExceptionMessage Invalid data model builder type `bad_type`
- */
public function testGetConfiguredBuilderWrongTypeThrowsException()
{
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage("Invalid data model builder type `bad_type`");
+
$stubEntity = $this->createMock('\\Propel\\Generator\\Model\\Entity');
$actual = $this->generatorConfig->getConfiguredBuilder($stubEntity, 'bad_type');
}
diff --git a/tests/Generator/Manager/BehaviorManagerTest.php b/tests/Generator/Manager/BehaviorManagerTest.php
index e1c6186c..761ad195 100644
--- a/tests/Generator/Manager/BehaviorManagerTest.php
+++ b/tests/Generator/Manager/BehaviorManagerTest.php
@@ -23,7 +23,7 @@
*/
class BehaviorManagerTest extends TestCase
{
- protected function setUp()
+ protected function setup(): void
{
parent::setUp();
require_once(__DIR__ . '/../../Fixtures/behavior-installer/src/gossi/propel/behavior/l10n/L10nBehavior.php');
diff --git a/tests/Generator/Migration/MigrationTestCase.php b/tests/Generator/Migration/MigrationTestCase.php
index 330ba273..481e9c50 100644
--- a/tests/Generator/Migration/MigrationTestCase.php
+++ b/tests/Generator/Migration/MigrationTestCase.php
@@ -34,7 +34,7 @@ class MigrationTestCase extends TestCaseFixturesDatabase
*/
protected $platform;
- public function setUp()
+ public function setUp(): void
{
parent::setUp();
if (!$this->con) {
diff --git a/tests/Generator/Model/BehaviorTest.php b/tests/Generator/Model/BehaviorTest.php
index 4e461a96..b551d547 100644
--- a/tests/Generator/Model/BehaviorTest.php
+++ b/tests/Generator/Model/BehaviorTest.php
@@ -1,5 +1,4 @@
assertEquals('', $b->getName(), 'Behavior name is null string by default');
$b->setName('foo');
- $this->assertEquals($b->getName(), 'foo', 'setName() sets the name, and getName() gets it');
+ $this->assertEquals('foo', $b->getName(), 'setName() sets the name, and getName() gets it');
}
public function testEntity()
@@ -45,22 +43,18 @@ public function testEntity()
public function testParameters()
{
$b = new Behavior();
- $this->assertEquals($b->getParameters(), [], 'Behavior parameters is an empty array by default');
+ $this->assertEquals([], $b->getParameters()->toArray(), 'Behavior parameters is an empty array by default');
$b->addParameter(['name' => 'foo', 'value' => 'bar']);
- $this->assertEquals($b->getParameters(), ['foo' => 'bar'], 'addParameter() sets a parameter from an associative array');
+ $this->assertEquals(['foo' => 'bar'], $b->getParameters()->toArray(), 'addParameter() sets a parameter from an associative array');
$b->addParameter(['name' => 'foo2', 'value' => 'bar2']);
- $this->assertEquals($b->getParameters(), ['foo' => 'bar', 'foo2' => 'bar2'], 'addParameter() adds a parameter from an associative array');
+ $this->assertEquals(['foo' => 'bar', 'foo2' => 'bar2'], $b->getParameters()->toArray(), 'addParameter() adds a parameter from an associative array');
$b->addParameter(['name' => 'foo', 'value' => 'bar3']);
- $this->assertEquals($b->getParameters(), ['foo' => 'bar3', 'foo2' => 'bar2'], 'addParameter() changes a parameter from an associative array');
- $this->assertEquals($b->getParameter('foo'), 'bar3', 'getParameter() retrieves a parameter value by name');
+ $this->assertEquals(['foo' => 'bar3', 'foo2' => 'bar2'], $b->getParameters()->toArray(), 'addParameter() changes a parameter from an associative array');
+ $this->assertEquals('bar3', $b->getParameter('foo'), 'getParameter() retrieves a parameter value by name');
$b->setParameters(['foo3' => 'bar3', 'foo4' => 'bar4']);
- $this->assertEquals($b->getParameters(), ['foo3' => 'bar3', 'foo4' => 'bar4'], 'setParameters() changes the whole parameter array');
+ $this->assertEquals(['foo3' => 'bar3', 'foo4' => 'bar4'], $b->getParameters()->toArray(), 'setParameters() changes the whole parameter array');
}
- /**
- * test if the tables get the package name from the properties file
- *
- */
public function testSchemaReader()
{
$schemaReader = new SchemaReader();
@@ -88,16 +82,15 @@ public function testSchemaReader()
$this->assertEquals('Entity1', $behavior->getEntity()->getName(), 'SchemaReader sets the behavior entity correctly');
$this->assertEquals(
['create_field' => 'created_on', 'update_field' => 'updated_on', 'disable_created_at' => false, 'disable_updated_at' => false],
- $behavior->getParameters(),
+ $behavior->getParameters()->toArray(),
'SchemaReader sets the behavior parameters correctly'
);
}
- /**
- * @expectedException \Propel\Generator\Exception\BehaviorNotFoundException
- */
public function testUnknownBehavior()
{
+ $this->expectException(BehaviorNotFoundException::class);
+
$schemaReader = new SchemaReader();
$content = <<
@@ -169,6 +162,6 @@ public function testGetColumnForParameter()
$appData = $schemaReader->parse($schema->url());
$entity = $appData->getDatabase('test1')->getEntityByName('Table1');
$behavior = $entity->getBehavior('timestampable');
- $this->assertEquals($entity->getField('created_on'), $behavior->getFieldForParameter('create_field'), 'getFieldForParameter() returns the configured field for behavior based on a parameter name');
+ $this->assertEquals($entity->getFieldByName('created_on'), $behavior->getFieldForParameter('create_field'), 'getFieldForParameter() returns the configured field for behavior based on a parameter name');
}
}
diff --git a/tests/Generator/Model/DatabaseTest.php b/tests/Generator/Model/DatabaseTest.php
index 53e48501..028361d3 100644
--- a/tests/Generator/Model/DatabaseTest.php
+++ b/tests/Generator/Model/DatabaseTest.php
@@ -1,5 +1,4 @@
-assertSame('bookstore', $database->getName());
+ $this->assertSame('bookstore', (string) $database->getName());
$this->assertSame(Model::DEFAULT_STRING_FORMAT, $database->getStringFormat());
$this->assertSame(Model::DEFAULT_ID_METHOD, $database->getIdMethod());
- $this->assertEmpty($database->getScope());
+ $this->assertTrue($database->getScope()->isEmpty());
$this->assertNull($database->getSchema());
$this->assertNull($database->getDomain('BOOLEAN'));
$this->assertNull($database->getGeneratorConfig());
@@ -58,8 +57,8 @@ public function testAddBehavior()
$behavior = $this->getBehaviorMock('foo');
$database = new Database();
+ $database->addBehavior($behavior);
- $this->assertInstanceOf('Propel\Generator\Model\Database', $database->addBehavior($behavior), 'Fluent api');
$this->assertInstanceOf('Propel\Generator\Model\Behavior', $database->getBehavior('foo'));
$this->assertSame($behavior, $database->getBehavior('foo'));
$this->assertTrue($database->hasBehavior('foo'));
@@ -93,7 +92,7 @@ public function testGetNextEntityBehavior()
$behavior = $database->getNextEntityBehavior();
$this->assertInstanceOf('Propel\Generator\Model\Behavior', $behavior);
- $this->assertSame('bar', $behavior->getName());
+ $this->assertSame('bar', (string) $behavior->getName());
}
public function testCantGetNextEntityBehavior()
@@ -187,11 +186,10 @@ public function testAddDomain()
$this->assertNull($database->getDomain('baz'));
}
- /**
- * @expectedException \InvalidArgumentException
- */
public function testSetInvalidDefaultStringFormat()
{
+ $this->expectException(\InvalidArgumentException::class);
+
$database = new Database();
$database->setStringFormat('FOO');
}
@@ -262,7 +260,7 @@ public function testEntityGetters()
{
$db = new Database();
$entity = $this->getEntityMock('First', ['tableName' => 'first_table', 'namespace' => 'my\\namespace']);
- $entity->expects($this->any())->method('getFullTableName')->willReturn('mySchema.first_table');
+ $entity->expects($this->any())->method('getFullTableName')->willReturn(Text::create('mySchema.first_table'));
$db->addEntity($entity);
$this->assertTrue($db->hasEntityByFullName('my\\namespace\\First'));
@@ -295,11 +293,12 @@ public function testAddEntities()
$db->addEntities($entities);
$this->assertCount(5, $db->getEntities());
- $this->assertEquals($entities, $db->getEntities());
+ $this->assertEquals($entities, $db->getEntities()->toArray());
}
public function testClone()
{
+ //no more clone method: use `myclabs/deep-copy` instead
$generatorConfig = $this->getMockBuilder('Propel\\Generator\\Config\\GeneratorConfig')
->disableOriginalConstructor()
->getMock();
@@ -314,7 +313,7 @@ public function testClone()
$db->setSchema($this->getSchemaMock());
$db->addVendor($vendor);
- $clone = clone $db;
+ $clone = deep_copy($db);
$this->assertEquals($db, $clone, 'The clone object is equal.');
$this->assertNotSame($db, $clone, 'The clone object is not the same.');
diff --git a/tests/Generator/Model/Diff/PropelDatabaseEntityComparatorTest.php b/tests/Generator/Model/Diff/DatabaseEntityComparatorTest.php
similarity index 93%
rename from tests/Generator/Model/Diff/PropelDatabaseEntityComparatorTest.php
rename to tests/Generator/Model/Diff/DatabaseEntityComparatorTest.php
index 8b9b25f1..8aad5211 100644
--- a/tests/Generator/Model/Diff/PropelDatabaseEntityComparatorTest.php
+++ b/tests/Generator/Model/Diff/DatabaseEntityComparatorTest.php
@@ -1,5 +1,4 @@
-platform = new MysqlPlatform();
}
- public function testCompareSameEntities()
+ public function testCompareSameEntities(): void
{
$d1 = new Database();
$d1->setPlatform($this->platform);
@@ -70,7 +65,7 @@ public function testCompareSameEntities()
$this->assertNull(DatabaseComparator::computeDiff($d1, $d2));
}
- public function testCompareNotSameEntities()
+ public function testCompareNotSameEntities(): void
{
$d1 = new Database();
$t1 = new Entity('Foo');
@@ -83,7 +78,7 @@ public function testCompareNotSameEntities()
$this->assertTrue($diff instanceof DatabaseDiff);
}
- public function testCompareAddedEntity()
+ public function testCompareAddedEntity(): void
{
$d1 = new Database();
$t1 = new Entity('Foo_Entity');
@@ -119,7 +114,7 @@ public function testCompareAddedEntity()
$this->assertEquals(['Bar' => $t4], $databaseDiff->getAddedEntities()->toArray());
}
- public function testCompareAddedEntitySkipSql()
+ public function testCompareAddedEntitySkipSql(): void
{
$d1 = new Database();
$t1 = new Entity('Foo_Entity');
@@ -153,7 +148,7 @@ public function testCompareAddedEntitySkipSql()
$this->assertEquals(0, $nbDiffs);
}
- public function testCompareRemovedEntity()
+ public function testCompareRemovedEntity(): void
{
$d1 = new Database();
$t1 = new Entity('Foo_Entity');
@@ -189,7 +184,7 @@ public function testCompareRemovedEntity()
$this->assertEquals(['Bar' => $t2], $databaseDiff->getRemovedEntities()->toArray());
}
- public function testCompareRemovedEntitySkipSql()
+ public function testCompareRemovedEntitySkipSql(): void
{
$d1 = new Database();
$t1 = new Entity('Foo_Entity');
@@ -224,7 +219,7 @@ public function testCompareRemovedEntitySkipSql()
$this->assertEquals(0, $nbDiffs);
}
- public function testCompareModifiedEntity()
+ public function testCompareModifiedEntity(): void
{
$d1 = new Database();
$t1 = new Entity('Foo_Entity');
@@ -266,7 +261,7 @@ public function testCompareModifiedEntity()
$this->assertEquals(['Foo_Entity' => $entityDiff], $databaseDiff->getModifiedEntities()->toArray());
}
- public function testCompareRenamedEntity()
+ public function testCompareRenamedEntity(): void
{
$d1 = new Database();
$t1 = new Entity('Foo_Entity');
@@ -308,7 +303,7 @@ public function testCompareRenamedEntity()
}
- public function testCompareSeveralEntityDifferences()
+ public function testCompareSeveralEntityDifferences(): void
{
$d1 = new Database();
$t1 = new Entity('Foo_Entity');
@@ -363,7 +358,7 @@ public function testCompareSeveralEntityDifferences()
$this->assertEquals(['Foo_Entity' => $entityDiff], $databaseDiff->getModifiedEntities()->toArray());
}
- public function testCompareSeveralRenamedSameEntities()
+ public function testCompareSeveralRenamedSameEntities(): void
{
$d1 = new Database();
$t1 = new Entity('entity1');
@@ -412,7 +407,7 @@ public function testCompareSeveralRenamedSameEntities()
$this->assertEquals(['entity1', 'entity2'], $databaseDiff->getRemovedEntities()->keys()->toArray());
}
- public function testRemoveEntity()
+ public function testRemoveEntity(): void
{
$dc = new DatabaseComparator();
$this->assertTrue($dc->getRemoveEntity());
@@ -446,12 +441,12 @@ public function testRemoveEntity()
$this->assertInstanceOf('Propel\Generator\Model\Diff\DatabaseDiff', $diff);
}
- public function testExcludedEntitiesWithoutRenaming()
+ public function testExcludedEntitiesWithoutRenaming(): void
{
$dc = new DatabaseComparator();
$this->assertCount(0, $dc->getExcludedEntities());
- $dc->setExcludedEntities(new Set(['foo']));
+ $dc->addExcludedEntities(['foo']);
$this->assertCount(1, $dc->getExcludedEntities());
$d1 = new Database();
@@ -459,10 +454,10 @@ public function testExcludedEntitiesWithoutRenaming()
$t2 = new Entity('Bar');
$d2->addEntity($t2);
- $diff = DatabaseComparator::computeDiff($d1, $d2, false, false, new Set(['Bar']));
+ $diff = DatabaseComparator::computeDiff($d1, $d2, false, false, ['Bar']);
$this->assertNull($diff);
- $diff = DatabaseComparator::computeDiff($d1, $d2, false, false, new Set(['Baz']));
+ $diff = DatabaseComparator::computeDiff($d1, $d2, false, false, ['Baz']);
$this->assertInstanceOf('Propel\Generator\Model\Diff\DatabaseDiff', $diff);
$d1 = new Database();
@@ -472,13 +467,13 @@ public function testExcludedEntitiesWithoutRenaming()
$t2 = new Entity('Bar');
$d2->addEntity($t2);
- $diff = DatabaseComparator::computeDiff($d1, $d2, false, false, new Set(['Bar', 'Foo']));
+ $diff = DatabaseComparator::computeDiff($d1, $d2, false, false, ['Bar', 'Foo']);
$this->assertNull($diff);
- $diff = DatabaseComparator::computeDiff($d1, $d2, false, false, new Set(['Foo']));
+ $diff = DatabaseComparator::computeDiff($d1, $d2, false, false, ['Foo']);
$this->assertInstanceOf('Propel\Generator\Model\Diff\DatabaseDiff', $diff);
- $diff = DatabaseComparator::computeDiff($d1, $d2, false, true, new Set(['Bar']));
+ $diff = DatabaseComparator::computeDiff($d1, $d2, false, true, ['Bar']);
$this->assertInstanceOf('Propel\Generator\Model\Diff\DatabaseDiff', $diff);
@@ -491,19 +486,19 @@ public function testExcludedEntitiesWithoutRenaming()
$t2 = new Entity('Foo');
$d2->addEntity($t2);
- $diff = DatabaseComparator::computeDiff($d1, $d2, false, false, new Set(['Bar', 'Foo']));
+ $diff = DatabaseComparator::computeDiff($d1, $d2, false, false, ['Bar', 'Foo']);
$this->assertNull($diff);
- $diff = DatabaseComparator::computeDiff($d1, $d2, false, false, new Set(['Bar']));
+ $diff = DatabaseComparator::computeDiff($d1, $d2, false, false, ['Bar']);
$this->assertInstanceOf('Propel\Generator\Model\Diff\DatabaseDiff', $diff);
}
- public function testExcludedEntitiesWithRenaming()
+ public function testExcludedEntitiesWithRenaming(): void
{
$dc = new DatabaseComparator();
$this->assertCount(0, $dc->getExcludedEntities());
- $dc->setExcludedEntities(new Set(['foo']));
+ $dc->addExcludedEntities(['foo']);
$this->assertCount(1, $dc->getExcludedEntities());
$d1 = new Database();
@@ -511,10 +506,10 @@ public function testExcludedEntitiesWithRenaming()
$t2 = new Entity('Bar');
$d2->addEntity($t2);
- $diff = DatabaseComparator::computeDiff($d1, $d2, true, false, new Set(['Bar']));
+ $diff = DatabaseComparator::computeDiff($d1, $d2, true, false, ['Bar']);
$this->assertNull($diff);
- $diff = DatabaseComparator::computeDiff($d1, $d2, true, false, new Set(['Baz']));
+ $diff = DatabaseComparator::computeDiff($d1, $d2, true, false, ['Baz']);
$this->assertInstanceOf('Propel\Generator\Model\Diff\DatabaseDiff', $diff);
$d1 = new Database();
@@ -524,13 +519,13 @@ public function testExcludedEntitiesWithRenaming()
$t2 = new Entity('Bar');
$d2->addEntity($t2);
- $diff = DatabaseComparator::computeDiff($d1, $d2, true, false, new Set(['Bar', 'Foo']));
+ $diff = DatabaseComparator::computeDiff($d1, $d2, true, false, ['Bar', 'Foo']);
$this->assertNull($diff);
- $diff = DatabaseComparator::computeDiff($d1, $d2, true, true, new Set(['Foo']));
+ $diff = DatabaseComparator::computeDiff($d1, $d2, true, true, ['Foo']);
$this->assertInstanceOf('Propel\Generator\Model\Diff\DatabaseDiff', $diff);
- $diff = DatabaseComparator::computeDiff($d1, $d2, true, true, new Set(['Bar']));
+ $diff = DatabaseComparator::computeDiff($d1, $d2, true, true, ['Bar']);
$this->assertInstanceOf('Propel\Generator\Model\Diff\DatabaseDiff', $diff);
@@ -543,10 +538,10 @@ public function testExcludedEntitiesWithRenaming()
$t2 = new Entity('Foo');
$d2->addEntity($t2);
- $diff = DatabaseComparator::computeDiff($d1, $d2, true, false, new Set(['Bar', 'Foo']));
+ $diff = DatabaseComparator::computeDiff($d1, $d2, true, false, ['Bar', 'Foo']);
$this->assertNull($diff);
- $diff = DatabaseComparator::computeDiff($d1, $d2, true, false, new Set(['Bar']));
+ $diff = DatabaseComparator::computeDiff($d1, $d2, true, false, ['Bar']);
$this->assertInstanceOf('Propel\Generator\Model\Diff\DatabaseDiff', $diff);
}
}
diff --git a/tests/Generator/Model/Diff/EntityDiffTest.php b/tests/Generator/Model/Diff/EntityDiffTest.php
index e7b6fcc6..9a5cca59 100644
--- a/tests/Generator/Model/Diff/EntityDiffTest.php
+++ b/tests/Generator/Model/Diff/EntityDiffTest.php
@@ -1,8 +1,16 @@
-platform = new MysqlPlatform();
}
diff --git a/tests/Generator/Model/Diff/EntityIndexComparatorTest.php b/tests/Generator/Model/Diff/EntityIndexComparatorTest.php
index 6056c406..370d87ab 100644
--- a/tests/Generator/Model/Diff/EntityIndexComparatorTest.php
+++ b/tests/Generator/Model/Diff/EntityIndexComparatorTest.php
@@ -1,13 +1,13 @@
-platform = new MysqlPlatform();
}
- public function testCompareSameIndices()
+ public function testCompareSameIndices(): void
{
$t1 = new Entity();
$c1 = new Field('Foo');
$c1->getDomain()->copy($this->platform->getDomainForType('DOUBLE'));
- $c1->getDomain()->replaceScale(2);
+ $c1->getDomain()->setScale(2);
$c1->getDomain()->setSize(3);
$c1->setNotNull(true);
$c1->getDomain()->setDefaultValue(new FieldDefaultValue(123, FieldDefaultValue::TYPE_VALUE));
@@ -49,10 +46,11 @@ public function testCompareSameIndices()
$i1 = new Index('Foo_Index');
$i1->addField($c1);
$t1->addIndex($i1);
+
$t2 = new Entity();
$c2 = new Field('Foo');
$c2->getDomain()->copy($this->platform->getDomainForType('DOUBLE'));
- $c2->getDomain()->replaceScale(2);
+ $c2->getDomain()->setScale(2);
$c2->getDomain()->setSize(3);
$c2->setNotNull(true);
$c2->getDomain()->setDefaultValue(new FieldDefaultValue(123, FieldDefaultValue::TYPE_VALUE));
@@ -64,7 +62,7 @@ public function testCompareSameIndices()
$this->assertNull(EntityComparator::computeDiff($t1, $t2));
}
- public function testCompareNotSameIndices()
+ public function testCompareNotSameIndices(): void
{
$t1 = new Entity();
$c1 = new Field('Foo');
@@ -93,7 +91,7 @@ public function testCompareNotSameIndices()
$this->assertTrue($diff instanceof EntityDiff);
}
- public function testCompareAddedIndices()
+ public function testCompareAddedIndices(): void
{
$t1 = new Entity();
$t2 = new Entity();
@@ -118,7 +116,7 @@ public function testCompareAddedIndices()
$this->assertEquals(['Foo_Index' => $i2], $tableDiff->getAddedIndices()->toArray());
}
- public function testCompareRemovedIndices()
+ public function testCompareRemovedIndices(): void
{
$t1 = new Entity();
$c1 = new Field('Bar');
@@ -143,7 +141,7 @@ public function testCompareRemovedIndices()
$this->assertEquals(['Bar_Index' => $i1], $tableDiff->getRemovedIndices()->toArray());
}
- public function testCompareModifiedIndices()
+ public function testCompareModifiedIndices(): void
{
$t1 = new Entity();
$c1 = new Field('Foo');
diff --git a/tests/Generator/Model/Diff/EntityPkFieldComparatorTest.php b/tests/Generator/Model/Diff/EntityPkFieldComparatorTest.php
index b4cb40f6..68e97ad9 100644
--- a/tests/Generator/Model/Diff/EntityPkFieldComparatorTest.php
+++ b/tests/Generator/Model/Diff/EntityPkFieldComparatorTest.php
@@ -1,12 +1,11 @@
-platform = new MysqlPlatform();
}
- public function testCompareSamePks()
+ public function testCompareSamePks(): void
{
$t1 = new Entity();
$c1 = new Field('Foo');
@@ -50,7 +46,7 @@ public function testCompareSamePks()
$this->assertNull(EntityComparator::computeDiff($t1, $t2));
}
- public function testCompareNotSamePks()
+ public function testCompareNotSamePks(): void
{
$t1 = new Entity();
$c1 = new Field('Foo');
@@ -64,7 +60,7 @@ public function testCompareNotSamePks()
$this->assertTrue($diff instanceof EntityDiff);
}
- public function testCompareAddedPkField()
+ public function testCompareAddedPkField(): void
{
$t1 = new Entity();
$t2 = new Entity();
@@ -86,7 +82,7 @@ public function testCompareAddedPkField()
$this->assertEquals(['Foo' => $c2], $tableDiff->getAddedPkFields()->toArray());
}
- public function testCompareRemovedPkField()
+ public function testCompareRemovedPkField(): void
{
$t1 = new Entity();
$c1 = new Field('Foo');
@@ -108,7 +104,7 @@ public function testCompareRemovedPkField()
$this->assertEquals(['Foo' => $c1], $tableDiff->getRemovedPkFields()->toArray());
}
- public function testCompareRenamedPkField()
+ public function testCompareRenamedPkField(): void
{
$t1 = new Entity();
$c1 = new Field('Foo');
@@ -141,7 +137,7 @@ public function testCompareRenamedPkField()
$this->assertTrue($tableDiff->getRemovedPkFields()->isEmpty());
}
- public function testCompareSeveralPrimaryKeyDifferences()
+ public function testCompareSeveralPrimaryKeyDifferences(): void
{
$t1 = new Entity();
$c1 = new Field('col1');
@@ -191,7 +187,7 @@ public function testCompareSeveralPrimaryKeyDifferences()
$this->assertEquals(['col3' => $c3], $tableDiff->getRemovedPkFields()->toArray());
}
- public function testCompareSeveralRenamedSamePrimaryKeys()
+ public function testCompareSeveralRenamedSamePrimaryKeys(): void
{
$t1 = new Entity();
$c1 = new Field('col1');
diff --git a/tests/Generator/Model/Diff/EntityRelationComparatorTest.php b/tests/Generator/Model/Diff/EntityRelationComparatorTest.php
index 58321264..b420e072 100644
--- a/tests/Generator/Model/Diff/EntityRelationComparatorTest.php
+++ b/tests/Generator/Model/Diff/EntityRelationComparatorTest.php
@@ -1,12 +1,11 @@
-platform = new MysqlPlatform();
}
- public function testCompareSameFks()
+ public function testCompareSameFks(): void
{
$c1 = new Field('Foo');
$c2 = new Field('Bar');
@@ -60,7 +56,7 @@ public function testCompareSameFks()
$this->assertNull($diff);
}
- public function testCompareNotSameFks()
+ public function testCompareNotSameFks(): void
{
$c1 = new Field('Foo');
$c2 = new Field('Bar');
@@ -74,10 +70,10 @@ public function testCompareNotSameFks()
$t2 = new Entity('Baz');
$diff = EntityComparator::computeDiff($t1, $t2);
- $this->assertTrue($diff instanceof EntityDiff);
+ $this->assertInstanceOf(EntityDiff::class, $diff);
}
- public function testCompareAddedFks()
+ public function testCompareAddedFks(): void
{
$db1 = new Database();
$db1->setPlatform($this->platform);
@@ -104,7 +100,7 @@ public function testCompareAddedFks()
$this->assertEquals(['baz_fk_4e99e8' => $fk2], $tableDiff->getAddedFks()->toArray());
}
- public function testCompareRemovedFks()
+ public function testCompareRemovedFks(): void
{
$db1 = new Database();
$db1->setPlatform($this->platform);
@@ -131,7 +127,7 @@ public function testCompareRemovedFks()
$this->assertEquals(['baz_fk_4e99e8' => $fk1], $tableDiff->getRemovedFks()->toArray());
}
- public function testCompareModifiedFks()
+ public function testCompareModifiedFks(): void
{
$db1 = new Database();
$db1->setPlatform($this->platform);
diff --git a/tests/Generator/Model/Diff/FieldComparatorTest.php b/tests/Generator/Model/Diff/FieldComparatorTest.php
index 1299b7a0..df448a5a 100644
--- a/tests/Generator/Model/Diff/FieldComparatorTest.php
+++ b/tests/Generator/Model/Diff/FieldComparatorTest.php
@@ -1,4 +1,12 @@
-platform = new MysqlPlatform();
}
- public function testCompareNoDifference()
+ public function testCompareNoDifference(): void
{
$c1 = new Field();
$c1->getDomain()->copy($this->platform->getDomainForType('DOUBLE'));
@@ -39,7 +46,7 @@ public function testCompareNoDifference()
$this->assertTrue(FieldComparator::compareFields($c1, $c2)->isEmpty());
}
- public function testCompareType()
+ public function testCompareType(): void
{
$c1 = new Field();
$c1->getDomain()->copy($this->platform->getDomainForType('VARCHAR'));
@@ -52,7 +59,7 @@ public function testCompareType()
$this->assertEquals($expectedChangedProperties, FieldComparator::compareFields($c1, $c2)->toArray());
}
- public function testCompareScale()
+ public function testCompareScale(): void
{
$c1 = new Field();
$c1->getDomain()->replaceScale(2);
@@ -62,7 +69,7 @@ public function testCompareScale()
$this->assertEquals($expectedChangedProperties, FieldComparator::compareFields($c1, $c2)->toArray());
}
- public function testCompareSize()
+ public function testCompareSize(): void
{
$c1 = new Field();
$c1->getDomain()->setSize(2);
@@ -72,7 +79,7 @@ public function testCompareSize()
$this->assertEquals($expectedChangedProperties, FieldComparator::compareFields($c1, $c2)->toArray());
}
- public function testCompareSqlType()
+ public function testCompareSqlType(): void
{
$c1 = new Field();
$c1->getDomain()->copy($this->platform->getDomainForType('INTEGER'));
@@ -83,7 +90,7 @@ public function testCompareSqlType()
$this->assertEquals($expectedChangedProperties, FieldComparator::compareFields($c1, $c2)->toArray());
}
- public function testCompareNotNull()
+ public function testCompareNotNull(): void
{
$c1 = new Field();
$c1->setNotNull(true);
@@ -93,7 +100,7 @@ public function testCompareNotNull()
$this->assertEquals($expectedChangedProperties, FieldComparator::compareFields($c1, $c2)->toArray());
}
- public function testCompareDefaultValueToNull()
+ public function testCompareDefaultValueToNull(): void
{
$c1 = new Field();
$c1->getDomain()->setDefaultValue(new FieldDefaultValue(123, FieldDefaultValue::TYPE_VALUE));
@@ -105,7 +112,7 @@ public function testCompareDefaultValueToNull()
$this->assertEquals($expectedChangedProperties, FieldComparator::compareFields($c1, $c2)->toArray());
}
- public function testCompareDefaultValueFromNull()
+ public function testCompareDefaultValueFromNull(): void
{
$c1 = new Field();
$c2 = new Field();
@@ -117,7 +124,7 @@ public function testCompareDefaultValueFromNull()
$this->assertEquals($expectedChangedProperties, FieldComparator::compareFields($c1, $c2)->toArray());
}
- public function testCompareDefaultValueValue()
+ public function testCompareDefaultValueValue(): void
{
$c1 = new Field();
$c1->getDomain()->setDefaultValue(new FieldDefaultValue(123, FieldDefaultValue::TYPE_VALUE));
@@ -129,7 +136,7 @@ public function testCompareDefaultValueValue()
$this->assertEquals($expectedChangedProperties, FieldComparator::compareFields($c1, $c2)->toArray());
}
- public function testCompareDefaultValueType()
+ public function testCompareDefaultValueType(): void
{
$c1 = new Field();
$c1->getDomain()->setDefaultValue(new FieldDefaultValue(123, FieldDefaultValue::TYPE_VALUE));
@@ -144,7 +151,7 @@ public function testCompareDefaultValueType()
/**
* @see http://www.propelorm.org/ticket/1141
*/
- public function testCompareDefaultExrpCurrentTimestamp()
+ public function testCompareDefaultExrpCurrentTimestamp(): void
{
$c1 = new Field();
$c1->getDomain()->setDefaultValue(new FieldDefaultValue("NOW()", FieldDefaultValue::TYPE_EXPR));
@@ -153,7 +160,7 @@ public function testCompareDefaultExrpCurrentTimestamp()
$this->assertTrue(FieldComparator::compareFields($c1, $c2)->isEmpty());
}
- public function testCompareAutoincrement()
+ public function testCompareAutoincrement(): void
{
$c1 = new Field();
$c1->setAutoIncrement(true);
@@ -163,7 +170,7 @@ public function testCompareAutoincrement()
$this->assertEquals($expectedChangedProperties, FieldComparator::compareFields($c1, $c2)->toArray());
}
- public function testCompareMultipleDifferences()
+ public function testCompareMultipleDifferences(): void
{
$c1 = new Field();
$c1->getDomain()->copy($this->platform->getDomainForType('INTEGER'));
diff --git a/tests/Generator/Model/Diff/IndexComparatorTest.php b/tests/Generator/Model/Diff/IndexComparatorTest.php
index 450702db..7f4b4c66 100644
--- a/tests/Generator/Model/Diff/IndexComparatorTest.php
+++ b/tests/Generator/Model/Diff/IndexComparatorTest.php
@@ -1,4 +1,12 @@
-assertFalse(IndexComparator::computeDiff($i1, $i2));
}
- public function testCompareType()
+ public function testCompareType(): void
{
$c1 = new Field('Foo');
$i1 = new Index('Foo_Index');
@@ -48,7 +56,7 @@ public function testCompareType()
$this->assertTrue(IndexComparator::computeDiff($i1, $i2));
}
- public function testCompareDifferentFields()
+ public function testCompareDifferentFields(): void
{
$c1 = new Field('Foo');
$i1 = new Index('Foo_Index');
@@ -58,7 +66,7 @@ public function testCompareDifferentFields()
$this->assertTrue(IndexComparator::computeDiff($i1, $i2));
}
- public function testCompareDifferentOrder()
+ public function testCompareDifferentOrder(): void
{
$c1 = new Field('Foo');
$c2 = new Field('Bar');
diff --git a/tests/Generator/Model/Diff/RelationComparatorTest.php b/tests/Generator/Model/Diff/RelationComparatorTest.php
index 12f38e7e..84ab8919 100644
--- a/tests/Generator/Model/Diff/RelationComparatorTest.php
+++ b/tests/Generator/Model/Diff/RelationComparatorTest.php
@@ -1,4 +1,4 @@
-assertFalse(RelationComparator::computeDiff($fk1, $fk2));
}
- public function testCompareLocalField()
+ public function testCompareLocalField(): void
{
$c1 = new Field('Foo');
$c2 = new Field('Bar');
@@ -57,7 +57,7 @@ public function testCompareLocalField()
$this->assertTrue(RelationComparator::computeDiff($fk1, $fk2));
}
- public function testCompareForeignField()
+ public function testCompareForeignField(): void
{
$c1 = new Field('Foo');
$c2 = new Field('Bar');
@@ -74,7 +74,7 @@ public function testCompareForeignField()
$this->assertTrue(RelationComparator::computeDiff($fk1, $fk2));
}
- public function testCompareFieldMappings()
+ public function testCompareFieldMappings(): void
{
$c1 = new Field('Foo');
$c2 = new Field('Bar');
@@ -94,7 +94,7 @@ public function testCompareFieldMappings()
$this->assertTrue(RelationComparator::computeDiff($fk1, $fk2));
}
- public function testCompareOnUpdate()
+ public function testCompareOnUpdate(): void
{
$c1 = new Field('Foo');
$c2 = new Field('Bar');
@@ -113,7 +113,7 @@ public function testCompareOnUpdate()
$this->assertTrue(RelationComparator::computeDiff($fk1, $fk2));
}
- public function testCompareOnDelete()
+ public function testCompareOnDelete(): void
{
$c1 = new Field('Foo');
$c2 = new Field('Bar');
@@ -132,7 +132,7 @@ public function testCompareOnDelete()
$this->assertTrue(RelationComparator::computeDiff($fk1, $fk2));
}
- public function testCompareSort()
+ public function testCompareSort(): void
{
$c1 = new Field('Foo');
$c2 = new Field('Bar');
diff --git a/tests/Generator/Model/DomainTest.php b/tests/Generator/Model/DomainTest.php
index 302e1897..2998cdbb 100644
--- a/tests/Generator/Model/DomainTest.php
+++ b/tests/Generator/Model/DomainTest.php
@@ -1,5 +1,4 @@
assertSame(2, $domain->getScale());
}
- public function testSetDatabase()
+ public function testSetDatabase(): void
{
$domain = new Domain();
$domain->setDatabase($this->getDatabaseMock('bookstore'));
@@ -37,7 +38,7 @@ public function testSetDatabase()
$this->assertInstanceOf('Propel\Generator\Model\Database', $domain->getDatabase());
}
- public function testReplaceMappingAndSqlTypes()
+ public function testReplaceMappingAndSqlTypes(): void
{
$value = $this->getFieldDefaultValueMock();
@@ -51,14 +52,14 @@ public function testReplaceMappingAndSqlTypes()
$this->assertInstanceOf('Propel\Generator\Model\FieldDefaultValue', $value);
}
- public function testGetNoPhpDefaultValue()
+ public function testGetNoPhpDefaultValue(): void
{
$domain = new Domain();
$this->assertNull($domain->getPhpDefaultValue());
}
- public function testGetPhpDefaultValue()
+ public function testGetPhpDefaultValue(): void
{
$value = $this->getFieldDefaultValueMock();
$value
@@ -77,7 +78,7 @@ public function testGetPhpDefaultValue()
* @dataProvider provideBooleanValues
*
*/
- public function testGetBooleanValue($mappingType, $booleanAsString, $expected)
+ public function testGetBooleanValue($mappingType, $booleanAsString, $expected): void
{
$value = $this->getFieldDefaultValueMock();
$value
@@ -92,7 +93,7 @@ public function testGetBooleanValue($mappingType, $booleanAsString, $expected)
$this->assertSame($expected, $domain->getPhpDefaultValue());
}
- public function provideBooleanValues()
+ public function provideBooleanValues(): array
{
return [
['BOOLEAN', 1, true],
@@ -110,7 +111,7 @@ public function provideBooleanValues()
];
}
- public function testGetPhpDefaultValueArray()
+ public function testGetPhpDefaultValueArray(): void
{
$value = $this->getFieldDefaultValueMock();
$value
@@ -122,10 +123,10 @@ public function testGetPhpDefaultValueArray()
$domain = new Domain('ARRAY');
$domain->setDefaultValue($value);
- $this->assertSame('||foo | bar | baz | foobar||', $domain->getPhpDefaultValue());
+ $this->assertSame('||foo | bar | baz | foobar||', $domain->getPhpDefaultValue()->toString());
}
- public function testGetPhpDefaultValueArrayNull()
+ public function testGetPhpDefaultValueArrayNull(): void
{
$value = $this->getFieldDefaultValueMock();
$value
@@ -140,7 +141,7 @@ public function testGetPhpDefaultValueArrayNull()
$this->assertNull($domain->getPhpDefaultValue());
}
- public function testGetPhpDefaultValueArrayDelimiter()
+ public function testGetPhpDefaultValueArrayDelimiter(): void
{
$value = $this->getFieldDefaultValueMock();
$value
@@ -155,7 +156,7 @@ public function testGetPhpDefaultValueArrayDelimiter()
$this->assertNull($domain->getPhpDefaultValue());
}
- public function testCantGetPhpDefaultValue()
+ public function testCantGetPhpDefaultValue(): void
{
$value = $this->getFieldDefaultValueMock();
$value
@@ -175,14 +176,14 @@ public function testCantGetPhpDefaultValue()
* @dataProvider provideSizeDefinitions
*
*/
- public function testGetSizeDefinition($size, $scale, $definition)
+ public function testGetSizeDefinition($size, $scale, $definition): void
{
$domain = new Domain('FLOAT', 'DOUBLE', $size, $scale);
$this->assertSame($definition, $domain->getSizeDefinition());
}
- public function provideSizeDefinitions()
+ public function provideSizeDefinitions(): array
{
return [
[10, null, '(10)'],
@@ -191,7 +192,7 @@ public function provideSizeDefinitions()
];
}
- public function testCopyDomain()
+ public function testCopyDomain(): void
{
$value = $this->getFieldDefaultValueMock();
@@ -211,34 +212,36 @@ public function testCopyDomain()
$this->assertSame('DOUBLE', $newDomain->getSqlType());
$this->assertSame(10, $newDomain->getSize());
$this->assertSame(2, $newDomain->getScale());
- $this->assertSame('Mapping between FLOAT and DOUBLE', $newDomain->getName());
+ $this->assertSame('Mapping between FLOAT and DOUBLE', $newDomain->getName()->toString());
$this->assertSame('Some description', $newDomain->getDescription());
$this->assertInstanceOf('Propel\Generator\Model\FieldDefaultValue', $value);
}
public function testCloneWithDefaultValue()
{
+ //Clone not supported. Use myclabs/deep-copy instead
$value = $this->getFieldDefaultValueMock();
$domain = new Domain();
$domain->setDefaultValue($value);
- $clonedDoman = clone $domain;
+ $clonedDomain = deep_copy($domain);
- $this->assertEquals($domain, $clonedDoman);
- $this->assertNotSame($domain, $clonedDoman);
+ $this->assertEquals($domain, $clonedDomain);
+ $this->assertNotSame($domain, $clonedDomain);
}
- public function testCloneWithoutDefaultValue()
+ public function testCloneWithoutDefaultValue(): void
{
+ //Clone not supported. Use myclabs/deep-copy instead
$domain = new Domain();
- $clonedDoman = clone $domain;
+ $clonedDomain = deep_copy($domain);
- $this->assertEquals($domain, $clonedDoman);
- $this->assertNotSame($domain, $clonedDoman);
+ $this->assertEquals($domain, $clonedDomain);
+ $this->assertNotSame($domain, $clonedDomain);
}
- private function getFieldDefaultValueMock()
+ private function getFieldDefaultValueMock(): FieldDefaultValue
{
$value = $this
->getMockBuilder('Propel\Generator\Model\FieldDefaultValue')
diff --git a/tests/Generator/Model/EntityTest.php b/tests/Generator/Model/EntityTest.php
index abc6bfd3..7bea2084 100644
--- a/tests/Generator/Model/EntityTest.php
+++ b/tests/Generator/Model/EntityTest.php
@@ -1,5 +1,4 @@
-assertSame('books', $entity->getName());
+ $this->assertSame('books', $entity->getName()->toString());
$this->assertFalse($entity->isAllowPkInsert());
$this->assertFalse($entity->isCrossRef());
$this->assertFalse($entity->isReloadOnInsert());
$this->assertFalse($entity->isReloadOnUpdate());
$this->assertFalse($entity->isSkipSql());
$this->assertFalse($entity->isReadOnly());
- $this->assertSame(0, $entity->getNumLazyLoadFields());
+ $this->assertSame(0, $entity->countLazyLoadFields());
$this->assertEmpty($entity->getChildrenNames());
$this->assertFalse($entity->hasRelations());
}
@@ -52,15 +52,15 @@ public function testCreateNewEntity()
* @dataProvider provideNamespaces
*
*/
- public function testSetNamespace($namespace, $expected)
+ public function testSetNamespace($namespace, $expected): void
{
$entity = new Entity();
$entity->setNamespace($namespace);
- $this->assertSame($expected, $entity->getNamespace());
+ $this->assertSame($expected, $entity->getNamespace()->toString());
}
- public function provideNamespaces()
+ public function provideNamespaces(): array
{
return [
['\Acme', '\Acme'],
@@ -72,7 +72,7 @@ public function provideNamespaces()
];
}
- public function testSetRepository()
+ public function testSetRepository(): void
{
$entity = new Entity('Book');
$entity->setRepository('BookRepository');
@@ -80,7 +80,7 @@ public function testSetRepository()
$this->assertEquals('BookRepository', $entity->getRepository());
}
- public function testNames()
+ public function testNames(): void
{
$entity = new Entity('Wurst\\Und\\Kaese');
$this->assertEquals('Kaese', $entity->getName());
@@ -88,25 +88,26 @@ public function testNames()
$entity = new Entity();
- $this->assertEmpty($entity->getName());
+ $this->assertEmpty($entity->getName()->toString());
$entity->setName('Book');
- $this->assertEquals('Book', $entity->getName());
- $this->assertEquals('book', $entity->getTableName());
+ $this->assertEquals('Book', $entity->getName()->toString());
+ $this->assertEquals('book', $entity->getTableName()->toString());
$entity->setName('BookAuthor');
- $this->assertEquals('BookAuthor', $entity->getName());
- $this->assertEquals('book_author', $entity->getTableName());
+ $entity->setTableName('');
+ $this->assertEquals('BookAuthor', $entity->getName()->toString());
+ $this->assertEquals('book_author', $entity->getTableName()->toString());
$entity->setTableName('book_has_author');
- $this->assertEquals('BookAuthor', $entity->getName());
- $this->assertEquals('book_has_author', $entity->getTableName());
+ $this->assertEquals('BookAuthor', $entity->getName()->toString());
+ $this->assertEquals('book_has_author', $entity->getTableName()->toString());
$entity->setScope('bookstore_');
- $this->assertEquals('bookstore_book_has_author', $entity->getScopedTableName());
+ $this->assertEquals('bookstore_book_has_author', $entity->getScopedTableName()->toString());
$entity->setNamespace('Bookstore');
- $this->assertEquals('Bookstore\\BookAuthor', $entity->getFullName());
+ $this->assertEquals('Bookstore\\BookAuthor', $entity->getFullName()->toString());
$entity = new Entity();
$database = new Database();
@@ -114,11 +115,11 @@ public function testNames()
$database->setNamespace('Bookstore');
$entity->setDatabase($database);
- $this->assertEquals('Bookstore', $entity->getNamespace());
- $this->assertEquals('bookings_', $entity->getScope());
+ $this->assertEquals('Bookstore', $entity->getNamespace()->toString());
+ $this->assertEquals('bookings_', $entity->getScope()->toString());
}
- public function testGetGeneratorConfig()
+ public function testGetGeneratorConfig(): void
{
$config = $this->getMockBuilder('Propel\Generator\Config\GeneratorConfig')
->disableOriginalConstructor()->getMock();
@@ -136,7 +137,7 @@ public function testGetGeneratorConfig()
$this->assertSame($config, $entity->getGeneratorConfig());
}
- public function testApplyBehaviors()
+ public function testApplyBehaviors(): void
{
$behavior = $this->getBehaviorMock('foo');
$behavior
@@ -167,7 +168,7 @@ public function testApplyBehaviors()
$entity->applyBehaviors();
}
- public function testGetAdditionalBuilders()
+ public function testGetAdditionalBuilders(): void
{
$additionalBehaviors = [
$this->getBehaviorMock('foo'),
@@ -186,7 +187,7 @@ public function testGetAdditionalBuilders()
$this->assertTrue($entity->hasAdditionalBuilders());
}
- public function testHasNoAdditionalBuilders()
+ public function testHasNoAdditionalBuilders(): void
{
$entity = new Entity();
$entity->addBehavior($this->getBehaviorMock('foo'));
@@ -195,24 +196,23 @@ public function testHasNoAdditionalBuilders()
$this->assertFalse($entity->hasAdditionalBuilders());
}
- public function testGetNameWithoutPlatform()
+ public function testGetNameWithoutPlatform(): void
{
$entity = new Entity('books');
- $this->assertSame('books', $entity->getName());
+ $this->assertSame('books', (string) $entity->getName());
}
/**
* @dataProvider provideSchemaNames
*
*/
- public function testGetNameWithPlatform($supportsSchemas, $schemaName, $expectedName)
+ public function testGetNameWithPlatform($supportsSchemas, $schemaName, $expectedName): void
{
$platform = $this->getPlatformMock($supportsSchemas);
$platform
- ->expects($supportsSchemas ? $this->once() : $this->never())
->method('getSchemaDelimiter')
- ->will($this->returnValue('.'))
+ ->will($this->returnValue($supportsSchemas ? '.' : ''))
;
$database = $this->getDatabaseMock($schemaName, [
@@ -232,48 +232,46 @@ public function testGetNameWithPlatform($supportsSchemas, $schemaName, $expected
$entity->setDatabase($database);
$entity->getDatabase()->setSchema($schema);
- $this->assertSame($expectedName, $entity->getFullTableName());
+ $this->assertEquals($expectedName, (string) $entity->getFullTableName());
}
- public function provideSchemaNames()
+ public function provideSchemaNames(): array
{
return [
[false, 'bookstore', 'books'],
- [false, null, 'books'],
+ [false, '', 'books'],
[true, 'bookstore', 'bookstore.books'],
];
}
- public function testGetOverrideSchemaName()
+ public function testGetOverrideSchemaName(): void
{
$entity = new Entity();
$entity->setDatabase($this->getDatabaseMock('bookstore'));
$entity->setSchemaName('my_schema');
- $this->assertEquals('my_schema', $entity->guessSchemaName());
+ $this->assertEquals('my_schema', $entity->getSchemaName());
}
- public function testSetDescription()
+ public function testSetDescription(): void
{
$entity = new Entity();
$this->assertFalse($entity->hasDescription());
$entity->setDescription('Some description');
- $this->assertNotNull($entity->getDescription());
- $this->assertSame('Some description', $entity->getDescription());
+ $this->assertEquals('Some description', (string) $entity->getDescription());
}
- /**
- * @expectedException \InvalidArgumentException
- */
- public function testSetInvalidStringFormat()
+ public function testSetInvalidStringFormat(): void
{
+ $this->expectException(\InvalidArgumentException::class);
+
$entity = new Entity();
$entity->setStringFormat('FOO');
}
- public function testGetStringFormatFromDatabase()
+ public function testGetStringFormatFromDatabase(): void
{
$database = $this->getDatabaseMock('bookstore');
$database
@@ -292,7 +290,7 @@ public function testGetStringFormatFromDatabase()
* @dataProvider provideStringFormats
*
*/
- public function testGetStringFormat($format)
+ public function testGetStringFormat($format): void
{
$entity = new Entity();
$entity->setStringFormat($format);
@@ -300,7 +298,7 @@ public function testGetStringFormat($format)
$this->assertSame($format, $entity->getStringFormat());
}
- public function provideStringFormats()
+ public function provideStringFormats(): array
{
return [
['XML'],
@@ -310,7 +308,7 @@ public function provideStringFormats()
];
}
- public function testAddSameFieldTwice()
+ public function testAddSameFieldTwice(): void
{
$entity = new Entity('books');
$field = $this->getFieldMock('created_at', ['phpName' => 'CreatedAt']);
@@ -321,7 +319,7 @@ public function testAddSameFieldTwice()
$entity->addField($field);
}
- public function testGetChildrenNames()
+ public function testGetChildrenNames(): void
{
$field = new Field('created_at');
$field->setInheritanceType('single');
@@ -344,7 +342,7 @@ public function testGetChildrenNames()
$this->assertSame('Propel\Generator\Model\Inheritance', $names[1]);
}
- public function testCantGetChildrenNames()
+ public function testCantGetChildrenNames(): void
{
$field = $this->getFieldMock('created_at', ['inheritance' => true]);
@@ -360,7 +358,7 @@ public function testCantGetChildrenNames()
$this->assertEmpty($entity->getChildrenNames());
}
- public function testAddInheritanceField()
+ public function testAddInheritanceField(): void
{
$entity = new Entity('books');
$field = $this->getFieldMock('created_at', ['inheritance' => true]);
@@ -373,7 +371,7 @@ public function testAddInheritanceField()
$this->assertTrue($entity->requiresTransactionInPostgres());
}
- public function testHasBehaviors()
+ public function testHasBehaviors(): void
{
$behavior1 = $this->getBehaviorMock('Foo');
$behavior2 = $this->getBehaviorMock('Bar');
@@ -396,7 +394,7 @@ public function testHasBehaviors()
$this->assertSame($behavior3, $entity->getBehavior('Baz'));
}
- public function testUnregisterBehavior()
+ public function testUnregisterBehavior(): void
{
$behavior = new Behavior();
$behavior->setName('foo');
@@ -410,7 +408,7 @@ public function testUnregisterBehavior()
$this->assertNull($behavior->getEntity());
}
- public function testAddField()
+ public function testAddField(): void
{
$entity = new Entity('books');
$field = $this->getFieldMock('createdAt');
@@ -418,23 +416,22 @@ public function testAddField()
$this->assertNull($entity->getChildrenField());
$this->assertTrue($entity->requiresTransactionInPostgres());
$this->assertTrue($entity->hasField($field));
- $this->assertSame($field, $entity->getField('createdAt'));
+ $this->assertSame($field, $entity->getFieldByName('createdAt'));
$this->assertCount(1, $entity->getFields());
- $this->assertSame(1, $entity->getNumFields());
+ $this->assertSame(1, $entity->countFields());
}
- /**
- * @expectedException \Propel\Generator\Exception\EngineException
- */
- public function testCantRemoveFieldWhichIsNotInEntity()
+ public function testCantRemoveFieldWhichIsNotInEntity(): void
{
+ $this->expectException(EngineException::class);
+
$field1 = $this->getFieldMock('title');
$entity = new Entity('books');
$entity->removeField($field1);
}
- public function testRemoveFieldByName()
+ public function testRemoveFieldByName(): void
{
$field1 = $this->getFieldMock('id');
$field2 = $this->getFieldMock('title');
@@ -444,15 +441,15 @@ public function testRemoveFieldByName()
$entity->addField($field1);
$entity->addField($field2);
$entity->addField($field3);
- $entity->removeField('title');
+ $entity->removeFieldByName('title');
$this->assertCount(2, $entity->getFields());
- $this->assertTrue($entity->hasField('id'));
- $this->assertTrue($entity->hasField('isbn'));
- $this->assertFalse($entity->hasField('title'));
+ $this->assertTrue($entity->hasFieldByName('id'));
+ $this->assertTrue($entity->hasFieldByName('isbn'));
+ $this->assertFalse($entity->hasFieldByName('title'));
}
- public function testRemoveField()
+ public function testRemoveField(): void
{
$field1 = $this->getFieldMock('id');
$field2 = $this->getFieldMock('title');
@@ -465,12 +462,12 @@ public function testRemoveField()
$entity->removeField($field2);
$this->assertCount(2, $entity->getFields());
- $this->assertTrue($entity->hasField('id'));
- $this->assertTrue($entity->hasField('isbn'));
- $this->assertFalse($entity->hasField('title'));
+ $this->assertTrue($entity->hasField($field1));
+ $this->assertTrue($entity->hasField($field3));
+ $this->assertFalse($entity->hasField($field2));
}
- public function testGetNumLazyLoadFields()
+ public function testCountLazyLoadFields(): void
{
$field1 = $this->getFieldMock('created_at');
$field2 = $this->getFieldMock('updated_at', ['lazy' => true]);
@@ -482,10 +479,10 @@ public function testGetNumLazyLoadFields()
$entity->addField($field2);
$entity->addField($field3);
- $this->assertSame(2, $entity->getNumLazyLoadFields());
+ $this->assertSame(2, $entity->countLazyLoadFields());
}
- public function testHasEnumFields()
+ public function testHasEnumFields(): void
{
$field1 = $this->getFieldMock('created_at');
$field2 = $this->getFieldMock('updated_at');
@@ -511,24 +508,21 @@ public function testHasEnumFields()
$this->assertTrue($entity->hasEnumFields());
}
- public function testCantGetField()
+ public function testCantGetField(): void
{
$entity = new Entity('books');
- $this->assertFalse($entity->hasField('FOO', true));
+ $this->assertFalse($entity->hasFieldByName('FOO'));
}
- /**
- * @expectedException \InvalidArgumentException
- */
- public function testCantGetFieldException()
+ public function testInexistentFieldReturnNull(): void
{
$entity = new Entity('books');
- $this->assertNull($entity->getField('FOO'));
+ $this->assertNull($entity->getFieldByName('FOO'));
}
- public function testSetAbstract()
+ public function testSetAbstract(): void
{
$entity = new Entity();
$this->assertFalse($entity->isAbstract());
@@ -537,7 +531,7 @@ public function testSetAbstract()
$this->assertTrue($entity->isAbstract());
}
- public function testAddIndex()
+ public function testAddIndex(): void
{
$entity = new Entity();
$index = new Index();
@@ -550,22 +544,20 @@ public function testAddIndex()
$this->assertCount(1, $entity->getIndices());
}
- /**
- * @expectedException \InvalidArgumentException
- */
- public function testAddEmptyIndex()
+ public function testAddEmptyIndex(): void
{
+ $this->expectException(\InvalidArgumentException::class);
+
$entity = new Entity();
$entity->addIndex(new Index());
$this->assertCount(1, $entity->getIndices());
}
- /**
- * @expectedException \InvalidArgumentException
- */
- public function testAddAlreadyCreatedIndex()
+ public function testAddAlreadyCreatedIndex(): void
{
+ $this->expectException(\InvalidArgumentException::class);
+
$index = $this->getIndexMock('idx_fake_entity');
$entity = new Entity();
$entity->addIndex($index);
@@ -574,7 +566,7 @@ public function testAddAlreadyCreatedIndex()
$entity->addIndex($index);
}
- public function testCreateIndex()
+ public function testCreateIndex(): void
{
$entity = new Entity();
$field1 = $this->getFieldMock('id_mock');
@@ -586,7 +578,7 @@ public function testCreateIndex()
$this->assertTrue($entity->isIndex([$field1, $field2]));
}
- public function testIsIndex()
+ public function testIsIndex(): void
{
$entity = new Entity();
$field1 = new Field('category_id');
@@ -604,10 +596,11 @@ public function testIsIndex()
$this->assertFalse($entity->isIndex(['asd']));
}
- public function testRemoveIndex()
+ public function testRemoveIndex(): void
{
$entity = new Entity();
- $index = $this->getIndexMock('idx_fake', ['entity' => $entity]);
+ $field = $this->getFieldMock('field_fake', ['entity' => $entity]);
+ $index = $this->getIndexMock('idx_fake', ['entity' => $entity, 'fields' => [$field]]);
$entity->addIndex($index);
$this->assertTrue($entity->hasIndex('idx_fake'));
@@ -616,7 +609,7 @@ public function testRemoveIndex()
$this->assertFalse($entity->hasIndex('idx_fake'));
}
- public function testAddUniqueIndex()
+ public function testAddUniqueIndex(): void
{
$entity = new Entity();
$entity->addUnique($this->getUniqueIndexMock('author_unq'));
@@ -624,7 +617,7 @@ public function testAddUniqueIndex()
$this->assertCount(1, $entity->getUnices());
}
- public function testRemoveUniqueIndex()
+ public function testRemoveUniqueIndex(): void
{
$entity = new Entity();
$unique = $this->getUniqueIndexMock('author_unq', ['entity' => $entity]);
@@ -636,7 +629,7 @@ public function testRemoveUniqueIndex()
$this->assertCount(0, $entity->getUnices());
}
- public function testIsUnique()
+ public function testIsUnique(): void
{
$entity = new Entity();
$field1 = $this->getFieldMock('category_id');
@@ -655,7 +648,7 @@ public function testIsUnique()
$this->assertTrue($entity->isUnique([$field2, $field1]));
}
- public function testIsUniqueWhenUniqueField()
+ public function testIsUniqueWhenUniqueField(): void
{
$entity = new Entity();
$field = $this->getFieldMock('unique_id',['entity' => $entity, 'unique' => true]);
@@ -663,7 +656,7 @@ public function testIsUniqueWhenUniqueField()
$this->assertTrue($entity->isUnique([$field]));
}
- public function testIsUniquePrimaryKey()
+ public function testIsUniquePrimaryKey(): void
{
$entity = new Entity();
$field = $this->getFieldMock('id', ['primary' => true, 'entity' => $entity]);
@@ -673,7 +666,7 @@ public function testIsUniquePrimaryKey()
$this->assertTrue($entity->isUnique([$field]));
}
- public function testisUniqueWithCompositePrimaryKey()
+ public function testisUniqueWithCompositePrimaryKey(): void
{
$entity = new Entity();
$field1 = $this->getFieldMock('author_id', ['primary' => true, 'entity' => $entity]);
@@ -687,7 +680,7 @@ public function testisUniqueWithCompositePrimaryKey()
$this->assertFalse($entity->isUnique([$field2, $field3]));
}
- public function testGetCompositePrimaryKey()
+ public function testGetCompositePrimaryKey(): void
{
$field1 = $this->getFieldMock('book_id', ['primary' => true]);
$field2 = $this->getFieldMock('author_id', ['primary' => true]);
@@ -707,7 +700,7 @@ public function testGetCompositePrimaryKey()
$this->assertSame($field1, $entity->getFirstPrimaryKeyField());
}
- public function testGetSinglePrimaryKey()
+ public function testGetSinglePrimaryKey(): void
{
$field1 = $this->getFieldMock('id', ['primary' => true]);
$field2 = $this->getFieldMock('title');
@@ -727,7 +720,7 @@ public function testGetSinglePrimaryKey()
$this->assertSame($field1, $entity->getFirstPrimaryKeyField());
}
- public function testGetNoPrimaryKey()
+ public function testGetNoPrimaryKey(): void
{
$field1 = $this->getFieldMock('id');
$field2 = $this->getFieldMock('title');
@@ -747,7 +740,7 @@ public function testGetNoPrimaryKey()
$this->assertNull($entity->getFirstPrimaryKeyField());
}
- public function testGetAutoIncrementPrimaryKey()
+ public function testGetAutoIncrementPrimaryKey(): void
{
$field1 = $this->getFieldMock('id', [
'primary' => true,
@@ -769,7 +762,7 @@ public function testGetAutoIncrementPrimaryKey()
$this->assertSame($field1, $entity->getAutoIncrementPrimaryKey());
}
- public function testAddIdMethodParameter()
+ public function testAddIdMethodParameter(): void
{
$parameter = $this
->getMockBuilder('Propel\Generator\Model\IdMethodParameter')
@@ -787,7 +780,7 @@ public function testAddIdMethodParameter()
$this->assertCount(1, $entity->getIdMethodParameters());
}
- public function testAddReferrerRelation()
+ public function testAddReferrerRelation(): void
{
$entity = new Entity('books');
$entity->addReferrer($this->getRelationMock());
@@ -795,7 +788,7 @@ public function testAddReferrerRelation()
$this->assertCount(1, $entity->getReferrers());
}
- public function testAddRelation()
+ public function testAddRelation(): void
{
$fk = $this->getRelationMock('fk_author_id', [
'target' => 'authors',
@@ -810,7 +803,7 @@ public function testAddRelation()
}));
}
- public function testAddRelations()
+ public function testAddRelations(): void
{
$authorRel = $this->getRelationMock('author_id', ['target' => 'Authors']);
$publisherRel = $this->getRelationMock('publisher_id', ['target' => 'Publishers']);
@@ -823,7 +816,7 @@ public function testAddRelations()
$this->assertSame($publisherRel, $entity->getRelation('publisher_id'));
}
- public function testGetRelationsReferencingEntity()
+ public function testGetRelationsReferencingEntity(): void
{
$fk1 = $this->getRelationMock('fk1', ['target' => 'authors']);
$fk2 = $this->getRelationMock('fk2', ['target' => 'categories']);
@@ -837,7 +830,7 @@ public function testGetRelationsReferencingEntity()
$this->assertCount(2, $entity->getRelationsReferencingEntity('authors'));
}
- public function testGetFieldRelations()
+ public function testGetFieldRelations(): void
{
$fk1 = $this->getRelationMock('fk1', [
'local_fields' => ['foo', 'author_id', 'bar']
@@ -855,7 +848,7 @@ public function testGetFieldRelations()
$this->assertContains($fk1, $entity->getFieldRelations('author_id'));
}
- public function testSetAlias()
+ public function testSetAlias(): void
{
$entity = new Entity('books');
@@ -863,10 +856,10 @@ public function testSetAlias()
$entity->setAlias('Book');
$this->assertTrue($entity->isAlias());
- $this->assertSame('Book', $entity->getAlias());
+ $this->assertSame('Book', $entity->getAlias()->toString());
}
- public function testSetContainsForeignPK()
+ public function testSetContainsForeignPK(): void
{
$entity = new Entity();
@@ -874,7 +867,7 @@ public function testSetContainsForeignPK()
$this->assertTrue($entity->getContainsForeignPK());
}
- public function testSetCrossReference()
+ public function testSetCrossReference(): void
{
$entity = new Entity('books');
@@ -886,7 +879,7 @@ public function testSetCrossReference()
$this->assertTrue($entity->isCrossRef());
}
- public function testSetSkipSql()
+ public function testSetSkipSql(): void
{
$entity = new Entity('books');
$entity->setSkipSql(true);
@@ -894,7 +887,7 @@ public function testSetSkipSql()
$this->assertTrue($entity->isSkipSql());
}
- public function testSetForReferenceOnly()
+ public function testSetForReferenceOnly(): void
{
$entity = new Entity('books');
$entity->setForReferenceOnly(true);
@@ -902,7 +895,7 @@ public function testSetForReferenceOnly()
$this->assertTrue($entity->isForReferenceOnly());
}
- public function testSetDatabaseWhenEntityBelongsToDifferentDatabase()
+ public function testSetDatabaseWhenEntityBelongsToDifferentDatabase(): void
{
$db1 = new Database('bookstore1');
$db2 =new Database('bookstore2');
@@ -913,17 +906,17 @@ public function testSetDatabaseWhenEntityBelongsToDifferentDatabase()
$this->assertSame($db2, $entity->getDatabase());
}
- public function testGetAutoincrementFieldNames()
+ public function testGetAutoincrementFieldNames(): void
{
$entity= new Entity();
$field1 = $this->getFieldMock('author_id', ['entity' => $entity, 'auto_increment' => true]);
$field2 = $this->getFieldMock('book_id', ['entity' => $entity, 'auto_increment' => true]);
$entity->addFields([$field1, $field2]);
- $this->assertEquals(['author_id', 'book_id'], $entity->getAutoIncrementFieldNames());
+ $this->assertEquals(['author_id', 'book_id'], $entity->getAutoIncrementFieldNames()->toArray());
}
- public function testHasAutoincrement()
+ public function testHasAutoincrement(): void
{
$entity1 = new Entity();
$field1 = $this->getFieldMock('id', ['auto_increment' => true, 'entity' => $entity1]);
@@ -938,7 +931,7 @@ public function testHasAutoincrement()
$this->assertFalse($entity2->hasAutoIncrement());
}
- public function testQuoteIdentifier()
+ public function testQuoteIdentifier(): void
{
$database = $this->getDatabaseMock('test_db', ['platform' => new SqlitePlatform()]);
$entity = new Entity();
@@ -948,7 +941,7 @@ public function testQuoteIdentifier()
$this->assertEquals('[text]', $entity->quoteIdentifier('text'));
}
- public function testNoQuoteIdentifier()
+ public function testNoQuoteIdentifier(): void
{
$database = $this->getDatabaseMock('test_db', ['platform' => new SqlitePlatform()]);
$entity = new Entity();
@@ -958,7 +951,7 @@ public function testNoQuoteIdentifier()
$this->assertEquals('text', $entity->quoteIdentifier('text'));
}
- public function testGetIdentifierQuoting()
+ public function testGetIdentifierQuoting(): void
{
$entity = new Entity();
$this->assertNull($entity->getIdentifierQuoting());
@@ -966,34 +959,35 @@ public function testGetIdentifierQuoting()
$this->assertTrue($entity->getIdentifierQuoting());
}
- /**
- * @expectedException \Propel\Runtime\Exception\RuntimeException
- */
- public function testQuoteIdentifierNoPlatform()
+ public function testQuoteIdentifierNoPlatform(): void
{
+ $this->expectException(RuntimeException::class);
+
$entity = new Entity();
$database = $this->getDatabaseMock('test_db');
$entity->setDatabase($database);
$entity->quoteIdentifier('text');
}
- public function testClone()
+ public function testClone(): void
{
+ //__clone() not supported anymore. Use myclabs/deep-copy instead
$entity = new Entity('Book');
$entity->addField($this->getFieldMock('id', ['entity' => $entity, 'primary' => true, 'auto_increment' => true]));
$entity->addField($this->getFieldMock('title', ['entity' => $entity]));
$entity->addField($this->getFieldMock('children', ['entity' => $entity, 'inheritance' => true]));
$entity->addRelation($this->getRelationMock('Rel1', ['entity' => $entity]));
- $clone = clone $entity;
+ $clone = deep_copy($entity);
$this->assertEquals($entity, $clone, 'Entities are equals');
$this->assertNotSame($entity, $clone, 'Entities are different objects');
$this->assertEquals($entity->getFields(), $clone->getFields(), 'Field sets are equals');
$this->assertNotSame($entity->getFields(), $clone->getFields(), 'Field sets are not the same object');
+ /** @var Field $field */
foreach ($entity->getFields() as $field) {
- $cloneField = $clone->getFieldByName($field->getName());
+ $cloneField = $clone->getFieldByName($field->getName()->toString());
$this->assertNotNull($cloneField, 'Cloned set contains the given field');
$this->assertNotSame($field, $cloneField, 'Fields are different objects');
}
@@ -1004,7 +998,7 @@ public function testClone()
$this->assertNotSame($entity->getRelation('Rel1'), $clone->getRelation('Rel1'));
}
- public function testGetCrossRelation()
+ public function testGetCrossRelation(): void
{
$user = new Entity('User');
$user->addField($this->getFieldMock('id', ['entity' => $user, 'primary' => true, 'required' => true]));
@@ -1036,7 +1030,7 @@ public function testGetCrossRelation()
$crossRels = $user->getCrossRelations();
$this->assertCount(1, $crossRels);
- $this->assertInstanceOf(CrossRelation::class, $crossRels[0]);
+ $this->assertTrue($crossRels->search(fn($elem): bool => $elem instanceof CrossRelation));
$this->assertTrue($user->hasCrossRelations());
$this->assertTrue($role->hasCrossRelations());
}
@@ -1048,14 +1042,14 @@ public function testGetCrossRelation()
* @param array $options An array of options
* @return Field
*/
- protected function getFieldMock($name, array $options = [])
+ protected function getFieldMock(string $name, array $options = []): Field
{
$defaults = [
'primary' => false,
'auto_increment' => false,
'inheritance' => false,
'lazy' => false,
- 'phpName' => NamingTool::toStudlyCase($name),
+ 'phpName' => Text::create($name)->toStudlyCase()->toString(),
'pg_transaction' => true,
'unique' => false,
'required' => false
@@ -1119,3 +1113,20 @@ protected function getFieldMock($name, array $options = [])
return $field;
}
}
+
+class Entity extends BaseEntity
+{
+ /**
+ * Executes behavior entity modifiers.
+ * This is only for testing purposes. Model\Database calls already `modifyEntity` on each behavior.
+ */
+ public function applyBehaviors(): void
+ {
+ foreach ($this->behaviors as $behavior) {
+ if (!$behavior->isEntityModified()) {
+ $behavior->getEntityModifier()->modifyEntity();
+ $behavior->setEntityModified(true);
+ }
+ }
+ }
+}
diff --git a/tests/Generator/Model/FieldDefaultValueTest.php b/tests/Generator/Model/FieldDefaultValueTest.php
index bfb55970..e88cda17 100644
--- a/tests/Generator/Model/FieldDefaultValueTest.php
+++ b/tests/Generator/Model/FieldDefaultValueTest.php
@@ -1,5 +1,4 @@
-assertTrue($def1->equals($def2));
@@ -44,7 +41,7 @@ public function testEquals($def1, $def2, $test)
}
}
- public function testIsExpression()
+ public function testIsExpression(): void
{
$default = new FieldDefaultValue('SUM', FieldDefaultValue::TYPE_EXPR);
$this->assertTrue($default->isExpression());
diff --git a/tests/Generator/Model/FieldTest.php b/tests/Generator/Model/FieldTest.php
index 82932e41..fdeb0768 100644
--- a/tests/Generator/Model/FieldTest.php
+++ b/tests/Generator/Model/FieldTest.php
@@ -1,5 +1,4 @@
-getEntityMock('FakeEntity');
$field->setEntity($entity);
- $this->assertSame('title', $field->getName());
+ $this->assertSame('title', $field->getName()->toString());
$this->assertEmpty($field->getAutoIncrementString());
- $this->assertSame('FIELD_TITLE', $field->getConstantName());
+ $this->assertSame('FIELD_TITLE', $field->getConstantName()->toString());
$this->assertSame('public', $field->getMutatorVisibility());
$this->assertSame('public', $field->getAccessorVisibility());
$this->assertEquals(0, $field->getSize());
@@ -50,7 +48,7 @@ public function testCreateNewField()
$this->assertNull($field->getPlatform());
}
- public function testGetNullDefaultValueString()
+ public function testGetNullDefaultValueString(): void
{
$domain = $this->getDomainMock();
$domain
@@ -68,7 +66,7 @@ public function testGetNullDefaultValueString()
/**
* @dataProvider provideDefaultValues
*/
- public function testGetDefaultValueString($mappingType, $value, $expected)
+ public function testGetDefaultValueString($mappingType, $value, $expected): void
{
$defaultValue = $this
->getMockBuilder('Propel\Generator\Model\FieldDefaultValue')
@@ -106,7 +104,7 @@ public function testGetDefaultValueString($mappingType, $value, $expected)
$this->assertSame($expected, $field->getDefaultValueString());
}
- public function provideDefaultValues()
+ public function provideDefaultValues(): array
{
return [
['DOUBLE', 3.14, '3.14'],
@@ -118,7 +116,7 @@ public function provideDefaultValues()
];
}
- public function testAddInheritance()
+ public function testAddInheritance(): void
{
$field = new Field();
@@ -142,7 +140,7 @@ public function testAddInheritance()
$this->assertCount(0, $field->getChildren());
}
- public function testIsDefaultSqlTypeFromDomain()
+ public function testIsDefaultSqlTypeFromDomain(): void
{
$toCopy = $this->getDomainMock();
$toCopy
@@ -186,14 +184,14 @@ public function testIsDefaultSqlTypeFromDomain()
$this->assertTrue($field->isDefaultSqlType($platform));
}
- public function testIsDefaultSqlType()
+ public function testIsDefaultSqlType(): void
{
$field = new Field();
$this->assertTrue($field->isDefaultSqlType());
}
- public function testGetNotNullString()
+ public function testGetNotNullString(): void
{
$platform = $this->getPlatformMock();
$platform
@@ -215,7 +213,7 @@ public function testGetNotNullString()
* @dataProvider providePdoTypes
*
*/
- public function testGetPdoType($mappingType, $pdoType)
+ public function testGetPdoType($mappingType, $pdoType): void
{
$domain = $this->getDomainMock();
$domain
@@ -231,7 +229,7 @@ public function testGetPdoType($mappingType, $pdoType)
$this->assertSame($pdoType, $field->getPDOType());
}
- public function providePdoTypes()
+ public function providePdoTypes(): array
{
return [
['CHAR', \PDO::PARAM_STR],
@@ -265,7 +263,7 @@ public function providePdoTypes()
];
}
- public function testEnumType()
+ public function testEnumType(): void
{
$domain = $this->getDomainMock();
$domain
@@ -286,7 +284,7 @@ public function testEnumType()
$this->assertContains('BAR', $field->getValueSet());
}
- public function testSetStringValueSet()
+ public function testSetStringValueSet(): void
{
$field = new Field();
$field->setValueSet(' FOO , BAR , BAZ');
@@ -296,7 +294,7 @@ public function testSetStringValueSet()
$this->assertContains('BAZ', $field->getValueSet());
}
- public function testPhpObjectType()
+ public function testPhpObjectType(): void
{
$domain = $this->getDomainMock();
$domain
@@ -316,7 +314,7 @@ public function testPhpObjectType()
/**
* @dataProvider provideMappingTemporalTypes
*/
- public function testTemporalType($mappingType)
+ public function testTemporalType($mappingType): void
{
$domain = $this->getDomainMock();
$domain
@@ -340,7 +338,7 @@ public function testTemporalType($mappingType)
$this->assertTrue($field->isTemporalType());
}
- public function provideMappingTemporalTypes()
+ public function provideMappingTemporalTypes(): array
{
return [
['DATE'],
@@ -354,7 +352,7 @@ public function provideMappingTemporalTypes()
/**
* @dataProvider provideMappingLobTypes
*/
- public function testLobType($mappingType, $phpType, $isPhpPrimitiveType)
+ public function testLobType($mappingType, $phpType, $isPhpPrimitiveType): void
{
$domain = $this->getDomainMock();
$domain
@@ -378,7 +376,7 @@ public function testLobType($mappingType, $phpType, $isPhpPrimitiveType)
$this->assertTrue($field->isLobType());
}
- public function provideMappingLobTypes()
+ public function provideMappingLobTypes(): array
{
return [
['VARBINARY', 'string', true],
@@ -390,7 +388,7 @@ public function provideMappingLobTypes()
/**
* @dataProvider provideMappingBooleanTypes
*/
- public function testBooleanType($mappingType)
+ public function testBooleanType($mappingType): void
{
$domain = $this->getDomainMock();
$domain
@@ -414,7 +412,7 @@ public function testBooleanType($mappingType)
$this->assertTrue($field->isBooleanType());
}
- public function provideMappingBooleanTypes()
+ public function provideMappingBooleanTypes(): array
{
return [
['BOOLEAN'],
@@ -425,7 +423,7 @@ public function provideMappingBooleanTypes()
/**
* @dataProvider provideMappingNumericTypes
*/
- public function testNumericType($mappingType, $phpType, $isPrimitiveNumericType)
+ public function testNumericType($mappingType, $phpType, $isPrimitiveNumericType): void
{
$domain = $this->getDomainMock();
$domain
@@ -450,7 +448,7 @@ public function testNumericType($mappingType, $phpType, $isPrimitiveNumericType)
$this->assertTrue($field->isNumericType());
}
- public function provideMappingNumericTypes()
+ public function provideMappingNumericTypes(): array
{
return [
['SMALLINT', 'int', true],
@@ -468,7 +466,7 @@ public function provideMappingNumericTypes()
/**
* @dataProvider provideMappingTextTypes
*/
- public function testTextType($mappingType)
+ public function testTextType($mappingType): void
{
$domain = $this->getDomainMock();
$domain
@@ -492,7 +490,7 @@ public function testTextType($mappingType)
$this->assertTrue($field->isTextType());
}
- public function provideMappingTextTypes()
+ public function provideMappingTextTypes(): array
{
return [
['CHAR'],
@@ -507,7 +505,7 @@ public function provideMappingTextTypes()
];
}
- public function testGetSizeDefinition()
+ public function testGetSizeDefinition(): void
{
$domain = $this->getDomainMock();
$domain
@@ -522,7 +520,7 @@ public function testGetSizeDefinition()
$this->assertSame('(10,2)', $field->getSizeDefinition());
}
- public function testGetConstantName()
+ public function testGetConstantName(): void
{
$entity = $this->getEntityMock('Article');
@@ -530,29 +528,29 @@ public function testGetConstantName()
$field->setEntity($entity);
$field->setColumnName('created_at');
- $this->assertSame('created_at', $field->getColumnName());
- $this->assertSame('FIELD_CREATED_AT', $field->getConstantName());
- $this->assertSame('ArticleEntityMap::FIELD_CREATED_AT', $field->getFullConstantName());
+ $this->assertEquals('created_at', $field->getColumnName());
+ $this->assertEquals('FIELD_CREATED_AT', $field->getConstantName());
+ $this->assertEquals('ArticleEntityMap::FIELD_CREATED_AT', $field->getFullConstantName());
}
- public function testSetDefaultPhpName()
+ public function testSetDefaultPhpName(): void
{
$field = new Field('createdAt');
- $this->assertSame('createdAt', $field->getName());
- $this->assertSame('created_at', $field->getColumnName());
+ $this->assertEquals('createdAt', $field->getName());
+ $this->assertEquals('created_at', $field->getColumnName());
}
- public function testSetCustomPhpName()
+ public function testSetCustomPhpName(): void
{
$field = new Field('creeeatedAt');
$field->setName('createdAt');
- $this->assertSame('createdAt', $field->getName());
- $this->assertSame('created_at', $field->getColumnName());
+ $this->assertEquals('createdAt', $field->getName());
+ $this->assertEquals('created_at', $field->getColumnName());
}
- public function testSetDefaultMutatorAndAccessorMethodsVisibility()
+ public function testSetDefaultMutatorAndAccessorMethodsVisibility(): void
{
$field = new Field();
$field->setAccessorVisibility('foo');
@@ -562,7 +560,7 @@ public function testSetDefaultMutatorAndAccessorMethodsVisibility()
$this->assertSame('public', $field->getMutatorVisibility());
}
- public function testSetMutatorAndAccessorMethodsVisibility()
+ public function testSetMutatorAndAccessorMethodsVisibility(): void
{
$field = new Field();
$field->setAccessorVisibility('private');
@@ -572,7 +570,7 @@ public function testSetMutatorAndAccessorMethodsVisibility()
$this->assertSame('private', $field->getMutatorVisibility());
}
- public function testGetPhpDefaultValue()
+ public function testGetPhpDefaultValue(): void
{
$domain = $this->getDomainMock();
$domain
@@ -587,7 +585,7 @@ public function testGetPhpDefaultValue()
$this->assertTrue($field->getPhpDefaultValue());
}
- public function testGetAutoIncrementStringThrowsEngineException()
+ public function testGetAutoIncrementStringThrowsEngineException(): void
{
$this->expectException('Propel\Generator\Exception\EngineException');
@@ -604,7 +602,7 @@ public function testGetAutoIncrementStringThrowsEngineException()
$field->getAutoIncrementString();
}
- public function testGetNativeAutoIncrementString()
+ public function testGetNativeAutoIncrementString(): void
{
$platform = $this->getPlatformMock();
$platform
@@ -627,15 +625,15 @@ public function testGetNativeAutoIncrementString()
$this->assertEquals('AUTO_INCREMENT', $field->getAutoIncrementString());
}
- public function testGetFullName()
+ public function testGetFullName(): void
{
$field = new Field('title');
$field->setEntity($this->getEntityMock('books'));
- $this->assertSame('books.TITLE', $field->getFullName());
+ $this->assertEquals('books.TITLE', $field->getFullName());
}
- public function testIsPhpArrayType()
+ public function testIsPhpArrayType(): void
{
$field = new Field();
$this->assertFalse($field->isPhpArrayType());
@@ -644,7 +642,7 @@ public function testIsPhpArrayType()
$this->assertTrue($field->isPhpArrayType());
}
- public function testSetSize()
+ public function testSetSize(): void
{
$domain = $this->getDomainMock();
$domain
@@ -665,7 +663,7 @@ public function testSetSize()
$this->assertSame(50, $field->getSize());
}
- public function testSetScale()
+ public function testSetScale(): void
{
$domain = $this->getDomainMock();
$domain
@@ -686,47 +684,47 @@ public function testSetScale()
$this->assertSame(2, $field->getScale());
}
- public function testGetDefaultDomain()
+ public function testGetDefaultDomain(): void
{
$field = new Field();
$this->assertInstanceOf('Propel\Generator\Model\Domain', $field->getDomain());
}
- public function testGetSingularName()
+ public function testGetSingularName(): void
{
$field = new Field('titles');
- $this->assertSame('title', $field->getSingularName());
+ $this->assertEquals('title', $field->getSingularName());
$this->assertTrue($field->isNamePlural());
}
- public function testSetEntity()
+ public function testSetEntity(): void
{
$field = new Field();
$field->setEntity($this->getEntityMock('books'));
$this->assertInstanceOf('Propel\Generator\Model\Entity', $field->getEntity());
- $this->assertSame('books', $field->getEntity()->getName());
+ $this->assertEquals('books', $field->getEntity()->getName());
}
- public function testSetDomain()
+ public function testSetDomain(): void
{
$field = new Field();
$field->setDomain($this->getDomainMock());
- $this->assertInstanceOf('Propel\Generator\Model\Domain', $field->getDomain());
+ $this->assertInstanceOf(Domain::class, $field->getDomain());
}
- public function testSetDescription()
+ public function testSetDescription(): void
{
$field = new Field();
$field->setDescription('Some description');
- $this->assertSame('Some description', $field->getDescription());
+ $this->assertEquals('Some description', $field->getDescription());
}
- public function testSetAutoIncrement()
+ public function testSetAutoIncrement(): void
{
$field = new Field();
$field->setAutoIncrement(true);
@@ -734,7 +732,7 @@ public function testSetAutoIncrement()
$this->assertTrue($field->isAutoIncrement());
}
- public function testSetPrimaryString()
+ public function testSetPrimaryString(): void
{
$field = new Field();
$field->setPrimaryString(true);
@@ -742,7 +740,7 @@ public function testSetPrimaryString()
$this->assertTrue($field->isPrimaryString());
}
- public function testSetNotNull()
+ public function testSetNotNull(): void
{
$field = new Field();
$field->setNotNull(true);
@@ -750,13 +748,13 @@ public function testSetNotNull()
$this->assertTrue($field->isNotNull());
}
- public function testPhpSingularName()
+ public function testPhpSingularName(): void
{
$field = new Field();
$field->setName('aliases');
- $this->assertEquals($field->getName(), 'aliases');
- $this->assertEquals($field->getSingularName(), 'aliase');
+ $this->assertEquals('aliases', $field->getName());
+ $this->assertEquals('alias', $field->getSingularName());
$field = new Field();
$field->setName('Aliases');
@@ -766,13 +764,13 @@ public function testPhpSingularName()
$this->assertEquals($field->getSingularName(), 'Alias');
}
- public function testGetMethodName()
+ public function testGetMethodName(): void
{
$field = new Field('title');
$this->assertEquals('Title', $field->getMethodName());
}
- public function testSetPhpType()
+ public function testSetPhpType(): void
{
$field = new Field('title');
$field->setType('VARCHAR');
@@ -780,7 +778,7 @@ public function testSetPhpType()
$this->assertEquals('string', $field->getPhpType());
}
- public function testGetPosition()
+ public function testGetPosition(): void
{
$field = new Field('foo');
$field->setPosition(1);
@@ -788,7 +786,7 @@ public function testGetPosition()
$this->assertSame(1, $field->getPosition());
}
- public function testGetInheritanceType()
+ public function testGetInheritanceType(): void
{
$field = new Field('foo');
$field->setInheritanceType('single');
@@ -796,7 +794,7 @@ public function testGetInheritanceType()
$this->assertEquals('single', $field->getInheritanceType());
}
- public function testIsInheritance()
+ public function testIsInheritance(): void
{
$field = new Field('foo');
$field->setInheritanceType('single');
@@ -806,7 +804,7 @@ public function testIsInheritance()
$this->assertFalse($field->isInheritance());
}
- public function testSetPrimaryKey()
+ public function testSetPrimaryKey(): void
{
$field= new Field('foo');
$this->assertFalse($field->isPrimaryKey());
@@ -815,7 +813,7 @@ public function testSetPrimaryKey()
$this->assertTrue($field->isPrimaryKey());
}
- public function testGetRelations()
+ public function testGetRelations(): void
{
$entity = new Entity('book');
$field = new Field('author_id');
@@ -828,10 +826,10 @@ public function testGetRelations()
$entity->addRelation($relation);
$this->assertTrue($field->isRelation());
- $this->assertSame([$relation], $field->getRelations());
+ $this->assertSame([$relation], $field->getRelations()->toArray());
}
- public function testHasMultipleFk()
+ public function testHasMultipleFk(): void
{
$entity = new Entity('book');
$field = new Field('author_id');
@@ -853,7 +851,7 @@ public function testHasMultipleFk()
$this->assertTrue($field->hasMultipleFK());
}
- public function testGetFieldType()
+ public function testGetFieldType(): void
{
$generatorConfig = $this
->getMockBuilder('Propel\Generator\Config\GeneratorConfig')
diff --git a/tests/Generator/Model/IndexTest.php b/tests/Generator/Model/IndexTest.php
index 2b0f01d4..fa2a7983 100644
--- a/tests/Generator/Model/IndexTest.php
+++ b/tests/Generator/Model/IndexTest.php
@@ -1,5 +1,4 @@
-setEntity($this->getEntityMock('db_books'));
@@ -29,7 +26,7 @@ public function testCreateNamedIndex()
$this->assertEquals('foo_idx', $index->getName());
$this->assertFalse($index->isUnique());
$this->assertInstanceOf('Propel\Generator\Model\Entity', $index->getEntity());
- $this->assertSame('db_books', $index->getEntity()->getName());
+ $this->assertEquals('db_books', $index->getEntity()->getName());
$this->assertCount(0, $index->getFields());
$this->assertTrue($index->getFields()->isEmpty());
}
@@ -38,7 +35,7 @@ public function testCreateNamedIndex()
* @dataProvider provideEntitySpecificAttributes
*
*/
- public function testCreateDefaultIndexName($tableName, $maxFieldNameLength, $indexName)
+ public function testCreateDefaultIndexName($tableName, $maxFieldNameLength, $indexName): void
{
$platform = $this->getPlatformMock(true, ['max_field_name_length' => $maxFieldNameLength]);
$database = $this->getDatabaseMock('bookstore', ['platform' => $platform]);
@@ -52,10 +49,10 @@ public function testCreateDefaultIndexName($tableName, $maxFieldNameLength, $ind
$index = new Index();
$index->setEntity($table);
- $this->assertSame($indexName, $index->getName());
+ $this->assertEquals($indexName, $index->getName());
}
- public function provideEntitySpecificAttributes()
+ public function provideEntitySpecificAttributes(): array
{
return [
[ 'books', 64, 'books_i_no_fields' ],
@@ -63,7 +60,7 @@ public function provideEntitySpecificAttributes()
];
}
- public function testAddIndexedFields()
+ public function testAddIndexedFields(): void
{
$columns = [
$this->getFieldMock('foo', [ 'size' => 100 ]),
@@ -77,12 +74,12 @@ public function testAddIndexedFields()
$this->assertFalse($index->getFields()->isEmpty());
$this->assertCount(3, $index->getFields());
- $this->assertSame(100, $index->getField('foo')->getSize());
- $this->assertSame(5, $index->getField('bar')->getSize());
- $this->assertEquals(0, $index->getField('baz')->getSize());
+ $this->assertSame(100, $index->getFieldByName('foo')->getSize());
+ $this->assertSame(5, $index->getFieldByName('bar')->getSize());
+ $this->assertEquals(0, $index->getFieldByName('baz')->getSize());
}
- public function testNoFieldAtFirstPosition()
+ public function testNoFieldAtFirstPosition(): void
{
$index = new Index();
@@ -92,24 +89,24 @@ public function testNoFieldAtFirstPosition()
/**
* @dataProvider provideFieldAttributes
*/
- public function testNoFieldAtPositionCaseSensitivity($name, $case)
+ public function testNoFieldAtPositionCaseSensitivity($name): void
{
$index = new Index();
$index->setEntity($this->getEntityMock('db_books'));
$index->addField($this->getFieldMock('foo', [ 'size' => 5 ]));
- $this->assertFalse($index->hasFieldAtPosition(0, $name, 5, $case));
+ $this->assertFalse($index->hasFieldAtPosition(0, $name, 5));
}
- public function provideFieldAttributes()
+ public function provideFieldAttributes(): array
{
return [
- [ 'bar', false ],
- [ 'BAR', true ],
+ [ 'bar' ],
+ [ 'BAR' ],
];
}
- public function testNoSizedFieldAtPosition()
+ public function testNoSizedFieldAtPosition(): void
{
$size = 5;
@@ -121,7 +118,7 @@ public function testNoSizedFieldAtPosition()
$this->assertFalse($index->hasFieldAtPosition(0, 'foo', $size));
}
- public function testHasFieldAtFirstPosition()
+ public function testHasFieldAtFirstPosition(): void
{
$index = new Index();
$index->setEntity($this->getEntityMock('db_books'));
@@ -130,7 +127,7 @@ public function testHasFieldAtFirstPosition()
$this->assertTrue($index->hasFieldAtPosition(0, 'foo'));
}
- public function testGetSuperordinate()
+ public function testGetSuperordinate(): void
{
$entity = $this->getEntityMock('db_books');
$index = new Index();
diff --git a/tests/Generator/Model/InheritanceTest.php b/tests/Generator/Model/InheritanceTest.php
index 7e0c950f..e13fc8fe 100644
--- a/tests/Generator/Model/InheritanceTest.php
+++ b/tests/Generator/Model/InheritanceTest.php
@@ -1,5 +1,4 @@
-getMockBuilder('Propel\Generator\Model\Field')
diff --git a/tests/Generator/Model/ModelFactoryTest.php b/tests/Generator/Model/ModelFactoryTest.php
index 90008a1e..001a0013 100644
--- a/tests/Generator/Model/ModelFactoryTest.php
+++ b/tests/Generator/Model/ModelFactoryTest.php
@@ -1,4 +1,4 @@
-modelFactory = new ModelFactory();
}
@@ -27,20 +24,15 @@ public function setUp()
/**
* @dataProvider provideBehaviors
*/
- public function testCreateBehavior($name, $class)
+ public function testCreateBehavior(string $name, string $class): void
{
- $type = sprintf(
- 'Propel\Generator\Behavior\%s\%sBehavior',
- $class,
- $class
+ $this->assertInstanceOf(
+ "Propel\\Generator\\Behavior\\{$class}\\{$class}Behavior",
+ $this->modelFactory->createBehavior(['name' => $name])
);
-
- $behavior = $this->modelFactory->createBehavior(['name' => $name]);
-
- $this->assertInstanceOf($type, $behavior);
}
- public function provideBehaviors()
+ public function provideBehaviors(): array
{
return [
['aggregate_field', 'AggregateField'],
@@ -54,6 +46,4 @@ public function provideBehaviors()
['timestampable', 'Timestampable'],
];
}
-
-
}
diff --git a/tests/Generator/Model/ModelTestCase.php b/tests/Generator/Model/ModelTestCase.php
index a4f8c2b0..19053112 100644
--- a/tests/Generator/Model/ModelTestCase.php
+++ b/tests/Generator/Model/ModelTestCase.php
@@ -1,5 +1,4 @@
[],
@@ -65,7 +66,7 @@ protected function getBehaviorMock($name, array $options = []): Behavior
$behavior
->expects($this->any())
->method('getName')
- ->will($this->returnValue($name))
+ ->will($this->returnValue(Text::create($name)))
;
$behavior
@@ -108,7 +109,7 @@ protected function getBehaviorMock($name, array $options = []): Behavior
* @param array $options An array of options
* @return Relation
*/
- protected function getRelationMock($name = null, array $options = [])
+ protected function getRelationMock(string $name = null, array $options = []): Relation
{
$defaults = [
'target' => '',
@@ -128,7 +129,7 @@ protected function getRelationMock($name = null, array $options = [])
$fk
->expects($this->any())
->method('getName')
- ->will($this->returnValue($name))
+ ->will($this->returnValue(Text::create($name)))
;
$fk
@@ -146,7 +147,7 @@ protected function getRelationMock($name = null, array $options = [])
$fk
->expects($this->any())
->method('getLocalFields')
- ->will($this->returnValue(new UniqueList($options['local_fields'])))
+ ->will($this->returnValue(new ArrayList($options['local_fields'])))
;
$fk
@@ -165,10 +166,11 @@ protected function getRelationMock($name = null, array $options = [])
* @param array $options An array of options
* @return Index
*/
- protected function getIndexMock($name = null, array $options = [])
+ protected function getIndexMock(string $name = null, array $options = []): Index
{
$defaults = [
- 'entity' => null
+ 'entity' => null,
+ 'fields' => []
];
$options = array_merge($defaults, $options);
@@ -185,13 +187,19 @@ protected function getIndexMock($name = null, array $options = [])
$index
->expects($this->any())
->method('getName')
- ->will($this->returnValue($name))
+ ->will($this->returnValue(Text::create($name)))
;
$index
->expects($this->any())
->method('getEntity')
->will($this->returnValue($options['entity']))
;
+ $index
+ ->expects($this->any())
+ ->method('getFields')
+ ->will($this->returnValue(new Set($options['fields'])))
+ ;
+
return $index;
}
@@ -203,7 +211,7 @@ protected function getIndexMock($name = null, array $options = [])
* @param array $options An array of options
* @return Unique
*/
- protected function getUniqueIndexMock($name = null, array $options = [])
+ protected function getUniqueIndexMock(string $name = null, array $options = []): Unique
{
$defaults = [
'entity' => null
@@ -223,7 +231,7 @@ protected function getUniqueIndexMock($name = null, array $options = [])
$unique
->expects($this->any())
->method('getName')
- ->will($this->returnValue($name))
+ ->will($this->returnValue(Text::create($name)))
;
$unique
->expects($this->any())
@@ -241,7 +249,7 @@ protected function getUniqueIndexMock($name = null, array $options = [])
* @param array $options An array of options
* @return Schema
*/
- protected function getSchemaMock($name = null, array $options = [])
+ protected function getSchemaMock(string $name = null, array $options = []): Schema
{
$defaults = [
'generator_config' => null,
@@ -257,7 +265,7 @@ protected function getSchemaMock($name = null, array $options = [])
$schema
->expects($this->any())
->method('getName')
- ->will($this->returnValue($name))
+ ->will($this->returnValue(Text::create($name)))
;
$schema
->expects($this->any())
@@ -276,7 +284,7 @@ protected function getSchemaMock($name = null, array $options = [])
* @param string $schemaDelimiter
* @return PlatformInterface
*/
- protected function getPlatformMock($supportsSchemas = true, array $options = [], $schemaDelimiter = '.')
+ protected function getPlatformMock(bool $supportsSchemas = true, array $options = [], string $schemaDelimiter = '.'): PlatformInterface
{
$defaults = [
'max_field_name_length' => null,
@@ -318,7 +326,7 @@ protected function getPlatformMock($supportsSchemas = true, array $options = [],
* @param array $options An array of options
* @return Domain
*/
- protected function getDomainMock($name = null, array $options = [])
+ protected function getDomainMock(string $name = null, array $options = []): Domain
{
$defaults = [];
@@ -333,7 +341,7 @@ protected function getDomainMock($name = null, array $options = [])
$domain
->expects($this->any())
->method('getName')
- ->will($this->returnValue($name))
+ ->will($this->returnValue(Text::create($name)))
;
return $domain;
@@ -346,7 +354,7 @@ protected function getDomainMock($name = null, array $options = [])
* @param array $options An array of options
* @return Entity
*/
- protected function getEntityMock($name, array $options = [])
+ protected function getEntityMock(string $name, array $options = []): Entity
{
$defaults = [
'name' => $name,
@@ -369,19 +377,19 @@ protected function getEntityMock($name, array $options = [])
$entity
->expects($this->any())
->method('getName')
- ->will($this->returnValue($name))
+ ->will($this->returnValue(Text::create($name)))
;
$entity
->expects($this->any())
->method('getFullName')
- ->will($this->returnValue($options['namespace'] . '\\' . $name))
+ ->will($this->returnValue(Text::create("{$options['namespace']}\\$name")))
;
$entity
->expects($this->any())
->method('getTableName')
- ->will($this->returnValue($options['tableName']))
+ ->will($this->returnValue(Text::create($options['tableName'])))
;
$entity
@@ -420,6 +428,18 @@ protected function getEntityMock($name, array $options = [])
->will($this->returnValue($options['database']))
;
+ $entity
+ ->expects($this->any())
+ ->method('getMutatorVisibility')
+ ->will($this->returnValue('public'))
+ ;
+
+ $entity
+ ->expects($this->any())
+ ->method('getAccessorVisibility')
+ ->will($this->returnValue('public'))
+ ;
+
return $entity;
}
@@ -430,7 +450,7 @@ protected function getEntityMock($name, array $options = [])
* @param array $options An array of options
* @return Database
*/
- protected function getDatabaseMock($name, array $options = [])
+ protected function getDatabaseMock(string $name, array $options = []): Database
{
$defaults = [
'platform' => null,
@@ -446,7 +466,7 @@ protected function getDatabaseMock($name, array $options = [])
$database
->expects($this->any())
->method('getName')
- ->will($this->returnValue($name))
+ ->will($this->returnValue(Text::create($name)))
;
$database
->expects($this->any())
@@ -464,7 +484,7 @@ protected function getDatabaseMock($name, array $options = [])
* @param array $options An array of options
* @return Field
*/
- protected function getFieldMock($name, array $options = [])
+ protected function getFieldMock(string $name, array $options = []): Field
{
$defaults = [
'size' => null,
@@ -482,7 +502,7 @@ protected function getFieldMock($name, array $options = [])
$field
->expects($this->any())
->method('getName')
- ->will($this->returnValue($name))
+ ->will($this->returnValue(Text::create($name)))
;
$field
diff --git a/tests/Generator/Model/PropelTypesTest.php b/tests/Generator/Model/PropelTypesTest.php
index 4baebad3..f0afe9ce 100644
--- a/tests/Generator/Model/PropelTypesTest.php
+++ b/tests/Generator/Model/PropelTypesTest.php
@@ -1,4 +1,4 @@
-assertTrue(PropelTypes::booleanValue(true));
$this->assertFalse(PropelTypes::booleanValue(false));
}
- public function testGetPdoTypeString()
+ public function testGetPdoTypeString(): void
{
$this->assertSame('\\PDO::PARAM_STR', PropelTypes::getPdoTypeString('VARCHAR'));
$this->assertEquals('\\PDO::PARAM_INT', PropelTypes::getPdoTypeString('INTEGER'));
diff --git a/tests/Generator/Model/RelationTest.php b/tests/Generator/Model/RelationTest.php
index 5ee57ef6..f12b7bb9 100644
--- a/tests/Generator/Model/RelationTest.php
+++ b/tests/Generator/Model/RelationTest.php
@@ -1,5 +1,4 @@
-assertSame('book_author', $fk->getName());
+ $this->assertEquals('book_author', $fk->getName());
$this->assertFalse($fk->hasOnUpdate());
$this->assertFalse($fk->hasOnDelete());
$this->assertFalse($fk->isComposite());
$this->assertFalse($fk->isSkipSql());
}
- public function testRelationIsForeignPrimaryKey()
+ public function testRelationIsForeignPrimaryKey(): void
{
$database = $this->getDatabaseMock('bookstore');
$platform = $this->getPlatformMock();
@@ -61,14 +60,14 @@ public function testRelationIsForeignPrimaryKey()
$foreignEntity
->expects($this->any())
- ->method('getField')
+ ->method('getFieldByName')
->with($this->equalTo('id'))
->will($this->returnValue($idField))
;
$localEntity
->expects($this->any())
- ->method('getField')
+ ->method('getFieldByName')
->with($this->equalTo('author_id'))
->will($this->returnValue($authorIdField))
;
@@ -87,7 +86,7 @@ public function testRelationIsForeignPrimaryKey()
$this->assertSame($idField, $fk->getForeignField(0));
}
- public function testRelationDoesNotUseRequiredFields()
+ public function testRelationDoesNotUseRequiredFields(): void
{
$column = $this->getFieldMock('author_id');
$column
@@ -99,7 +98,7 @@ public function testRelationDoesNotUseRequiredFields()
$table = $this->getEntityMock('books');
$table
->expects($this->once())
- ->method('getField')
+ ->method('getFieldByName')
->with($this->equalTo('author_id'))
->will($this->returnValue($column))
;
@@ -111,7 +110,7 @@ public function testRelationDoesNotUseRequiredFields()
$this->assertFalse($fk->isLocalFieldsRequired());
}
- public function testRelationUsesRequiredFields()
+ public function testRelationUsesRequiredFields(): void
{
$column = $this->getFieldMock('author_id');
$column
@@ -123,7 +122,7 @@ public function testRelationUsesRequiredFields()
$table = $this->getEntityMock('books');
$table
->expects($this->once())
- ->method('getField')
+ ->method('getFieldByName')
->with($this->equalTo('author_id'))
->will($this->returnValue($column))
;
@@ -135,7 +134,7 @@ public function testRelationUsesRequiredFields()
$this->assertTrue($fk->isLocalFieldsRequired());
}
- public function testCantGetInverseRelation()
+ public function testCantGetInverseRelation(): void
{
$database = $this->getDatabaseMock('bookstore');
$platform = $this->getPlatformMock(false);
@@ -160,7 +159,7 @@ public function testCantGetInverseRelation()
$foreignEntity
->expects($this->any())
->method('getRelations')
- ->will($this->returnValue([]))
+ ->will($this->returnValue(new Set([])))
;
$fk = new Relation();
@@ -168,12 +167,12 @@ public function testCantGetInverseRelation()
$fk->addReference('author_id', 'id');
$fk->setForeignEntityName('authors');
- $this->assertSame('authors', $fk->getForeignEntityName());
+ $this->assertEquals('authors', $fk->getForeignEntityName());
$this->assertNull($fk->getInverseFK());
$this->assertFalse($fk->isMatchedByInverseFK());
}
- public function testGetInverseRelation()
+ public function testGetInverseRelation(): void
{
$database = $this->getDatabaseMock('bookstore');
$platform = $this->getPlatformMock(true);
@@ -198,7 +197,7 @@ public function testGetInverseRelation()
$foreignEntity
->expects($this->any())
->method('getRelations')
- ->will($this->returnValue([$inversedFk]))
+ ->will($this->returnValue(new Set([$inversedFk])))
;
$fk = new Relation();
@@ -206,20 +205,20 @@ public function testGetInverseRelation()
$fk->addReference('author_id', 'id');
$fk->setForeignEntityName('authors');
- $this->assertSame('authors', $fk->getForeignEntityName());
+ $this->assertEquals('authors', $fk->getForeignEntityName());
$this->assertInstanceOf('Propel\Generator\Model\Entity', $fk->getForeignEntity());
$this->assertSame($inversedFk, $fk->getInverseFK());
$this->assertTrue($fk->isMatchedByInverseFK());
}
- public function testGetLocalField()
+ public function testGetLocalField(): void
{
$column = $this->getFieldMock('id');
$table = $this->getEntityMock('books');
$table
->expects($this->any())
- ->method('getField')
+ ->method('getFieldByName')
->with($this->equalTo('author_id'))
->will($this->returnValue($column))
;
@@ -232,7 +231,7 @@ public function testGetLocalField()
$this->assertInstanceOf('Propel\Generator\Model\Field', $fk->getLocalField(0));
}
- public function testRelationIsNotLocalPrimaryKey()
+ public function testRelationIsNotLocalPrimaryKey(): void
{
$pks = [$this->getFieldMock('id')];
@@ -250,7 +249,7 @@ public function testRelationIsNotLocalPrimaryKey()
$this->assertFalse($fk->isLocalPrimaryKey());
}
- public function testRelationIsLocalPrimaryKey()
+ public function testRelationIsLocalPrimaryKey(): void
{
$pks = [
$this->getFieldMock('book_id'),
@@ -272,7 +271,7 @@ public function testRelationIsLocalPrimaryKey()
$this->assertTrue($fk->isLocalPrimaryKey());
}
- public function testGetOtherRelations()
+ public function testGetOtherRelations(): void
{
$fk = new Relation();
@@ -284,7 +283,7 @@ public function testGetOtherRelations()
$table
->expects($this->once())
->method('getRelations')
- ->will($this->returnValue($fks))
+ ->will($this->returnValue(new Set($fks)))
;
$fk->setEntity($table);
@@ -292,7 +291,7 @@ public function testGetOtherRelations()
$this->assertCount(2, $fk->getOtherFks());
}
- public function testClearReferences()
+ public function testClearReferences(): void
{
$fk = new Relation();
$fk->addReference('book_id', 'id');
@@ -303,7 +302,7 @@ public function testClearReferences()
$this->assertCount(0, $fk->getForeignFields());
}
- public function testAddMultipleReferences()
+ public function testAddMultipleReferences(): void
{
$fk = new Relation();
$fk->addReference('book_id', 'id');
@@ -313,16 +312,16 @@ public function testAddMultipleReferences()
$this->assertCount(2, $fk->getLocalFields());
$this->assertCount(2, $fk->getForeignFields());
- $this->assertSame('book_id', $fk->getLocalFields()->get(0));
- $this->assertSame('id', $fk->getForeignFields()->get(0));
- $this->assertSame('id', $fk->getMappedForeignField('book_id'));
+ $this->assertEquals('book_id', $fk->getLocalFields()->get(0));
+ $this->assertEquals('id', $fk->getForeignFields()->get(0));
+ $this->assertEquals('id', $fk->getMappedForeignField('book_id'));
- $this->assertSame('author_id', $fk->getLocalFields()->get(1));
- $this->assertSame('id', $fk->getForeignFields()->get(1));
- $this->assertSame('id', $fk->getMappedForeignField('author_id'));
+ $this->assertEquals('author_id', $fk->getLocalFields()->get(1));
+ $this->assertEquals('id', $fk->getForeignFields()->get(1));
+ $this->assertEquals('id', $fk->getMappedForeignField('author_id'));
}
- public function testAddSingleStringReference()
+ public function testAddSingleStringReference(): void
{
$fk = new Relation();
$fk->addReference('author_id', 'id');
@@ -331,10 +330,10 @@ public function testAddSingleStringReference()
$this->assertCount(1, $fk->getLocalFields());
$this->assertCount(1, $fk->getForeignFields());
- $this->assertSame('author_id', $fk->getMappedLocalField('id'));
+ $this->assertEquals('author_id', $fk->getMappedLocalField('id'));
}
- public function testAddSingleArrayReference()
+ public function testAddSingleArrayReference(): void
{
$reference = ['local' => 'author_id', 'foreign' => 'id'];
@@ -348,7 +347,7 @@ public function testAddSingleArrayReference()
$this->assertSame($reference['local'], $fk->getMappedLocalField($reference['foreign']));
}
- public function testAddSingleFieldReference()
+ public function testAddSingleFieldReference(): void
{
$fk = new Relation();
$fk->addReference(
@@ -360,27 +359,27 @@ public function testAddSingleFieldReference()
$this->assertCount(1, $fk->getLocalFields());
$this->assertCount(1, $fk->getForeignFields());
- $this->assertSame('author_id', $fk->getMappedLocalField('id'));
+ $this->assertEquals('author_id', $fk->getMappedLocalField('id'));
}
- public function testSetEntity()
+ public function testSetEntity(): void
{
$table = $this->getEntityMock('book');
$table
->expects($this->once())
->method('getSchemaName')
- ->will($this->returnValue('books'))
+ ->will($this->returnValue(new Text('books')))
;
$fk = new Relation();
$fk->setEntity($table);
$this->assertInstanceOf('Propel\Generator\Model\Entity', $fk->getEntity());
- $this->assertSame('books', $fk->getSchemaName());
- $this->assertSame('book', $fk->getEntityName());
+ $this->assertEquals('books', $fk->getSchemaName());
+ $this->assertEquals('book', $fk->getEntityName());
}
- public function testSetDefaultJoin()
+ public function testSetDefaultJoin(): void
{
$fk = new Relation();
$fk->setDefaultJoin('INNER');
@@ -388,19 +387,19 @@ public function testSetDefaultJoin()
$this->assertSame('INNER', $fk->getDefaultJoin());
}
- public function testSetNames()
+ public function testSetNames(): void
{
$fk = new Relation();
$fk->setName('book_author');
$fk->setField('author');
$fk->setRefField('books');
- $this->assertSame('book_author', $fk->getName());
+ $this->assertEquals('book_author', $fk->getName());
$this->assertSame('author', $fk->getField());
$this->assertSame('books', $fk->getRefField());
}
- public function testSkipSql()
+ public function testSkipSql(): void
{
$fk = new Relation();
$fk->setSkipSql(true);
@@ -408,7 +407,7 @@ public function testSkipSql()
$this->assertTrue($fk->isSkipSql());
}
- public function testGetOnActionBehaviors()
+ public function testGetOnActionBehaviors(): void
{
$fk = new Relation();
$fk->setOnUpdate('SETNULL');
@@ -425,14 +424,14 @@ public function testGetOnActionBehaviors()
* @dataProvider provideOnActionBehaviors
*
*/
- public function testNormalizeRelation($behavior, $normalized)
+ public function testNormalizeRelation($behavior, $normalized): void
{
$fk = new Relation();
$this->assertSame($normalized, $fk->normalizeFKey($behavior));
}
- public function provideOnActionBehaviors()
+ public function provideOnActionBehaviors(): array
{
return [
[null, ''],
diff --git a/tests/Generator/Model/SchemaTest.php b/tests/Generator/Model/SchemaTest.php
index b9f5f559..b7fca8c8 100644
--- a/tests/Generator/Model/SchemaTest.php
+++ b/tests/Generator/Model/SchemaTest.php
@@ -1,5 +1,4 @@
-getPlatformMock();
@@ -32,7 +30,7 @@ public function testCreateNewSchema()
$this->assertFalse($schema->hasMultipleDatabases());
}
- public function testJoinMultipleSchemasWithSameEntityTwice()
+ public function testJoinMultipleSchemasWithSameEntityTwice(): void
{
$database1 = new Database('bookstore');
$database1->addEntity($this->getEntityMock('books'));
@@ -51,7 +49,7 @@ public function testJoinMultipleSchemasWithSameEntityTwice()
$schema->joinSchemas([$subSchema1]);
}
- public function testJoinMultipleSchemasWithSameDatabase()
+ public function testJoinMultipleSchemasWithSameDatabase(): void
{
$behavior = $this->getBehaviorMock('sluggable');
@@ -67,7 +65,7 @@ public function testJoinMultipleSchemasWithSameDatabase()
$database
->expects($this->any())
->method('getEntities')
- ->will($this->returnValue($tables))
+ ->will($this->returnValue(new Set($tables)))
;
$database
->expects($this->any())
@@ -83,11 +81,11 @@ public function testJoinMultipleSchemasWithSameDatabase()
$schema->joinSchemas([$subSchema1]);
- $this->assertCount(1, $schema->getDatabases(false));
+ $this->assertCount(1, $schema->getDatabases());
$this->assertSame(2, $schema->countEntities());
}
- public function testJoinMultipleSchemasWithoutEntities()
+ public function testJoinMultipleSchemasWithoutEntities(): void
{
$subSchema1 = new Schema($this->getPlatformMock());
$subSchema1->addDatabase(new Database('bookstore'));
@@ -108,7 +106,7 @@ public function testJoinMultipleSchemasWithoutEntities()
$this->assertTrue($schema->hasDatabase('skatestore'));
}
- public function testGetFirstDatabase()
+ public function testGetFirstDatabase(): void
{
$db = new Database('bookstore');
$schema = new Schema($this->getPlatformMock());
@@ -117,7 +115,7 @@ public function testGetFirstDatabase()
$this->assertSame($db, $schema->getDatabase());
}
- public function testDatabases()
+ public function testDatabases(): void
{
$db1 = new Database('bookstore');
$db2 = new Database('shoestore');
@@ -133,14 +131,14 @@ public function testDatabases()
$this->assertTrue($schema->hasMultipleDatabases());
}
- public function testGetNoDatabase()
+ public function testGetNoDatabase(): void
{
$schema = new Schema($this->getPlatformMock());
$this->assertNull($schema->getDatabase('shoestore'));
}
- public function testExternalSchema()
+ public function testExternalSchema(): void
{
$p1 = $this->getPlatformMock();
$p2 = $this->getPlatformMock();
@@ -157,7 +155,7 @@ public function testExternalSchema()
$this->assertSame($p2, $child->getPlatform());
}
- public function testAddArrayDatabase()
+ public function testAddArrayDatabase(): void
{
$config = $this
->getMockBuilder('Propel\Generator\Config\GeneratorConfig')
@@ -181,18 +179,18 @@ public function testAddArrayDatabase()
$this->assertFalse($schema->hasMultipleDatabases());
}
- public function testAddArrayDatabaseWithDefaultPlatform()
+ public function testAddArrayDatabaseWithDefaultPlatform(): void
{
$schema = new Schema($this->getPlatformMock());
$schema->addDatabase(new Database('bookstore'));
- $this->assertCount(1, $schema->getDatabases(false));
+ $this->assertCount(1, $schema->getDatabases());
$this->assertTrue($schema->hasDatabase('bookstore'));
$this->assertFalse($schema->hasDatabase('foostore'));
$this->assertFalse($schema->hasMultipleDatabases());
}
- public function testAddDatabase()
+ public function testAddDatabase(): void
{
$database1 = $this->getDatabaseMock('bookstore');
$database2 = $this->getDatabaseMock('shoestore');
@@ -204,22 +202,22 @@ public function testAddDatabase()
$schema->addDatabase($database1);
$schema->addDatabase($database2);
- $this->assertCount(2, $schema->getDatabases(false));
+ $this->assertCount(2, $schema->getDatabases());
$this->assertTrue($schema->hasDatabase('bookstore'));
$this->assertTrue($schema->hasDatabase('shoestore'));
$this->assertFalse($schema->hasDatabase('foostore'));
$this->assertTrue($schema->hasMultipleDatabases());
}
- public function testSetName()
+ public function testSetName(): void
{
$schema = new Schema();
$schema->setName('bookstore-schema');
- $this->assertSame('bookstore-schema', $schema->getName());
+ $this->assertEquals('bookstore-schema', $schema->getName());
}
- public function testSetGeneratorConfig()
+ public function testSetGeneratorConfig(): void
{
$config = $this->getMockBuilder('Propel\Generator\Config\GeneratorConfig')
->disableOriginalConstructor()->getMock();
diff --git a/tests/Generator/Model/UniqueTest.php b/tests/Generator/Model/UniqueTest.php
index 4e923656..31add238 100644
--- a/tests/Generator/Model/UniqueTest.php
+++ b/tests/Generator/Model/UniqueTest.php
@@ -1,5 +1,4 @@
getPlatformMock(true, ['max_field_name_length' => $maxFieldNameLength]);
$database = $this->getDatabaseMock('bookstore', ['platform' => $platform]);
@@ -38,10 +37,10 @@ public function testCreateDefaultUniqueIndexName($entityName, $maxFieldNameLengt
$index->setEntity($entity);
$this->assertTrue($index->isUnique());
- $this->assertSame($indexName, $index->getName());
+ $this->assertEquals($indexName, $index->getName());
}
- public function provideEntitySpecificAttributes()
+ public function provideEntitySpecificAttributes(): array
{
return [
[ 'books', 64, 'books_u_no_fields' ],
diff --git a/tests/Generator/Model/VendorInfoTest.php b/tests/Generator/Model/VendorInfoTest.php
index ac642ff5..77294866 100644
--- a/tests/Generator/Model/VendorInfoTest.php
+++ b/tests/Generator/Model/VendorInfoTest.php
@@ -1,5 +1,4 @@
-setType('foo');
@@ -30,7 +27,7 @@ public function testSetupObject()
$this->assertSame('foo', $info->getType());
}
- public function testSetUpObjectWithParameters()
+ public function testSetUpObjectWithParameters(): void
{
$info = new Vendor('foo', ['bar' => 'baz']);
@@ -39,7 +36,7 @@ public function testSetUpObjectWithParameters()
$this->assertEquals('baz', $info->getParameter('bar'));
}
- public function testGetSetType()
+ public function testGetSetType(): void
{
$info = new Vendor('foo');
@@ -47,7 +44,7 @@ public function testGetSetType()
$this->assertTrue($info->isEmpty());
}
- public function testSetParameter()
+ public function testSetParameter(): void
{
$info = new Vendor();
$info->setParameter('foo', 'bar');
@@ -57,7 +54,7 @@ public function testSetParameter()
$this->assertSame('bar', $info->getParameter('foo'));
}
- public function testSetParameters()
+ public function testSetParameters(): void
{
$info = new Vendor();
$info->setParameters(['foo' => 'bar', 'baz' => 'bat']);
@@ -67,7 +64,7 @@ public function testSetParameters()
$this->assertArrayHasKey('baz', $info->getParameters());
}
- public function testMergeVendorInfo()
+ public function testMergeVendorInfo(): void
{
$current = new Vendor('mysql');
$current->setParameters(['foo' => 'bar', 'baz' => 'bat']);
diff --git a/tests/Generator/Platform/DefaultPlatformTest.php b/tests/Generator/Platform/DefaultPlatformTest.php
index dcb82eba..e7ad1b7a 100644
--- a/tests/Generator/Platform/DefaultPlatformTest.php
+++ b/tests/Generator/Platform/DefaultPlatformTest.php
@@ -9,6 +9,7 @@
use Propel\Generator\Model\Field;
use Propel\Generator\Model\PropelTypes;
+use Propel\Generator\Platform\PlatformInterface;
use Propel\Generator\Platform\SqlDefaultPlatform;
use \Propel\Tests\TestCase;
@@ -19,9 +20,9 @@ class DefaultPlatformTest extends TestCase
/**
* Get the Platform object for this class
*
- * @return \Propel\Generator\Platform\PlatformInterface
+ * @return PlatformInterface
*/
- protected function getPlatform()
+ protected function getPlatform(): PlatformInterface
{
if (null === $this->platform) {
$this->platform = new SqlDefaultPlatform();
@@ -30,7 +31,7 @@ protected function getPlatform()
return $this->platform;
}
- protected function tearDown()
+ protected function tearDown(): void
{
$this->platform = null;
}
diff --git a/tests/Generator/Platform/MssqlPlatformTest.php b/tests/Generator/Platform/MssqlPlatformTest.php
index 644c8658..606028d0 100644
--- a/tests/Generator/Platform/MssqlPlatformTest.php
+++ b/tests/Generator/Platform/MssqlPlatformTest.php
@@ -17,6 +17,7 @@
use Propel\Generator\Model\Entity;
use Propel\Generator\Model\Model;
use Propel\Generator\Platform\MssqlPlatform;
+use Propel\Generator\Platform\PlatformInterface;
/**
*
@@ -28,7 +29,7 @@ class MssqlPlatformTest extends PlatformTestProvider
*
* @return MssqlPlatform
*/
- protected function getPlatform()
+ protected function getPlatform(): PlatformInterface
{
return new MssqlPlatform();
}
diff --git a/tests/Generator/Platform/MysqlPlatformMigrationMyISAMTest.php b/tests/Generator/Platform/MysqlPlatformMigrationMyISAMTest.php
index 396d7217..3225e33d 100644
--- a/tests/Generator/Platform/MysqlPlatformMigrationMyISAMTest.php
+++ b/tests/Generator/Platform/MysqlPlatformMigrationMyISAMTest.php
@@ -13,6 +13,7 @@
use Propel\Generator\Config\GeneratorConfig;
use Propel\Generator\Model\Column;
use Propel\Generator\Platform\MysqlPlatform;
+use Propel\Generator\Platform\PlatformInterface;
use Propel\Generator\Platform\SqlDefaultPlatform;
use Propel\Tests\VfsTrait;
@@ -30,7 +31,7 @@ class MysqlPlatformMigrationMyISAMTest extends PlatformMigrationTestProvider
*
* @return SqlDefaultPlatform
*/
- protected function getPlatform()
+ protected function getPlatform(): PlatformInterface
{
if (null === $this->platform) {
$this->platform = new MysqlPlatform();
diff --git a/tests/Generator/Platform/MysqlPlatformMigrationTest.php b/tests/Generator/Platform/MysqlPlatformMigrationTest.php
index f2770979..45666365 100644
--- a/tests/Generator/Platform/MysqlPlatformMigrationTest.php
+++ b/tests/Generator/Platform/MysqlPlatformMigrationTest.php
@@ -14,6 +14,7 @@
use Propel\Generator\Config\GeneratorConfig;
use Propel\Generator\Model\Diff\DatabaseComparator;
use Propel\Generator\Platform\MysqlPlatform;
+use Propel\Generator\Platform\PlatformInterface;
use Propel\Tests\VfsTrait;
/**
@@ -31,7 +32,7 @@ class MysqlPlatformMigrationTest extends PlatformMigrationTestProvider
*
* @return MysqlPlatform
*/
- protected function getPlatform()
+ protected function getPlatform(): PlatformInterface
{
if (null === $this->platform) {
$this->platform = new MysqlPlatform();
diff --git a/tests/Generator/Platform/MysqlPlatformMyISAMTest.php b/tests/Generator/Platform/MysqlPlatformMyISAMTest.php
index 5222f001..9f11927e 100644
--- a/tests/Generator/Platform/MysqlPlatformMyISAMTest.php
+++ b/tests/Generator/Platform/MysqlPlatformMyISAMTest.php
@@ -19,6 +19,7 @@
use Propel\Generator\Model\Model;
use Propel\Generator\Model\Vendor;
use Propel\Generator\Platform\MysqlPlatform;
+use Propel\Generator\Platform\PlatformInterface;
use Propel\Generator\Schema\SchemaReader;
use Propel\Tests\VfsTrait;
@@ -36,7 +37,7 @@ class MysqlPlatformMyISAMTest extends PlatformTestProvider
*
* @return MysqlPlatform
*/
- protected function getPlatform(): MysqlPlatform
+ protected function getPlatform(): PlatformInterface
{
if (null === $this->platform) {
$this->platform = new MysqlPlatform();
diff --git a/tests/Generator/Platform/MysqlPlatformTest.php b/tests/Generator/Platform/MysqlPlatformTest.php
index 54592738..a5a70a63 100644
--- a/tests/Generator/Platform/MysqlPlatformTest.php
+++ b/tests/Generator/Platform/MysqlPlatformTest.php
@@ -19,6 +19,7 @@
use Propel\Generator\Model\Model;
use Propel\Generator\Model\Vendor;
use Propel\Generator\Platform\MysqlPlatform;
+use Propel\Generator\Platform\PlatformInterface;
use Propel\Generator\Schema\SchemaReader;
use Propel\Tests\VfsTrait;
@@ -36,7 +37,7 @@ class MysqlPlatformTest extends PlatformTestProvider
*
* @return MysqlPlatform
*/
- protected function getPlatform(): MysqlPlatform
+ protected function getPlatform(): PlatformInterface
{
if (null === $this->platform) {
$this->platform = new MysqlPlatform();
diff --git a/tests/Generator/Platform/OraclePlatformMigrationTest.php b/tests/Generator/Platform/OraclePlatformMigrationTest.php
index 1ecc691c..08758262 100644
--- a/tests/Generator/Platform/OraclePlatformMigrationTest.php
+++ b/tests/Generator/Platform/OraclePlatformMigrationTest.php
@@ -14,6 +14,7 @@
use Propel\Generator\Model\Column;
use Propel\Generator\Model\Diff\DatabaseComparator;
use Propel\Generator\Platform\OraclePlatform;
+use Propel\Generator\Platform\PlatformInterface;
/**
*
@@ -25,7 +26,7 @@ class OraclePlatformMigrationTest extends PlatformMigrationTestProvider
*
* @return OraclePlatform
*/
- protected function getPlatform()
+ protected function getPlatform(): PlatformInterface
{
return new OraclePlatform();
}
diff --git a/tests/Generator/Platform/OraclePlatformTest.php b/tests/Generator/Platform/OraclePlatformTest.php
index b30e6303..bb0d97ec 100644
--- a/tests/Generator/Platform/OraclePlatformTest.php
+++ b/tests/Generator/Platform/OraclePlatformTest.php
@@ -17,6 +17,7 @@
use Propel\Generator\Model\Entity;
use Propel\Generator\Model\Model;
use Propel\Generator\Platform\OraclePlatform;
+use Propel\Generator\Platform\PlatformInterface;
/**
*
@@ -28,7 +29,7 @@ class OraclePlatformTest extends PlatformTestProvider
*
* @return OraclePlatform
*/
- protected function getPlatform()
+ protected function getPlatform(): PlatformInterface
{
return new OraclePlatform();
}
diff --git a/tests/Generator/Platform/PgsqlPlatformMigrationTest.php b/tests/Generator/Platform/PgsqlPlatformMigrationTest.php
index aa2176d5..68dfc5fa 100644
--- a/tests/Generator/Platform/PgsqlPlatformMigrationTest.php
+++ b/tests/Generator/Platform/PgsqlPlatformMigrationTest.php
@@ -16,6 +16,7 @@
use Propel\Generator\Model\Entity;
use Propel\Generator\Model\Diff\FieldComparator;
use Propel\Generator\Platform\PgsqlPlatform;
+use Propel\Generator\Platform\PlatformInterface;
use Propel\Generator\Schema\SchemaReader;
/**
@@ -29,7 +30,7 @@ class PgsqlPlatformMigrationTest extends PlatformMigrationTestProvider
*
* @return PgsqlPlatform
*/
- protected function getPlatform()
+ protected function getPlatform(): PlatformInterface
{
return new PgsqlPlatform();
}
diff --git a/tests/Generator/Platform/PgsqlPlatformTest.php b/tests/Generator/Platform/PgsqlPlatformTest.php
index 85a67b85..375b772c 100644
--- a/tests/Generator/Platform/PgsqlPlatformTest.php
+++ b/tests/Generator/Platform/PgsqlPlatformTest.php
@@ -19,6 +19,7 @@
use Propel\Generator\Model\PropelTypes;
use Propel\Generator\Model\Entity;
use Propel\Generator\Platform\PgsqlPlatform;
+use Propel\Generator\Platform\PlatformInterface;
/**
*
@@ -30,7 +31,7 @@ class PgsqlPlatformTest extends PlatformTestProvider
*
* @return PgsqlPlatform
*/
- protected function getPlatform()
+ protected function getPlatform(): PlatformInterface
{
return new PgsqlPlatform();
}
diff --git a/tests/Generator/Platform/ProvaTest.php b/tests/Generator/Platform/ProvaTest.php
index 6044b209..0f242ec2 100644
--- a/tests/Generator/Platform/ProvaTest.php
+++ b/tests/Generator/Platform/ProvaTest.php
@@ -23,10 +23,11 @@
use Propel\Generator\Model\Field;
use Propel\Generator\Model\FieldDefaultValue;
use Propel\Generator\Platform\MssqlPlatform;
+use Propel\Generator\Platform\PlatformInterface;
class ProvaTest extends PlatformTestProvider
{
- protected function getPlatform()
+ protected function getPlatform(): PlatformInterface
{
return new MssqlPlatform();
}
diff --git a/tests/Generator/Platform/SqlitePlatformTest.php b/tests/Generator/Platform/SqlitePlatformTest.php
index c7b789f5..b072b12e 100644
--- a/tests/Generator/Platform/SqlitePlatformTest.php
+++ b/tests/Generator/Platform/SqlitePlatformTest.php
@@ -16,6 +16,7 @@
use Propel\Generator\Model\IdMethodParameter;
use Propel\Generator\Model\Entity;
use Propel\Generator\Model\Model;
+use Propel\Generator\Platform\PlatformInterface;
use Propel\Generator\Platform\SqlitePlatform;
use Propel\Runtime\Adapter\AdapterFactory;
use Propel\Runtime\Connection\ConnectionFactory;
@@ -30,7 +31,7 @@ class SqlitePlatformTest extends PlatformTestProvider
*
* @return SqlitePlatform
*/
- protected function getPlatform()
+ protected function getPlatform(): PlatformInterface
{
return new SqlitePlatform();
}
diff --git a/tests/Generator/Reverse/PgsqlSchemaParserTest.php b/tests/Generator/Reverse/PgsqlSchemaParserTest.php
index 17bd5ec5..49ebb629 100644
--- a/tests/Generator/Reverse/PgsqlSchemaParserTest.php
+++ b/tests/Generator/Reverse/PgsqlSchemaParserTest.php
@@ -27,7 +27,7 @@
*/
class PgsqlSchemaParserTest extends TestCaseFixturesDatabase
{
- protected function setUp()
+ protected function setUp(): void
{
parent::setUp();
Propel::init(__DIR__ . '/../../Fixtures/reverse/pgsql/build/conf/reverse-bookstore-conf.php');
@@ -40,7 +40,7 @@ protected function setUp()
}
}
- protected function tearDown()
+ protected function tearDown(): void
{
if ($this->con) {
$this->con->rollback();
diff --git a/tests/Generator/Schema/Dumper/XmlDumperTest.php b/tests/Generator/Schema/Dumper/XmlDumperTest.php
index a84d94ca..6318bf4c 100644
--- a/tests/Generator/Schema/Dumper/XmlDumperTest.php
+++ b/tests/Generator/Schema/Dumper/XmlDumperTest.php
@@ -1,4 +1,4 @@
-dumper = new XmlDumper();
+ }
+
+ public function testDumpDatabaseSchema(): void
{
- $database = include realpath(__DIR__.'/../../../Resources/blog-database.php');
+ $database = include __DIR__ . '/../../../Resources/blog-database.php';
$this->assertSame($this->getExpectedXml('blog-database.xml'), $this->dumper->dump($database));
}
- public function testDumpMyISAMSchema()
+ public function testDumpMyISAMSchema(): void
{
$platform = new MysqlPlatform();
- $schema = include realpath(__DIR__.'/../../../Resources/blog-schema.php');
+ $schema = include __DIR__ . '/../../../Resources/blog-schema.php';
$platform->doFinalInitialization($schema);
$this->assertSame($this->getExpectedXml('blog-schema.xml'), $this->dumper->dumpSchema($schema));
}
- protected function getExpectedXml($filename)
- {
- return trim(file_get_contents(realpath(__DIR__.'/../../../Resources/'.$filename)));
- }
-
- protected function setUp()
- {
- $this->dumper = new XmlDumper();
- }
-
- protected function tearDown()
+ protected function getExpectedXml(string $filename): string
{
- $this->dumper = null;
+ return trim(file_get_contents(__DIR__.'/../../../Resources/'.$filename));
}
}
diff --git a/tests/Generator/Schema/Loader/JsonSchemaLoaderTest.php b/tests/Generator/Schema/Loader/JsonSchemaLoaderTest.php
index c05b15af..a1593f44 100644
--- a/tests/Generator/Schema/Loader/JsonSchemaLoaderTest.php
+++ b/tests/Generator/Schema/Loader/JsonSchemaLoaderTest.php
@@ -1,4 +1,4 @@
-addJsonSchema();
$this->loader = new JsonSchemaLoader(new FileLocator());
}
- public function testSupports()
+ public function testSupports(): void
{
$this->assertTrue($this->loader->supports('foo.json'), '->supports() returns true if the resource is loadable');
$this->assertFalse($this->loader->supports('foo.bar'), '->supports() returns false if the resource is not loadable');
$this->assertFalse($this->loader->supports($this->getRoot()->url()), '->supports() returns false if the resource is not a string.');
}
- public function testJsonSchemaCanBeLoaded()
+ public function testJsonSchemaCanBeLoaded(): void
{
$actual = $this->loader->load(vfsStream::url('root/schema.json'));
$this->assertEquals('bookstore', $actual['database']['name']);
$this->assertEquals('Book', $actual['database']['entities'][0]['name']);
}
- /**
- * @expectedException \InvalidArgumentException
- * @expectedExceptionMessage The file "inexistent.json" does not exist (in:
- */
- public function testJsonFileDoesNotExist()
+ public function testJsonFileDoesNotExist(): void
{
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage("The file \"inexistent.json\" does not exist (in:");
+
$this->loader->load('inexistent.json');
}
- /**
- * @expectedException \phootwork\json\JsonException
- * @expectedExceptionMessage Syntax error
- */
- public function testJsonFileHasInvalidContent()
+ public function testJsonFileHasInvalidContent(): void
{
+ $this->expectException(JsonException::class);
+ $this->expectExceptionMessage('Syntax error');
+
$content = <<loader->load(vfsStream::url('root/nonvalid.json'));
}
- /**
- * @expectedException \phootwork\json\JsonException
- * @expectedExceptionMessage Syntax error
- */
- public function testJsonFileIsEmpty()
+ public function testJsonFileIsEmpty(): void
{
+ $this->expectException(JsonException::class);
+ $this->expectExceptionMessage('Syntax error');
+
vfsStream::newFile('empty.json')->at($this->getRoot())->setContent('');
$this->loader->load(vfsStream::url('root/empty.json'));
}
- /**
- * @expectedException \phootwork\file\exception\FileException
- * @expectedExceptionMessage You don't have permissions to access notreadable.json file
- */
- public function testJsonFileNotReadableThrowsException()
+ public function testJsonFileNotReadableThrowsException(): void
{
+ $this->expectException(FileException::class);
+ $this->expectExceptionMessage('You don\'t have permissions to access notreadable.json file');
$content = <<addPhpSchema();
@@ -39,21 +43,19 @@ public function testPhpSchemaCanBeLoaded()
$this->assertEquals('Book', $actual['database']['entities'][0]['name']);
}
- /**
- * @expectedException \InvalidArgumentException
- * @expectedExceptionMessage The file "vfs://root/inexistent.php" does not exist
- */
public function testPhpFileDoesNotExist()
{
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage("The file \"vfs://root/inexistent.php\" does not exist");
+
$this->loader->load(vfsStream::url('root/inexistent.php'));
}
- /**
- * @expectedException Propel\Generator\Schema\Exception\InvalidArgumentException
- * @expectedExceptionMessage The schema file 'vfs://root/nonvalid.php' has invalid content.
- */
public function testPhpFileHasInvalidContent()
{
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage("The schema file 'vfs://root/nonvalid.php' has invalid content.");
+
$content = <<loader->load(vfsStream::url('root/nonvalid.php'));
}
- /**
- * @expectedException Propel\Generator\Schema\Exception\InvalidArgumentException
- * @expectedExceptionMessage The schema file 'vfs://root/empty.php' has invalid content.
- */
public function testPhpFileIsEmpty()
{
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage("The schema file 'vfs://root/empty.php' has invalid content.");
+
vfsStream::newFile('empty.php')->at($this->getRoot())->setContent('');
$this->loader->load(vfsStream::url('root/empty.php'));
}
- /**
- * @expectedException Propel\Generator\Schema\Exception\InputOutputException
- * @expectedExceptionMessage You don't have permissions to access schema file
- */
public function testSchemaFileNotReadableThrowsException()
{
+ $this->expectException(InputOutputException::class);
+ $this->expectExceptionMessage("You don't have permissions to access schema file");
+
$content = <<addXmlSchema();
@@ -38,21 +42,19 @@ public function testXmlSchemaCanBeLoaded()
$this->assertEquals('Book', $actual['database']['entity'][0]['name']);
}
- /**
- * @expectedException \InvalidArgumentException
- * @expectedExceptionMessage The file "vfs://root/inexistent.xml" does not exist
- */
public function testXmlFileDoesNotExist()
{
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('The file "vfs://root/inexistent.xml" does not exist');
+
$this->loader->load(vfsStream::url('root/inexistent.xml'));
}
- /**
- * @expectedException Propel\Generator\Schema\Exception\InvalidArgumentException
- * @expectedExceptionMessage The schema file 'vfs://root/nonvalid.xml' has invalid content.
- */
public function testXmlFileHasInvalidContent()
{
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage("The schema file `vfs://root/nonvalid.xml` has invalid content.");
+
$content = <<loader->load(vfsStream::url('root/nonvalid.xml'));
}
- /**
- * @expectedException Propel\Generator\Schema\Exception\InvalidArgumentException
- * @expectedExceptionMessage The schema file 'vfs://root/empty.xml' has invalid content.
- */
public function testXmlFileIsEmpty()
{
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage("The schema file `vfs://root/empty.xml` has invalid content.");
+
vfsStream::newFile('empty.xml')->at($this->getRoot())->setContent('');
$this->loader->load(vfsStream::url('root/empty.xml'));
}
- /**
- * @expectedException phootwork\file\exception\FileException
- * @expectedExceptionMessage You don't have permissions to access
- */
public function testSchemaFileNotReadableThrowsException()
{
+ $this->expectException(FileException::class);
+ $this->expectExceptionMessage("You don't have permissions to access");
+
$content = <<
diff --git a/tests/Generator/Schema/Loader/YamlSchemaLoaderTest.php b/tests/Generator/Schema/Loader/YamlSchemaLoaderTest.php
index bb6ad7f3..31674afb 100644
--- a/tests/Generator/Schema/Loader/YamlSchemaLoaderTest.php
+++ b/tests/Generator/Schema/Loader/YamlSchemaLoaderTest.php
@@ -1,4 +1,4 @@
-addYamlSchema();
@@ -39,21 +43,19 @@ public function testYamlSchemaCanBeLoaded()
$this->assertEquals('Book', $actual['database']['entities']['Book']['name']);
}
- /**
- * @expectedException \InvalidArgumentException
- * @expectedExceptionMessage The file "vfs://root/inexistent.yaml" does not exist
- */
public function testYamlFileDoesNotExist()
{
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('The file "vfs://root/inexistent.yaml" does not exist');
+
$this->loader->load(vfsStream::url('root/inexistent.yaml'));
}
- /**
- * @expectedException Symfony\Component\Yaml\Exception\ParseException
- * @expectedExceptionMessage The content is not valid yaml.
- */
public function testYamlFileHasInvalidContent()
{
+ $this->expectException(ParseException::class);
+ $this->expectExceptionMessage('The content of the schema file `vfs://root/nonvalid.yaml` is not valid yaml.');
+
$content = <<loader->load(vfsStream::url('root/nonvalid.yaml'));
}
- /**
- * @expectedException Symfony\Component\Yaml\Exception\ParseException
- * @expectedExceptionMessage The content is not valid yaml.
- */
public function testYamlFileIsEmpty()
{
+ $this->expectException(ParseException::class);
+ $this->expectExceptionMessage('The content of the schema file `vfs://root/empty.yaml` is not valid yaml.');
+
vfsStream::newFile('empty.yaml')->at($this->getRoot())->setContent('');
$this->loader->load(vfsStream::url('root/empty.yaml'));
}
- /**
- * @expectedException phootwork\file\exception\FileException
- * @expectedExceptionMessage You don't have permissions to access
- */
public function testSchemaFileNotReadableThrowsException()
{
+ $this->expectException(FileException::class);
+ $this->expectExceptionMessage('You don\'t have permissions to access');
+
$content = <<parse(__DIR__ . '/../../Fixtures/bookstore/schema.xml');
- $this->assertEquals(34, count($schema->getDatabase()->getEntities()), 'Correct number of entities');
- $this->assertEquals(1, count($schema->getDatabases()), 'Only one database');
+ $this->assertEquals(34, $schema->getDatabase()->getEntities()->count(), 'Correct number of entities');
+ $this->assertEquals(1, $schema->getDatabases()->count(), 'Only one database');
$this->assertEquals('bookstore', $schema->getDatabase()->getName());
$entity = $schema->getDatabase()->getEntityByName('Book');
- $this->assertEquals(2, count($entity->getRelations()), 'Book entity has 2 relations');
+ $this->assertEquals(2, $entity->getRelations()->count(), 'Book entity has 2 relations');
$entity = $schema->getDatabase()->getEntityByName('Author');
- $this->assertEquals(0, count($entity->getRelations()), 'Author entity has no relation');
+ $this->assertEquals(0, $entity->getRelations()->count(), 'Author entity has no relation');
$entity = $schema->getDatabase()->getEntityByName('BookListRel');
$this->assertTrue($entity->isCrossRef());
- $this->assertEquals(2, count($entity->getRelations()), 'Cross entities have 2 relations');
+ $this->assertEquals(2, $entity->getRelations()->count(), 'Cross entities have 2 relations');
}
public function testExternalSchema()
@@ -43,18 +43,18 @@ public function testExternalSchema()
$reader = new SchemaReader();
$schema = $reader->parse(vfsStream::url('root/book.schema.xml'));
- $this->assertEquals(3, count($schema->getDatabase()->getEntities()), 'Correct number of entities');
- $this->assertEquals(1, count($schema->getDatabases()), 'Only one database');
+ $this->assertEquals(3, $schema->getDatabase()->getEntities()->count(), 'Correct number of entities');
+ $this->assertEquals(1, $schema->getDatabases()->count(), 'Only one database');
$this->assertEquals('bookstore', $schema->getDatabase()->getName());
$entity = $schema->getDatabase()->getEntityByName('Book');
- $this->assertEquals(2, count($entity->getRelations()), 'Book entity has 2 relations');
+ $this->assertEquals(2, $entity->getRelations()->count(), 'Book entity has 2 relations');
$entity = $schema->getDatabase()->getEntityByName('Author');
- $this->assertEquals(0, count($entity->getRelations()), 'Author entity has no relation');
+ $this->assertEquals(0, $entity->getRelations()->count(), 'Author entity has no relation');
$entity = $schema->getDatabase()->getEntityByName('Publisher');
- $this->assertEquals(0, count($entity->getRelations()), 'Publisher entity has no relation');
+ $this->assertEquals(0, $entity->getRelations()->count(), 'Publisher entity has no relation');
}
public function testBehaviors()
@@ -62,12 +62,12 @@ public function testBehaviors()
$reader = new SchemaReader();
$schema = $reader->parse(__DIR__ . '/../../Fixtures/bookstore/behavior-auto-add-pk-schema.xml');
- $this->assertEquals(3, count($schema->getDatabase()->getEntities()), 'Correct number of entities');
- $this->assertEquals(1, count($schema->getDatabases()), 'Only one database');
+ $this->assertEquals(3, $schema->getDatabase()->getEntities()->count(), 'Correct number of entities');
+ $this->assertEquals(1, $schema->getDatabases()->count(), 'Only one database');
$this->assertEquals('bookstore-behavior', $schema->getDatabase()->getName());
$entity = $schema->getDatabase()->getEntityByName('Entity6');
- $this->assertEquals(0, count($entity->getRelations()), 'Entity6 entity has 0 relations');
+ $this->assertEquals(0, $entity->getRelations()->count(), 'Entity6 entity has 0 relations');
$this->assertTrue($entity->hasBehavior('auto_add_pk'));
}
}
diff --git a/tests/TestCase.php b/tests/TestCase.php
index e6531ce3..9d443dac 100644
--- a/tests/TestCase.php
+++ b/tests/TestCase.php
@@ -1,5 +1,4 @@
-getDriver();
@@ -48,7 +50,7 @@ protected function getSql($sql, $source = 'mysql', $target = null)
return $sql;
}
- protected function tearDown()
+ protected function tearDown(): void
{
parent::tearDown();
if (Configuration::$globalConfiguration) {
@@ -63,7 +65,7 @@ protected function tearDown()
* @param string $db
* @return bool
*/
- protected function isDb($db = 'mysql')
+ protected function isDb(string $db = 'mysql'): bool
{
return $this->getDriver() == $db;
}
@@ -71,7 +73,7 @@ protected function isDb($db = 'mysql')
/**
* @return bool
*/
- protected function runningOnPostgreSQL()
+ protected function runningOnPostgreSQL(): bool
{
return $this->isDb('pgsql');
}
@@ -79,7 +81,7 @@ protected function runningOnPostgreSQL()
/**
* @return bool
*/
- protected function runningOnMySQL()
+ protected function runningOnMySQL(): bool
{
return $this->isDb('mysql');
}
@@ -87,7 +89,7 @@ protected function runningOnMySQL()
/**
* @return bool
*/
- protected function runningOnSQLite()
+ protected function runningOnSQLite(): bool
{
return $this->isDb('sqlite');
}
@@ -95,7 +97,7 @@ protected function runningOnSQLite()
/**
* @return bool
*/
- protected function runningOnOracle()
+ protected function runningOnOracle(): bool
{
return $this->isDb('oracle');
}
@@ -103,15 +105,15 @@ protected function runningOnOracle()
/**
* @return bool
*/
- protected function runningOnMSSQL()
+ protected function runningOnMSSQL(): bool
{
return $this->isDb('mssql');
}
/**
- * @return \Propel\Generator\Platform\PlatformInterface
+ * @return PlatformInterface
*/
- protected function getPlatform()
+ protected function getPlatform(): PlatformInterface
{
$className = sprintf('\\Propel\\Generator\\Platform\\%sPlatform', ucfirst($this->getDriver()));
@@ -119,9 +121,10 @@ protected function getPlatform()
}
/**
- * @return \Propel\Generator\Reverse\SchemaParserInterface
+ * @param ConnectionInterface $con
+ * @return SchemaParserInterface
*/
- protected function getParser($con)
+ protected function getParser(ConnectionInterface $con): SchemaParserInterface
{
$className = sprintf('\\Propel\\Generator\\Reverse\\%sSchemaParser', ucfirst($this->getDriver()));
diff --git a/tests/VfsTrait.php b/tests/VfsTrait.php
index 9b09fae0..254c0e47 100644
--- a/tests/VfsTrait.php
+++ b/tests/VfsTrait.php
@@ -1,4 +1,4 @@
-root) {
+ if (!isset($this->root)) {
$this->root = vfsStream::setup();
}