diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 9b49bae5..00000000 --- a/.travis.yml +++ /dev/null @@ -1,26 +0,0 @@ -language: php - -php: - - 5.3 - - 5.4 - - 5.5 - - 5.6 - - 7.0 - -before_script: - - composer self-update - - composer install - -script: phpunit --coverage-clover=coverage.clover - -after_script: - - wget https://scrutinizer-ci.com/ocular.phar - - php ocular.phar code-coverage:upload --format=php-clover coverage.clover - -notifications: - webhooks: - urls: - - https://webhooks.gitter.im/e/64a455d3354c06acfc92 - on_success: change - on_failure: always - on_start: false diff --git a/Generator/Column.php b/Generator/Column.php index 93904ae6..86daf1a0 100644 --- a/Generator/Column.php +++ b/Generator/Column.php @@ -75,7 +75,7 @@ class Column protected string|array $credentials = 'AdmingenAllowed'; - protected bool $filtersCredentials = false; + protected bool|string|array $filtersCredentials = false; protected string $gridClass = ''; diff --git a/Tests/Builder/BaseBuilderTest.php b/Tests/Builder/BaseBuilderTest.php index d7e0e049..91763089 100755 --- a/Tests/Builder/BaseBuilderTest.php +++ b/Tests/Builder/BaseBuilderTest.php @@ -7,57 +7,57 @@ class BaseBuilderTest extends TestCase { - public function testGetSimpleClassName() + public function testGetSimpleClassName(): void { $builder = new BaseBuilder(); $this->assertEquals('BaseBuilder', $builder->getSimpleClassName(), 'getSimpleClassName remove the namespaced part of get_class'); $this->assertEquals('Bar', $builder->getSimpleClassName('\\Foo\\Bar'), 'getSimpleClassName remove the namespaced part of get_class'); } - public function testGetDefaultTemplateName() + public function testGetDefaultTemplateName(): void { $builder = new BaseBuilder(); $this->assertEquals('BaseBuilder.php.twig', $builder->getDefaultTemplateName(), 'getDefaultTemplateName return the twig file path'); } - public function testSetVariables() + public function testSetVariables(): void { $builder = new BaseBuilder(); - $builder->setVariables(array('foo' => 'bar')); - $this->assertEquals(array('foo' => 'bar'), $builder->getVariables(), 'setVariables accept an array'); + $builder->setVariables(['foo' => 'bar']); + $this->assertEquals(['foo' => 'bar'], $builder->getVariables(), 'setVariables accept an array'); } - public function testGetVariable() + public function testGetVariable(): void { $builder = new BaseBuilder(); - $builder->setVariables(array('foo' => 'bar')); + $builder->setVariables(['foo' => 'bar']); $this->assertEquals('bar', $builder->getVariable('foo','default')); $this->assertEquals('default', $builder->getVariable('nonexistant','default')); - $builder->setVariables(array('foo' => array('bar' =>'bazz'))); + $builder->setVariables(['foo' => ['bar' =>'bazz']]); $foo = $builder->getVariable('foo'); $this->assertEquals('bazz', $foo['bar']); } - public function testHasVariable() + public function testHasVariable(): void { $builder = new BaseBuilder(); - $builder->setVariables(array('foo' => 'bar')); + $builder->setVariables(['foo' => 'bar']); $this->assertTrue($builder->hasVariable('foo'), 'hasVariable return true on a valid key'); $this->assertFalse($builder->hasVariable('var'), 'hasVariable return false on a invalid key'); } - public function testGetCode() + public function testGetCode(): void { $builder = $this->initBuilder(); $this->assertEquals('Hello cedric!'."\n", $builder->getCode()); - $builder->setVariables(array('name' => 'Tux')); + $builder->setVariables(['name' => 'Tux']); $this->assertEquals('Hello Tux!'."\n", $builder->getCode(), 'If I change variables code is changed'); } - public function testWriteOnDisk() + public function testWriteOnDisk(): void { $builder = $this->initBuilder(); @@ -65,13 +65,13 @@ public function testWriteOnDisk() $this->assertTrue(file_exists(sys_get_temp_dir() . '/test.php')); $this->assertEquals('Hello cedric!'."\n", file_get_contents(sys_get_temp_dir() . '/test.php')); - $builder->setVariables(array('name' => 'Tux')); + $builder->setVariables(['name' => 'Tux']); $builder->writeOnDisk(sys_get_temp_dir()); $this->assertTrue($builder->mustOverwriteIfExists()); $this->assertTrue(file_exists(sys_get_temp_dir() . '/test.php')); $this->assertEquals('Hello Tux!'."\n", file_get_contents(sys_get_temp_dir() . '/test.php'), 'If i change variables code is changed'); - $builder->setVariables(array('name' => 'cedric')); + $builder->setVariables(['name' => 'cedric']); $builder->setMustOverwriteIfExists(false); $builder->writeOnDisk(sys_get_temp_dir()); $this->assertFalse($builder->mustOverwriteIfExists()); @@ -84,14 +84,14 @@ public function testWriteOnDisk() $this->assertEquals('Hello cedric!'."\n", file_get_contents(sys_get_temp_dir() . '/test.php'), 'If i change variables on a non existant files code is generated'); } - public function testGetModelClass() + public function testGetModelClass(): void { $builder = new BaseBuilder(); - $builder->setVariables(array('model' => 'Admingenerator\DemoBundle\Entity\Movie')); + $builder->setVariables(['model' => 'Admingenerator\DemoBundle\Entity\Movie']); $this->assertEquals('Movie', $builder->getModelClass()); } - protected function initBuilder() + protected function initBuilder(): BaseBuilder { $builder = new BaseBuilder(); $generator = $this->getMockBuilder('Admingenerator\GeneratorBundle\Builder\Generator') @@ -102,8 +102,8 @@ protected function initBuilder() $builder->setGenerator($generator); $builder->setMustOverwriteIfExists(true); $builder->setOutputName('test.php'); - $builder->setTemplateDirs(array(__DIR__.'/Fixtures/')); - $builder->setVariables(array('name' => 'cedric')); + $builder->setTemplateDirs([__DIR__.'/Fixtures/']); + $builder->setVariables(['name' => 'cedric']); $builder->setTemplateName($builder->getDefaultTemplateName()); return $builder; diff --git a/Tests/ClassLoader/AdmingeneratedClassLoaderTest.php b/Tests/ClassLoader/AdmingeneratedClassLoaderTest.php index 9d405820..0f302b39 100755 --- a/Tests/ClassLoader/AdmingeneratedClassLoaderTest.php +++ b/Tests/ClassLoader/AdmingeneratedClassLoaderTest.php @@ -10,22 +10,22 @@ class AdmingeneratedClassLoaderTest extends TestCase /** * @dataProvider getLoadClassTests */ - public function testLoadClass($className, $testClassName, $message) + public function testLoadClass($className, $testClassName, $message): void { $loader = new AdmingeneratedClassLoader(); - $loader->setBasePath(realpath(sys_get_temp_dir())); + $loader->register(realpath(sys_get_temp_dir())); $loader->loadClass($testClassName); $this->assertTrue(class_exists($className), $message); } - public function getLoadClassTests() + public function getLoadClassTests(): array { - return array( - array( + return [ + [ '\\Admingenerated\\AdmingeneratorDemoBundle\\BaseController\\ListController', 'Admingenerated\\AdmingeneratorDemoBundle\\BaseController\\ListController', '->loadClass() loads admingenerated class' - ), - ); + ], + ]; } } diff --git a/Tests/DependencyInjection/ConfigurationTest.php b/Tests/DependencyInjection/ConfigurationTest.php index 85b79b09..574c5056 100755 --- a/Tests/DependencyInjection/ConfigurationTest.php +++ b/Tests/DependencyInjection/ConfigurationTest.php @@ -3,14 +3,15 @@ namespace Admingenerator\GeneratorBundle\Tests\DependencyInjection; use Admingenerator\GeneratorBundle\DependencyInjection\Configuration; +use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Definition\Processor; -class ConfigurationTest extends \PHPUnit_Framework_TestCase +class ConfigurationTest extends TestCase { /** * Test that default configuration is correctly initialized */ - public function testDefaultConfig() + public function testDefaultConfig(): void { $processor = new Processor(); $config = $processor->processConfiguration(new Configuration('admingen_generator'), array()); @@ -21,13 +22,10 @@ public function testDefaultConfig() /** * Get waiting default values from configuration. If $key is not null * and is in first level keys, returns value of this specific key only. - * - * @param string $key - * @return mixed */ - private function getBundleDefaultConfig($key = null) + private function getBundleDefaultConfig(string $key = null): mixed { - static $defaultConfiguration = array( + static $defaultConfiguration = [ 'generate_base_in_project_dir' => false, 'use_doctrine_orm' => false, 'use_doctrine_odm' => false, @@ -46,22 +44,22 @@ private function getBundleDefaultConfig($key = null) 'use_doctrine_orm_batch_remove' => false, 'use_doctrine_odm_batch_remove' => false, 'use_propel_batch_remove' => false, - 'twig' => array( + 'twig' => [ 'use_form_resources' => true, 'use_localized_date' => false, 'date_format' => 'Y-m-d', 'datetime_format' => 'Y-m-d H:i:s', 'localized_date_format' => 'medium', 'localized_datetime_format' => 'medium', - 'number_format' => array( + 'number_format' => [ 'decimal' => 0, 'decimal_point' => '.', 'thousand_separator' => ',' - ) - ), - 'templates_dirs' => array(), - 'form_types' => array( - 'doctrine_orm' => array( + ] + ], + 'templates_dirs' => [], + 'form_types' => [ + 'doctrine_orm' => [ 'datetime' => 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', 'vardatetime' => 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', 'datetimetz' => 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', @@ -78,8 +76,8 @@ private function getBundleDefaultConfig($key = null) 'collection' => 'Symfony\Component\Form\Extension\Core\Type\CollectionType', 'array' => 'Symfony\Component\Form\Extension\Core\Type\CollectionType', 'boolean' => 'Symfony\Component\Form\Extension\Core\Type\CheckboxType', - ), - 'doctrine_odm' => array( + ], + 'doctrine_odm' => [ 'datetime' => 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', 'timestamp' => 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', 'vardatetime' => 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', @@ -101,8 +99,8 @@ private function getBundleDefaultConfig($key = null) 'collection' => 'Symfony\Component\Form\Extension\Core\Type\CollectionType', 'hash' => 'Symfony\Component\Form\Extension\Core\Type\CollectionType', 'boolean' => 'Symfony\Component\Form\Extension\Core\Type\CheckboxType', - ), - 'propel' => array( + ], + 'propel' => [ 'TIMESTAMP' => 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', 'BU_TIMESTAMP' => 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', 'DATE' => 'Symfony\Component\Form\Extension\Core\Type\DateType', @@ -129,10 +127,10 @@ private function getBundleDefaultConfig($key = null) 'ENUM' => 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', 'BOOLEAN' => 'Symfony\Component\Form\Extension\Core\Type\CheckboxType', 'BOOLEAN_EMU' => 'Symfony\Component\Form\Extension\Core\Type\CheckboxType', - ), - ), - 'filter_types' => array( - 'doctrine_orm' => array( + ], + ], + 'filter_types' => [ + 'doctrine_orm' => [ 'datetime' => 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', 'vardatetime' => 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', 'datetimetz' => 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', @@ -149,8 +147,8 @@ private function getBundleDefaultConfig($key = null) 'collection' => 'Symfony\Component\Form\Extension\Core\Type\CollectionType', 'array' => 'Symfony\Component\Form\Extension\Core\Type\TextType', 'boolean' => 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', - ), - 'doctrine_odm' => array( + ], + 'doctrine_odm' => [ 'datetime' => 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', 'timestamp' => 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', 'vardatetime' => 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', @@ -172,8 +170,8 @@ private function getBundleDefaultConfig($key = null) 'collection' => 'Symfony\Component\Form\Extension\Core\Type\CollectionType', 'hash' => 'Symfony\Component\Form\Extension\Core\Type\TextType', 'boolean' => 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', - ), - 'propel' => array( + ], + 'propel' => [ 'TIMESTAMP' => 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', 'BU_TIMESTAMP' => 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', 'DATE' => 'Symfony\Component\Form\Extension\Core\Type\DateType', @@ -200,16 +198,13 @@ private function getBundleDefaultConfig($key = null) 'ENUM' => 'Symfony\Component\Form\Extension\Core\Type\TextType', 'BOOLEAN' => 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', 'BOOLEAN_EMU' => 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', - ), - ), - 'stylesheets' => array(), - 'javascripts' => array(), + ], + ], + 'stylesheets' => [], + 'javascripts' => [], 'default_action_after_save' => 'edit', 'throw_exceptions' => false, - 'use_doctrine_orm_batch_remove' => false, - 'use_doctrine_odm_batch_remove' => false, - 'use_propel_batch_remove' => false, - ); + ]; if (!is_null($key) && array_key_exists($key, $defaultConfiguration)) { return $defaultConfiguration[$key]; diff --git a/Tests/Filesystem/RelativePathComputerTest.php b/Tests/Filesystem/RelativePathComputerTest.php index 31bf2087..a8973a59 100644 --- a/Tests/Filesystem/RelativePathComputerTest.php +++ b/Tests/Filesystem/RelativePathComputerTest.php @@ -2,32 +2,29 @@ namespace Admingenerator\GeneratorBundle\Tests\Filesystem; use Admingenerator\GeneratorBundle\Filesystem\RelativePathComputer; +use LogicException; +use PHPUnit\Framework\TestCase; -/** - * Class RelativePathComputerTest - * @package Admingenerator\GeneratorBundle\Tests\Filesystem - * @author Stéphane Escandell - */ -class RelativePathComputerTest extends \PHPUnit_Framework_TestCase +class RelativePathComputerTest extends TestCase { - public function testComputingToParent() + public function testComputingToParent(): void { $referencePath = __FILE__; $computer = new RelativePathComputer($referencePath); $this->assertEquals(str_repeat('..' . DIRECTORY_SEPARATOR, 1), $computer->computeToParent(dirname($referencePath))); - $this->assertEquals(str_repeat('..' . DIRECTORY_SEPARATOR, 3), $computer->computeToParent(dirname(dirname(dirname($referencePath))))); + $this->assertEquals(str_repeat('..' . DIRECTORY_SEPARATOR, 3), $computer->computeToParent(dirname($referencePath, 3))); $referencePath = dirname($referencePath); $computer = new RelativePathComputer($referencePath); $this->assertEquals(str_repeat('..' . DIRECTORY_SEPARATOR, 1), $computer->computeToParent(dirname($referencePath))); - $this->assertEquals(str_repeat('..' . DIRECTORY_SEPARATOR, 3), $computer->computeToParent(dirname(dirname(dirname($referencePath))))); + $this->assertEquals(str_repeat('..' . DIRECTORY_SEPARATOR, 3), $computer->computeToParent(dirname($referencePath, 3))); } - public function testExceptionThrowIfNotParent() + public function testExceptionThrowIfNotParent(): void { $computer = new RelativePathComputer(__FILE__); - $this->setExpectedException('\LogicException'); + $this->expectException(LogicException::class); $computer->computeToParent(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Fake'); } diff --git a/Tests/Generator/ActionTest.php b/Tests/Generator/ActionTest.php index 4b8628fd..ed8a5234 100755 --- a/Tests/Generator/ActionTest.php +++ b/Tests/Generator/ActionTest.php @@ -8,30 +8,27 @@ class ActionTest extends TestCase { - public function testGetName() + public function testGetName(): void { - $from_to_array = array( + $from_to_array = [ 'name' => 'name', 'underscored_name' => 'underscored_name', - ); + ]; $this->checkAction($from_to_array, 'getName'); } - public function testGetLabel() + public function testGetLabel(): void { - $from_to_array = array( + $from_to_array = [ 'name' => 'Name', 'underscored_name' => 'Underscored name', - ); + ]; $this->checkAction($from_to_array, 'getLabel'); } - /** - * @param string $method - */ - protected function checkAction($from_to_array, $method) + protected function checkAction(array $from_to_array, string $method): void { foreach ($from_to_array as $from => $to) { $action = new Action($from); diff --git a/Tests/Generator/ColumnTest.php b/Tests/Generator/ColumnTest.php index 6c811dfb..125442cb 100755 --- a/Tests/Generator/ColumnTest.php +++ b/Tests/Generator/ColumnTest.php @@ -9,69 +9,69 @@ class ColumnTest extends TestCase { - public function testGetName() + public function testGetName(): void { - $from_to_array = array( + $from_to_array = [ 'name' => 'name', 'underscored_name' => 'underscored_name', - ); + ]; $this->checkColumn($from_to_array, 'getName'); } - public function testGetGetter() + public function testGetGetter(): void { - $from_to_array = array( + $from_to_array = [ 'name' => 'name', 'underscored_name' => 'underscoredName', - ); + ]; $this->checkColumn($from_to_array, 'getGetter'); } - public function testGetLabel() + public function testGetLabel(): void { - $from_to_array = array( + $from_to_array = [ 'name' => 'Name', 'underscored_name' => 'Underscored name', - ); + ]; $this->checkColumn($from_to_array, 'getLabel'); } - public function testSetProperty() + public function testSetProperty(): void { - $options = array( + $options = [ 'label' => 'my label', 'getter' => 'getFoo', 'sort_on' => 'foo', 'sortOn' => 'foo', 'dbType' => 'text', 'formType' => 'choices', - 'formOptions' => array('foo' => 'bar'), + 'formOptions' => ['foo' => 'bar'], 'filterType' => 'choice', - 'filterOptions' => array('bar' => 'foo'), - ); + 'filterOptions' => ['bar' => 'foo'], + ]; $column = new Column("test", false); foreach ($options as $option => $value) { $column->setProperty($option, $value); - $this->assertEquals($value, call_user_func_array(array($column, 'get'.InflectorFactory::create()->build()->classify($option)), array())); + $this->assertEquals($value, call_user_func_array([$column, 'get'.InflectorFactory::create()->build()->classify($option)], [])); } } - public function testSetAddFormFilterOptionsPhpFunction() + public function testSetAddFormFilterOptionsPhpFunction(): void { $column = new Column("test", false); - $addOptions = array('years' => array('.range' => array('from' => 1900, 'to' => 1915, 'step' => 5))); + $addOptions = ['years' => ['.range' => ['start' => 1900, 'end' => 1915, 'step' => 5]]]; $column->setAddFormOptions($addOptions); $options = $column->getFormOptions(); - $testOptions = array(1900, 1905, 1910, 1915); + $testOptions = [1900, 1905, 1910, 1915]; $this->assertEquals($testOptions, $options['years']); @@ -82,35 +82,32 @@ public function testSetAddFormFilterOptionsPhpFunction() $this->assertEquals($testOptions, $options['years']); } - public function testCredentials() + public function testCredentials(): void { $column = new Column('test', false); - $column->setCredentials(array('credential1', 'credential2')); - $column->setFiltersCredentials(array('credential3', 'credential4')); + $column->setCredentials(['credential1', 'credential2']); + $column->setFiltersCredentials(['credential3', 'credential4']); - $this->assertEquals(array('credential1', 'credential2'), $column->getCredentials()); - $this->assertEquals(array('credential3', 'credential4'), $column->getFiltersCredentials()); + $this->assertEquals(['credential1', 'credential2'], $column->getCredentials()); + $this->assertEquals(['credential3', 'credential4'], $column->getFiltersCredentials()); - $column->setFiltersCredentials(array()); + $column->setFiltersCredentials([]); - $this->assertEquals(array(), $column->getFiltersCredentials()); + $this->assertEquals([], $column->getFiltersCredentials()); } - public function testFiltersCredentialsFallbackOnCredentialsIfNotCustomized() + public function testFiltersCredentialsFallbackOnCredentialsIfNotCustomized(): void { $column = new Column('test', false); - $column->setCredentials(array('credential1', 'credential2')); + $column->setCredentials(['credential1', 'credential2']); - $this->assertEquals(array('credential1', 'credential2'), $column->getFiltersCredentials()); + $this->assertEquals(['credential1', 'credential2'], $column->getFiltersCredentials()); } - /** - * @param string $method - */ - protected function checkColumn($from_to_array, $method) + protected function checkColumn(array $from_to_array, string $method): void { foreach ($from_to_array as $from => $to) { $column = new Column($from, false); diff --git a/Tests/Mocks/Doctrine/ConnectionMock.php b/Tests/Mocks/Doctrine/ConnectionMock.php index e2f5b76d..625eac89 100755 --- a/Tests/Mocks/Doctrine/ConnectionMock.php +++ b/Tests/Mocks/Doctrine/ConnectionMock.php @@ -2,106 +2,83 @@ namespace Admingenerator\GeneratorBundle\Tests\Mocks\Doctrine; -class ConnectionMock extends \Doctrine\DBAL\Connection +use Doctrine\DBAL\Connection; +use Doctrine\DBAL\Platforms\AbstractPlatform; +use Override; + +class ConnectionMock extends Connection { - private $_fetchOneResult; - private $_platformMock; - private $_lastInsertId = 0; - private $_inserts = array(); - private $_executeUpdates = array(); + private DatabasePlatformMock $_platformMock; + private int $_lastInsertId = 0; + private array $_inserts = []; + private array $_executeUpdates = []; + private DatabasePlatformMock $_platform; - public function __construct(array $params, $driver, $config = null, $eventManager = null) + public function __construct(array $params, $driver, $config = null) { $this->_platformMock = new DatabasePlatformMock(); - parent::__construct($params, $driver, $config, $eventManager); + parent::__construct($params, $driver, $config); // Override possible assignment of platform to database platform mock $this->_platform = $this->_platformMock; } - /** - * @override - */ - public function getDatabasePlatform() + #[Override] + public function getDatabasePlatform(): AbstractPlatform { return $this->_platformMock; } - /** - * @override - */ - public function insert($tableName, array $data, array $types = array()) + #[Override] + public function insert($table, array $data, array $types = array()): int { - $this->_inserts[$tableName][] = $data; + $this->_inserts[$table][] = $data; + return $this->_lastInsertId++; } - /** - * @override - */ - public function executeUpdate($query, array $params = array(), array $types = array()) - { - $this->_executeUpdates[] = array('query' => $query, 'params' => $params, 'types' => $types); - } - /** - * @override - */ - public function lastInsertId($seqName = null) + #[Override] + public function lastInsertId($seqName = null): int { return $this->_lastInsertId; } - /** - * @override - */ - public function fetchColumn($statement, array $params = array(), $colnum = 0, array $types = array()) + #[Override] + public function quote($value, $type = null): string { - return $this->_fetchOneResult; - } - - /** - * @override - */ - public function quote($input, $type = null) - { - if (is_string($input)) { - return "'" . $input . "'"; + if (is_string($value)) { + return "'" . $value . "'"; } - return $input; + return $value; } /* Mock API */ - public function setFetchOneResult($fetchOneResult) - { - $this->_fetchOneResult = $fetchOneResult; - } - - public function setDatabasePlatform($platform) + public function setDatabasePlatform($platform): void { $this->_platformMock = $platform; } - public function setLastInsertId($id) + public function setLastInsertId($id): void { $this->_lastInsertId = $id; } - public function getInserts() + public function getInserts(): array { return $this->_inserts; } - public function getExecuteUpdates() + public function getExecuteUpdates(): array { return $this->_executeUpdates; } - public function reset() + public function reset(): void { - $this->_inserts = array(); + $this->_inserts = []; $this->_lastInsertId = 0; } } diff --git a/Tests/Mocks/Doctrine/DatabasePlatformMock.php b/Tests/Mocks/Doctrine/DatabasePlatformMock.php index 172e5b2e..818943a6 100755 --- a/Tests/Mocks/Doctrine/DatabasePlatformMock.php +++ b/Tests/Mocks/Doctrine/DatabasePlatformMock.php @@ -2,96 +2,155 @@ namespace Admingenerator\GeneratorBundle\Tests\Mocks\Doctrine; -class DatabasePlatformMock extends \Doctrine\DBAL\Platforms\AbstractPlatform +use Doctrine\DBAL\Connection; +use Doctrine\DBAL\Platforms\AbstractPlatform; +use Doctrine\DBAL\Platforms\DateIntervalUnit; +use Doctrine\DBAL\Platforms\Exception\NotSupported; +use Doctrine\DBAL\Platforms\Keywords\KeywordList; +use Doctrine\DBAL\Schema\AbstractSchemaManager; +use Doctrine\DBAL\Schema\TableDiff; +use Doctrine\DBAL\TransactionIsolationLevel; +use Override; + +class DatabasePlatformMock extends AbstractPlatform { - private $_sequenceNextValSql = ""; - private $_prefersIdentityColumns = true; - private $_prefersSequences = false; + private string $_sequenceNextValSql = ""; - /** - * @override - */ - public function getNativeDeclaration(array $field) {} + #[Override] + public function getSequenceNextValSQL($sequence): string + { + return $this->_sequenceNextValSql; + } - /** - * @override - */ - public function getPortableDeclaration(array $field) {} + #[Override] + public function getBooleanTypeDeclarationSQL(array $column): string + { + return ''; + } - /** - * @override - */ - public function prefersIdentityColumns() + #[Override] + public function getIntegerTypeDeclarationSQL(array $column): string { - return $this->_prefersIdentityColumns; + return ''; } - /** - * @override - */ - public function prefersSequences() + #[Override] + public function getBigIntTypeDeclarationSQL(array $column): string { - return $this->_prefersSequences; + return ''; } - /** @override */ - public function getSequenceNextValSQL($sequenceName) + #[Override] + public function getSmallIntTypeDeclarationSQL(array $column): string { - return $this->_sequenceNextValSql; + return ''; } - /** @override */ - public function getBooleanTypeDeclarationSQL(array $field) {} + #[Override] + protected function _getCommonIntegerTypeDeclarationSQL(array $column): string + { + return ''; + } - /** @override */ - public function getIntegerTypeDeclarationSQL(array $field) {} + #[Override] + public function getClobTypeDeclarationSQL(array $column): string + { + return ''; + } - /** @override */ - public function getBigIntTypeDeclarationSQL(array $field) {} + /* MOCK API */ - /** @override */ - public function getSmallIntTypeDeclarationSQL(array $field) {} + public function getName(): string + { + return 'mock'; + } - /** @override */ - protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef) {} + #[Override] + protected function initializeDoctrineTypeMappings(): void + { - /** @override */ - public function getVarcharTypeDeclarationSQL(array $field) {} + } - /** @override */ - public function getClobTypeDeclarationSQL(array $field) {} + #[Override] + public function getBlobTypeDeclarationSQL(array $column): string + { + throw NotSupported::new(__METHOD__); + } - /* MOCK API */ + #[Override] + public function getLocateExpression(string $string, string $substring, ?string $start = null): string + { + return ''; + } - public function setPrefersIdentityColumns($bool) + #[Override] + public function getDateDiffExpression(string $date1, string $date2): string { - $this->_prefersIdentityColumns = $bool; + return ''; } - public function setPrefersSequences($bool) + #[Override] + protected function getDateArithmeticIntervalExpression(string $date, string $operator, string $interval, DateIntervalUnit $unit,): string { - $this->_prefersSequences = $bool; + return ''; } - public function setSequenceNextValSql($sql) + #[Override] + public function getCurrentDatabaseExpression(): string { - $this->_sequenceNextValSql = $sql; + return ''; } - public function getName() + #[Override] + public function getAlterTableSQL(TableDiff $diff): array { - return 'mock'; + return []; + } + + #[Override] + public function getListViewsSQL(string $database): string + { + return ''; + } + + #[Override] + public function getSetTransactionIsolationSQL(TransactionIsolationLevel $level): string + { + return ''; } - protected function initializeDoctrineTypeMappings() + #[Override] + public function getDateTimeTypeDeclarationSQL(array $column): string { + return ''; + } + #[Override] + public function getDateTypeDeclarationSQL(array $column): string + { + return ''; + } + + #[Override] + public function getTimeTypeDeclarationSQL(array $column): string + { + return ''; } - /** - * Gets the SQL Snippet used to declare a BLOB column type. - */ - public function getBlobTypeDeclarationSQL(array $field) + + #[Override] + protected function createReservedKeywordsList(): KeywordList + { + return new class extends KeywordList { + protected function getKeywords(): array + { + return []; + } + }; + } + + #[Override] + public function createSchemaManager(Connection $connection): AbstractSchemaManager { - throw DBALException::notSupported(__METHOD__); + return $connection->createSchemaManager(); } } diff --git a/Tests/Mocks/Doctrine/DriverConnectionMock.php b/Tests/Mocks/Doctrine/DriverConnectionMock.php index dfdd5fbf..9e8b157e 100755 --- a/Tests/Mocks/Doctrine/DriverConnectionMock.php +++ b/Tests/Mocks/Doctrine/DriverConnectionMock.php @@ -2,16 +2,45 @@ namespace Admingenerator\GeneratorBundle\Tests\Mocks\Doctrine; -class DriverConnectionMock implements \Doctrine\DBAL\Driver\Connection +use Doctrine\DBAL\Driver\Connection; +use Doctrine\DBAL\Driver\Result; +use Doctrine\DBAL\Driver\Statement; + +class DriverConnectionMock implements Connection { - public function prepare($prepareString) {} - public function query() { return new StatementMock; } - public function quote($input, $type=\PDO::PARAM_STR) {} - public function exec($statement) {} - public function lastInsertId($name = null) {} - public function beginTransaction() {} - public function commit() {} - public function rollBack() {} + public function prepare($sql): Statement + { + return new StatementMock(); + } + public function query(string $sql): Result + { + return new ResultMock(); + } + public function quote($value, $type=\PDO::PARAM_STR): string + { + return ''; + } + public function exec($sql): int|string + { + return ''; + } + public function lastInsertId($name = null): int|string + { + return 0; + } + public function beginTransaction(): void + {} + public function commit(): void + {} + public function rollBack(): void + {} public function errorCode() {} - public function errorInfo() {} + + public function getNativeConnection(): void + {} + + public function getServerVersion(): string + { + return ''; + } } diff --git a/Tests/Mocks/Doctrine/DriverMock.php b/Tests/Mocks/Doctrine/DriverMock.php index cef27ed5..d01a6acb 100755 --- a/Tests/Mocks/Doctrine/DriverMock.php +++ b/Tests/Mocks/Doctrine/DriverMock.php @@ -2,71 +2,39 @@ namespace Admingenerator\GeneratorBundle\Tests\Mocks\Doctrine; -class DriverMock implements \Doctrine\DBAL\Driver -{ - private $_platformMock; +use Doctrine\DBAL\Driver; +use Doctrine\DBAL\Driver\API\ExceptionConverter; +use Doctrine\DBAL\Platforms\AbstractPlatform; +use Doctrine\DBAL\ServerVersionProvider; +use Override; - private $_schemaManagerMock; +class DriverMock implements Driver +{ + private ?DatabasePlatformMock $_platformMock = null; - public function connect(array $params, $username = null, $password = null, array $driverOptions = array()) + public function connect(array $params, $username = null, $password = null, array $driverOptions = array()): Driver\Connection { return new DriverConnectionMock(); } - /** - * Constructs the Sqlite PDO DSN. - * - * @return string The DSN. - * @override - */ - protected function _constructPdoDsn(array $params) - { - return ""; - } - - /** - * @override - */ - public function getDatabasePlatform() + #[Override] + public function getDatabasePlatform(ServerVersionProvider $versionProvider): AbstractPlatform { - if (! $this->_platformMock) { + if (!$this->_platformMock) { $this->_platformMock = new DatabasePlatformMock; } return $this->_platformMock; } - /** - * @override - */ - public function getSchemaManager(\Doctrine\DBAL\Connection $conn) - { - if ($this->_schemaManagerMock == null) { - return new SchemaManagerMock($conn); - } else { - return $this->_schemaManagerMock; - } - } - /* MOCK API */ - - public function setDatabasePlatform(\Doctrine\DBAL\Platforms\AbstractPlatform $platform) - { - $this->_platformMock = $platform; - } - - public function setSchemaManager(\Doctrine\DBAL\Schema\AbstractSchemaManager $sm) - { - $this->_schemaManagerMock = $sm; - } - public function getName() { return 'mock'; } - public function getDatabase(\Doctrine\DBAL\Connection $conn) + public function getExceptionConverter(): ExceptionConverter { - return; + return new ExceptionConverterMock(); } } diff --git a/Tests/Mocks/Doctrine/EntityManagerMock.php b/Tests/Mocks/Doctrine/EntityManagerMock.php index a929a4ef..481ef0d3 100755 --- a/Tests/Mocks/Doctrine/EntityManagerMock.php +++ b/Tests/Mocks/Doctrine/EntityManagerMock.php @@ -21,55 +21,30 @@ namespace Admingenerator\GeneratorBundle\Tests\Mocks\Doctrine; +use Doctrine\DBAL\Connection; +use Doctrine\ORM\EntityManager; +use Doctrine\ORM\UnitOfWork; + /** * Special EntityManager mock used for testing purposes. */ -class EntityManagerMock extends \Doctrine\ORM\EntityManager +class EntityManagerMock extends EntityManager { - private $_uowMock; - private $_proxyFactoryMock; - private $_idGenerators = array(); - /** * @override */ - public function getUnitOfWork() + public function getUnitOfWork(): UnitOfWork { - return isset($this->_uowMock) ? $this->_uowMock : parent::getUnitOfWork(); + return parent::getUnitOfWork(); } /* Mock API */ - /** - * Sets a (mock) UnitOfWork that will be returned when getUnitOfWork() is called. - * - * @param \Doctrine\ORM\UnitOfWork $uow - */ - public function setUnitOfWork($uow) - { - $this->_uowMock = $uow; - } - - public function setProxyFactory($proxyFactory) - { - $this->_proxyFactoryMock = $proxyFactory; - } - - public function getProxyFactory() - { - return isset($this->_proxyFactoryMock) ? $this->_proxyFactoryMock : parent::getProxyFactory(); - } - /** * Mock factory method to create an EntityManager. - * - * @param unknown_type $conn - * @param \Doctrine\ORM\Configuration $config - * @param \Doctrine\Common\EventManager $eventManager - * @return EntityManagerMock */ - public static function create($conn, \Doctrine\ORM\Configuration $config = null, - \Doctrine\Common\EventManager $eventManager = null) + public static function create(Connection $conn, \Doctrine\ORM\Configuration $config = null, + \Doctrine\Common\EventManager $eventManager = null): EntityManagerMock { if (is_null($config)) { $config = new \Doctrine\ORM\Configuration(); diff --git a/Tests/Mocks/Doctrine/ExceptionConverterMock.php b/Tests/Mocks/Doctrine/ExceptionConverterMock.php new file mode 100644 index 00000000..133ae993 --- /dev/null +++ b/Tests/Mocks/Doctrine/ExceptionConverterMock.php @@ -0,0 +1,18 @@ +queryFilter = $this->initQueryFilter(); } - public function testAddStringFilter() + public function testAddStringFilter(): void { $this->queryFilter->addStringFilter('title', 'test'); $this->assertEquals('SELECT q FROM Admingenerator\GeneratorBundle\Tests\QueryFilter\Entity\Movie q WHERE q.title LIKE :q_title_0', $this->queryFilter->getQuery()->getDql()); } - public function testAddTextFilter() + public function testAddTextFilter(): void { $this->queryFilter->addTextFilter('desc', 'test'); $this->assertEquals('SELECT q FROM Admingenerator\GeneratorBundle\Tests\QueryFilter\Entity\Movie q WHERE q.desc LIKE :q_desc_0', $this->queryFilter->getQuery()->getDql()); } - public function testAddDefaultFilter() + public function testAddDefaultFilter(): void { $this->queryFilter->addDefaultFilter('title', 'test'); $this->assertEquals('SELECT q FROM Admingenerator\GeneratorBundle\Tests\QueryFilter\Entity\Movie q WHERE q.title = :q_title_0', $this->queryFilter->getQuery()->getDql()); } - public function testFilterOnAssociation() + public function testFilterOnAssociation(): void { $this->queryFilter->addTextFilter('producer.name', 'test'); $this->assertEquals('SELECT q FROM Admingenerator\GeneratorBundle\Tests\QueryFilter\Entity\Movie q INNER JOIN q.producer producer_table_filter_join WHERE producer_table_filter_join.name LIKE :producer_table_filter_join_name_0', $this->queryFilter->getQuery()->getDql()); } - public function testMultipleFiltersOnAssociation() + public function testMultipleFiltersOnAssociation(): void { $this->queryFilter->addTextFilter('producer.name', 'test'); $this->queryFilter->addBooleanFilter('producer.published', true); @@ -56,52 +61,50 @@ public function testMultipleFiltersOnAssociation() $this->assertEquals('SELECT q FROM Admingenerator\GeneratorBundle\Tests\QueryFilter\Entity\Movie q INNER JOIN q.producer producer_table_filter_join WHERE producer_table_filter_join.name LIKE :producer_table_filter_join_name_0 AND producer_table_filter_join.published = :producer_table_filter_join_published_1', $this->queryFilter->getQuery()->getDql()); } - public function testCall() + public function testCall(): void { $this->queryFilter->addFooFilter('title', 'test'); $this->assertEquals('SELECT q FROM Admingenerator\GeneratorBundle\Tests\QueryFilter\Entity\Movie q WHERE q.title = :q_title_0', $this->queryFilter->getQuery()->getDql()); } - protected function initQueryFilter() + protected function initQueryFilter(): DoctrineQueryFilter { $em = $this->_getTestEntityManager(); - $qb = new \Doctrine\ORM\QueryBuilder($em); + $qb = new QueryBuilder($em); $query = $qb->select('q') ->from('Admingenerator\GeneratorBundle\Tests\QueryFilter\Entity\Movie', 'q'); - $queryFilter = new DoctrineQueryFilter($query); - - return $queryFilter; + return new DoctrineQueryFilter($query); } /** * Creates an EntityManager for testing purposes. * - * @return \Admingenerator\GeneratorBundle\Tests\Mocks\Doctrine\EntityManagerMock + * @return EntityManagerMock */ - protected function _getTestEntityManager($conn = null, $conf = null, $eventManager = null) + protected function _getTestEntityManager($conn = null, $conf = null, $eventManager = null): EntityManagerMock { - $config = new \Doctrine\ORM\Configuration(); + $config = new Configuration(); - $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver()); + $config->setMetadataDriverImpl(new AttributeDriver([])); $config->setProxyDir(__DIR__ . '/Proxies'); $config->setProxyNamespace('Doctrine\Tests\Proxies'); if ($conn === null) { - $conn = array( + $conn = [ 'driverClass' => '\Admingenerator\GeneratorBundle\Tests\Mocks\Doctrine\DriverMock', 'wrapperClass' => '\Admingenerator\GeneratorBundle\Tests\Mocks\Doctrine\ConnectionMock', 'user' => 'john', 'password' => 'wayne' - ); + ]; } if (is_array($conn)) { - $conn = \Doctrine\DBAL\DriverManager::getConnection($conn, $config, $eventManager); + $conn = DriverManager::getConnection($conn, $config); } - return \Admingenerator\GeneratorBundle\Tests\Mocks\Doctrine\EntityManagerMock::create($conn, $config, $eventManager); + return EntityManagerMock::create($conn, $config, $eventManager); } } diff --git a/Tests/QueryFilter/Entity/Movie.php b/Tests/QueryFilter/Entity/Movie.php index 3142bfa0..377b0cab 100755 --- a/Tests/QueryFilter/Entity/Movie.php +++ b/Tests/QueryFilter/Entity/Movie.php @@ -1,132 +1,74 @@ id; } - /** - * Set title - * - * @param string $title - */ - public function setTitle($title) + public function setTitle(string $title): void { $this->title = $title; } - /** - * Get title - * - * @return string - */ - public function getTitle() + public function getTitle(): ?string { return $this->title; } - /** - * Set desc - * - * @param string $desc - */ - public function setDesc($desc) + public function setDesc(string $desc): void { $this->desc = $desc; } - /** - * Get desc - * - * @return string - */ - public function getDesc() + public function getDesc(): ?string { return $this->desc; } - /** - * Set is_published - * - * @param boolean $isPublished - */ - public function setIsPublished($isPublished) + public function setIsPublished(?bool $isPublished): void { $this->is_published = $isPublished; } - /** - * Get is_published - * - * @return boolean - */ - public function getIsPublished() + public function getIsPublished(): ?bool { return $this->is_published; } - /** - * @param Producer $producer - * - * @return Movie - */ - public function setProducer(Producer $producer) + public function setProducer(?Producer $producer): self { $this->producer = $producer; return $this; } - /** - * @return Producer - */ - public function getProducer() + public function getProducer(): ?Producer { return $this->producer; } diff --git a/Tests/QueryFilter/Entity/MovieRepository.php b/Tests/QueryFilter/Entity/MovieRepository.php index 499d9f16..0bd508fd 100755 --- a/Tests/QueryFilter/Entity/MovieRepository.php +++ b/Tests/QueryFilter/Entity/MovieRepository.php @@ -4,12 +4,6 @@ use Doctrine\ORM\EntityRepository; -/** - * MovieRepository - * - * This class was generated by the Doctrine ORM. Add your own custom - * repository methods below. - */ class MovieRepository extends EntityRepository { } diff --git a/Tests/QueryFilter/Entity/Producer.php b/Tests/QueryFilter/Entity/Producer.php index c21e16e9..611e38ff 100755 --- a/Tests/QueryFilter/Entity/Producer.php +++ b/Tests/QueryFilter/Entity/Producer.php @@ -3,75 +3,44 @@ use Doctrine\ORM\Mapping as ORM; -/** - * @ORM\Entity() - * @ORM\Table(name="producer") - */ +#[ORM\Entity] +#[ORM\Table(name: 'producer')] class Producer { - /** - * @ORM\Id - * @ORM\Column(type="integer") - * @ORM\GeneratedValue(strategy="AUTO") - */ - protected $id; + #[ORM\Id] + #[ORM\Column] + #[ORM\GeneratedValue(strategy: 'AUTO')] + protected ?int $id = null; - /** - * @ORM\Column(length="255") - * @ORM\Index - */ - protected $name; + #[ORM\Column(length: 255)] + protected ?string $name = null; - /** - * @ORM\Column(type="boolean") - */ - protected $published = true; + #[ORM\Column] + protected bool $published = true; - /** - * Get id - * - * @return integer - */ - public function getId() + public function getId(): ?int { return $this->id; } - /** - * Set name - * - * @param string $name - */ - public function setName($name) + public function setName(string $name): void { $this->name = $name; } - /** - * Get name - * - * @return string - */ - public function getName() + public function getName(): ?string { return $this->name; } - /** - * @param $published - * @return Producer - */ - public function setPublished($published) + public function setPublished(mixed $published): self { $this->published = !!$published; return $this; } - /** - * @return bool - */ - public function isPublished() + public function isPublished(): bool { return $this->published; } diff --git a/Tests/TestCase.php b/Tests/TestCase.php index 6874f0fe..5d50b80e 100755 --- a/Tests/TestCase.php +++ b/Tests/TestCase.php @@ -2,15 +2,13 @@ namespace Admingenerator\GeneratorBundle\Tests; +use PHPUnit\Framework\TestCase as PHPUnitTestCase; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; -/* - * @author Cedric LOMBARDOT - */ -class TestCase extends \PHPUnit_Framework_TestCase +class TestCase extends PHPUnitTestCase { - protected function getContainer() + protected function getContainer(): ContainerBuilder { return new ContainerBuilder(new ParameterBag(array( 'kernel.debug' => false, diff --git a/Tests/Twig/Extension/ArrayExtensionTest.php b/Tests/Twig/Extension/ArrayExtensionTest.php index b7463723..b274ed9b 100755 --- a/Tests/Twig/Extension/ArrayExtensionTest.php +++ b/Tests/Twig/Extension/ArrayExtensionTest.php @@ -3,118 +3,110 @@ namespace Admingenerator\GeneratorBundle\Tests\Twig\Extension; use Admingenerator\GeneratorBundle\Twig\Extension\ArrayExtension; +use InvalidArgumentException; +use LogicException; +use PHPUnit\Framework\TestCase; /** - * This class test the Admingenerator\GeneratorBundle\Twig\Extension\ArrayExtension - * - * @author Stéphane Escandell + * This class tests the Admingenerator\GeneratorBundle\Twig\Extension\ArrayExtension */ -class ArrayExtensionTest extends \PHPUnit_Framework_TestCase +class ArrayExtensionTest extends TestCase { - /** - * @var ArrayExtension - */ - private $extension; + private ?ArrayExtension $extension = null; - public function setUp() + public function setUp(): void { $this->extension = new ArrayExtension(); } - public function testMapByWithNumericKey() + public function testMapByWithNumericKey(): void { $source = array( - array('val0FromArray1', 'val1FromArray1'), - array('val0FromArray2', 'val1FromArray2') + ['val0FromArray1', 'val1FromArray1'], + ['val0FromArray2', 'val1FromArray2'] ); $this->assertEquals( - array('val0FromArray1', 'val0FromArray2'), + ['val0FromArray1', 'val0FromArray2'], $this->extension->mapBy($source, 0) ); $this->assertEquals( - array('val1FromArray1', 'val1FromArray2'), + ['val1FromArray1', 'val1FromArray2'], $this->extension->mapBy($source, 1) ); } - public function testMapByWithNamedKey() + public function testMapByWithNamedKey(): void { - $source = array( - array('foo' => 'fooFromArray1', 'bar' => 'barFromArray1'), - array('foo' => 'fooFromArray2', 'bar' => 'barFromArray2') - ); + $source = [ + ['foo' => 'fooFromArray1', 'bar' => 'barFromArray1'], + ['foo' => 'fooFromArray2', 'bar' => 'barFromArray2'] + ]; $this->assertEquals( - array('barFromArray1', 'barFromArray2'), + ['barFromArray1', 'barFromArray2'], $this->extension->mapBy($source, 'bar') ); } - public function testMapByOnObject() + public function testMapByOnObject(): void { - $source = array( + $source = [ new TestObject() - ); + ]; $this->assertEquals( - array('foo'), + ['foo'], $this->extension->mapBy($source, 'foo') ); $this->assertEquals( - array('foobar'), + ['foobar'], $this->extension->mapBy($source, 'foobar') ); } - /** - * @expectedException \InvalidArgumentException - */ - public function testMapByReturnsExceptionOnNonArrayOrObject() + public function testMapByReturnsExceptionOnNonArrayOrObject(): void { - $this->extension->mapBy(array('foo'), 0); + $this->expectException(InvalidArgumentException::class); + $this->extension->mapBy(['foo'], 0); } - /** - * @expectedException \LogicException - */ - public function testMapByReturnsExceptionOnNonExistingKeyForArray() + public function testMapByReturnsExceptionOnNonExistingKeyForArray(): void { - $this->extension->mapBy(array(array('foo')), 5); + $this->expectException(LogicException::class); + $this->extension->mapBy([['foo']], 5); } - /** - * @expectedException \LogicException - */ - public function testMapByReturnsExceptionOnNonExistingPropertyOrMethodOnObject() + public function testMapByReturnsExceptionOnNonExistingPropertyOrMethodOnObject(): void { - $this->extension->mapBy(array(new TestObject()), 'dontExists'); + $this->expectException(LogicException::class); + $this->extension->mapBy([new TestObject()], 'dontExists'); } - public function testFlattenWithFlatArrays() + public function testFlattenWithFlatArrays(): void { - $source = array( - array('foo' => 'fooFromArray1', 'bar' => 'barFromArray1'), - array('foo' => 'fooFromArray2', 'bar' => 'barFromArray2') - ); + $source = [ + ['foo' => 'fooFromArray1', 'bar' => 'barFromArray1'], + ['foo' => 'fooFromArray2', 'bar' => 'barFromArray2'] + ]; $this->assertEquals( - array('fooFromArray1', 'barFromArray1', 'fooFromArray2', 'barFromArray2'), + ['fooFromArray1', 'barFromArray1', 'fooFromArray2', 'barFromArray2'], $this->extension->flatten($source) ); } - public function testFlattenWithNestedArrays() + public function testFlattenWithNestedArrays(): void { - $source = array( - array('foo' => 'fooFromArray1', 'bar' => array('barFromArray1')), - array('foo' => 'fooFromArray2', 'bar' => 'barFromArray2') - ); + $source = [ + ['foo' => 'fooFromArray1', 'bar' => ['barFromArray1']], + ['foo' => 'fooFromArray2', 'bar' => 'barFromArray2'] + ]; $this->assertEquals( - array('fooFromArray1', 'barFromArray1', 'fooFromArray2', 'barFromArray2'), + ['fooFromArray1', 'barFromArray1', 'fooFromArray2', 'barFromArray2'], $this->extension->flatten($source) ); } diff --git a/Tests/Twig/Extension/BaseExtensionTest.php b/Tests/Twig/Extension/BaseExtensionTest.php index 7098e726..9985b7be 100644 --- a/Tests/Twig/Extension/BaseExtensionTest.php +++ b/Tests/Twig/Extension/BaseExtensionTest.php @@ -1,50 +1,41 @@ twigVariables = $this->getTwigVariables(); } - protected function runTwigTests(array $templates, array $returns) + protected function runTwigTests(array $templates, array $returns): void { - if (array_diff(array_keys($templates), array_keys($returns))) { - throw new \LogicException(sprintf( + if ($diff = array_diff(array_keys($templates), array_keys($returns))) { + throw new LogicException(sprintf( 'Error: invalid test case. Templates and returns keys mismatch: templates:[%s], returns:[%s] => [%s]', implode(', ', array_keys($templates)), implode(', ', array_keys($returns)), - implode(', ', array_diff(array_keys($templates), array_keys($returns))) + implode(', ', $diff), )); } $twig = $this->getEnvironment($templates); @@ -52,23 +43,23 @@ protected function runTwigTests(array $templates, array $returns) foreach ($templates as $name => $tpl) { $this->assertEquals( $returns[$name][0], - $twig->loadTemplate($name)->render($this->twigVariables), - $returns[$name][1] + $twig->render($name, $this->twigVariables), + $returns[$name][1], ); } } - protected function getEnvironment($templates, $options = array()) + protected function getEnvironment($templates, $options = []): Environment { $twig = new Environment( new ArrayLoader($templates), array_merge( - array( + [ 'debug' => true, 'cache' => false, 'autoescape' => false, - ), - $options + ], + $options, ) ); $twig->addExtension($this->getTestedExtension()); diff --git a/Tests/Twig/Extension/ConfigExtensionTest.php b/Tests/Twig/Extension/ConfigExtensionTest.php index 3cc81a59..bb259057 100644 --- a/Tests/Twig/Extension/ConfigExtensionTest.php +++ b/Tests/Twig/Extension/ConfigExtensionTest.php @@ -3,33 +3,27 @@ namespace Admingenerator\GeneratorBundle\Tests\Twig\Extension; use Admingenerator\GeneratorBundle\Twig\Extension\ConfigExtension; +use InvalidArgumentException; +use PHPUnit\Framework\TestCase; /** - * This class test the Admingenerator\GeneratorBundle\Twig\Extension\ConfigExtension - * - * @author Piotr Gołębiewski + * This class tests the Admingenerator\GeneratorBundle\Twig\Extension\ConfigExtension */ -class ConfigExtensionTest extends \PHPUnit_Framework_TestCase +class ConfigExtensionTest extends TestCase { - /** - * @var ConfigExtension - */ - private $extension; - - /** - * @var array - */ - private $exampleConfig = array( - 'array1' => array('val0' => 'val0FromArray1', 'val1' => 'val1FromArray1'), - 'array2' => array('val0FromArray2', 'val1FromArray2'), - ); + private ?ConfigExtension $extension = null; - public function setUp() + private array $exampleConfig = [ + 'array1' => ['val0' => 'val0FromArray1', 'val1' => 'val1FromArray1'], + 'array2' => ['val0FromArray2', 'val1FromArray2'], + ]; + + public function setUp(): void { $this->extension = new ConfigExtension($this->exampleConfig); } - public function testGetAdmingeneratorConfig() + public function testGetAdmingeneratorConfig(): void { $this->assertEquals( $this->exampleConfig['array1']['val0'], @@ -42,11 +36,9 @@ public function testGetAdmingeneratorConfig() ); } - /** - * @expectedException \InvalidArgumentException - */ public function testGetAdmingeneratorConfigReturnsExceptionOnUnknownKey() { + $this->expectException(InvalidArgumentException::class); $this->extension->getAdmingeneratorConfig('unknown.key'); } } diff --git a/Tests/Twig/Extension/EchoExtensionTest.php b/Tests/Twig/Extension/EchoExtensionTest.php index e456f42e..18f20f5b 100755 --- a/Tests/Twig/Extension/EchoExtensionTest.php +++ b/Tests/Twig/Extension/EchoExtensionTest.php @@ -6,277 +6,265 @@ use Twig\Extension\AbstractExtension; /** - * This class test the Admingenerator\GeneratorBundle\Twig\Extension\EchoExtension - * - * @author Cedric LOMBARDOT - * @author Stéphane Escandell + * This class tests the Admingenerator\GeneratorBundle\Twig\Extension\EchoExtension */ class EchoExtensionTest extends BaseExtensionTest { - /** - * @var bool - */ - protected $useJms = false; - - /** - * @return AbstractExtension - */ - protected function getTestedExtension() + protected bool $useJms = false; + + protected function getTestedExtension(): EchoExtension { return new EchoExtension($this->useJms); } - /** - * @return array - */ - protected function getTwigVariables() + protected function getTwigVariables(): array { $object = new TestObject(); - return array( + return [ 'obj' => $object, 'name' => 'cedric', - 'arr' => array('obj' => 'val'), - ); + 'arr' => ['obj' => 'val'], + ]; } - public function testGetEchoTrans() + public function testGetEchoTrans(): void { - $tpls = array( + $tpls = [ 'string' => '{{ echo_trans( "foo" ) }}', 'variable_key' => '{{ echo_trans( name ) }}', 'quote_included' => '{{ echo_trans( "My awesome \"title\"") }}' - ); + ]; - $returns = array( - 'string' => array( + $returns = [ + 'string' => [ '{{ "foo"|trans({}, "Admingenerator")|raw }}', 'trans return a good trans tag with string elements' - ), - 'variable_key' => array( + ], + 'variable_key' => [ '{{ "cedric"|trans({}, "Admingenerator")|raw }}', 'trans return a good trans tag with variable as key' - ), - 'quote_included' => array( + ], + 'quote_included' => [ '{{ "My awesome \"title\""|trans({}, "Admingenerator")|raw }}', 'trans return a good trans tag with variable as key' - ), - ); + ], + ]; $this->runTwigTests($tpls, $returns); } - public function testGetEchoTransWithEscape() + public function testGetEchoTransWithEscape(): void { - $tpls = array( + $tpls = [ 'string' => '{{ echo_trans( "foo", {}, "Admingenerator", "html_attr" ) }}', 'variable_key' => '{{ echo_trans( name, {}, "Admingenerator", "html_attr" ) }}', - ); + ]; - $returns = array( - 'string' => array( + $returns = [ + 'string' => [ '{{ "foo"|trans({}, "Admingenerator")|escape("html_attr") }}', 'trans return a good trans tag with string elements' - ), - 'variable_key' => array( + ], + 'variable_key' => [ '{{ "cedric"|trans({}, "Admingenerator")|escape("html_attr") }}', 'trans return a good trans tag with variable as key' - ), - ); + ], + ]; $this->runTwigTests($tpls, $returns); } - public function testGetEchoTransWithParameters() + public function testGetEchoTransWithParameters(): void { - $tpls = array( + $tpls = [ 'string' => "{{ echo_trans('Display all %foo% %bar% results', { 'foo': 'foo', 'bar': 'bar' }) }}", 'variable_key' => '{{ echo_trans(name, { \'foo\': \'foo\', \'bar\': \'bar\' }) }}', 'quote_in_param_value' => '{{ echo_trans(name, { \'foo\': \'foo\\\'s\', \'bar\': \'bar\' }) }}', - ); + ]; - $returns = array( - 'string' => array( + $returns = [ + 'string' => [ '{{ "Display all %foo% %bar% results"|trans({\'%foo%\': \'foo\',\'%bar%\': \'bar\',}, "Admingenerator")|raw }}', 'trans return a good trans tag with string elements' - ), - 'variable_key' => array( + ], + 'variable_key' => [ '{{ "cedric"|trans({\'%foo%\': \'foo\',\'%bar%\': \'bar\',}, "Admingenerator")|raw }}', 'trans return a good trans tag with variable as key' - ), - 'quote_in_param_value' => array( + ], + 'quote_in_param_value' => [ '{{ "cedric"|trans({\'%foo%\': \'foo\\\'s\',\'%bar%\': \'bar\',}, "Admingenerator")|raw }}', 'trans return a good trans tag with variable as key' - ), - ); + ], + ]; $this->runTwigTests($tpls, $returns); } - public function testGetEchoTransWithParameterBag() + public function testGetEchoTransWithParameterBag(): void { - $tpls = array( + $tpls = [ 'string_bc' => "{{ echo_trans('You\'re editing {{ Book.title }} written by {{ Book.author.name }}!') }}", 'string_with_full_param_bag' => "{{ echo_trans('You\'re editing %book% written by %author%!|{ %book%: Book.title, %author%: Book.author.name }|') }}", 'string_with_abbrev_param_bag' => "{{ echo_trans('You\'re editing %Book.title% written by %Book.author.name%!|{ Book.title, Book.author.name }|') }}", 'string_with_full_param_bag_and_params' => "{{ echo_trans('You\'re editing %book% written by %foo%!|{ %book%: Book.title }|',{ 'foo': 'foo' }) }}", 'string_with_abbrev_param_bag_and_params' => "{{ echo_trans('You\'re editing %Book.title% written by %foo%!|{ Book.title }|',{ 'foo': 'foo' }) }}", - ); + ]; - $returns = array( - 'string_bc' => array( + $returns = [ + 'string_bc' => [ '{{ "You\'re editing %Book.title% written by %Book.author.name%!"|trans({\'%Book.title%\': Book.title,\'%Book.author.name%\': Book.author.name,}, "Admingenerator")|raw }}', 'trans return a good trans tag with string elements' - ), - 'string_with_full_param_bag' => array( + ], + 'string_with_full_param_bag' => [ '{{ "You\'re editing %book% written by %author%!"|trans({\'%book%\': Book.title,\'%author%\': Book.author.name,}, "Admingenerator")|raw }}', 'trans return a good trans tag with string elements' - ), - 'string_with_abbrev_param_bag' => array( + ], + 'string_with_abbrev_param_bag' => [ '{{ "You\'re editing %Book.title% written by %Book.author.name%!"|trans({\'%Book.title%\': Book.title,\'%Book.author.name%\': Book.author.name,}, "Admingenerator")|raw }}', 'trans return a good trans tag with string elements' - ), - 'string_with_full_param_bag_and_params' => array( + ], + 'string_with_full_param_bag_and_params' => [ '{{ "You\'re editing %book% written by %foo%!"|trans({\'%foo%\': \'foo\',\'%book%\': Book.title,}, "Admingenerator")|raw }}', 'trans return a good trans tag with string elements' - ), - 'string_with_abbrev_param_bag_and_params' => array( + ], + 'string_with_abbrev_param_bag_and_params' => [ '{{ "You\'re editing %Book.title% written by %foo%!"|trans({\'%foo%\': \'foo\',\'%Book.title%\': Book.title,}, "Admingenerator")|raw }}', 'trans return a good trans tag with string elements' - ), - ); + ], + ]; $this->runTwigTests($tpls, $returns); } - public function testGetEchoPath() + public function testGetEchoPath(): void { - $tpls = array( + $tpls = [ 'string' => '{{ echo_path( "foo" ) }}', 'variable' => '{{ echo_path( name ) }}', 'array' => '{{ echo_path( arr.obj ) }}', 'string_filtered' => '{{ echo_path( "foo", null, ["foo", "bar"] ) }}', 'variable_filtered' => '{{ echo_path( name, null, ["foo", "bar"] ) }}', 'array_filtered' => '{{ echo_path( arr.obj, null, ["foo", "bar"] ) }}', - ); + ]; - $returns = array( - 'string' => array( + $returns = [ + 'string' => [ '{{ path("foo") }}', 'Path return a good Path tag with string elements' - ), - 'variable' => array( + ], + 'variable' => [ '{{ path("cedric") }}', 'Path return a good Path tag with variable' - ), - 'array' => array( + ], + 'array' => [ '{{ path("val") }}', 'Path return a good Path tag with array element' - ), - 'string_filtered' => array( + ], + 'string_filtered' => [ '{{ path("foo")|foo|bar }}', 'Path return a good Path tag with string elements and filters' - ), - 'variable_filtered' => array( + ], + 'variable_filtered' => [ '{{ path("cedric")|foo|bar }}', 'Path return a good Path tag with variable and filters' - ), - 'array_filtered' => array( + ], + 'array_filtered' => [ '{{ path("val")|foo|bar }}', 'Path return a good Path tag with array element and filters' - ), - ); + ], + ]; $this->runTwigTests($tpls, $returns); } - public function testGetEchoIfGrantedWithoutJms() + public function testGetEchoIfGrantedWithoutJms(): void { $this->useJms = false; - $tpls = array( + $tpls = [ 'simple' => '{{ echo_if_granted ( "ROLE_A" ) }}', 'with_object' => '{{ echo_if_granted ( "ROLE_A", \'modelName\' ) }}', - ); + ]; - $returns = array( - 'simple' => array( + $returns = [ + 'simple' => [ '{% if is_granted(\'ROLE_A\') %}', - 'If granted work with a simple role'), - 'with_object' => array( + 'If granted work with a simple role'], + 'with_object' => [ '{% if is_granted(\'ROLE_A\', modelName is defined ? modelName : null) %}', 'If granted work with an object' - ), - ); + ], + ]; $this->runTwigTests($tpls, $returns); } - public function testGetEchoIfGrantedWithJms() + public function testGetEchoIfGrantedWithJms(): void { $this->useJms = true; - $tpls = array( + $tpls = [ 'simple' => '{{ echo_if_granted ( "hasRole(\'ROLE_A\')" ) }}', 'complex' => '{{ echo_if_granted ( "hasRole(\'ROLE_A\')\') or (hasRole(\'ROLE_B\') and hasRole(\'ROLE_C\')" ) }}', 'with_object' => '{{ echo_if_granted ( "hasRole(\'ROLE_A\')", \'modelName\' ) }}', - ); + ]; - $returns = array( - 'simple' => array( + $returns = [ + 'simple' => [ '{% if is_expr_granted(\'hasRole(\'ROLE_A\')\') %}', - 'If granted work with a simple role'), - 'complex' => array( + 'If granted work with a simple role'], + 'complex' => [ '{% if is_expr_granted(\'hasRole(\'ROLE_A\')\') or (hasRole(\'ROLE_B\') and hasRole(\'ROLE_C\')\') %}', 'If granted work with a complex role expression' - ), - 'with_object' => array( + ], + 'with_object' => [ '{% if is_expr_granted(\'hasRole(\'ROLE_A\')\', modelName is defined ? modelName : null) %}', 'If granted work with an object' - ), - ); + ], + ]; $this->runTwigTests($tpls, $returns); } - public function testGetEchoRender() + public function testGetEchoRender(): void { - $tpls = array( + $tpls = [ 'controller' => '{{ echo_render( "MyController" ) }}', 'with_params' => '{{ echo_render( "MyController", {"hello": name } ) }}', - ); + ]; - $returns = array( - 'controller' => array( + $returns = [ + 'controller' => [ '{{ render(controller("MyController", { })) }}', 'controller return a good controller tag' - ), - 'with_params' => array( + ], + 'with_params' => [ '{{ render(controller("MyController", { hello: \'cedric\' })) }}', 'controller return a good controller tag' - ), - ); + ], + ]; $this->runTwigTests($tpls, $returns); } public function testConvertAsForm() { - $tpls = array( + $tpls = [ 'no_modifications' => "{{ 'my string'|convert_as_form('unused') }}", 'no_modifications_on_specific_characters' => "{{ '\"\'&<>;{}()[]\\\/'|convert_as_form('unused') }}", 'query_builder' => "{{ \"'query_builder' => 'function(\$er) { return \$er->createQueryBuilder(); }',\"|convert_as_form('MyEntityType') }}", 'query' => "{{ \"'query' => 'function() { return MyModel::GetPeerTable(); }',\"|convert_as_form('ModelType') }}", 'php_call' => "{{ \"'__php(strtolower(\'TeSt\'))'\"|convert_as_form('unused') }}", 'php_call_and_string' => "{{ \"'__php(strtolower(\'TeSt\'))','my other string'\"|convert_as_form('unused') }}", - ); - - $returns = array( - 'no_modifications' => array('my string', "convert_as_form doesn't modify string"), - 'no_modifications_on_specific_characters' => array("\"'&<>;{}()[]\\/", "convert_as_form doesn't modify specific characters"), - 'query_builder' => array("'query_builder' => function(\$er) { return \$er->createQueryBuilder(); },", 'convert_as_form properly transforms query_builder'), - 'query' => array("'query' => function() { return MyModel::GetPeerTable(); },", 'convert_as_form properly transforms query'), - 'php_call' => array("strtolower('TeSt')", 'convert_as_form properly transforms __php'), - 'php_call_and_string' => array("strtolower('TeSt'),'my other string'", 'convert_as_form properly transforms __php'), - ); + ]; + + $returns = [ + 'no_modifications' => ['my string', "convert_as_form doesn't modify string"], + 'no_modifications_on_specific_characters' => ["\"'&<>;{}()[]\\/", "convert_as_form doesn't modify specific characters"], + 'query_builder' => ["'query_builder' => function(\$er) { return \$er->createQueryBuilder(); },", 'convert_as_form properly transforms query_builder'], + 'query' => ["'query' => function() { return MyModel::GetPeerTable(); },", 'convert_as_form properly transforms query'], + 'php_call' => ["strtolower('TeSt')", 'convert_as_form properly transforms __php'], + 'php_call_and_string' => ["strtolower('TeSt'),'my other string'", 'convert_as_form properly transforms __php'], + ]; $this->runTwigTests($tpls, $returns); } diff --git a/Tests/Twig/Extension/TestObject.php b/Tests/Twig/Extension/TestObject.php index 5058a10b..6b2283a1 100644 --- a/Tests/Twig/Extension/TestObject.php +++ b/Tests/Twig/Extension/TestObject.php @@ -3,12 +3,10 @@ /** * Dummy object for EchoExtensionTest - * - * @author Cedric LOMBARDOT */ class TestObject { - public static $called = array( + public static array $called = array( '__toString' => 0, 'foo' => 0, 'getFooBar' => 0, @@ -19,13 +17,13 @@ public function __construct($bar = 'bar') } - public static function reset() + public static function reset(): void { - self::$called = array( + self::$called = [ '__toString' => 0, 'foo' => 0, 'getFooBar' => 0, - ); + ]; } public function __toString() @@ -35,14 +33,14 @@ public function __toString() return 'foo'; } - public function foo() + public function foo(): string { ++self::$called['foo']; return 'foo'; } - public function getFooBar() + public function getFooBar(): string { ++self::$called['getFooBar']; diff --git a/Twig/Extension/ConfigExtension.php b/Twig/Extension/ConfigExtension.php index dc61748a..8ab3de45 100644 --- a/Twig/Extension/ConfigExtension.php +++ b/Twig/Extension/ConfigExtension.php @@ -22,7 +22,7 @@ public function getFunctions(): array ]; } - public function getAdmingeneratorConfig(string $name): ?string + public function getAdmingeneratorConfig(string $name): array|string|null { $search_in = $this->bundleConfig; $path = explode('.', $name); diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 09e5ded2..fe489e53 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -7,7 +7,6 @@ convertWarningsToExceptions="true" processIsolation="false" stopOnFailure="false" - syntaxCheck="false" bootstrap="./Tests/bootstrap.php"> @@ -17,12 +16,4 @@ ./Tests - - - ./ - - ./Tests - - -