Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PHP Attributes for Environment and Configuration Variables, and Exception Handling #55

Merged
merged 2 commits into from
Jun 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/Attribute/Config.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

namespace Spiral\Testing\Attribute;

use Attribute;
use Closure;

#[Attribute(flags: Attribute::TARGET_METHOD|Attribute::IS_REPEATABLE)]
final class Config
{
public ?Closure $closure;

public function __construct(
public string $path,
public mixed $value = null,
callable $closure = null,
) {
$this->closure = $closure !== null ? $closure(...) : null;
}
}
17 changes: 17 additions & 0 deletions src/Attribute/Env.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

declare(strict_types=1);

namespace Spiral\Testing\Attribute;

use Attribute;

#[Attribute(flags: Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
final class Env
{
public function __construct(
public readonly string $key,
public readonly int|string|null|bool $value = null,
) {
}
}
12 changes: 12 additions & 0 deletions src/Attribute/WithoutExceptionHandling.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

declare(strict_types=1);

namespace Spiral\Testing\Attribute;

use Attribute;

#[Attribute(flags: Attribute::TARGET_METHOD)]
final class WithoutExceptionHandling
{
}
36 changes: 32 additions & 4 deletions src/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,9 @@ public function defineDirectories(string $root): array
{
return [
'root' => $root,
'app' => $root.'/app',
'runtime' => $root.'/runtime',
'cache' => $root.'/runtime/cache',
'app' => $root . '/app',
'runtime' => $root . '/runtime',
'cache' => $root . '/runtime/cache',
];
}

Expand All @@ -80,7 +80,8 @@ protected function setUp(): void
parent::setUp();

if (static::MAKE_APP_ON_STARTUP) {
$this->initApp(static::ENV);
$variables = [...static::ENV, ...$this->getEnvVariablesFromConfig()];
$this->initApp($variables);
}
}

Expand Down Expand Up @@ -142,6 +143,9 @@ public function makeApp(array $env = []): AbstractKernel
public function initApp(array $env = []): void
{
$this->app = $this->makeApp($env);
$this->suppressExceptionHandlingIfAttributeDefined();
$this->updateConfigFromAttribute();

(new \ReflectionClass(ContainerScope::class))
->setStaticPropertyValue('container', $this->app->getContainer());
}
Expand All @@ -166,4 +170,28 @@ protected function tearDown(): void
(new \ReflectionClass(ContainerScope::class))
->setStaticPropertyValue('container', null);
}


/**
* @template TClass
*
* @param class-string<TClass> $attribute
* @param null|non-empty-string $method Method name
*
* @return array<int, TClass>
*/
protected function getTestAttributes(string $attribute, string $method = null): array
{
try {
$methodName = $method ?? (\method_exists($this, 'name') ? $this->name() : $this->getName(false));
$result = [];
$attributes = (new \ReflectionMethod($this, $methodName))->getAttributes($attribute);
foreach ($attributes as $attr) {
$result[] = $attr->newInstance();
}
return $result;
} catch (\Throwable) {
return [];
}
}
}
9 changes: 9 additions & 0 deletions src/Traits/InteractsWithConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Spiral\Config\ConfiguratorInterface;
use Spiral\Config\Patch\Set;
use Spiral\Core\ConfigsInterface;
use Spiral\Testing\Attribute;

trait InteractsWithConfig
{
Expand Down Expand Up @@ -52,4 +53,12 @@ public function updateConfig(string $key, mixed $data): void

$this->getConfigs()->modify($config, new Set($key, $data));
}

private function updateConfigFromAttribute(): void
{
foreach ($this->getTestAttributes(Attribute\Config::class) as $attribute) {
\assert($attribute instanceof Attribute\Config);
$this->updateConfig($attribute->path, $attribute->closure?->__invoke() ?? $attribute->value);
}
}
}
17 changes: 17 additions & 0 deletions src/Traits/InteractsWithCore.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Spiral\Boot\Bootloader\BootloaderInterface;
use Spiral\Boot\Environment;
use Spiral\Boot\EnvironmentInterface;
use Spiral\Testing\Attribute;

trait InteractsWithCore
{
Expand Down Expand Up @@ -175,4 +176,20 @@ public function assertEnvironmentHasKey(string $key): void
\sprintf('Environment does not have key with name [%s].', $key)
);
}

