4. Developer corner

Target group: Developers

Writing own variable resolvers

With variables it is possible to add information to a process start which is resolved when submitting a form. This extension ships some variable resolvers already, e.g. for translation or language information.

You can write your own variable resolvers dependent on your needs. Variable resolvers are implemented as PSR-14 event listeners.

The event listener receives the event Brotkrueml\JobRouterBase\Event\ResolveFinisherVariableEvent. It provides the following methods:

getFieldType(): int

Get the field type, like 1 for text or 2 for int. Have a look in the class Brotkrueml\JobRouterBase\Enumeration\FieldTypeEnumeration for the available field types.

getValue(): string

Get the current value of the field. One or more variables can be defined inside.

setValue(string $value): void

Set the new value after resolving one or more variables.

getCorrelationId(): string

Get the current correlation ID.

getFormValues(): array

Get the form values, e.g. ['company' => 'Acme Ltd.', 'name' => 'John Smith'].

getRequest(): \\Psr\\Http\\Message\\ServerRequestInterface

Get the current request.

Hint

Some variable resolvers are already shipped with the extension. Have a look into the folder Classes/Domain/VariableResolver for implementation details.

Example

As an example we want to resolve a variable to a cookie value.

  1. Create the event listener

    <?php
    declare(strict_types=1);
    
    namespace YourVender\YourExtension\EventListener;
    
    use Brotkrueml\JobRouterBase\Event\ResolveFinisherVariableEvent;
    use Psr\Http\Message\ServerRequestInterface;
    
    final class TheCookieVariableResolver
    {
       private const COOKIE_NAME = 'the_cookie';
       private const VARIABLE = '{__theCookieValue}';
    
       public function __invoke(ResolveFinisherVariableEvent $event): void
       {
          $value = $event->getValue();
    
          if (str_pos($value, self::VARIABLE) === false) {
             // Variable is not available, do nothing
             return;
          }
    
          $cookies = $event->getRequest()->getCookieParams();
    
          $variableValue = $cookies[self::COOKIE_NAME] ?? '';
          $value = str_replace(self::VARIABLE, $variableValue, $value);
    
          $event->setValue($value);
       }
    }
    

    Important

    Variables have to start with {__. Otherwise the variable resolver is not called for a value.

  2. Register your event listener in Configuration/Services.yaml

    services:
       YourVendor\YourExtension\EventListener\TheCookieVariableResolver:
          tags:
             - name: event.listener
               identifier: 'your-extension/cookie-variable-resolver'
               event: Brotkrueml\JobRouterBase\Event\ResolveFinisherVariableEvent