Skip to content

Commit

Permalink
Refactor: Fix deprecation notices that was introduced with Symfony 5.1 (
Browse files Browse the repository at this point in the history
#483)

* Refactor: Shiny new `Kernel.php`

* Refactor: No more `ContainerInterface`

* Refactor: Bootstrap overhaul

* Refactor: No need to ignore `src/Kernel.php` anymore with psalm

* Refactor: Fixed :töhötys: of reading `.env.local.php`

* Refactor: Fixed deprecation notices that was caused by using `Response::create()` method - that method has been marked as deprecated since Symfony 5.1

* Fixed ECS warnings

* Lets use `$request->get()` instead of `$request->request->get()` to avoid deprecation notices

* Fixed ECS warnings

* Fixed ECS warnings
  • Loading branch information
tarlepp committed Jun 4, 2020
1 parent bd44385 commit 2d8bd15
Show file tree
Hide file tree
Showing 11 changed files with 54 additions and 98 deletions.
5 changes: 3 additions & 2 deletions bin/console
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ declare(strict_types = 1);
use App\Kernel;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Dotenv\Dotenv;
use Symfony\Component\ErrorHandler\Debug;

set_time_limit(0);
Expand All @@ -15,8 +16,8 @@ if (in_array(PHP_SAPI, ['cli', 'phpdbg', 'embed'], true) === false) {

require dirname(__DIR__) . '/vendor/autoload.php';

if (!class_exists(Application::class)) {
throw new RuntimeException('You need to add "symfony/framework-bundle" as a Composer dependency.');
if (!class_exists(Application::class) || !class_exists(Dotenv::class)) {
throw new LogicException('You need to add "symfony/framework-bundle" and "symfony/dotenv" as Composer dependencies.');
}

$input = new ArgvInput();
Expand Down
17 changes: 9 additions & 8 deletions bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,29 +13,30 @@
use App\Utils\JSON;
use Symfony\Component\Dotenv\Dotenv;

$environmentFile = (string)\getenv('ENVIRONMENT_FILE');
$readableChannel = (string)\getenv('ENV_TEST_CHANNEL_READABLE');
$environmentFile = (string)getenv('ENVIRONMENT_FILE');
$readableChannel = (string)getenv('ENV_TEST_CHANNEL_READABLE');

// Application is started against 'fastest' library, so we need to override database name manually
if (\strlen($readableChannel) > 0) {
// Parse current '.env.test' file
$variables = (new Dotenv(false))->parse(\file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . $environmentFile));
if (strlen($readableChannel) > 0) {
// Parse current environment file - most likely '.env.test' file because `$readableChannel` exists
$variables = (new Dotenv())->parse(file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . $environmentFile));

/** @noinspection PhpUnhandledExceptionInspection */
$applicationConfig = JSON::decode(file_get_contents($variables['APPLICATION_CONFIG']), true);

// Specify new database name for current test env
$databaseName = $applicationConfig['DATABASE_NAME'] . '_' . $readableChannel;

// Replace DATABASE_URL variable with proper database name
$databaseUrl = \str_replace(
$databaseUrl = str_replace(
'/' . $applicationConfig['DATABASE_NAME'] . '?',
'/' . $databaseName . '?',
$applicationConfig['DATABASE_URL']
);

// And finally populate new variables to current environment
\putenv('DATABASE_NAME=' . $databaseName);
\putenv('DATABASE_URL=' . $databaseUrl);
putenv('DATABASE_NAME=' . $databaseName);
putenv('DATABASE_URL=' . $databaseUrl);
}

require __DIR__ . '/config/bootstrap.php';
20 changes: 11 additions & 9 deletions config/bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@

require dirname(__DIR__) . '/vendor/autoload.php';

if (!class_exists(Dotenv::class)) {
throw new LogicException('You need to add "symfony/dotenv" as Composer dependencies.');
}

// Set fastest environment
if (class_exists(FastestEnvironment::class)) {
FastestEnvironment::setFromRequest();
Expand All @@ -14,25 +18,23 @@
// Ensure that current working directory is project root - this is needed to make relative paths to working properly
chdir(dirname(__DIR__));

$localPhpEnvFile = dirname(__DIR__) . '/.env.local.php';

// Load cached env vars if the .env.local.php file exists
// Run "composer dump-env prod" to create it (requires symfony/flex >=1.2)
/** @noinspection UsingInclusionReturnValueInspection */
/** @noinspection PhpIncludeInspection */
if (is_array($env = @include dirname(__DIR__) . '/.env.local.php')
/** @noinspection UsingInclusionReturnValueInspection */
if (is_readable($localPhpEnvFile) && is_array($env = include $localPhpEnvFile)
&& ($_SERVER['APP_ENV'] ?? $_ENV['APP_ENV'] ?? $env['APP_ENV'] ?? null) === ($env['APP_ENV'] ?? null)
) {
foreach ($env as $k => $v) {
$_ENV[$k] ??= (isset($_SERVER[$k]) && strncmp($k, 'HTTP_', 5) !== 0 ? $_SERVER[$k] : $v);
}
} elseif (class_exists(Dotenv::class)) {
// load all the .env files
(new Dotenv(false))->loadEnv(dirname(__DIR__) . '/.env');
} else {
throw new RuntimeException(
'Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.'
);
}

// load all the .env files
(new Dotenv())->loadEnv(dirname(__DIR__) . '/.env');

/** @noinspection AdditionOperationOnArraysInspection */
$_SERVER += $_ENV;
$_SERVER['APP_ENV'] = $_ENV['APP_ENV'] = ($_SERVER['APP_ENV'] ?? $_ENV['APP_ENV'] ?? null) ?: 'dev';
Expand Down
2 changes: 0 additions & 2 deletions psalm.xml
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@

<ignoreFiles>
<directory name="vendor" />

<file name="src/Kernel.php" />
</ignoreFiles>
</projectFiles>

Expand Down
14 changes: 7 additions & 7 deletions src/AutoMapper/RestRequestMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@ abstract class RestRequestMapper implements MapperInterface
/**
* {@inheritdoc}
*
* @param array|object $source
* @param string $targetClass
* @param array|array<int, mixed> $context
* @param array|object $source
* @param string $targetClass
* @param array<int, mixed> $context
*
* @return RestDtoInterface
*/
Expand All @@ -57,9 +57,9 @@ public function map($source, string $targetClass, array $context = []): RestDtoI
/**
* {@inheritdoc}
*
* @param array|object $source
* @param object $destination
* @param array|array<int, mixed> $context
* @param array|object $source
* @param object $destination
* @param array<int, mixed> $context
*
* @return RestDtoInterface
*/
Expand Down Expand Up @@ -117,7 +117,7 @@ private function getObject(Request $request, RestDtoInterface $restDto): RestDto
$transformer = 'transform' . ucfirst($property);

/** @var int|string|array|null $value */
$value = $request->request->get($property);
$value = $request->get($property);

if (method_exists($this, $transformer)) {
/** @var int|string|object|array|null $value */
Expand Down
68 changes: 11 additions & 57 deletions src/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,88 +2,42 @@
declare(strict_types = 1);
/**
* /src/Kernel.php
*
* @author TLe, Tarmo Leppänen <tarmo.leppanen@protacon.com>
*/

namespace App;

use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Routing\RouteCollectionBuilder;
use Throwable;
use function dirname;
use const PHP_VERSION_ID;
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;

/**
* Class Kernel
*
* @package App
* @author TLe, Tarmo Leppänen <tarmo.leppanen@protacon.com>
*/
class Kernel extends BaseKernel
{
use MicroKernelTrait;

private const CONFIG_EXTS = '.{php,xml,yaml,yml}';

/**
* {@inheritdoc}
*/
public function registerBundles(): iterable
{
/** @noinspection PhpIncludeInspection */
/** @noinspection UsingInclusionReturnValueInspection */
$contents = require $this->getProjectDir() . '/config/bundles.php';

foreach ($contents as $class => $envs) {
if ($envs[$this->environment] ?? $envs['all'] ?? false) {
yield new $class();
}
}
}

/** @noinspection PhpMissingParentCallCommonInspection */
/**
* {@inheritdoc}
*/
public function getProjectDir(): string
protected function configureContainer(ContainerConfigurator $container): void
{
return dirname(__DIR__);
$container->import('../config/{packages}/*.yaml');
$container->import('../config/{packages}/' . $this->environment . '/*.yaml');
$container->import('../config/{services}.yaml');
$container->import('../config/{services}_' . $this->environment . '.yaml');
}

/**
* {@inheritdoc}
*
* @throws Throwable
*/
protected function configureContainer(ContainerBuilder $container, LoaderInterface $loader): void
protected function configureRoutes(RoutingConfigurator $routes): void
{
$container->addResource(new FileResource($this->getProjectDir() . '/config/bundles.php'));
$container->setParameter('container.dumper.inline_class_loader', PHP_VERSION_ID < 70400 || $this->debug);
$container->setParameter('container.dumper.inline_factories', true);
$confDir = $this->getProjectDir() . '/config';

$loader->load($confDir . '/{packages}/*' . self::CONFIG_EXTS, 'glob');
$loader->load($confDir . '/{packages}/' . $this->environment . '/*' . self::CONFIG_EXTS, 'glob');
$loader->load($confDir . '/{services}' . self::CONFIG_EXTS, 'glob');
$loader->load($confDir . '/{services}_' . $this->environment . self::CONFIG_EXTS, 'glob');
}

/**
* {@inheritdoc}
*
* @throws Throwable
*/
protected function configureRoutes(RouteCollectionBuilder $routes): void
{
$confDir = $this->getProjectDir() . '/config';

$routes->import($confDir . '/{routes}/' . $this->environment . '/*' . self::CONFIG_EXTS, '/', 'glob');
$routes->import($confDir . '/{routes}/*' . self::CONFIG_EXTS, '/', 'glob');
$routes->import($confDir . '/{routes}' . self::CONFIG_EXTS, '/', 'glob');
$routes->import('../config/{routes}/' . $this->environment . '/*.yaml');
$routes->import('../config/{routes}/*.yaml');
$routes->import('../config/{routes}.yaml');
}
}
12 changes: 6 additions & 6 deletions src/Utils/Tests/Auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
use App\Utils\JSON;
use JsonException;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
use Throwable;
use UnexpectedValueException;
use function array_key_exists;
Expand All @@ -35,16 +35,16 @@
*/
class Auth
{
private ContainerInterface $testContainer;
private KernelInterface $kernel;

/**
* Auth constructor.
*
* @param ContainerInterface $container
* @param KernelInterface $kernel
*/
public function __construct(ContainerInterface $container)
public function __construct(KernelInterface $kernel)
{
$this->testContainer = $container;
$this->kernel = $kernel;
}

/**
Expand Down Expand Up @@ -142,7 +142,7 @@ private function getToken(string $username, string $password): string
if (!array_key_exists($hash, $cache)) {
// Get client
/** @var KernelBrowser $client */
$client = $this->testContainer->get('test.client');
$client = $this->kernel->getContainer()->get('test.client');

// Create request to make login using given credentials
$client->request(
Expand Down
8 changes: 4 additions & 4 deletions tests/Integration/Entity/LogRequestTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ public function testThatGetterReturnsExpectedValue(string $field, string $type,
$logRequest = new LogRequest(
[],
Request::create(''),
Response::create('abcdefgh'),
new Response('abcdefgh'),
new User(),
new ApiKey()
);
Expand Down Expand Up @@ -173,7 +173,7 @@ public function testThatSensitiveDataIsCleanedFromHeaders(
$request = Request::create('');
$request->headers->replace($headers->getArrayCopy());

$logRequest = new LogRequest($properties->getArrayCopy(), $request, Response::create());
$logRequest = new LogRequest($properties->getArrayCopy(), $request, new Response());

static::assertSame($expected->getArrayCopy(), $logRequest->getHeaders());
}
Expand All @@ -197,7 +197,7 @@ public function testThatSensitiveDataIsCleanedFromParameters(
$request = Request::create('', 'POST');
$request->request->replace($parameters->getArrayCopy());

$logRequest = new LogRequest($properties->getArrayCopy(), $request, Response::create());
$logRequest = new LogRequest($properties->getArrayCopy(), $request, new Response());

static::assertSame($expected->getArrayCopy(), $logRequest->getParameters());
}
Expand All @@ -214,7 +214,7 @@ public function testThatSensitiveDataIsCleanedFromParameters(
*/
public function testThatDetermineParametersWorksLikeExpected(string $content, StringableArrayObject $expected): void
{
$logRequest = new LogRequest([], Request::create(''), Response::create());
$logRequest = new LogRequest([], Request::create(''), new Response());

$request = Request::create('', 'GET', [], [], [], [], $content);

Expand Down
2 changes: 1 addition & 1 deletion tests/Integration/Rest/Traits/Methods/CountMethodTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ public function testThatTraitCallsServiceMethods(): void

// Create request and response
$request = Request::create('/count');
$response = Response::create('123');
$response = new Response('123');

$resource
->expects(static::once())
Expand Down
2 changes: 1 addition & 1 deletion tests/Integration/Rest/Traits/Methods/FindMethodTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ public function testThatTraitCallsServiceMethods(): void

// Create request and response
$request = Request::create('/');
$response = Response::create('[]');
$response = new Response('[]');

$resource
->expects(static::once())
Expand Down
2 changes: 1 addition & 1 deletion tests/Integration/Rest/Traits/Methods/IdsMethodTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ public function testThatTraitCallsServiceMethods(): void

// Create request and response
$request = Request::create('/');
$response = Response::create('[]');
$response = new Response('[]');

$resource
->expects(static::once())
Expand Down

0 comments on commit 2d8bd15

Please sign in to comment.