deblan.io-murph/core/Crud/Field/Field.php

89 lines
2.7 KiB
PHP
Raw Normal View History

2021-05-12 12:04:03 +02:00
<?php
namespace App\Core\Crud\Field;
use Symfony\Component\OptionsResolver\OptionsResolver;
2021-05-13 17:33:06 +02:00
use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
2021-05-12 12:04:03 +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:33:06 +02:00
public function buildView(Environment $twig, $entity, array $options, ?string $locale = null)
2021-05-12 12:04:03 +02:00
{
return $twig->render($this->getView($options), [
2021-05-12 15:24:01 +02:00
'entity' => $entity,
2021-05-13 17:33:06 +02:00
'value' => $this->getValue($entity, $options, $locale),
2021-05-12 12:04:03 +02:00
'options' => $options,
]);
}
public function configureOptions(OptionsResolver $resolver): OptionsResolver
{
$resolver->setDefaults([
'property' => null,
'property_builder' => null,
'view' => null,
2021-05-12 12:44:48 +02:00
'raw' => false,
2021-05-15 17:23:22 +02:00
'sort' => null,
2021-05-12 12:04:03 +02:00
'attr' => [],
]);
$resolver->setRequired('view');
$resolver->setAllowedTypes('property', ['null', 'string']);
$resolver->setAllowedTypes('view', 'string');
$resolver->setAllowedTypes('attr', 'array');
2021-05-12 12:44:48 +02:00
$resolver->setAllowedTypes('raw', 'boolean');
2021-05-12 12:04:03 +02:00
$resolver->setAllowedTypes('property_builder', ['null', 'callable']);
2021-05-15 17:23:22 +02:00
$resolver->setAllowedValues('sort', function($value) {
if ($value === null) {
return true;
}
if (!is_array($value)) {
return false;
}
$isValidParam1 = !empty($value[0]) && is_string($value[0]);
$isValidParam2 = !empty($value[1]) && (is_string($value[1]) || is_callable($value[1]));
return $isValidParam1 && $isValidParam2;
});
2021-05-12 12:04:03 +02:00
return $resolver;
}
2021-05-13 17:33:06 +02:00
protected function getValue($entity, array $options, ?string $locale = null)
2021-05-12 12:04:03 +02:00
{
if (null !== $options['property']) {
2021-05-12 15:51:08 +02:00
$propertyAccessor = PropertyAccess::createPropertyAccessorBuilder()->getPropertyAccessor();
2021-05-13 17:33:06 +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 12:04:03 +02:00
} elseif (null !== $options['property_builder']) {
$value = call_user_func($options['property_builder'], $entity, $options);
} else {
2021-05-12 15:24:01 +02:00
$value = null;
2021-05-12 12:04:03 +02:00
}
return $value;
}
protected function getView(array $options)
{
return $options['view'];
}
}