Skip to content

Engine contexts should be immutable and implement Context::with() methods #28

Description

@ericges

As a result, engine should implement setContext(ContextInterface)

Making it possible to replace a context with a modified version.

Example

current/legacy

<?php

namespace App\Flare\Mod;

use HeimrichHannot\FlareBundle\Engine\Context\InteractiveContext;
use HeimrichHannot\FlareBundle\Engine\Engine;
use HeimrichHannot\FlareBundle\Engine\Mod\AbstractMod;
use Symfony\Component\OptionsResolver\OptionsResolver;

class PageItemsMod extends AbstractMod
{
    public static function getType(): string
    {
        return 'app.page_items';
    }

    public function __invoke(Engine $engine, array $options): void
    {
        $context = $engine->getContext();

        if (!$context instanceof InteractiveContext) {
            return;
        }

        $context->paginatorConfig = $context->getPaginatorConfig()->with(
            itemsPerPage: $options['items_per_page'],
        );
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->define('items_per_page')
            ->default(0)
            ->allowedTypes('int')
            ->allowedValues(static fn (int $value): bool => $value >= 0);
    }
}

future proposal

<?php

namespace App\Flare\Mod;

use HeimrichHannot\FlareBundle\Engine\Context\InteractiveContext;
use HeimrichHannot\FlareBundle\Engine\Engine;
use HeimrichHannot\FlareBundle\Engine\Mod\AbstractMod;
use Symfony\Component\OptionsResolver\OptionsResolver;

class PageItemsMod extends AbstractMod
{
    public static function getType(): string
    {
        return 'app.page_items';
    }

    public function __invoke(Engine $engine, array $options): void
    {
        $context = $engine->getContext();

        if (!$context instanceof InteractiveContext) {
            return;
        }

		$engine->setContext(
			$context->withPaginatorConfig(
				$context->getPaginatorConfig()->with(
		            itemsPerPage: $options['items_per_page'],
				)
			)
		);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->define('items_per_page')
            ->default(0)
            ->allowedTypes('int')
            ->allowedValues(static fn (int $value): bool => $value >= 0);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions