forked from ezsystems/repository-forms
/
FieldValueTransformer.php
64 lines (57 loc) · 1.7 KB
/
FieldValueTransformer.php
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
54
55
56
57
58
59
60
61
62
63
64
<?php
/**
* This file is part of the eZ RepositoryForms package.
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
* @version //autogentag//
*/
namespace EzSystems\RepositoryForms\FieldType\DataTransformer;
use eZ\Publish\API\Repository\FieldType;
use eZ\Publish\SPI\FieldType\Value;
use Symfony\Component\Form\DataTransformerInterface;
/**
* Generic data transformer for FieldTypes values.
* Uses FieldType::toHash() / FieldType::fromHash().
*/
class FieldValueTransformer implements DataTransformerInterface
{
/**
* @var eZ\Publish\API\Repository\FieldType
*/
private $fieldType;
public function __construct(FieldType $fieldType)
{
$this->fieldType = $fieldType;
}
/**
* Transforms a FieldType Value into a hash using `FieldTpe::toHash()`.
* This hash is compatible with `reverseTransform()`.
*
* @param mixed $value
*
* @return array|null the value's hash, or null if $value was not a FieldType Value
*/
public function transform($value)
{
if (!$value instanceof Value) {
return null;
}
return $this->fieldType->toHash($value);
}
/**
* Transforms a hash into a FieldType Value using `FieldType::fromHash()`.
* The FieldValue is compatible with `transform()`.
*
* @param mixed $value
*
* @return \eZ\Publish\SPI\FieldType\Value
*/
public function reverseTransform($value)
{
if ($value === null) {
return $this->fieldType->getEmptyValue();
}
return $this->fieldType->fromHash($value);
}
}