Valinor/tests/Functional/Definition/Repository/Cache/Compiler/FunctionDefinitionCompilerTest.php
Romain Canon 2d70efbfbb feat: extract file watching feature in own cache implementation
When the application runs in a development environment, the cache
implementation should be decorated with `FileWatchingCache` to prevent
invalid cache entries states, which can result in the library not
behaving as expected (missing property value, callable with outdated
signature, …).

```php
$cache = new \CuyZ\Valinor\Cache\FileSystemCache('path/to/cache-dir');

if ($isApplicationInDevelopmentEnvironment) {
    $cache = new \CuyZ\Valinor\Cache\FileWatchingCache($cache);
}

(new \CuyZ\Valinor\MapperBuilder())
    ->withCache($cache)
    ->mapper()
    ->map(SomeClass::class, [/* … */]);
```

This behavior now forces to explicitly inject `FileWatchingCache`, when
it was done automatically before; but because it shouldn't be used in
a production environment, it will increase overall performance.
2022-05-23 20:28:02 +02:00

73 lines
2.1 KiB
PHP

<?php
declare(strict_types=1);
namespace CuyZ\Valinor\Tests\Functional\Definition\Repository\Cache\Compiler;
use CuyZ\Valinor\Definition\EmptyAttributes;
use CuyZ\Valinor\Definition\FunctionDefinition;
use CuyZ\Valinor\Definition\ParameterDefinition;
use CuyZ\Valinor\Definition\Parameters;
use CuyZ\Valinor\Definition\Repository\Cache\Compiler\FunctionDefinitionCompiler;
use CuyZ\Valinor\Type\Types\NativeStringType;
use Error;
use PHPUnit\Framework\TestCase;
use stdClass;
final class FunctionDefinitionCompilerTest extends TestCase
{
private FunctionDefinitionCompiler $compiler;
protected function setUp(): void
{
parent::setUp();
$this->compiler = new FunctionDefinitionCompiler();
}
public function test_function_is_compiled_correctly(): void
{
$function = new FunctionDefinition(
'foo',
'foo:42-1337',
'foo/bar',
stdClass::class,
new Parameters(
new ParameterDefinition(
'bar',
'foo::bar',
NativeStringType::get(),
false,
false,
'foo',
EmptyAttributes::get()
)
),
NativeStringType::get()
);
$code = $this->compiler->compile($function);
$compiledFunction = $this->eval($code);
self::assertInstanceOf(FunctionDefinition::class, $compiledFunction);
self::assertSame('foo', $compiledFunction->name());
self::assertSame('foo:42-1337', $compiledFunction->signature());
self::assertSame('foo/bar', $compiledFunction->fileName());
self::assertSame(stdClass::class, $compiledFunction->class());
self::assertTrue($compiledFunction->parameters()->has('bar'));
self::assertInstanceOf(NativeStringType::class, $compiledFunction->returnType());
}
/**
* @return FunctionDefinition|bool
*/
private function eval(string $code)
{
try {
return eval("return $code;");
} catch (Error $exception) {
self::fail($exception->getMessage());
}
}
}