DEPRECATION WARNING

This documentation is not using the current rendering mechanism and is probably outdated. The extension maintainer should switch to the new system. Details on how to use the rendering mechanism can be found here.

Data pre-processor service

Gives the possibility to modify the data used to create an object, just before it is converted.

For instance, you can use this feature to dynamically change the value of an input by the result of an external service.

Usage

You can activate this service for a given configuration object by attaching it to the ServiceFactory in the static function getConfigurationObjectServices(). Use the constant ServiceInterface::SERVICE_DATA_PRE_PROCESSOR as an identifier for this service (see example below).

You then have to implement the interface DataPreProcessorInterface in every class which needs this feature, and write your own public static function dataPreProcessor(DataPreProcessor $data) implementation.

Attention

Please be aware that this feature will not run more than once on configuration objects which use the CacheService. It means that in this case you should not use any function which can return dynamic values in here, as it will be called only once.

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
use Romm\ConfigurationObject\ConfigurationObjectInterface;
use Romm\ConfigurationObject\Service\ServiceFactory;
use Romm\ConfigurationObject\Traits\ConfigurationObject\DefaultConfigurationObjectTrait;
use Romm\ConfigurationObject\Service\ServiceInterface;
use Romm\ConfigurationObject\Service\Items\DataPreProcessorInterface;
use Romm\ConfigurationObject\Service\Items\DataPreProcessor;

class Person implements ConfigurationObjectInterface, DataPreProcessorInterface
{

    use DefaultConfigurationObjectTrait;

    const AUTO_CITY = 'auto';

    /**
     * @var string
     */
    protected $city;

    /**
     * @var string
     */
    protected $zipCode;

    /**
     * @return ServiceFactory
     */
    public static function getConfigurationObjectServices()
    {
        return ServiceFactory::getInstance()
            ->attach(ServiceInterface::SERVICE_DATA_PRE_PROCESSOR);
    }

    /**
     * Will check if the value of `$data['city']` is set to `auto`. If yes,
     * an external service is used to fetch the city automatically from the
     * zip code.
     *
     * @var array $data
     */
    public static function dataPreProcessor(DataPreProcessor $processor)
    {
        $data = $processor->getData();

        if (self::AUTO_CITY === $data['city']) {
            $zipCode = $data['zipCode'];

            $data['city'] = GeographicUtility::fetchCityFromZipCode($zipCode);

            $processor->setData($data);
        }
    }
}