Meta Data

Additional data was introduced since the release of the Validation feature. You're able to send additional data alongside the main payload in order to use it within your validation class. This can come in handy when for instance you want to be able to validate a value which isn't available inside your main object or is strictly private and therefore can not be sent within the HTTP request body.

Basic idea

<?php

declare(strict_types=1);

namespace Basic\Example\Plugin\Magento\Newsletter\Model;

use MageHook\Hook\ManagerInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Newsletter\Model\Subscriber as Subject;
use Magento\Store\Model\StoreManagerInterface;

/**
 * Class Subscriber
 *
 * @package Basic\Example\Plugin\Magento\Newsletter\Model
 */
class Subscriber
{
    /** @var HookManagerInterface $hookEventsManagerInterface */
    protected $hookEventsManagerInterface;

    /**
     * OrderRepositoryInterface constructor.
     * @param HookManagerInterface $hookEventsManagerInterface
     */
    public function __construct(
        HookManagerInterface $hookEventsManagerInterface
    ) {
        $this->hookEventsManagerInterface = $hookEventsManagerInterface;
    }

    /**
     * @param Subject $subject
     *
     * @return Subject
     */
    public function afterSave(Subject $subject): Subject
    {
        if ($subject->isStatusChanged()) {
            $additional = [];
            
            try {
                $store = $this->storeManagerInterface->getStore($subject->getStoreId());
                
                $additional['store_name']   = $store->getName();
                $additional['store_active'] = (bool) $store->getIsActive();
            } catch (NoSuchEntityException $exception) {
                // Just send the webhook without any additional data
            }

            $this->hookEventsManagerInterface->fire('newsletter_subscription_change', $subject->getData(), $additional);
        }

        return $subject;
    }
}

In this example, we just listen to a newsletter subscription change and get some extra store information based on the store ID who have been reached out via the $subject data. This can also be done within for instance the Validation class, but we try to keep that one as clean as possible. Still, in this example, you do have to check if the $additional['store_name'] and $additional['store_active'] are set.

The public key

Along with the additional data option comes the public array key. This key has been reserved for all the data you want to send along extra and will be included in the final request body.

When we refer back to the example above, this would look like this:

use MageHook\Hook\Model\Queue\OperationMessageInterface as OperationMessage;

...
$additional[OperationMessage::PUBLIC_DATA_KEY] = [
    'store_name'  => $store->getName(),
    'store_active => (bool) $store->getIsActive()
];
...

Last updated