diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..0142188 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,26 @@ +# EditorConfig is awesome: http://EditorConfig.org + +# Top-most EditorConfig file +root = true + +# Unix-style newlines with a newline ending every file +[*] +end_of_line = lf +insert_final_newline = true + +# JS / PHP +[*.{js,php,phpt}] +charset = utf-8 +indent_style = tab +indent_size = 4 + +# NEON +[*.neon] +charset = utf-8 +indent_style = tab +indent_size = 4 + +# Composer, NPM, Travis, BitbucketPipelines +[{composer.json,package.json,.travis.yml,bitbucket-pipelines.yml}] +indent_style = space +indent_size = 2 diff --git a/.gitattributes b/.gitattributes index 8af211b..9848c5f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,4 +1,8 @@ -.gitattributes export-ignore -.gitignore export-ignore -.travis.yml export-ignore -tests/ export-ignore +/.docs export-ignore +/tests export-ignore +/.editorconfig export-ignore +/.gitattributes export-ignore +/.gitignore export-ignore +/.travis.yml export-ignore +/LICENSE export-ignore +/phpstan.neon export-ignore diff --git a/.gitignore b/.gitignore index 9624eee..394ff5b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,11 @@ -.idea/ -vendor/ +# IDE +/.idea -composer.lock +# Composer +/vendor +/composer.lock + +# Tests +/tests/*.log +/tests/tmp +/tests/coverage.html diff --git a/src/run-tests b/bin/testbench similarity index 100% rename from src/run-tests rename to bin/testbench diff --git a/composer.json b/composer.json index 02e6e69..462c860 100644 --- a/composer.json +++ b/composer.json @@ -14,17 +14,18 @@ } ], "require": { - "php": ">=5.6.0", - "kdyby/fake-session": "^2.0", - "nette/application": "^2.4 || ^v3.0", - "nette/bootstrap": "^2.4 || ^v3.0", - "nette/di": "^2.4 || ^v3.0", - "nette/safe-stream": "^2.3", - "nette/security": "^2.4 || ^v3.0", - "nette/tester": "^2.0", - "nette/utils": "^2.4 || ^v3.0" + "php": ">=7.1", + "kdyby/fake-session": "^2.0.0", + "nette/application": "^2.4.12 || ^3.0", + "nette/bootstrap": "^2.4.6 || ^3.0", + "nette/di": "^2.4.13 || ^3.0", + "nette/safe-stream": "^2.3.3", + "nette/security": "^2.4.3 || ^3.0", + "nette/tester": "^2.0.2", + "nette/utils": "^2.5.2 || ^v3.0" }, "require-dev": { + "ninjify/qa": "^0.8.0", "latte/latte": "^2.4", "nette/forms": "^2.4 || ^v3.0", "nette/robot-loader": "^2.4 || ^v3.0", @@ -36,6 +37,8 @@ "nette/database": "^2.4 || ^v3.0", "zenify/doctrine-migrations": "^2.3" }, + "prefer-stable": true, + "minimum-stability": "dev", "autoload": { "psr-4": { "Testbench\\": [ @@ -53,12 +56,31 @@ ] }, "bin": [ - "src/run-tests" + "bin/testbench" ], "suggest": { "kdyby/doctrine": "Allows enhanced database tests using Doctrine", "kdyby/doctrine-dbal-batchimport": "Allows SQL scripts import for Doctrine (required with kdyby/doctrine)", "nette/database": "Allows enhanced database tests using Nette\\Database", "zenify/doctrine-migrations": "Migrate database to the fresh state" + }, + "scripts": { + "qa": [ + "linter src tests", + "codesniffer src tests" + ], + "phpstan-install": [ + "mkdir -p temp/phpstan", + "composer require -d temp/phpstan phpstan/phpstan:0.10", + "composer require -d temp/phpstan phpstan/phpstan-nette:0.10" + ], + "phpstan": [ + "temp/phpstan/vendor/bin/phpstan analyse -l max -c phpstan.neon src" + ] + }, + "extra": { + "branch-alias": { + "dev-develop": "3.0.x-dev" + } } } diff --git a/ruleset.xml b/ruleset.xml new file mode 100644 index 0000000..7a17219 --- /dev/null +++ b/ruleset.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + /src/Response/CSVResponse.php + + + + /tests + diff --git a/src/Bootstrap.php b/src/Bootstrap.php index 5c0b7db..b435792 100644 --- a/src/Bootstrap.php +++ b/src/Bootstrap.php @@ -1,7 +1,10 @@ - 0) { //\Tester\Environment::setup already called - \Tester\Environment::setup(); + Environment::setup(); } date_default_timezone_set('Europe/Prague'); if (class_exists('Tracy\Debugger')) { - \Tracy\Debugger::$logDirectory = self::$tempDir; + Debugger::$logDirectory = self::$tempDir; } $_ENV = $_GET = $_POST = $_FILES = []; diff --git a/src/ContainerFactory.php b/src/ContainerFactory.php index ff1910d..1313047 100644 --- a/src/ContainerFactory.php +++ b/src/ContainerFactory.php @@ -1,13 +1,23 @@ -addParameters($config); - $configurator->onCompile[] = function (\Nette\Configurator $configurator, \Nette\DI\Compiler $compiler) use ($config) { + $configurator->onCompile[] = function (Configurator $configurator, Compiler $compiler) use ($config): void { $compiler->addConfig($config); - $compiler->addExtension('testbench', new \Testbench\TestbenchExtension); - self::registerAdditionalExtension($compiler, 'fakeSession', new \Kdyby\FakeSession\DI\FakeSessionExtension); + $compiler->addExtension('testbench', new TestbenchExtension()); + self::registerAdditionalExtension($compiler, 'fakeSession', new FakeSessionExtension()); if (class_exists('Kdyby\Console\DI\ConsoleExtension')) { - self::registerAdditionalExtension($compiler, 'console', new \Kdyby\Console\DI\ConsoleExtension); + self::registerAdditionalExtension($compiler, 'console', new ConsoleExtension()); } }; - $configurator->setTempDirectory(\Testbench\Bootstrap::$tempDir); // shared container for performance purposes - $configurator->setDebugMode(FALSE); + $configurator->setTempDirectory(Bootstrap::$tempDir); // shared container for performance purposes + $configurator->setDebugMode(false); - if (is_callable(\Testbench\Bootstrap::$onBeforeContainerCreate)) { - call_user_func_array(\Testbench\Bootstrap::$onBeforeContainerCreate, [$configurator]); + if (is_callable(Bootstrap::$onBeforeContainerCreate)) { + call_user_func_array(Bootstrap::$onBeforeContainerCreate, [$configurator]); } self::$container = $configurator->createContainer(); @@ -49,14 +56,14 @@ final public static function create($new = FALSE, $config = []) /** * Register extension if not registered by user. */ - private static function registerAdditionalExtension(\Nette\DI\Compiler $compiler, $name, $newExtension) + private static function registerAdditionalExtension(Compiler $compiler, $name, $newExtension): void { $extensions = []; $config = $compiler->getConfig(); - foreach (isset($config['extensions']) ? $config['extensions'] : [] as $extension) { + foreach ($config['extensions'] ?? [] as $extension) { if (is_string($extension)) { $extensions[] = $extension; - } elseif ($extension instanceof \Nette\DI\Statement) { + } elseif ($extension instanceof Statement) { $extensions[] = $extension->getEntity(); } } @@ -67,12 +74,12 @@ private static function registerAdditionalExtension(\Nette\DI\Compiler $compiler final public function __clone() { - throw new \Exception('Clone is not allowed'); + throw new Exception('Clone is not allowed'); } - final public function __wakeup() + final public function __wakeup(): void { - throw new \Exception('Unserialization is not allowed'); + throw new Exception('Unserialization is not allowed'); } } diff --git a/src/DatabasesRegistry.php b/src/DatabasesRegistry.php index f812922..abed5cb 100644 --- a/src/DatabasesRegistry.php +++ b/src/DatabasesRegistry.php @@ -1,4 +1,4 @@ -dataFile = 'nette.safe://' . \Testbench\Bootstrap::$tempDir . '/../databases.testbench'; + $this->dataFile = 'nette.safe://' . Bootstrap::$tempDir . '/../databases.testbench'; } /** * @return TRUE if registration successful or FALSE if database record already exists */ - public function registerDatabase($databaseName) + public function registerDatabase(string $databaseName): bool { if (file_exists($this->dataFile)) { $data = file_get_contents($this->dataFile); @@ -28,9 +28,9 @@ public function registerDatabase($databaseName) fwrite($handle, $databaseName . "\n"); fclose($handle); - return TRUE; + return true; } else { //database already exists in log file - return FALSE; + return false; } } diff --git a/src/Mocks/ApplicationRequestMock.php b/src/Mocks/ApplicationRequestMock.php index f67a999..728d09b 100644 --- a/src/Mocks/ApplicationRequestMock.php +++ b/src/Mocks/ApplicationRequestMock.php @@ -1,11 +1,26 @@ -onConnect($this); @@ -27,21 +39,22 @@ public function connect() public function __construct( array $params, DBAL\Driver $driver, - DBAL\Configuration $config = NULL, - Common\EventManager $eventManager = NULL - ) { - $container = \Testbench\ContainerFactory::create(FALSE); - $this->onConnect[] = function (DoctrineConnectionMock $connection) use ($container) { - if ($this->__testbench_databaseName !== NULL) { //already initialized (needed for pgsql) + ?DBAL\Configuration $config = null, + ?Common\EventManager $eventManager = null + ) + { + $container = ContainerFactory::create(false); + $this->onConnect[] = function (DoctrineConnectionMock $connection) use ($container): void { + if ($this->__testbench_databaseName !== null) { //already initialized (needed for pgsql) return; } try { $config = $container->parameters['testbench']; - if ($config['shareDatabase'] === TRUE) { - $registry = new \Testbench\DatabasesRegistry; - $dbName = $container->parameters['testbench']['dbprefix'] . getenv(\Tester\Environment::THREAD); + if ($config['shareDatabase'] === true) { + $registry = new DatabasesRegistry(); + $dbName = $container->parameters['testbench']['dbprefix'] . getenv(Environment::THREAD); if ($registry->registerDatabase($dbName)) { - $this->__testbench_database_setup($connection, $container, TRUE); + $this->__testbench_database_setup($connection, $container, true); } else { $this->__testbench_databaseName = $dbName; $this->__testbench_database_change($connection, $container); @@ -49,39 +62,39 @@ public function __construct( } else { // always create new test database $this->__testbench_database_setup($connection, $container); } - } catch (\Exception $e) { - \Tester\Assert::fail($e->getMessage()); + } catch (Throwable $e) { + Assert::fail($e->getMessage()); } }; parent::__construct($params, $driver, $config, $eventManager); } /** @internal */ - public function __testbench_database_setup($connection, \Nette\DI\Container $container, $persistent = FALSE) + public function __testbench_database_setup($connection, Container $container, $persistent = false): void { $config = $container->parameters['testbench']; - $this->__testbench_databaseName = $config['dbprefix'] . getenv(\Tester\Environment::THREAD); + $this->__testbench_databaseName = $config['dbprefix'] . getenv(Environment::THREAD); $this->__testbench_database_drop($connection, $container); $this->__testbench_database_create($connection, $container); foreach ($config['sqls'] as $file) { - \Kdyby\Doctrine\Dbal\BatchImport\Helpers::loadFromFile($connection, $file); + Helpers::loadFromFile($connection, $file); } - if ($config['migrations'] === TRUE) { - if (class_exists(\Zenify\DoctrineMigrations\Configuration\Configuration::class)) { - /** @var \Zenify\DoctrineMigrations\Configuration\Configuration $migrationsConfig */ - $migrationsConfig = $container->getByType(\Zenify\DoctrineMigrations\Configuration\Configuration::class); + if ($config['migrations'] === true) { + if (class_exists(Configuration::class)) { + /** @var Configuration $migrationsConfig */ + $migrationsConfig = $container->getByType(Configuration::class); $migrationsConfig->__construct($container, $connection); $migrationsConfig->registerMigrationsFromDirectory($migrationsConfig->getMigrationsDirectory()); - $migration = new \Doctrine\DBAL\Migrations\Migration($migrationsConfig); + $migration = new Migration($migrationsConfig); $migration->migrate($migrationsConfig->getLatestVersion()); } } - if ($persistent === FALSE) { - register_shutdown_function(function () use ($connection, $container) { + if ($persistent === false) { + register_shutdown_function(function () use ($connection, $container): void { $this->__testbench_database_drop($connection, $container); }); } @@ -89,10 +102,9 @@ public function __testbench_database_setup($connection, \Nette\DI\Container $con /** * @internal - * * @param $connection \Kdyby\Doctrine\Connection */ - public function __testbench_database_create($connection, \Nette\DI\Container $container) + public function __testbench_database_create($connection, Container $container): void { $connection->exec("CREATE DATABASE {$this->__testbench_databaseName}"); $this->__testbench_database_change($connection, $container); @@ -100,10 +112,9 @@ public function __testbench_database_create($connection, \Nette\DI\Container $co /** * @internal - * * @param $connection \Kdyby\Doctrine\Connection */ - public function __testbench_database_change($connection, \Nette\DI\Container $container) + public function __testbench_database_change($connection, Container $container): void { if ($connection->getDatabasePlatform() instanceof MySqlPlatform) { $connection->exec("USE {$this->__testbench_databaseName}"); @@ -114,10 +125,9 @@ public function __testbench_database_change($connection, \Nette\DI\Container $co /** * @internal - * * @param $connection \Kdyby\Doctrine\Connection */ - public function __testbench_database_drop($connection, \Nette\DI\Container $container) + public function __testbench_database_drop($connection, Container $container): void { if (!$connection->getDatabasePlatform() instanceof MySqlPlatform) { $this->__testbench_database_connect($connection, $container); @@ -127,20 +137,19 @@ public function __testbench_database_drop($connection, \Nette\DI\Container $cont /** * @internal - * * @param $connection \Kdyby\Doctrine\Connection */ - public function __testbench_database_connect($connection, \Nette\DI\Container $container, $databaseName = NULL) + public function __testbench_database_connect($connection, Container $container, $databaseName = null): void { //connect to an existing database other than $this->_databaseName - if ($databaseName === NULL) { + if ($databaseName === null) { $dbname = $container->parameters['testbench']['dbname']; if ($dbname) { $databaseName = $dbname; } elseif ($connection->getDatabasePlatform() instanceof PostgreSqlPlatform) { $databaseName = 'postgres'; } else { - throw new \LogicException('You should setup existing database name using testbench:dbname option.'); + throw new LogicException('You should setup existing database name using testbench:dbname option.'); } } diff --git a/src/Mocks/HttpRequestMock.php b/src/Mocks/HttpRequestMock.php index a2cb765..56abd8d 100644 --- a/src/Mocks/HttpRequestMock.php +++ b/src/Mocks/HttpRequestMock.php @@ -1,15 +1,16 @@ -setQuery($query); } parent::__construct( $url, - NULL, //deprecated + null, //deprecated $post, $files, $cookies, diff --git a/src/Mocks/NetteDatabaseConnectionMock.php b/src/Mocks/NetteDatabaseConnectionMock.php index fcc377e..68824d9 100644 --- a/src/Mocks/NetteDatabaseConnectionMock.php +++ b/src/Mocks/NetteDatabaseConnectionMock.php @@ -1,32 +1,49 @@ -onConnect[] = function (NetteDatabaseConnectionMock $connection) use ($container) { - if ($this->__testbench_databaseName !== NULL) { //already initialized (needed for pgsql) + $container = ContainerFactory::create(false); + $this->onConnect[] = function (NetteDatabaseConnectionMock $connection) use ($container): void { + if ($this->__testbench_databaseName !== null) { //already initialized (needed for pgsql) return; } try { $config = $container->parameters['testbench']; - if ($config['shareDatabase'] === TRUE) { - $registry = new \Testbench\DatabasesRegistry; - $dbName = $container->parameters['testbench']['dbprefix'] . getenv(\Tester\Environment::THREAD); + if ($config['shareDatabase'] === true) { + $registry = new DatabasesRegistry(); + $dbName = $container->parameters['testbench']['dbprefix'] . getenv(Environment::THREAD); if ($registry->registerDatabase($dbName)) { - $this->__testbench_database_setup($connection, $container, TRUE); + $this->__testbench_database_setup($connection, $container, true); } else { $this->__testbench_databaseName = $dbName; $this->__testbench_database_change($connection, $container); @@ -34,28 +51,28 @@ public function __construct($dsn, $user = NULL, $password = NULL, array $options } else { // always create new test database $this->__testbench_database_setup($connection, $container); } - } catch (\Exception $e) { - \Tester\Assert::fail($e->getMessage()); + } catch (Throwable $e) { + Assert::fail($e->getMessage()); } }; parent::__construct($dsn, $user, $password, $options); } /** @internal */ - public function __testbench_database_setup($connection, \Nette\DI\Container $container, $persistent = FALSE) + public function __testbench_database_setup($connection, Container $container, $persistent = false): void { $config = $container->parameters['testbench']; - $this->__testbench_databaseName = $config['dbprefix'] . getenv(\Tester\Environment::THREAD); + $this->__testbench_databaseName = $config['dbprefix'] . getenv(Environment::THREAD); $this->__testbench_database_drop($connection, $container); $this->__testbench_database_create($connection, $container); foreach ($config['sqls'] as $file) { - \Nette\Database\Helpers::loadFromFile($connection, $file); + Helpers::loadFromFile($connection, $file); } - if ($persistent === FALSE) { - register_shutdown_function(function () use ($connection, $container) { + if ($persistent === false) { + register_shutdown_function(function () use ($connection, $container): void { $this->__testbench_database_drop($connection, $container); }); } @@ -63,10 +80,9 @@ public function __testbench_database_setup($connection, \Nette\DI\Container $con /** * @internal - * * @param $connection \Nette\Database\Connection */ - public function __testbench_database_create($connection, \Nette\DI\Container $container) + public function __testbench_database_create($connection, Container $container): void { $connection->query("CREATE DATABASE {$this->__testbench_databaseName}"); $this->__testbench_database_change($connection, $container); @@ -74,10 +90,9 @@ public function __testbench_database_create($connection, \Nette\DI\Container $co /** * @internal - * * @param $connection \Nette\Database\Connection */ - public function __testbench_database_change($connection, \Nette\DI\Container $container) + public function __testbench_database_change($connection, Container $container): void { if ($connection->getSupplementalDriver() instanceof MySqlDriver) { $connection->query("USE {$this->__testbench_databaseName}"); @@ -88,10 +103,9 @@ public function __testbench_database_change($connection, \Nette\DI\Container $co /** * @internal - * * @param $connection \Nette\Database\Connection */ - public function __testbench_database_drop($connection, \Nette\DI\Container $container) + public function __testbench_database_drop($connection, Container $container): void { if (!$connection->getSupplementalDriver() instanceof MySqlDriver) { $this->__testbench_database_connect($connection, $container); @@ -101,32 +115,31 @@ public function __testbench_database_drop($connection, \Nette\DI\Container $cont /** * @internal - * * @param $connection \Nette\Database\Connection */ - public function __testbench_database_connect($connection, \Nette\DI\Container $container, $databaseName = NULL) + public function __testbench_database_connect($connection, Container $container, $databaseName = null): void { //connect to an existing database other than $this->_databaseName - if ($databaseName === NULL) { + if ($databaseName === null) { $dbname = $container->parameters['testbench']['dbname']; if ($dbname) { $databaseName = $dbname; } elseif ($connection->getSupplementalDriver() instanceof PgSqlDriver) { $databaseName = 'postgres'; } else { - throw new \LogicException('You should setup existing database name using testbench:dbname option.'); + throw new LogicException('You should setup existing database name using testbench:dbname option.'); } } $dsn = preg_replace('~dbname=[a-z0-9_-]+~i', "dbname=$databaseName", $connection->getDsn()); - $dbr = (new \Nette\Reflection\ClassType($connection))->getParentClass(); //:-( + $dbr = (new ClassType($connection))->getParentClass(); //:-( $params = $dbr->getProperty('params'); - $params->setAccessible(TRUE); + $params->setAccessible(true); $params = $params->getValue($connection); $options = $dbr->getProperty('options'); - $options->setAccessible(TRUE); + $options->setAccessible(true); $options = $options->getValue($connection); $connection->disconnect(); diff --git a/src/Mocks/PresenterMock.php b/src/Mocks/PresenterMock.php index 3956b1f..8c5966a 100644 --- a/src/Mocks/PresenterMock.php +++ b/src/Mocks/PresenterMock.php @@ -1,39 +1,42 @@ -autoCanonicalize = FALSE; + $this->autoCanonicalize = false; return parent::run($request); } - public function startup() + public function startup(): void { - if ($this->getParameter('__terminate') === TRUE) { + if ($this->getParameter('__terminate') === true) { $this->terminate(); } parent::startup(); $this->onStartup($this); } - public function afterRender() + public function afterRender(): void { $this->terminate(); } public function isAjax() { - return FALSE; + return false; } public function link($destination, $args = []) @@ -41,7 +44,7 @@ public function link($destination, $args = []) if (!is_array($args)) { $args = array_slice(func_get_args(), 1); } - $params = urldecode(http_build_query($args, NULL, ', ')); + $params = urldecode(http_build_query($args, null, ', ')); $params = $params ? "($params)" : ''; return "plink|$destination$params"; } diff --git a/src/Providers/IDatabaseProvider.php b/src/Providers/IDatabaseProvider.php index e53cbd3..180f8d3 100644 --- a/src/Providers/IDatabaseProvider.php +++ b/src/Providers/IDatabaseProvider.php @@ -1,7 +1,9 @@ -isDir()) { rmdir($entry); @@ -89,13 +94,13 @@ public function prepareArguments(array $args, $testsDir) unset($parameters['--bootstrap']); } - if ($pathToTests === NULL) { + if ($pathToTests === null) { $pathToTests = $testsDir; } $args = $environmentVariables; foreach ($parameters as $key => $value) { //return to the Tester format - if ($value === TRUE) { //singles + if ($value === true) { //singles $args[] = $key; continue; } @@ -118,7 +123,7 @@ public function findVendorDirectory() $recursionLimit = 10; $findVendor = function ($dirName = 'vendor/bin', $dir = __DIR__) use (&$findVendor, &$recursionLimit) { if (!$recursionLimit--) { - throw new \Exception('Cannot find vendor directory.'); + throw new Exception('Cannot find vendor directory.'); } $found = $dir . "/$dirName"; if (is_dir($found) || is_file($found)) { diff --git a/src/Testbench.php b/src/Testbench.php index d7bdd08..b92e03c 100644 --- a/src/Testbench.php +++ b/src/Testbench.php @@ -1,11 +1,11 @@ - NULL, // custom initial test database name (should not be needed) + 'dbname' => null, // custom initial test database name (should not be needed) 'dbprefix' => '_testbench_', // database prefix for created tests databases - 'migrations' => FALSE, // set TRUE if you want to use Doctrine migrations - 'shareDatabase' => FALSE, // should Testbench always create new databases (FALSE) or use shared databases (TRUE) + 'migrations' => false, // set TRUE if you want to use Doctrine migrations + 'shareDatabase' => false, // should Testbench always create new databases (FALSE) or use shared databases (TRUE) 'sqls' => [], // sqls you want to import during new test database creation 'url' => 'http://test.bench/', // fake URL for HTTP request mock ]; - public function loadConfiguration() + public function loadConfiguration(): void { $builder = $this->compiler->getContainerBuilder(); $builder->parameters[$this->name] = $this->validateConfig($this->defaults); @@ -24,7 +27,7 @@ public function loadConfiguration() //TODO: $builder->addDefinition($this->prefix('applicationRequestMock'))->setClass('Testbench\ApplicationRequestMock'); } - public function beforeCompile() + public function beforeCompile(): void { $builder = $this->compiler->getContainerBuilder(); @@ -41,10 +44,10 @@ public function beforeCompile() /** * 'wrapperClass' is not a service! */ - private function prepareDoctrine() + private function prepareDoctrine(): void { - $doctrineConnectionSectionKeys = ['dbname' => NULL, 'driver' => NULL, 'connection' => NULL]; - /** @var \Nette\DI\CompilerExtension $extension */ + $doctrineConnectionSectionKeys = ['dbname' => null, 'driver' => null, 'connection' => null]; + /** @var CompilerExtension $extension */ foreach ($this->compiler->getExtensions('Kdyby\Doctrine\DI\OrmExtension') as $extension) { if (array_intersect_key($extension->config, $doctrineConnectionSectionKeys)) { $extension->config['wrapperClass'] = 'Testbench\Mocks\DoctrineConnectionMock'; @@ -58,10 +61,10 @@ private function prepareDoctrine() } } - private function prepareNetteDatabase(\Nette\DI\ContainerBuilder $builder) + private function prepareNetteDatabase(ContainerBuilder $builder): void { - $ndbConnectionSectionKeys = ['dsn' => NULL, 'user' => NULL, 'password' => NULL]; - /** @var \Nette\DI\CompilerExtension $extension */ + $ndbConnectionSectionKeys = ['dsn' => null, 'user' => null, 'password' => null]; + /** @var CompilerExtension $extension */ foreach ($this->compiler->getExtensions('Nette\Bridges\DatabaseDI\DatabaseExtension') as $extension) { if (array_intersect_key($extension->config, $ndbConnectionSectionKeys)) { $extensionConfig = $extension->config; @@ -71,7 +74,7 @@ private function prepareNetteDatabase(\Nette\DI\ContainerBuilder $builder) $extensionConfig['dsn'], $extensionConfig['user'], $extensionConfig['password'], - isset($extensionConfig['options']) ? ($extensionConfig['options'] + ['lazy' => TRUE]) : [], + isset($extensionConfig['options']) ? ($extensionConfig['options'] + ['lazy' => true]) : [], ]); } else { foreach ($extension->config as $sectionName => $sectionConfig) { @@ -81,7 +84,7 @@ private function prepareNetteDatabase(\Nette\DI\ContainerBuilder $builder) $sectionConfig['dsn'], $sectionConfig['user'], $sectionConfig['password'], - isset($sectionConfig['options']) ? ($sectionConfig['options'] + ['lazy' => TRUE]) : [], + isset($sectionConfig['options']) ? ($sectionConfig['options'] + ['lazy' => true]) : [], ]); } } diff --git a/src/Traits/TCompiledContainer.php b/src/Traits/TCompiledContainer.php index df86c43..9a174f2 100644 --- a/src/Traits/TCompiledContainer.php +++ b/src/Traits/TCompiledContainer.php @@ -1,14 +1,17 @@ -changeRunLevel($really ? \Testbench::FINE : \Testbench::QUICK); + $this->changeRunLevel($really ? Testbench::FINE : Testbench::QUICK); } - protected function markTestAsVerySlow($really = TRUE) + protected function markTestAsVerySlow($really = true): void { - $this->changeRunLevel($really ? \Testbench::SLOW : \Testbench::QUICK); + $this->changeRunLevel($really ? Testbench::SLOW : Testbench::QUICK); } } diff --git a/src/Traits/TComponent.php b/src/Traits/TComponent.php index c06a2cc..3f66d7a 100644 --- a/src/Traits/TComponent.php +++ b/src/Traits/TComponent.php @@ -1,17 +1,19 @@ -getName()) { $name = $component->getReflection()->getShortName(); if (preg_match('~class@anonymous.*~', $name)) { @@ -20,21 +22,21 @@ protected function attachToPresenter(IComponent $component, $name = NULL) } } if (!$this->__testbench_presenterMock) { - $container = \Testbench\ContainerFactory::create(FALSE); + $container = ContainerFactory::create(false); $this->__testbench_presenterMock = $container->getByType('Testbench\Mocks\PresenterMock'); $container->callInjects($this->__testbench_presenterMock); } - $this->__testbench_presenterMock->onStartup[] = function (Mocks\PresenterMock $presenter) use ($component, $name) { + $this->__testbench_presenterMock->onStartup[] = function (Mocks\PresenterMock $presenter) use ($component, $name): void { try { $presenter->removeComponent($component); - } catch (\Nette\InvalidArgumentException $exc) { + } catch (InvalidArgumentException $exc) { } $presenter->addComponent($component, $name); }; - $this->__testbench_presenterMock->run(new Mocks\ApplicationRequestMock); + $this->__testbench_presenterMock->run(new Mocks\ApplicationRequestMock()); } - protected function checkRenderOutput(IComponent $control, $expected, array $renderParameters = []) + protected function checkRenderOutput(IComponent $control, $expected, array $renderParameters = []): void { if (!$control->getParent()) { $this->attachToPresenter($control); @@ -42,9 +44,9 @@ protected function checkRenderOutput(IComponent $control, $expected, array $rend ob_start(); $control->render(...$renderParameters); if (is_file($expected)) { - \Tester\Assert::matchFile($expected, ob_get_clean()); + Assert::matchFile($expected, ob_get_clean()); } else { - \Tester\Assert::match($expected, ob_get_clean()); + Assert::match($expected, ob_get_clean()); } } diff --git a/src/Traits/TDoctrine.php b/src/Traits/TDoctrine.php index a919067..aeb5c06 100644 --- a/src/Traits/TDoctrine.php +++ b/src/Traits/TDoctrine.php @@ -1,21 +1,21 @@ -getByType('Doctrine\DBAL\Connection'); if (!$connection instanceof Mocks\DoctrineConnectionMock) { $serviceNames = $container->findByType('Doctrine\DBAL\Connection'); - throw new \LogicException(sprintf( + throw new LogicException(sprintf( 'The service %s should be instance of Testbench\Mocks\DoctrineConnectionMock, to allow lazy schema initialization.', reset($serviceNames) )); diff --git a/src/Traits/TNetteDatabase.php b/src/Traits/TNetteDatabase.php index 390a0fa..36414b6 100644 --- a/src/Traits/TNetteDatabase.php +++ b/src/Traits/TNetteDatabase.php @@ -1,23 +1,26 @@ -getByType('Nette\Database\Connection'); if (!$connection instanceof Mocks\NetteDatabaseConnectionMock) { $serviceNames = $container->findByType('Nette\Database\Connection'); - throw new \LogicException(sprintf( + throw new LogicException(sprintf( 'The service %s should be instance of Testbench\Mocks\NetteDatabaseConnectionMock, to allow lazy schema initialization.', reset($serviceNames) )); } - /** @var \Nette\Database\Context $context */ + /** @var Context $context */ $context = $container->getByType('Nette\Database\Context'); return $context; } diff --git a/src/Traits/TPresenter.php b/src/Traits/TPresenter.php index fc34079..657e1d8 100644 --- a/src/Traits/TPresenter.php +++ b/src/Traits/TPresenter.php @@ -1,57 +1,72 @@ -removeService('httpRequest'); $headers = $this->__testbench_ajaxMode ? ['X-Requested-With' => 'XMLHttpRequest'] : []; - $url = new \Nette\Http\UrlScript($container->parameters['testbench']['url']); + $url = new UrlScript($container->parameters['testbench']['url']); $container->addService('httpRequest', new Mocks\HttpRequestMock($url, $params, $post, [], [], $headers)); $presenterFactory = $container->getByType('Nette\Application\IPresenterFactory'); $this->__testbench_presenter = $presenterFactory->createPresenter($presenter); - $this->__testbench_presenter->autoCanonicalize = FALSE; - $this->__testbench_presenter->invalidLinkMode = \Nette\Application\UI\Presenter::INVALID_LINK_EXCEPTION; + $this->__testbench_presenter->autoCanonicalize = false; + $this->__testbench_presenter->invalidLinkMode = Presenter::INVALID_LINK_EXCEPTION; $postCopy = $post; if (isset($params['do'])) { foreach ($post as $key => $field) { - if (is_array($field) && array_key_exists(\Nette\Forms\Form::REQUIRED, $field)) { + if (is_array($field) && array_key_exists(Form::REQUIRED, $field)) { $post[$key] = $field[0]; } } } - /** @var \Kdyby\FakeSession\Session $session */ + /** @var Session $session */ $session = $this->__testbench_presenter->getSession(); $session->setFakeId('testbench.fakeId'); $session->getSection('Nette\Forms\Controls\CsrfProtection')->token = 'testbench.fakeToken'; @@ -65,7 +80,7 @@ protected function check($destination, $params = [], $post = []) ); try { $this->__testbench_httpCode = 200; - $this->__testbench_exception = NULL; + $this->__testbench_exception = null; $response = $this->__testbench_presenter->run($request); if (isset($params['do'])) { @@ -75,9 +90,9 @@ protected function check($destination, $params = [], $post = []) foreach ($form->getControls() as $control) { if (array_key_exists($control->getName(), $postCopy)) { $subvalues = $postCopy[$control->getName()]; - $rq = \Nette\Forms\Form::REQUIRED; + $rq = Form::REQUIRED; if (is_array($subvalues) && array_key_exists($rq, $subvalues) && $subvalues[$rq]) { - if ($control->isRequired() !== TRUE) { + if ($control->isRequired() !== true) { Assert::fail("field '{$control->name}' should be defined as required, but it's not"); } } @@ -99,7 +114,7 @@ protected function check($destination, $params = [], $post = []) } return $response; - } catch (\Exception $exc) { + } catch (Throwable $exc) { $this->__testbench_exception = $exc; $this->__testbench_httpCode = $exc->getCode(); throw $exc; @@ -110,23 +125,21 @@ protected function check($destination, $params = [], $post = []) * @param string $destination fully qualified presenter name (module:module:presenter) * @param array $params provided to the presenter usually via URL * @param array $post provided to the presenter via POST - * - * @return \Nette\Application\Responses\TextResponse - * @throws \Exception + * @throws Exception */ - protected function checkAction($destination, $params = [], $post = []) + protected function checkAction(string $destination, array $params = [], array $post = []): TextResponse { - /** @var \Nette\Application\Responses\TextResponse $response */ + /** @var TextResponse $response */ $response = $this->check($destination, $params, $post); if (!$this->__testbench_exception) { Assert::same(200, $this->getReturnCode()); Assert::type('Nette\Application\Responses\TextResponse', $response); Assert::type('Nette\Application\UI\ITemplate', $response->getSource()); - $html = (string)$response->getSource(); + $html = (string) $response->getSource(); //DOMDocument doesn't handle HTML tags inside of script tags very well $html = preg_replace('~)<[^<]*)*<\/script>~', '', $html); //http://stackoverflow.com/a/6660315/3135248 - $dom = @\Tester\DomQuery::fromHtml($html); + $dom = @DomQuery::fromHtml($html); Assert::true($dom->has('html'), "missing 'html' tag"); Assert::true($dom->has('title'), "missing 'title' tag"); Assert::true($dom->has('body'), "missing 'body' tag"); @@ -135,23 +148,19 @@ protected function checkAction($destination, $params = [], $post = []) } /** - * @param string $destination - * @param string $signal * @param array $params * @param array $post - * - * @return \Nette\Application\IResponse */ - protected function checkSignal($destination, $signal, $params = [], $post = []) + protected function checkSignal(string $destination, string $signal, array $params = [], array $post = []): IResponse { - return $this->checkRedirect($destination, FALSE, [ + return $this->checkRedirect($destination, false, [ 'do' => $signal, ] + $params, $post); } protected function checkAjaxSignal($destination, $signal, $params = [], $post = []) { - $this->__testbench_ajaxMode = TRUE; + $this->__testbench_ajaxMode = true; $response = $this->check($destination, [ 'do' => $signal, ] + $params, $post); @@ -160,32 +169,29 @@ protected function checkAjaxSignal($destination, $signal, $params = [], $post = Assert::same(200, $this->getReturnCode()); Assert::type('Nette\Application\Responses\JsonResponse', $response); } - $this->__testbench_ajaxMode = FALSE; + $this->__testbench_ajaxMode = false; return $response; } /** * @param string $destination fully qualified presenter name (module:module:presenter) - * @param string $path * @param array $params provided to the presenter usually via URL * @param array $post provided to the presenter via POST - * - * @return \Nette\Application\Responses\RedirectResponse - * @throws \Exception + * @throws Exception */ - protected function checkRedirect($destination, $path = '/', $params = [], $post = []) + protected function checkRedirect(string $destination, string $path = '/', array $params = [], array $post = []): RedirectResponse { - /** @var \Nette\Application\Responses\RedirectResponse $response */ + /** @var RedirectResponse $response */ $response = $this->check($destination, $params, $post); if (!$this->__testbench_exception) { Assert::same(200, $this->getReturnCode()); Assert::type('Nette\Application\Responses\RedirectResponse', $response); Assert::same(302, $response->getCode()); if ($path) { - if (!\Tester\Assert::isMatching("~^https?://test\.bench{$path}(?(?=\?).+)$~", $response->getUrl())) { + if (!Assert::isMatching("~^https?://test\.bench{$path}(?(?=\?).+)$~", $response->getUrl())) { $path = Dumper::color('yellow') . Dumper::toLine($path) . Dumper::color('white'); $url = Dumper::color('yellow') . Dumper::toLine($response->getUrl()) . Dumper::color('white'); - $originalUrl = new \Nette\Http\Url($response->getUrl()); + $originalUrl = new Url($response->getUrl()); Assert::fail( str_repeat(' ', strlen($originalUrl->getHostUrl()) - 13) // strlen('Failed: path ') = 13 . "path $path doesn't match\n$url\nafter redirect" @@ -200,13 +206,11 @@ protected function checkRedirect($destination, $path = '/', $params = [], $post * @param string $destination fully qualified presenter name (module:module:presenter) * @param array $params provided to the presenter usually via URL * @param array $post provided to the presenter via POST - * - * @return \Nette\Application\Responses\JsonResponse - * @throws \Exception + * @throws Exception */ - protected function checkJson($destination, $params = [], $post = []) + protected function checkJson(string $destination, array $params = [], array $post = []): JsonResponse { - /** @var \Nette\Application\Responses\JsonResponse $response */ + /** @var JsonResponse $response */ $response = $this->check($destination, $params, $post); if (!$this->__testbench_exception) { Assert::same(200, $this->getReturnCode()); @@ -222,7 +226,7 @@ protected function checkJson($destination, $params = [], $post = []) * @param array $params provided to the presenter usually via URL * @param array $post provided to the presenter via POST */ - public function checkJsonScheme($destination, array $scheme, $params = [], $post = []) + public function checkJsonScheme(string $destination, array $scheme, array $params = [], array $post = []): void { $response = $this->checkJson($destination, $params, $post); Assert::same($scheme, $response->getPayload()); @@ -230,21 +234,18 @@ public function checkJsonScheme($destination, array $scheme, $params = [], $post /** * @param string $destination fully qualified presenter name (module:module:presenter) - * @param string $formName * @param array $post provided to the presenter via POST - * @param string|boolean $path Path after redirect or FALSE if it's form without redirect - * - * @return \Nette\Application\Responses\RedirectResponse - * @throws \Tester\AssertException + * @param string|bool $path Path after redirect or FALSE if it's form without redirect + * @throws AssertException */ - protected function checkForm($destination, $formName, $post = [], $path = '/') + protected function checkForm(string $destination, string $formName, array $post = [], $path = '/'): RedirectResponse { if (is_string($path)) { return $this->checkRedirect($destination, $path, [ 'do' => $formName . '-submit', ], $post); } elseif (is_bool($path)) { - /** @var \Nette\Application\Responses\RedirectResponse $response */ + /** @var RedirectResponse $response */ $response = $this->check($destination, [ 'do' => $formName . '-submit', ], $post); @@ -254,7 +255,7 @@ protected function checkForm($destination, $formName, $post = [], $path = '/') } return $response; } else { - \Tester\Assert::fail('Path should be string or boolean (probably FALSE).'); + Assert::fail('Path should be string or boolean (probably FALSE).'); } } @@ -263,18 +264,16 @@ protected function checkForm($destination, $formName, $post = [], $path = '/') * @param $formName * @param array $post provided to the presenter via POST * @param string|bool $path - * - * @return \Nette\Application\IResponse - * @throws \Exception + * @throws Exception */ - protected function checkAjaxForm($destination, $formName, $post = [], $path = FALSE) + protected function checkAjaxForm(string $destination, $formName, array $post = [], $path = false): IResponse { if (is_string($path)) { $this->checkForm($destination, $formName, $post, $path); Assert::false($this->__testbench_presenter->isAjax()); } - $this->__testbench_presenter = NULL; //FIXME: not very nice, but performance first - $this->__testbench_ajaxMode = TRUE; + $this->__testbench_presenter = null; //FIXME: not very nice, but performance first + $this->__testbench_ajaxMode = true; $response = $this->check($destination, [ 'do' => $formName . '-submit', ], $post); @@ -283,8 +282,8 @@ protected function checkAjaxForm($destination, $formName, $post = [], $path = FA Assert::same(200, $this->getReturnCode()); Assert::type('Nette\Application\Responses\JsonResponse', $response); } - $this->__testbench_presenter = NULL; - $this->__testbench_ajaxMode = FALSE; + $this->__testbench_presenter = null; + $this->__testbench_ajaxMode = false; return $response; } @@ -292,20 +291,18 @@ protected function checkAjaxForm($destination, $formName, $post = [], $path = FA * @param string $destination fully qualified presenter name (module:module:presenter) * @param array $params provided to the presenter usually via URL * @param array $post provided to the presenter via POST - * - * @return \Nette\Application\Responses\TextResponse - * @throws \Exception + * @throws Exception */ - protected function checkRss($destination, $params = [], $post = []) + protected function checkRss(string $destination, array $params = [], array $post = []): TextResponse { - /** @var \Nette\Application\Responses\TextResponse $response */ + /** @var TextResponse $response */ $response = $this->check($destination, $params, $post); if (!$this->__testbench_exception) { Assert::same(200, $this->getReturnCode()); Assert::type('Nette\Application\Responses\TextResponse', $response); Assert::type('Nette\Application\UI\ITemplate', $response->getSource()); - $dom = \Tester\DomQuery::fromXml($response->getSource()); + $dom = DomQuery::fromXml($response->getSource()); Assert::true($dom->has('rss'), "missing 'rss' element"); Assert::true($dom->has('channel'), "missing 'channel' element"); Assert::true($dom->has('title'), "missing 'title' element"); @@ -319,20 +316,18 @@ protected function checkRss($destination, $params = [], $post = []) * @param string $destination fully qualified presenter name (module:module:presenter) * @param array $params provided to the presenter usually via URL * @param array $post provided to the presenter via POST - * - * @return \Nette\Application\Responses\TextResponse - * @throws \Exception + * @throws Exception */ - protected function checkSitemap($destination, $params = [], $post = []) + protected function checkSitemap(string $destination, array $params = [], array $post = []): TextResponse { - /** @var \Nette\Application\Responses\TextResponse $response */ + /** @var TextResponse $response */ $response = $this->check($destination, $params, $post); if (!$this->__testbench_exception) { Assert::same(200, $this->getReturnCode()); Assert::type('Nette\Application\Responses\TextResponse', $response); Assert::type('Nette\Application\UI\ITemplate', $response->getSource()); - $xml = \Tester\DomQuery::fromXml($response->getSource()); + $xml = DomQuery::fromXml($response->getSource()); Assert::same('urlset', $xml->getName(), 'root element is'); $url = $xml->children(); Assert::same('url', $url->getName(), "child of 'urlset'"); @@ -342,66 +337,49 @@ protected function checkSitemap($destination, $params = [], $post = []) } /** - * @param \Nette\Security\IIdentity|integer $id + * @param IIdentity|int $id * @param array|null $roles * @param array|null $data - * - * @return \Nette\Security\User */ - protected function logIn($id = 1, $roles = NULL, $data = NULL) + protected function logIn($id = 1, $roles = null, $data = null): User { - if ($id instanceof \Nette\Security\IIdentity) { + if ($id instanceof IIdentity) { $identity = $id; } else { - $identity = new \Nette\Security\Identity($id, $roles, $data); + $identity = new Identity($id, $roles, $data); } - /** @var \Nette\Security\User $user */ - $user = \Testbench\ContainerFactory::create(FALSE)->getByType('Nette\Security\User'); + /** @var User $user */ + $user = ContainerFactory::create(false)->getByType('Nette\Security\User'); $user->login($identity); return $user; } - /** - * @return \Nette\Security\User - */ - protected function logOut() + protected function logOut(): User { - /** @var \Nette\Security\User $user */ - $user = \Testbench\ContainerFactory::create(FALSE)->getByType('Nette\Security\User'); + /** @var User $user */ + $user = ContainerFactory::create(false)->getByType('Nette\Security\User'); $user->logout(); return $user; } - /** - * @return bool - */ - protected function isUserLoggedIn() + protected function isUserLoggedIn(): bool { - /** @var \Nette\Security\User $user */ - $user = \Testbench\ContainerFactory::create(FALSE)->getByType('Nette\Security\User'); + /** @var User $user */ + $user = ContainerFactory::create(false)->getByType('Nette\Security\User'); return $user->isLoggedIn(); } - /** - * @return \Nette\Application\UI\Presenter - */ - protected function getPresenter() + protected function getPresenter(): Presenter { return $this->__testbench_presenter; } - /** - * @return integer - */ - protected function getReturnCode() + protected function getReturnCode(): int { return $this->__testbench_httpCode; } - /** - * @return \Exception - */ - protected function getException() + protected function getException(): Throwable { return $this->__testbench_exception; }