murph-skeleton/core/Crud/Field/Field.php

74 lines
2.2 KiB
PHP
Raw Normal View History

2021-05-12 10:18:34 +02:00
<?php
namespace App\Core\Crud\Field;
use Symfony\Component\OptionsResolver\OptionsResolver;
2021-05-13 17:49:19 +02:00
use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
2021-05-12 10:18:34 +02:00
use Symfony\Component\PropertyAccess\PropertyAccess;
use Twig\Environment;
/**
* class Field.
*
* @author Simon Vieille <simon@deblan.fr>
*/
abstract class Field
{
2021-05-13 17:49:19 +02:00
public function buildView(Environment $twig, $entity, array $options, ?string $locale = null)
2021-05-12 10:18:34 +02:00
{
return $twig->render($this->getView($options), [
2021-05-12 15:23:32 +02:00
'entity' => $entity,
2021-05-13 17:49:19 +02:00
'value' => $this->getValue($entity, $options, $locale),
2021-05-12 10:18:34 +02:00
'options' => $options,
]);
}
public function configureOptions(OptionsResolver $resolver): OptionsResolver
{
$resolver->setDefaults([
'property' => null,
'property_builder' => null,
'view' => null,
'raw' => false,
2021-05-12 10:18:34 +02:00
'attr' => [],
]);
$resolver->setRequired('view');
$resolver->setAllowedTypes('property', ['null', 'string']);
$resolver->setAllowedTypes('view', 'string');
$resolver->setAllowedTypes('attr', 'array');
$resolver->setAllowedTypes('raw', 'boolean');
2021-05-12 10:18:34 +02:00
$resolver->setAllowedTypes('property_builder', ['null', 'callable']);
return $resolver;
}
2021-05-13 17:49:19 +02:00
protected function getValue($entity, array $options, ?string $locale = null)
2021-05-12 10:18:34 +02:00
{
if (null !== $options['property']) {
2021-05-12 15:51:53 +02:00
$propertyAccessor = PropertyAccess::createPropertyAccessorBuilder()->getPropertyAccessor();
2021-05-13 17:49:19 +02:00
try {
$value = $propertyAccessor->getValue($entity, $options['property']);
} catch (NoSuchPropertyException $e) {
if (null !== $locale) {
$value = $propertyAccessor->getValue($entity->translate($locale), $options['property']);
} else {
throw $e;
}
}
2021-05-12 10:18:34 +02:00
} elseif (null !== $options['property_builder']) {
$value = call_user_func($options['property_builder'], $entity, $options);
} else {
2021-05-12 15:23:32 +02:00
$value = null;
2021-05-12 10:18:34 +02:00
}
return $value;
}
protected function getView(array $options)
{
return $options['view'];
}
}