Skip to content

Introduction

Magewire knowledge required

It is highly advisable to possess a foundational understanding of Magewire in order to fully leverage the Evaluation API concept. Much of its functionality is inspired by Magewire's state handling, transitioning seamlessly between backend and frontend operations.

The evaluation API is a crucial concept for many dynamic components operating within the checkout process. Its primary purpose is to enable developers to transmit an evaluation state from the backend to the frontend. This evaluation state could represent various scenarios, such as a specific value required to meet specified requirements before proceeding. From the backend's viewpoint, this component already possesses an evaluation state with a result type of "Error Message". This error message can be triggered either immediately or when a specific frontend action occurs, such as pressing the proceed to next step button.

In essence, the Evaluation API serves as a powerful mechanism for seamlessly defining a comprehensive set of frontend instructions, all orchestrated via the backend and bridging the gap between backend processes and frontend interactions.

The Evaluation API spans beyond Magewire components, integrated into diverse contexts since version 1.1.13.

Why use it?

The Evaluation API provides an extensible foundation for passing certain instructions to the frontend both when loading the checkout and subsequent Magewire update requests. Additionally, maintainability is improved because it is driven by the backend which allows Magento goodies (such as Plugins) to be used in order to change the behaviour if/when required.

Example scenario

Consider the following example where we have a numeric value and two buttons - one to increase the value and one to decrease it.

From the backend point of view, when the value doesn't meet its requirements, the component class returns an evaluation result of "Error Message", containing a user-friendly prompt to instruct the customer to increment the value before they can proceed. Now, remember, this is merely the state transmitted to the frontend. As long as the customer doesn't initiate any actions, nothing will happen.

On the frontend, the customer encounters a value 0 and therefore clicks the "increment" button. Being a Magewire-driven component, the action is sent back to the server, where the evaluation state undergoes automatic re-evaluation after Magewire completes its full update lifecycle. This time, the value has been incremented, leading to a successful evaluation result.

Upon receiving the server's response, the Evaluation API updates the component's previous evaluation state to reflect the successful result, thereby removing any restrictions and marking the component as completed.

<?php

class ExampleScenario extends \Magewirephp\Magewire\Component implements \Hyva\Checkout\Model\Magewire\Component\EvaluationInterface
{
    public int $count = 0;

    public function increment()
    {
        $this->count++;
    }

    public function decrements()
    {
        $this->count--;
    }

    // Evaluated upon page load and after triggering the increment or decrement actions.
    public function evaluateCompletion(EvaluationResultFactory $resultFactory): EvaluationResult
    {
        if ($this->count > 0) {
            // Mark the component as completed. This should be the final status if all functions are operating correctly.
            return $resultFactory->createSuccess();
        }

        // This triggers a Magento flash message to inform customers when attempting to navigate forward or place an order.
        return $resultFactory->createErrorMessage()
            ->withMessage('Count value must be greater than zero.')
            ->withVisibilityDuration(5000)
            ->asWarning();

        // Initiates a custom window event when customers attempt to navigate forward or place an order.
        return $resultFactory->createEvent()
            ->withCustomEvent('count-failure')
    }
}

Dispatch immediately

In certain scenarios, specific evaluation results feature a dispatch capability, empowering developers to chain the dispatch() method. This action prevents the result from being bound to a button-click trigger, ensuring that the message is promptly displayed as soon as the XHR response is received from the server.

<input type="number" wire:model="count"/>

<button type="button" wire:click="increment">Increment</button>
<button type="button" wire:click="decrement">Decrement</button>

Example result

The Evaluation API operates on a server-driven basis, meaning results are processed either upon page rendering or when triggered by certain Magewire updates, such as method calls or value syncing. In the event of an error message, it is automatically bound to the Validation API by default. Consequently, the message will promptly display once the customer presses the primary button in the checkout navigation bar.

Result type requirements

Hyvä Checkout comes equipped with various evaluation result types by default. These types are available in Hyva\Checkout\Model\Magewire\Component\Evaluation, where additional result types have been introduced across different versions. Therefore, available result types may differ depending on the version installed.

Backend type class

When implementing a component with the EvaluationInterface, it's necessary to include an evaluateCompletion() method within the component. This method automatically receives the $resultFactory as an argument, enabling developers to easily generate the desired result.

<?php

class Event extends \Hyva\Checkout\Model\Magewire\Component\Evaluation\EvaluationResult
{
    // Inject the required (reusable) capabilities.
    use \Hyva\Checkout\Model\Magewire\Component\Evaluation\Concern\DetailsCapabilities;
    use \Hyva\Checkout\Model\Magewire\Component\Evaluation\Concern\DispatchCapabilities;

    public const TYPE = 'event';

    private string $event = 'evaluation:event:default';

    public function getArguments(\Magewirephp\Magewire\Component $component): array
    {
        return [
            'event' => $this->event,
            'detail' => $this->getDetails($component)
        ];
    }

    // Offer developers the flexibility to execute custom events.
    public function withCustomEvent(string $event): self
    {
        $this->event = $event;

        // Always return $this to allow method chaining.
        return $this;
    }
}

Capabilities

Capabilities refer to reusable Traits that are adaptable for various scenarios in order to cater for different requirements. Put simply, each result type can possess its own unique set of capabilities. When utilized, developers are tasked with defining the relevant arguments within the getArguments() result array.

<?php

class CustomResultType extends \Hyva\Checkout\Model\Magewire\Component\Evaluation\EvaluationResult
{
    // Injects a 'withStackPosition' method.
    use \Hyva\Checkout\Model\Magewire\Component\Evaluation\Concern\StackingCapabilities;

    public function getArguments(Component $component): array
    {
        return [
            'stack' => [
                'position' => $this->stackPosition // $stackPosition by default returns 500.
            ]
        ];
    }
}

All available capabilities can be found in Hyva\Checkout\Model\Magewire\Component\Evaluation\Concern.

Frontend processor

Each result must have its own unique result type processor from a frontend perspective. A processor is simply a callback that will be automatically picked up either during page rendering or when the component is updated.

Before 1.1.12 use hyvaCheckout.evaluation.processors['event'] = () => {}

hyvaCheckout.evaluation.registerProcessor('event', (component, el, result) => {
    if (result.dispatch || false) {
        window.dispatchEvent(new CustomEvent(result.arguments.event, {detail: result.arguments.detail}))

        return result.result;
    }

    // Bind it onto the validation API to be triggered on a primary button click.
    hyvaCheckout.validation.register(
        result.hash,
        () => window.dispatchEvent(new CustomEvent(result.arguments.event, {detail: result.arguments.detail})),
        el,
        result.id
    )

    return result.result;
})

The callback 'result' argument

The result arguments has a fixed set of variables evaluated by the checkout Evaluation Hydrator.

  • arguments array: Type arguments, which can vary per result type.
  • dispatch bool: To be dispatched immediately or not.
  • result bool: Positive or negative type result.
  • type string: Result type name.
  • id string: The Magewire component ID.
  • hash string: SHA1 hash of the result array values.

More insights can be found in: \Hyva\Checkout\Model\Magewire\Component\Hydrator\Evaluation