/**
* @return array<non-empty-string, mixed>
*/
private function getEnvVariablesFromConfig(): array
{
$variables = [];

foreach ($this->getTestAttributes(Attribute\Env::class) as $attribute) {
\assert($attribute instanceof Attribute\Env);

$variables[$attribute->key] = $attribute->value;
}

return $variables;
}
}
8 changes: 8 additions & 0 deletions src/Traits/InteractsWithExceptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Spiral\Exceptions\ExceptionHandlerInterface;
use Spiral\Exceptions\ExceptionRendererInterface;
use Spiral\Exceptions\Verbosity;
use Spiral\Testing\Attribute\WithoutExceptionHandling;

trait InteractsWithExceptions
{
Expand Down Expand Up @@ -48,4 +49,11 @@ public function report(\Throwable $exception,): void
}
);
}

private function suppressExceptionHandlingIfAttributeDefined(): void
{
if (\count($this->getTestAttributes(WithoutExceptionHandling::class)) > 0) {
$this->withoutExceptionHandling();
}
}
}
34 changes: 34 additions & 0 deletions tests/src/Attribute/ConfigTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

declare(strict_types=1);

namespace Spiral\Testing\Tests\Attribute;

use Spiral\Storage\Config\StorageConfig;
use Spiral\Testing\Attribute\Config;
use Spiral\Testing\Tests\TestCase;

final class ConfigTest extends TestCase
{
public function testDefaultSettings(): void
{
$config = $this->getConfig(StorageConfig::CONFIG);
$this->assertSame('uploads', $config['default']);
}

#[Config('storage.default', 'replaced')]
public function testReplaceUsingAttribute(): void
{
$config = $this->getConfig(StorageConfig::CONFIG);
$this->assertSame('replaced', $config['default']);
}

#[Config('storage.default', 'replaced')]
#[Config('storage.servers.static.adapter', 'test')]
public function testMultipleAttributes(): void
{
$config = $this->getConfig(StorageConfig::CONFIG);
$this->assertSame('replaced', $config['default']);
$this->assertSame('test', $config['servers']['static']['adapter']);
}
}
37 changes: 37 additions & 0 deletions tests/src/Attribute/EnvTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

declare(strict_types=1);

namespace Spiral\Testing\Tests\Attribute;

use Spiral\Testing\Attribute\Env;
use Spiral\Testing\Tests\TestCase;

final class EnvTest extends TestCase
{
public const ENV = [
'FOO' => 'BAR',
'BAZ' => 'QUX'
];

public function testDefaultEnv(): void
{
$this->assertEnvironmentValueSame('FOO', 'BAR');
$this->assertEnvironmentValueSame('BAZ', 'QUX');
}

#[Env('FOO', 'BAZ')]
public function testEnvFromAttribute(): void
{
$this->assertEnvironmentValueSame('FOO', 'BAZ');
$this->assertEnvironmentValueSame('BAZ', 'QUX');
}

#[Env('FOO', 'BAZ')]
#[Env('BAZ', 'BAZ')]
public function testMultipleAttributes(): void
{
$this->assertEnvironmentValueSame('FOO', 'BAZ');
$this->assertEnvironmentValueSame('BAZ', 'BAZ');
}
}
40 changes: 40 additions & 0 deletions tests/src/Attribute/WithoutExceptionHandlingTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

declare(strict_types=1);

namespace Spiral\Testing\Tests\Attribute;

use Spiral\Exceptions\ExceptionHandler;
use Spiral\Exceptions\ExceptionHandlerInterface;
use Spiral\Testing\Attribute\WithoutExceptionHandling;
use Spiral\Testing\Tests\TestCase;

final class WithoutExceptionHandlingTest extends TestCase
{
public function testDefaultHandler(): void
{
$this->assertInstanceOf(
ExceptionHandler::class,
$this->getContainer()->get(ExceptionHandlerInterface::class)
);
}

public function testSuppressWithMethod(): void
{
$this->withoutExceptionHandling();

$this->assertNotInstanceOf(
ExceptionHandler::class,
$this->getContainer()->get(ExceptionHandlerInterface::class)
);
}

#[WithoutExceptionHandling]
public function testSuppressWithAttribute(): void
{
$this->assertNotInstanceOf(
ExceptionHandler::class,
$this->getContainer()->get(ExceptionHandlerInterface::class)
);
}
}