Skip to content
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
1 change: 0 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
],
"require": {
"php": ">=8.1",
"symfony/property-access": ">=5.4,<8",
"psr/event-dispatcher": "^1.0"
},
"require-dev": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
namespace Finite\Extension\Symfony\Bundle\DependencyInjection;

use Finite\Extension\Twig\FiniteExtension as TwigExtension;
use Finite\Extractor\MemoizedStatePropertyExtractor;
use Finite\Extractor\ReflectionStatePropertyExtractor;
use Finite\Extractor\StatePropertyExtractor;
use Finite\StateMachine;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
Expand All @@ -18,8 +21,11 @@ public function load(array $configs, ContainerBuilder $container): void
{
$container->addDefinitions(
[
StatePropertyExtractor::class => (new Definition(MemoizedStatePropertyExtractor::class))
->setArgument('$decorated', new Definition(ReflectionStatePropertyExtractor::class)),
StateMachine::class => (new Definition(StateMachine::class))
->setArgument('$dispatcher', new Reference('event_dispatcher'))
->setArgument('$statePropertyExtractor', new Reference(StatePropertyExtractor::class))
->setPublic(true),
TwigExtension::class => (new Definition(TwigExtension::class))
->setArgument('$stateMachine', new Reference(StateMachine::class))
Expand Down
33 changes: 33 additions & 0 deletions src/Extractor/MemoizedStatePropertyExtractor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

declare(strict_types=1);

namespace Finite\Extractor;

final class MemoizedStatePropertyExtractor implements StatePropertyExtractor
{
use StatePropertyExtractorTrait;

/**
* @var array <class-string, array<int, \ReflectionProperty>>
*/
private array $cache = [];

public function __construct(
private readonly StatePropertyExtractor $decorated = new ReflectionStatePropertyExtractor(),
) {
}

#[\Override]
public function extractAll(object $object): array
{
if (isset($this->cache[$object::class])) {
/** @var array<int, \ReflectionProperty> $value */
$value = $this->cache[$object::class];

return $value;
}

return $this->cache[$object::class] = $this->decorated->extractAll($object);
}
}
52 changes: 52 additions & 0 deletions src/Extractor/ReflectionStatePropertyExtractor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

declare(strict_types=1);

namespace Finite\Extractor;

use Finite\State;

final class ReflectionStatePropertyExtractor implements StatePropertyExtractor
{
use StatePropertyExtractorTrait;

#[\Override]
public function extractAll(object $object): array
{
$properties = [];

$reflectionClass = new \ReflectionClass($object);
/** @psalm-suppress DocblockTypeContradiction */
do {
foreach ($reflectionClass->getProperties() as $property) {
/** @var \ReflectionUnionType|\ReflectionIntersectionType|\ReflectionNamedType $reflectionType */
$reflectionType = $property->getType();
if (null === $reflectionType) {
continue;
}

if ($reflectionType instanceof \ReflectionUnionType) {
continue;
}

if ($reflectionType instanceof \ReflectionIntersectionType) {
continue;
}

/** @var class-string $name */
$name = $reflectionType->getName();
if (!enum_exists($name)) {
continue;
}

$reflectionEnum = new \ReflectionEnum($name);
/** @psalm-suppress TypeDoesNotContainType */
if ($reflectionEnum->implementsInterface(State::class)) {
$properties[] = $property;
}
}
} while ($reflectionClass = $reflectionClass->getParentClass());

return $properties;
}
}
18 changes: 18 additions & 0 deletions src/Extractor/StatePropertyExtractor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

declare(strict_types=1);

namespace Finite\Extractor;

interface StatePropertyExtractor
{
/**
* @param class-string|null $stateClass
*/
public function extract(object $object, ?string $stateClass = null): \ReflectionProperty;

/**
* @return array<int, \ReflectionProperty>
*/
public function extractAll(object $object): array;
}
49 changes: 49 additions & 0 deletions src/Extractor/StatePropertyExtractorTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

declare(strict_types=1);

namespace Finite\Extractor;

use Finite\Exception\BadStateClassException;
use Finite\Exception\NonUniqueStateException;
use Finite\Exception\NoStateFoundException;

trait StatePropertyExtractorTrait
{
/**
* @param class-string|null $stateClass
*/
#[\Override]
public function extract(object $object, ?string $stateClass = null): \ReflectionProperty
{
if ($stateClass && !enum_exists($stateClass)) {
throw new NoStateFoundException(\sprintf('Enum "%s" does not exists', $stateClass));
}

$properties = $this->extractAll($object);
if (null !== $stateClass) {
foreach ($properties as $property) {
if ((string) $property->getType() === $stateClass) {
return $property;
}
}

throw new BadStateClassException(\sprintf('Found no state on object "%s" with class "%s"', $object::class, $stateClass));
}

if (1 === \count($properties)) {
return $properties[0];
}

if (\count($properties) > 1) {
throw new NonUniqueStateException('Found multiple states on object '.$object::class);
}

throw new NoStateFoundException('Found no state on object '.$object::class);
}

/**
* @return array<int, \ReflectionProperty>
*/
abstract public function extractAll(object $object): array;
}
99 changes: 11 additions & 88 deletions src/StateMachine.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,11 @@
use Finite\Event\EventDispatcher;
use Finite\Event\PostTransitionEvent;
use Finite\Event\PreTransitionEvent;
use Finite\Exception\BadStateClassException;
use Finite\Exception\NonUniqueStateException;
use Finite\Exception\NoStateFoundException;
use Finite\Exception\TransitionNotReachableException;
use Finite\Extractor\MemoizedStatePropertyExtractor;
use Finite\Extractor\StatePropertyExtractor;
use Finite\Transition\TransitionInterface;
use Psr\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\PropertyAccess\PropertyAccess;

/**
* @api
Expand All @@ -23,6 +21,7 @@ class StateMachine
{
public function __construct(
private readonly EventDispatcherInterface $dispatcher = new EventDispatcher(),
private readonly StatePropertyExtractor $statePropertyExtractor = new MemoizedStatePropertyExtractor(),
) {
}

Expand All @@ -35,7 +34,7 @@ public function apply(object $object, string $transitionName, ?string $stateClas
throw new TransitionNotReachableException('Unable to apply transition '.$transitionName);
}

$property = $this->extractStateProperty($object, $stateClass);
$property = $this->statePropertyExtractor->extract($object, $stateClass);
$fromState = $this->extractState($object, $stateClass);
$transition = array_values(
array_filter(
Expand All @@ -47,13 +46,8 @@ public function apply(object $object, string $transitionName, ?string $stateClas
$this->dispatcher->dispatch(new PreTransitionEvent($object, $transition, $fromState));

$transition->process($object);
PropertyAccess::createPropertyAccessor()->setValue(
$object,
$property->getName(),
$transition->getTargetState(),
);
$property->setValue($object, $transition->getTargetState());

/** @var object $object */
$this->dispatcher->dispatch(new PostTransitionEvent($object, $transition, $fromState));
}

Expand Down Expand Up @@ -105,15 +99,15 @@ public function getStateClasses(object $object): array
return array_filter(
array_map(
fn (\ReflectionProperty $property): string => (string) $property->getType(),
$this->extractStateProperties($object),
$this->statePropertyExtractor->extractAll($object),
),
fn (?string $name): bool => enum_exists($name),
);
}

public function hasState(object $object): bool
{
return \count($this->extractStateProperties($object)) > 0;
return \count($this->statePropertyExtractor->extractAll($object)) > 0;
}

public function getDispatcher(): EventDispatcherInterface
Expand All @@ -126,82 +120,11 @@ public function getDispatcher(): EventDispatcherInterface
*/
private function extractState(object $object, ?string $stateClass = null): State&\BackedEnum
{
$property = $this->extractStateProperty($object, $stateClass);

/** @psalm-suppress MixedReturnStatement */
return PropertyAccess::createPropertyAccessor()->getValue($object, $property->getName());
}

/**
* @param class-string|null $stateClass
*/
private function extractStateProperty(object $object, ?string $stateClass = null): \ReflectionProperty
{
if ($stateClass && !enum_exists($stateClass)) {
throw new NoStateFoundException(\sprintf('Enum "%s" does not exists', $stateClass));
}
$property = $this->statePropertyExtractor->extract($object, $stateClass);

$properties = $this->extractStateProperties($object);
if (null !== $stateClass) {
foreach ($properties as $property) {
if ((string) $property->getType() === $stateClass) {
return $property;
}
}

throw new BadStateClassException(\sprintf('Found no state on object "%s" with class "%s"', $object::class, $stateClass));
}

if (1 === \count($properties)) {
return $properties[0];
}

if (\count($properties) > 1) {
throw new NonUniqueStateException('Found multiple states on object '.$object::class);
}

throw new NoStateFoundException('Found no state on object '.$object::class);
}

/**
* @return array<int, \ReflectionProperty>
*/
private function extractStateProperties(object $object): array
{
$properties = [];

$reflectionClass = new \ReflectionClass($object);
/** @psalm-suppress DocblockTypeContradiction */
do {
foreach ($reflectionClass->getProperties() as $property) {
/** @var \ReflectionUnionType|\ReflectionIntersectionType|\ReflectionNamedType $reflectionType */
$reflectionType = $property->getType();
if (null === $reflectionType) {
continue;
}

if ($reflectionType instanceof \ReflectionUnionType) {
continue;
}

if ($reflectionType instanceof \ReflectionIntersectionType) {
continue;
}

/** @var class-string $name */
$name = $reflectionType->getName();
if (!enum_exists($name)) {
continue;
}

$reflectionEnum = new \ReflectionEnum($name);
/** @psalm-suppress TypeDoesNotContainType */
if ($reflectionEnum->implementsInterface(State::class)) {
$properties[] = $property;
}
}
} while ($reflectionClass = $reflectionClass->getParentClass());
/** @var State&\BackedEnum $value */
$value = $property->getValue($object);

return $properties;
return $value;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Finite\Extension\Symfony\Bundle\DependencyInjection\FiniteExtension;
use Finite\Extension\Twig\FiniteExtension as TwigExtension;
use Finite\Extractor\StatePropertyExtractor;
use Finite\StateMachine;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ContainerBuilder;
Expand All @@ -20,7 +21,8 @@ public function testItLoadsServices(): void

$container->expects($this->once())->method('addDefinitions')->with(
$this->logicalAnd(
$this->countOf(2),
$this->countOf(3),
$this->arrayHasKey(StatePropertyExtractor::class),
$this->arrayHasKey(StateMachine::class),
$this->arrayHasKey(TwigExtension::class),
),
Expand Down
28 changes: 28 additions & 0 deletions tests/Extractor/MemoizedStatePropertyExtractorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace Finite\Tests\Extractor;

use Finite\Extractor\MemoizedStatePropertyExtractor;
use Finite\Extractor\StatePropertyExtractor;
use PHPUnit\Framework\TestCase;

final class MemoizedStatePropertyExtractorTest extends TestCase
{
public function testItMemoizeResult(): void
{
$decorated = $this->createMock(StatePropertyExtractor::class);
$extractor = new MemoizedStatePropertyExtractor($decorated);

$decorated
->expects($this->once())
->method('extractAll')
->with($this->isInstanceOf(\stdClass::class))
->willReturn([$this->createMock(\ReflectionProperty::class)]);

$object = new \stdClass();
$extractor->extractAll($object);
$extractor->extractAll($object);
}
}
Loading