Source of file BooleanOrNullTransformer.php

Size: 1,465 Bytes - Last Modified: 2023-11-16T22:56:02+01:00

/home/websites/teicee/packagist/site/phpdoc/conf/../vendor/teicee/core-bundle/src/Form/DataTransformer/BooleanOrNullTransformer.php

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
<?php
namespace TIC\CoreBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

/**
 * Conversion pour valeur booléenne à 3 niveau (vrai/faux/null).
 */
class BooleanOrNullTransformer implements DataTransformerInterface
{
	protected $values = array(
		'null'  =>  '',
		'false' => '0',
		'true'  => '1',
	);

	private $nullable;

	/**
	 * Construct the data transformer with parameters.
	 *
	 * @param   bool    $notnull        Disable the 'null' option ('null' as 'false')
	 */
	public function __construct(bool $notnull = null)
	{
		$this->nullable = empty($notnull);
	}

	/**
	 * Transforms from DB value to form value.
	 *
	 * @param   mixed       $value
	 * @return  string                  Label for true, false or null
	 */
	public function transform(mixed $value): string
	{
		if ($this->nullable && $value === null) return $this->values['null'];
		return empty($value) ? $this->values['false'] : $this->values['true'];
	}

	/**
	 * Reverse transforms form value to db value.
	 *
	 * @param   mixed       $value
	 * @return  bool|null
	 */
	public function reverseTransform(mixed $value): ?bool
	{
		if ($value === null || $value === $this->values['null'])
			return $this->nullable ? null : false;
		
		if ($value === $this->values['false']) return false;
		if ($value === $this->values['true'])  return true;
		
		return empty($value) ? false : true;
	}

}