apply more cs rules for php-cs

This commit is contained in:
2023-10-17 13:27:03 +02:00
parent 0b0cbed9db
commit bc2041cbdd
1485 changed files with 8169 additions and 9620 deletions

View File

@@ -17,12 +17,12 @@ use Chill\DocGeneratorBundle\Entity\DocGeneratorTemplate;
interface ContextManagerInterface
{
/**
* @throws ContextNotFoundException When the context is not found.
* @throws ContextNotFoundException when the context is not found
*/
public function getContextByDocGeneratorTemplate(DocGeneratorTemplate $docGeneratorTemplate): DocGeneratorContextInterface;
/**
* @throws ContextNotFoundException When the context is not found.
* @throws ContextNotFoundException when the context is not found
*/
public function getContextByKey(string $searchedKey): DocGeneratorContextInterface;

View File

@@ -15,6 +15,7 @@ use Symfony\Component\Form\FormBuilderInterface;
/**
* @template T of object
*
* @extends DocGeneratorContextInterface<T>
*/
interface DocGeneratorContextWithAdminFormInterface extends DocGeneratorContextInterface

View File

@@ -16,6 +16,7 @@ use Symfony\Component\Form\FormBuilderInterface;
/**
* @template T of object
*
* @extends DocGeneratorContextInterface<T>
*/
interface DocGeneratorContextWithPublicFormInterface extends DocGeneratorContextInterface
@@ -28,7 +29,7 @@ interface DocGeneratorContextWithPublicFormInterface extends DocGeneratorContext
public function buildPublicForm(FormBuilderInterface $builder, DocGeneratorTemplate $template, mixed $entity): void;
/**
* Fill the form with initial data
* Fill the form with initial data.
*
* @param T $entity
*/
@@ -42,14 +43,14 @@ interface DocGeneratorContextWithPublicFormInterface extends DocGeneratorContext
public function hasPublicForm(DocGeneratorTemplate $template, mixed $entity): bool;
/**
* Transform the data from the form into serializable data, storable into messenger's message
* Transform the data from the form into serializable data, storable into messenger's message.
*
* @param T $entity
*/
public function contextGenerationDataNormalize(DocGeneratorTemplate $template, mixed $entity, array $data): array;
/**
* Reverse the data from the messenger's message into data usable for doc's generation
* Reverse the data from the messenger's message into data usable for doc's generation.
*
* @param T $entity
*/

View File

@@ -11,9 +11,7 @@ declare(strict_types=1);
namespace Chill\DocGeneratorBundle\Context\Exception;
use RuntimeException;
class ContextNotFoundException extends RuntimeException
class ContextNotFoundException extends \RuntimeException
{
public function __construct($contextName)
{

View File

@@ -11,13 +11,7 @@ declare(strict_types=1);
namespace Chill\DocGeneratorBundle\Context\Exception;
use LogicException;
use function get_class;
use function gettype;
use function is_object;
class UnexpectedTypeException extends LogicException
class UnexpectedTypeException extends \LogicException
{
public function __construct($value, string $expectedType)
{

View File

@@ -15,16 +15,13 @@ use Chill\DocGeneratorBundle\Context\ContextManager;
use Chill\DocGeneratorBundle\Context\DocGeneratorContextWithPublicFormInterface;
use Chill\DocGeneratorBundle\Context\Exception\ContextNotFoundException;
use Chill\DocGeneratorBundle\Entity\DocGeneratorTemplate;
use Chill\DocGeneratorBundle\GeneratorDriver\DriverInterface;
use Chill\DocGeneratorBundle\Repository\DocGeneratorTemplateRepository;
use Chill\DocGeneratorBundle\Service\Generator\GeneratorInterface;
use Chill\DocGeneratorBundle\Service\Messenger\RequestGenerationMessage;
use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\DocStoreBundle\Service\StoredObjectManagerInterface;
use Chill\MainBundle\Pagination\PaginatorFactory;
use Chill\MainBundle\Serializer\Model\Collection;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
@@ -37,9 +34,6 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use function strlen;
use const JSON_PRETTY_PRINT;
final class DocGeneratorTemplateController extends AbstractController
{
@@ -155,10 +149,7 @@ final class DocGeneratorTemplateController extends AbstractController
try {
$context = $this->contextManager->getContextByDocGeneratorTemplate($template);
} catch (ContextNotFoundException $e) {
throw new NotFoundHttpException(
'Context not found.',
$e
);
throw new NotFoundHttpException('Context not found.', $e);
}
$entity = $this
@@ -167,9 +158,7 @@ final class DocGeneratorTemplateController extends AbstractController
->find($entityId);
if (null === $entity) {
throw new NotFoundHttpException(
sprintf('Entity with classname %s and id %s is not found', $context->getEntityClass(), $entityId)
);
throw new NotFoundHttpException(sprintf('Entity with classname %s and id %s is not found', $context->getEntityClass(), $entityId));
}
$contextGenerationData = [
@@ -230,7 +219,7 @@ final class DocGeneratorTemplateController extends AbstractController
// if is test, render the data or generate the doc
if ($isTest && isset($form) && $form['show_data']->getData()) {
return $this->render('@ChillDocGenerator/Generator/debug_value.html.twig', [
'datas' => json_encode($context->getData($template, $entity, $contextGenerationData), JSON_PRETTY_PRINT),
'datas' => json_encode($context->getData($template, $entity, $contextGenerationData), \JSON_PRETTY_PRINT),
]);
}
if ($isTest) {
@@ -250,7 +239,7 @@ final class DocGeneratorTemplateController extends AbstractController
'Content-Transfer-Encoding', 'binary',
'Content-Type' => 'application/vnd.oasis.opendocument.text',
'Content-Disposition' => 'attachment; filename="generated.odt"',
'Content-Length' => strlen($generated),
'Content-Length' => \strlen($generated),
],
);
}

View File

@@ -15,7 +15,6 @@ use Chill\DocGeneratorBundle\Entity\DocGeneratorTemplate;
use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Service\DocGenerator\AccompanyingPeriodContext;
use DateTime;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Persistence\ObjectManager;
@@ -59,7 +58,7 @@ class LoadDocGeneratorTemplate extends AbstractFixture
->setFilename($template['file']['filename'])
->setKeyInfos(json_decode($template['file']['key'], true))
->setIv(json_decode($template['file']['iv'], true))
->setCreatedAt(new DateTime('today'))
->setCreatedAt(new \DateTime('today'))
->setType($template['file']['type']);
$manager->persist($newStoredObj);

View File

@@ -30,7 +30,7 @@ class ChillDocGeneratorExtension extends Extension implements PrependExtensionIn
$config = $this->processConfiguration($configuration, $configs);
$container->setParameter('chill_doc_generator', $config);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../config'));
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../config'));
$loader->load('services.yaml');
$loader->load('services/controller.yaml');
$loader->load('services/fixtures.yaml');

View File

@@ -17,7 +17,9 @@ use Symfony\Component\Serializer\Annotation as Serializer;
/**
* @ORM\Entity
*
* @ORM\Table(name="chill_docgen_template")
*
* @Serializer\DiscriminatorMap(typeProperty="type", mapping={
* "docgen_template": DocGeneratorTemplate::class
* })
@@ -41,6 +43,7 @@ class DocGeneratorTemplate
/**
* @ORM\Column(type="text", nullable=true)
*
* @Serializer\Groups({"read"})
*/
private ?string $description = null;
@@ -59,14 +62,18 @@ class DocGeneratorTemplate
/**
* @ORM\Id
*
* @ORM\GeneratedValue
*
* @ORM\Column(type="integer")
*
* @Serializer\Groups({"read"})
*/
private int $id;
/**
* @ORM\Column(type="json")
*
* @Serializer\Groups({"read"})
*/
private array $name = [];

View File

@@ -13,5 +13,5 @@ namespace Chill\DocGeneratorBundle\GeneratorDriver;
interface DriverInterface
{
public function generateFromString(string $template, string $resourceType, array $data, ?string $templateName = null): string;
public function generateFromString(string $template, string $resourceType, array $data, string $templateName = null): string;
}

View File

@@ -11,16 +11,13 @@ declare(strict_types=1);
namespace Chill\DocGeneratorBundle\GeneratorDriver\Exception;
use RuntimeException;
use Throwable;
/**
* A exception to throw when there are syntax errors in the
* template file.
*/
class TemplateException extends RuntimeException
class TemplateException extends \RuntimeException
{
public function __construct(private readonly array $errors, $code = 0, ?Throwable $previous = null)
public function __construct(private readonly array $errors, $code = 0, \Throwable $previous = null)
{
parent::__construct('Error while generating document from template', $code, $previous);
}

View File

@@ -20,7 +20,6 @@ use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Throwable;
final class RelatorioDriver implements DriverInterface
{
@@ -34,7 +33,7 @@ final class RelatorioDriver implements DriverInterface
$this->url = $parameterBag->get('chill_doc_generator')['driver']['relatorio']['url'];
}
public function generateFromString(string $template, string $resourceType, array $data, ?string $templateName = null): string
public function generateFromString(string $template, string $resourceType, array $data, string $templateName = null): string
{
$form = new FormDataPart(
[
@@ -84,7 +83,7 @@ final class RelatorioDriver implements DriverInterface
]);
throw $e;
} catch (Throwable $exception) {
} catch (\Throwable $exception) {
$this
->logger
->error(

View File

@@ -58,7 +58,7 @@ final class DocGeneratorTemplateRepository implements ObjectRepository
*
* @return DocGeneratorTemplate[]
*/
public function findBy(array $criteria, ?array $orderBy = null, $limit = null, $offset = null): array
public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null): array
{
return $this->repository->findBy($criteria, $orderBy, $limit, $offset);
}
@@ -85,7 +85,7 @@ final class DocGeneratorTemplateRepository implements ObjectRepository
->getResult();
}
public function findOneBy(array $criteria, ?array $orderBy = null): ?DocGeneratorTemplate
public function findOneBy(array $criteria, array $orderBy = null): ?DocGeneratorTemplate
{
return $this->repository->findOneBy($criteria, $orderBy);
}

View File

@@ -12,10 +12,7 @@ declare(strict_types=1);
namespace Chill\DocGeneratorBundle\Serializer\Encoder;
use Symfony\Component\Serializer\Encoder\EncoderInterface;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
use function array_keys;
use function is_array;
class DocGenEncoder implements EncoderInterface
{
@@ -38,21 +35,21 @@ class DocGenEncoder implements EncoderInterface
private function canonicalizeKey(string $path, string $key): string
{
return '' === $path ? $key : $path . '_' . $key;
return '' === $path ? $key : $path.'_'.$key;
}
private function isAssociative(array $data)
{
$keys = array_keys($data);
$keys = \array_keys($data);
return array_keys($keys) !== $keys;
return \array_keys($keys) !== $keys;
}
private function recusiveEncoding(array $data, array &$result, $path)
{
if ($this->isAssociative($data)) {
foreach ($data as $key => $value) {
if (is_array($value)) {
if (\is_array($value)) {
$this->recusiveEncoding($value, $result, $this->canonicalizeKey($path, $key));
} else {
$result[$this->canonicalizeKey($path, $key)] = $value;

View File

@@ -14,14 +14,11 @@ namespace Chill\DocGeneratorBundle\Serializer\Helper;
use Symfony\Component\Serializer\Mapping\ClassMetadata;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use function array_merge;
use function is_array;
class NormalizeNullValueHelper
{
public function __construct(private readonly NormalizerInterface $normalizer, private readonly ?string $discriminatorType = null, private readonly ?string $discriminatorValue = null) {}
public function normalize(array $attributes, string $format = 'docgen', ?array $context = [], ?ClassMetadata $classMetadata = null)
public function normalize(array $attributes, string $format = 'docgen', ?array $context = [], ClassMetadata $classMetadata = null)
{
$data = [];
$data['isNull'] = true;
@@ -36,7 +33,7 @@ class NormalizeNullValueHelper
} else {
$data[$key] = match ($class) {
'array', 'bool', 'double', 'float', 'int', 'resource', 'string', 'null' => '',
default => $this->normalizer->normalize(null, $format, array_merge(
default => $this->normalizer->normalize(null, $format, \array_merge(
$this->getContextForAttribute($key, $context, $classMetadata),
['docgen:expects' => $class]
)),
@@ -57,10 +54,10 @@ class NormalizeNullValueHelper
if (null !== $attributeMetadata) {
/** @var \Symfony\Component\Serializer\Mapping\AttributeMetadata $attributeMetadata */
$initialContext = array_merge(
$initialContext = \array_merge(
$initialContext,
$attributeMetadata->getNormalizationContextForGroups(
is_array($initialContext['groups']) ? $initialContext['groups'] : [$initialContext['groups']]
\is_array($initialContext['groups']) ? $initialContext['groups'] : [$initialContext['groups']]
)
);
}

View File

@@ -11,7 +11,6 @@ declare(strict_types=1);
namespace Chill\DocGeneratorBundle\Serializer\Normalizer;
use ArrayObject;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ReadableCollection;
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
@@ -26,10 +25,10 @@ class CollectionDocGenNormalizer implements ContextAwareNormalizerInterface, Nor
use NormalizerAwareTrait;
/**
* @param Collection $object
* @param Collection $object
* @param string|null $format
*
* @return array|ArrayObject|bool|float|int|string|void|null
* @return array|\ArrayObject|bool|float|int|string|void|null
*/
public function normalize($object, $format = null, array $context = [])
{

View File

@@ -14,8 +14,6 @@ namespace Chill\DocGeneratorBundle\Serializer\Normalizer;
use Chill\DocGeneratorBundle\Serializer\Helper\NormalizeNullValueHelper;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Doctrine\Common\Collections\ReadableCollection;
use ReflectionClass;
use RuntimeException;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessor;
use Symfony\Component\Serializer\Exception\ExceptionInterface;
@@ -28,15 +26,6 @@ use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use function array_filter;
use function array_key_exists;
use function array_merge;
use function get_class;
use function implode;
use function in_array;
use function is_array;
use function is_object;
class DocGenObjectNormalizer implements NormalizerAwareInterface, NormalizerInterface
{
use NormalizerAwareTrait;
@@ -55,27 +44,22 @@ class DocGenObjectNormalizer implements NormalizerAwareInterface, NormalizerInte
$classMetadataKey = $object ?? $context['docgen:expects'] ?? null;
if (null === $classMetadataKey) {
throw new RuntimeException('Could not determine the metadata for this object. Either provide a non-null object, or a "docgen:expects" key in the context');
throw new \RuntimeException('Could not determine the metadata for this object. Either provide a non-null object, or a "docgen:expects" key in the context');
}
if (!$this->classMetadataFactory->hasMetadataFor($classMetadataKey)) {
throw new LogicException(sprintf(
'This object does not have metadata: %s. Add groups on this entity to allow to serialize with the format %s and groups %s',
is_object($object) ? $object::class : '(todo' /*$context['docgen:expects'],*/ ,
$format,
implode(', ', ($context['groups'] ?? []))
));
throw new LogicException(sprintf('This object does not have metadata: %s. Add groups on this entity to allow to serialize with the format %s and groups %s', \is_object($object) ? $object::class : '(todo' /* $context['docgen:expects'], */ , $format, \implode(', ', $context['groups'] ?? [])));
}
$metadata = $this->classMetadataFactory->getMetadataFor($classMetadataKey);
$expectedGroups = array_key_exists(AbstractNormalizer::GROUPS, $context) ?
is_array($context[AbstractNormalizer::GROUPS]) ? $context[AbstractNormalizer::GROUPS] : [$context[AbstractNormalizer::GROUPS]]
$expectedGroups = \array_key_exists(AbstractNormalizer::GROUPS, $context) ?
\is_array($context[AbstractNormalizer::GROUPS]) ? $context[AbstractNormalizer::GROUPS] : [$context[AbstractNormalizer::GROUPS]]
: [];
$attributes = array_filter(
$attributes = \array_filter(
$metadata->getAttributesMetadata(),
static function (AttributeMetadata $a) use ($expectedGroups) {
foreach ($a->getGroups() as $g) {
if (in_array($g, $expectedGroups, true)) {
if (\in_array($g, $expectedGroups, true)) {
return true;
}
}
@@ -93,10 +77,10 @@ class DocGenObjectNormalizer implements NormalizerAwareInterface, NormalizerInte
public function supportsNormalization($data, $format = null): bool
{
return 'docgen' === $format && (is_object($data) || null === $data);
return 'docgen' === $format && (\is_object($data) || null === $data);
}
private function getExpectedType(AttributeMetadata $attribute, ReflectionClass $reflection): string
private function getExpectedType(AttributeMetadata $attribute, \ReflectionClass $reflection): string
{
$type = null;
@@ -104,48 +88,32 @@ class DocGenObjectNormalizer implements NormalizerAwareInterface, NormalizerInte
// we have to get the expected content
if ($reflection->hasProperty($attribute->getName())) {
if (!$reflection->getProperty($attribute->getName())->hasType()) {
throw new \LogicException(sprintf(
'Could not determine how the content is determined for the attribute %s on class %s. Add a type on this property',
$attribute->getName(),
$reflection->getName()
));
throw new \LogicException(sprintf('Could not determine how the content is determined for the attribute %s on class %s. Add a type on this property', $attribute->getName(), $reflection->getName()));
}
$type = $reflection->getProperty($attribute->getName())->getType();
} elseif ($reflection->hasMethod($method = 'get' . ucfirst($attribute->getName()))) {
} elseif ($reflection->hasMethod($method = 'get'.ucfirst($attribute->getName()))) {
if (!$reflection->getMethod($method)->hasReturnType()) {
throw new \LogicException(sprintf(
'Could not determine how the content is determined for the attribute %s on class %s. Add a return type on the method',
$attribute->getName(),
$reflection->getName()
));
throw new \LogicException(sprintf('Could not determine how the content is determined for the attribute %s on class %s. Add a return type on the method', $attribute->getName(), $reflection->getName()));
}
$type = $reflection->getMethod($method)->getReturnType();
} elseif ($reflection->hasMethod($method = 'is' . ucfirst($attribute->getName()))) {
} elseif ($reflection->hasMethod($method = 'is'.ucfirst($attribute->getName()))) {
if (!$reflection->getMethod($method)->hasReturnType()) {
throw new \LogicException(sprintf(
'Could not determine how the content is determined for the attribute %s on class %s. Add a return type on the method',
$attribute->getName(),
$reflection->getName()
));
throw new \LogicException(sprintf('Could not determine how the content is determined for the attribute %s on class %s. Add a return type on the method', $attribute->getName(), $reflection->getName()));
}
$type = $reflection->getMethod($method)->getReturnType();
} elseif ($reflection->hasMethod($attribute->getName())) {
if (!$reflection->getMethod($attribute->getName())->hasReturnType()) {
throw new \LogicException(sprintf(
'Could not determine how the content is determined for the attribute %s on class %s. Add a return type on the method',
$attribute->getName(),
$reflection->getName()
));
throw new \LogicException(sprintf('Could not determine how the content is determined for the attribute %s on class %s. Add a return type on the method', $attribute->getName(), $reflection->getName()));
}
$type = $reflection->getMethod($attribute->getName())->getReturnType();
} else {
$reflection = $reflection->getParentClass();
}
} while (null === $type && $reflection instanceof ReflectionClass);
} while (null === $type && $reflection instanceof \ReflectionClass);
if ($type instanceof \ReflectionNamedType) {
return $type->getName();
@@ -156,22 +124,19 @@ class DocGenObjectNormalizer implements NormalizerAwareInterface, NormalizerInte
return ReadableCollection::class;
}
$class = new ReflectionClass($classString);
$class = new \ReflectionClass($classString);
if ($class->implementsInterface(ReadableCollection::class)) {
return ReadableCollection::class;
}
}
throw new \LogicException(sprintf("The automatic normalization of intersection types is not supported, unless a %s is contained in the intersected types", ReadableCollection::class));
throw new \LogicException(sprintf('The automatic normalization of intersection types is not supported, unless a %s is contained in the intersected types', ReadableCollection::class));
} elseif (null === $type ?? null) {
throw new \LogicException(sprintf(
'Could not determine the type for this attribute: %s. Add a return type to the method or property declaration',
$attribute->getName()
));
throw new \LogicException(sprintf('Could not determine the type for this attribute: %s. Add a return type to the method or property declaration', $attribute->getName()));
}
throw new \LogicException(sprintf("The automatic normalization of %s is not supported", $type::class));
throw new \LogicException(sprintf('The automatic normalization of %s is not supported', $type::class));
}
/**
@@ -211,13 +176,13 @@ class DocGenObjectNormalizer implements NormalizerAwareInterface, NormalizerInte
return $normalizer->normalize($keys, $format, $context, $metadata);
}
private function normalizeNullOutputValue(mixed $format, array $context, AttributeMetadata $attribute, ReflectionClass $reflection)
private function normalizeNullOutputValue(mixed $format, array $context, AttributeMetadata $attribute, \ReflectionClass $reflection)
{
$type = $this->getExpectedType($attribute, $reflection);
switch ($type) {
case 'array':
if (in_array('is-translatable', $attribute->getNormalizationContextForGroups(['docgen:read']), true)) {
if (\in_array('is-translatable', $attribute->getNormalizationContextForGroups(['docgen:read']), true)) {
return '';
}
@@ -237,7 +202,7 @@ class DocGenObjectNormalizer implements NormalizerAwareInterface, NormalizerInte
return $this->normalizer->normalize(
null,
$format,
array_merge(
\array_merge(
$context,
['docgen:expects' => $type]
)
@@ -246,13 +211,11 @@ class DocGenObjectNormalizer implements NormalizerAwareInterface, NormalizerInte
}
/**
* @param $object
* @param $format
* @param array|AttributeMetadata[] $attributes
*
* @throws ExceptionInterface
*
* @return array
*
* @throws ExceptionInterface
*/
private function normalizeObject($object, $format, array $context, array $expectedGroups, ClassMetadata $metadata, array $attributes)
{
@@ -269,10 +232,10 @@ class DocGenObjectNormalizer implements NormalizerAwareInterface, NormalizerInte
/** @var AttributeMetadata $attribute */
$value = $this->propertyAccess->getValue($object, $attribute->getName());
$key = $attribute->getSerializedName() ?? $attribute->getName();
$objectContext = array_merge(
$objectContext = \array_merge(
$context,
$attribute->getNormalizationContextForGroups(
is_array($context['groups']) ? $context['groups'] : [$context['groups']]
\is_array($context['groups']) ? $context['groups'] : [$context['groups']]
)
);
$isTranslatable = $objectContext['is-translatable'] ?? false;
@@ -284,7 +247,7 @@ class DocGenObjectNormalizer implements NormalizerAwareInterface, NormalizerInte
// when normalizing collection, we should not preserve keys (to ensure that the result is a list)
// this is why we make call to the normalizer again to use the CollectionDocGenNormalizer
$data[$key] =
$this->normalizer->normalize($value, $format, array_merge(
$this->normalizer->normalize($value, $format, \array_merge(
$objectContext,
$attribute->getNormalizationContextForGroups($expectedGroups)
));
@@ -293,15 +256,15 @@ class DocGenObjectNormalizer implements NormalizerAwareInterface, NormalizerInte
foreach ($value as $k => $v) {
$arr[$k] =
$this->normalizer->normalize($v, $format, array_merge(
$this->normalizer->normalize($v, $format, \array_merge(
$objectContext,
$attribute->getNormalizationContextForGroups($expectedGroups)
));
}
$data[$key] = $arr;
} elseif (is_object($value)) {
} elseif (\is_object($value)) {
$data[$key] =
$this->normalizer->normalize($value, $format, array_merge(
$this->normalizer->normalize($value, $format, \array_merge(
$objectContext,
$attribute->getNormalizationContextForGroups($expectedGroups)
));

View File

@@ -13,15 +13,13 @@ namespace Chill\DocGeneratorBundle\Service\Context;
use Chill\MainBundle\Entity\Location;
use Chill\MainBundle\Entity\User;
use DateTimeImmutable;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class BaseContextData
{
public function __construct(private readonly NormalizerInterface $normalizer) {}
public function getData(?User $user = null): array
public function getData(User $user = null): array
{
$data = [];
@@ -30,11 +28,11 @@ class BaseContextData
'docgen',
['docgen:expects' => User::class, 'groups' => ['docgen:read']]
);
$data['createdAt'] = $this->normalizer->normalize(new DateTimeImmutable(), 'docgen', [
'docgen:expects' => DateTimeImmutable::class, 'groups' => ['docgen:read'],
$data['createdAt'] = $this->normalizer->normalize(new \DateTimeImmutable(), 'docgen', [
'docgen:expects' => \DateTimeImmutable::class, 'groups' => ['docgen:read'],
]);
$data['createdAtDate'] = $this->normalizer->normalize(new DateTimeImmutable('today'), 'docgen', [
'docgen:expects' => DateTimeImmutable::class, 'groups' => ['docgen:read'],
$data['createdAtDate'] = $this->normalizer->normalize(new \DateTimeImmutable('today'), 'docgen', [
'docgen:expects' => \DateTimeImmutable::class, 'groups' => ['docgen:read'],
]);
$data['location'] = $this->normalizer->normalize(
$user instanceof User ? $user->getCurrentLocation() : null,

View File

@@ -32,19 +32,22 @@ class Generator implements GeneratorInterface
/**
* @template T of File|null
* @template B of bool
* @param B $isTest
*
* @param B $isTest
* @param (B is true ? T : null) $testFile
*
* @psalm-return (B is true ? string : null)
*
* @throws \Symfony\Component\Serializer\Exception\ExceptionInterface|\Throwable
*/
public function generateDocFromTemplate(
DocGeneratorTemplate $template,
int $entityId,
array $contextGenerationDataNormalized,
?StoredObject $destinationStoredObject = null,
bool $isTest = false,
?File $testFile = null,
?User $creator = null
int $entityId,
array $contextGenerationDataNormalized,
StoredObject $destinationStoredObject = null,
bool $isTest = false,
File $testFile = null,
User $creator = null
): ?string {
if ($destinationStoredObject instanceof StoredObject && StoredObject::STATUS_PENDING !== $destinationStoredObject->getStatus()) {
$this->logger->info(self::LOG_PREFIX.'Aborting generation of an already generated document');
@@ -53,7 +56,7 @@ class Generator implements GeneratorInterface
$this->logger->info(self::LOG_PREFIX.'Starting generation of a document', [
'entity_id' => $entityId,
'destination_stored_object' => $destinationStoredObject === null ? null : $destinationStoredObject->getId()
'destination_stored_object' => null === $destinationStoredObject ? null : $destinationStoredObject->getId(),
]);
$context = $this->contextManager->getContextByDocGeneratorTemplate($template);
@@ -107,12 +110,13 @@ class Generator implements GeneratorInterface
$this->logger->info(self::LOG_PREFIX.'Finished generation of a document', [
'is_test' => true,
'entity_id' => $entityId,
'destination_stored_object' => $destinationStoredObject === null ? null : $destinationStoredObject->getId()
'destination_stored_object' => null === $destinationStoredObject ? null : $destinationStoredObject->getId(),
]);
return $generatedResource;
}
/** @var StoredObject $destinationStoredObject */
/* @var StoredObject $destinationStoredObject */
$destinationStoredObject
->setType($template->getFile()->getType())
->setFilename(sprintf('%s_odt', uniqid('doc_', true)))

View File

@@ -11,15 +11,12 @@ declare(strict_types=1);
namespace Chill\DocGeneratorBundle\Service\Generator;
use RuntimeException;
use Throwable;
class GeneratorException extends RuntimeException
class GeneratorException extends \RuntimeException
{
/**
* @param string[] $errors
*/
public function __construct(private readonly array $errors = [], ?Throwable $previous = null)
public function __construct(private readonly array $errors = [], \Throwable $previous = null)
{
parent::__construct(
'Could not generate the document',

View File

@@ -21,18 +21,21 @@ interface GeneratorInterface
/**
* @template T of File|null
* @template B of bool
* @param B $isTest
*
* @param B $isTest
* @param (B is true ? T : null) $testFile
*
* @psalm-return (B is true ? string : null)
*
* @throws \Symfony\Component\Serializer\Exception\ExceptionInterface|\Throwable
*/
public function generateDocFromTemplate(
DocGeneratorTemplate $template,
int $entityId,
array $contextGenerationDataNormalized,
?StoredObject $destinationStoredObject = null,
bool $isTest = false,
?File $testFile = null,
?User $creator = null
int $entityId,
array $contextGenerationDataNormalized,
StoredObject $destinationStoredObject = null,
bool $isTest = false,
File $testFile = null,
User $creator = null
): ?string;
}

View File

@@ -11,9 +11,7 @@ declare(strict_types=1);
namespace Chill\DocGeneratorBundle\Service\Generator;
use RuntimeException;
class ObjectReadyException extends RuntimeException
class ObjectReadyException extends \RuntimeException
{
public function __construct()
{

View File

@@ -11,11 +11,9 @@ declare(strict_types=1);
namespace Chill\DocGeneratorBundle\Service\Generator;
use RuntimeException;
class RelatedEntityNotFoundException extends RuntimeException
class RelatedEntityNotFoundException extends \RuntimeException
{
public function __construct(string $relatedEntityClass, int $relatedEntityId, ?\Throwable $previous = null)
public function __construct(string $relatedEntityClass, int $relatedEntityId, \Throwable $previous = null)
{
parent::__construct(
sprintf('Related entity not found: %s, %s', $relatedEntityClass, $relatedEntityId),

View File

@@ -30,11 +30,10 @@ final readonly class OnGenerationFails implements EventSubscriberInterface
public function __construct(private DocGeneratorTemplateRepository $docGeneratorTemplateRepository, private EntityManagerInterface $entityManager, private LoggerInterface $logger, private MailerInterface $mailer, private StoredObjectRepository $storedObjectRepository, private TranslatorInterface $translator, private UserRepositoryInterface $userRepository) {}
public static function getSubscribedEvents()
{
return [
WorkerMessageFailedEvent::class => 'onMessageFailed'
WorkerMessageFailedEvent::class => 'onMessageFailed',
];
}
@@ -82,11 +81,13 @@ final readonly class OnGenerationFails implements EventSubscriberInterface
if (null === $creator = $this->userRepository->find($creatorId)) {
$this->logger->error(self::LOG_PREFIX.'Creator not found with given id', ['creator_id', $creatorId]);
return;
}
if (null === $creator->getEmail() || '' === $creator->getEmail()) {
$this->logger->info(self::LOG_PREFIX.'Creator does not have any email', ['user' => $creator->getUsernameCanonical()]);
return;
}
@@ -104,6 +105,7 @@ final readonly class OnGenerationFails implements EventSubscriberInterface
if (null === $template = $this->docGeneratorTemplateRepository->find($message->getTemplateId())) {
$this->logger->info(self::LOG_PREFIX.'Template not found', ['template_id' => $message->getTemplateId()]);
return;
}

View File

@@ -22,7 +22,7 @@ use Symfony\Component\Messenger\Exception\UnrecoverableMessageHandlingException;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
/**
* Handle the request of document generation
* Handle the request of document generation.
*/
class RequestGenerationHandler implements MessageHandlerInterface
{
@@ -35,11 +35,11 @@ class RequestGenerationHandler implements MessageHandlerInterface
public function __invoke(RequestGenerationMessage $message)
{
if (null === $template = $this->docGeneratorTemplateRepository->find($message->getTemplateId())) {
throw new \RuntimeException('template not found: ' . $message->getTemplateId());
throw new \RuntimeException('template not found: '.$message->getTemplateId());
}
if (null === $destinationStoredObject = $this->storedObjectRepository->find($message->getDestinationStoredObjectId())) {
throw new \RuntimeException('destination stored object not found : ' . $message->getDestinationStoredObjectId());
throw new \RuntimeException('destination stored object not found : '.$message->getDestinationStoredObjectId());
}
if ($destinationStoredObject->getGenerationTrialsCounter() >= self::AUTHORIZED_TRIALS) {

View File

@@ -17,6 +17,7 @@ use Symfony\Component\Serializer\Exception\UnexpectedValueException;
/**
* @internal
*
* @coversNothing
*/
final class DocGenEncoderTest extends TestCase

View File

@@ -18,6 +18,7 @@ use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/**
* @internal
*
* @coversNothing
*/
class CollectionDocGenNormalizerTest extends KernelTestCase
@@ -38,7 +39,7 @@ class CollectionDocGenNormalizerTest extends KernelTestCase
(object) ['v' => 'baz'],
]);
//filter to get non continuous indexes
// filter to get non continuous indexes
$criteria = new Criteria();
$criteria->where(Criteria::expr()->neq('v', 'bar'));

View File

@@ -24,6 +24,7 @@ use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/**
* @internal
*
* @coversNothing
*/
final class DocGenObjectNormalizerTest extends KernelTestCase
@@ -238,6 +239,7 @@ class TestableParentClass
{
/**
* @Serializer\Groups("docgen:read")
*
* @Serializer\Context(normalizationContext={"groups": "docgen:read:foo"}, groups={"docgen:read"})
*/
public ?TestableChildClass $child;

View File

@@ -15,11 +15,11 @@ use Chill\DocGeneratorBundle\Service\Context\BaseContextData;
use Chill\MainBundle\Entity\User;
use Prophecy\PhpUnit\ProphecyTrait;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/**
* @internal
*
* @coversNothing
*/
final class BaseContextDataTest extends KernelTestCase
@@ -56,7 +56,7 @@ final class BaseContextDataTest extends KernelTestCase
}
private function buildBaseContext(
?NormalizerInterface $normalizer = null
NormalizerInterface $normalizer = null
): BaseContextData {
return new BaseContextData(
$normalizer ?? self::$container->get(NormalizerInterface::class)

View File

@@ -28,6 +28,7 @@ use Psr\Log\NullLogger;
/**
* @internal
*
* @coversNothing
*/
class GeneratorTest extends TestCase
@@ -71,7 +72,6 @@ class GeneratorTest extends TestCase
$storedObjectManager->read($templateStoredObject)->willReturn('template');
$storedObjectManager->write($destinationStoredObject, 'generated')->shouldBeCalled();
$generator = new Generator(
$contextManagerInterface->reveal(),
$driver->reveal(),