Generate a context for docgen, on accompanying period

This commit is contained in:
Julien Fastré 2021-11-30 23:23:02 +01:00
parent 3404d3669c
commit de4e83b3fb
19 changed files with 433 additions and 128 deletions

View File

@ -12,7 +12,6 @@ declare(strict_types=1);
namespace Chill\DocGeneratorBundle; namespace Chill\DocGeneratorBundle;
use Chill\DocGeneratorBundle\Context\DocGeneratorContextInterface; use Chill\DocGeneratorBundle\Context\DocGeneratorContextInterface;
use Chill\MainBundle\Routing\LocalMenuBuilderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle; use Symfony\Component\HttpKernel\Bundle\Bundle;

View File

@ -1,14 +1,20 @@
<?php <?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\DocGeneratorBundle\Context; namespace Chill\DocGeneratorBundle\Context;
class ContextManager class ContextManager
{ {
private iterable $contexts; private iterable $contexts;
/**
* @param iterable $contexts
*/
public function __construct(iterable $contexts) public function __construct(iterable $contexts)
{ {
$this->contexts = $contexts; $this->contexts = $contexts;

View File

@ -16,11 +16,6 @@ namespace Chill\DocGeneratorBundle\Context;
*/ */
interface DocGeneratorContextInterface interface DocGeneratorContextInterface
{ {
public static function getKey(): string;
public function getName(): string;
/** /**
* Get the data that will be injected to the generated document. * Get the data that will be injected to the generated document.
* *
@ -35,6 +30,10 @@ interface DocGeneratorContextInterface
*/ */
public function getForm($entity); public function getForm($entity);
public static function getKey(): string;
public function getName(): string;
/** /**
* has form. * has form.
*/ */

View File

@ -1,11 +1,25 @@
<?php <?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\DocGeneratorBundle\Context\Exception; namespace Chill\DocGeneratorBundle\Context\Exception;
class UnexpectedTypeException extends \LogicException use LogicException;
use function get_class;
use function gettype;
use function is_object;
class UnexpectedTypeException extends LogicException
{ {
public function __construct($value, string $expectedType) public function __construct($value, string $expectedType)
{ {
parent::__construct(sprintf('Expected argument of type "%s", "%s" given', $expectedType, \is_object($value) ? \get_class($value) : \gettype($value))); parent::__construct(sprintf('Expected argument of type "%s", "%s" given', $expectedType, is_object($value) ? get_class($value) : gettype($value)));
} }
} }

View File

@ -23,16 +23,6 @@ use function get_class;
*/ */
class HouseholdMemberSelectionContext implements DocGeneratorContextInterface class HouseholdMemberSelectionContext implements DocGeneratorContextInterface
{ {
public function getName(): string
{
return 'household member';
}
public static function getKey(): string
{
return self::class;
}
/** /**
* Get the data that will be injected to the generated document. * Get the data that will be injected to the generated document.
* *
@ -99,6 +89,16 @@ class HouseholdMemberSelectionContext implements DocGeneratorContextInterface
return $builder; return $builder;
} }
public static function getKey(): string
{
return self::class;
}
public function getName(): string
{
return 'household member';
}
/** /**
* has form. * has form.
*/ */

View File

@ -11,6 +11,7 @@ declare(strict_types=1);
namespace Chill\DocGeneratorBundle\Controller; namespace Chill\DocGeneratorBundle\Controller;
use Base64Url\Base64Url;
use ChampsLibres\AsyncUploaderBundle\TempUrl\TempUrlGeneratorInterface; use ChampsLibres\AsyncUploaderBundle\TempUrl\TempUrlGeneratorInterface;
use Chill\DocGeneratorBundle\Context\HouseholdMemberSelectionContext; use Chill\DocGeneratorBundle\Context\HouseholdMemberSelectionContext;
use Chill\DocGeneratorBundle\Entity\DocGeneratorTemplate; use Chill\DocGeneratorBundle\Entity\DocGeneratorTemplate;
@ -19,23 +20,19 @@ use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\MainBundle\Pagination\PaginatorFactory; use Chill\MainBundle\Pagination\PaginatorFactory;
use Chill\MainBundle\Serializer\Model\Collection; use Chill\MainBundle\Serializer\Model\Collection;
use Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodWorkEvaluation; use Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodWorkEvaluation;
use Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodWorkEvaluationDocument; use Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodWorkEvaluationDocument;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\Exception\TransferException; use GuzzleHttp\Exception\TransferException;
use PhpOffice\PhpWord\TemplateProcessor; use PhpOffice\PhpWord\TemplateProcessor;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\HeaderUtils;
use ChampsLibres\AsyncUploaderBundle\TempUrl\TempUrlOpenstackGenerator;
use Jose\Component\Core\JWK;
use Base64Url\Base64Url;
use Symfony\Component\HttpKernel\KernelInterface; use Symfony\Component\HttpFoundation\Response;
// TODO à mettre dans services // TODO à mettre dans services
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
@ -43,13 +40,13 @@ use Symfony\Contracts\HttpClient\HttpClientInterface;
final class DocGeneratorTemplateController extends AbstractController final class DocGeneratorTemplateController extends AbstractController
{ {
private DocGeneratorTemplateRepository $docGeneratorTemplateRepository; private HttpClientInterface $client;
private PaginatorFactory $paginatorFactory; private DocGeneratorTemplateRepository $docGeneratorTemplateRepository;
private KernelInterface $kernel; private KernelInterface $kernel;
private HttpClientInterface $client; private PaginatorFactory $paginatorFactory;
public function __construct( public function __construct(
DocGeneratorTemplateRepository $docGeneratorTemplateRepository, DocGeneratorTemplateRepository $docGeneratorTemplateRepository,
@ -78,7 +75,8 @@ final class DocGeneratorTemplateController extends AbstractController
): Response { ): Response {
$getUrlGen = $tempUrlGenerator->generate( $getUrlGen = $tempUrlGenerator->generate(
'GET', 'GET',
$template->getFile()->getFilename()); $template->getFile()->getFilename()
);
$data = $this->client->request('GET', $getUrlGen->url); $data = $this->client->request('GET', $getUrlGen->url);
@ -92,23 +90,25 @@ final class DocGeneratorTemplateController extends AbstractController
$dataDecrypted = openssl_decrypt($data->getContent(), $method, $keyGoodFormat, 1, $ivGoodFormat); $dataDecrypted = openssl_decrypt($data->getContent(), $method, $keyGoodFormat, 1, $ivGoodFormat);
if ($dataDecrypted === FALSE) { if (false === $dataDecrypted) {
throw new \Exception("Error during Decrypt ", 1); throw new \Exception('Error during Decrypt ', 1);
} }
$tmpfnameDeCrypted = tempnam($this->kernel->getCacheDir(), 'DECRYPT_DOC_TEMPLATE'); // plus ou moins $tmpfnameDeCrypted = tempnam($this->kernel->getCacheDir(), 'DECRYPT_DOC_TEMPLATE'); // plus ou moins
if (!$handle = fopen($tmpfnameDeCrypted, 'a')) { if (!$handle = fopen($tmpfnameDeCrypted, 'ab')) {
echo "Cannot open file ($tmpfnameDeCrypted)"; echo "Cannot open file ({$tmpfnameDeCrypted})";
exit; exit;
} }
if (fwrite($handle, $dataDecrypted) === FALSE) { if (fwrite($handle, $dataDecrypted) === false) {
echo "Cannot write to file ($tmpfnameDeCrypted)"; echo "Cannot write to file ({$tmpfnameDeCrypted})";
exit; exit;
} }
dump("Success, wrote ($dataDecrypted) to file ($tmpfnameDeCrypted)"); dump("Success, wrote ({$dataDecrypted}) to file ({$tmpfnameDeCrypted})");
fclose($handle); fclose($handle);

View File

@ -12,10 +12,11 @@ declare(strict_types=1);
namespace Chill\DocGeneratorBundle\DataFixtures\ORM; namespace Chill\DocGeneratorBundle\DataFixtures\ORM;
use Chill\DocGeneratorBundle\Entity\DocGeneratorTemplate; use Chill\DocGeneratorBundle\Entity\DocGeneratorTemplate;
use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodWorkEvaluation; use Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodWorkEvaluation;
use DateTime;
use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Persistence\ObjectManager; use Doctrine\Persistence\ObjectManager;
use Chill\DocStoreBundle\Entity\StoredObject;
/** /**
* Load DocGeneratorTemplate. * Load DocGeneratorTemplate.
@ -32,7 +33,7 @@ class LoadDocGeneratorTemplate extends AbstractFixture
'filename' => 'pKNlhCrQDCRsAuC8vYHDKa', 'filename' => 'pKNlhCrQDCRsAuC8vYHDKa',
'key' => '{"alg":"A256CBC","ext":true,"k":"_VihnD41-VDHlpS-ouwtbMPnu-OXVdtA7ENQWWtAQYM","key_ops":["encrypt","decrypt"],"kty":"oct"}', 'key' => '{"alg":"A256CBC","ext":true,"k":"_VihnD41-VDHlpS-ouwtbMPnu-OXVdtA7ENQWWtAQYM","key_ops":["encrypt","decrypt"],"kty":"oct"}',
'iv' => '[86,231,83,148,117,107,149,173,130,19,105,194,224,145,8,48]', 'iv' => '[86,231,83,148,117,107,149,173,130,19,105,194,224,145,8,48]',
'type' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' 'type' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
], ],
'context' => 'Chill\DocGeneratorBundle\Context\HouseholdMemberSelectionContext', 'context' => 'Chill\DocGeneratorBundle\Context\HouseholdMemberSelectionContext',
'entities' => [AccompanyingPeriodWorkEvaluation::class], 'entities' => [AccompanyingPeriodWorkEvaluation::class],
@ -43,7 +44,7 @@ class LoadDocGeneratorTemplate extends AbstractFixture
'filename' => 'pKNlhCrQDCRsAuC8vYHDKa', 'filename' => 'pKNlhCrQDCRsAuC8vYHDKa',
'key' => '{"alg":"A256CBC","ext":true,"k":"_VihnD41-VDHlpS-ouwtbMPnu-OXVdtA7ENQWWtAQYM","key_ops":["encrypt","decrypt"],"kty":"oct"}', 'key' => '{"alg":"A256CBC","ext":true,"k":"_VihnD41-VDHlpS-ouwtbMPnu-OXVdtA7ENQWWtAQYM","key_ops":["encrypt","decrypt"],"kty":"oct"}',
'iv' => '[86,231,83,148,117,107,149,173,130,19,105,194,224,145,8,48]', 'iv' => '[86,231,83,148,117,107,149,173,130,19,105,194,224,145,8,48]',
'type' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' 'type' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
], ],
'context' => 'Chill\DocGeneratorBundle\Context\HouseholdMemberSelectionContext', 'context' => 'Chill\DocGeneratorBundle\Context\HouseholdMemberSelectionContext',
'entities' => ['Chill\PersonBundle\Entity\AccompanyingPeriod', 'Chill\PersonBundle\Entity\SocialWork\SocialAction', AccompanyingPeriodWorkEvaluation::class], 'entities' => ['Chill\PersonBundle\Entity\AccompanyingPeriod', 'Chill\PersonBundle\Entity\SocialWork\SocialAction', AccompanyingPeriodWorkEvaluation::class],
@ -57,7 +58,7 @@ class LoadDocGeneratorTemplate extends AbstractFixture
->setFilename($template['file']['filename']) ->setFilename($template['file']['filename'])
->setKeyInfos(json_decode($template['file']['key'], true)) ->setKeyInfos(json_decode($template['file']['key'], true))
->setIv(json_decode($template['file']['iv'], true)) ->setIv(json_decode($template['file']['iv'], true))
->setCreationDate(new \DateTime('today')) ->setCreationDate(new DateTime('today'))
->setType($template['file']['type']); ->setType($template['file']['type']);
$manager->persist($newStoredObj); $manager->persist($newStoredObj);

View File

@ -11,9 +11,9 @@ declare(strict_types=1);
namespace Chill\DocGeneratorBundle\Entity; namespace Chill\DocGeneratorBundle\Entity;
use Chill\DocStoreBundle\Entity\StoredObject;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation as Serializer; use Symfony\Component\Serializer\Annotation as Serializer;
use Chill\DocStoreBundle\Entity\StoredObject;
/** /**
* @ORM\Entity * @ORM\Entity
@ -63,7 +63,6 @@ class DocGeneratorTemplate
*/ */
private int $id; private int $id;
/** /**
* @ORM\Column(type="json") * @ORM\Column(type="json")
* @Serializer\Groups({"read"}) * @Serializer\Groups({"read"})
@ -100,7 +99,6 @@ class DocGeneratorTemplate
return $this->name; return $this->name;
} }
public function setContext(string $context): self public function setContext(string $context): self
{ {
$this->context = $context; $this->context = $context;

View File

@ -14,13 +14,13 @@ namespace Chill\DocGeneratorBundle\Form;
use Chill\DocGeneratorBundle\Context\ContextManager; use Chill\DocGeneratorBundle\Context\ContextManager;
use Chill\DocGeneratorBundle\Context\DocGeneratorContextInterface; use Chill\DocGeneratorBundle\Context\DocGeneratorContextInterface;
use Chill\DocGeneratorBundle\Entity\DocGeneratorTemplate; use Chill\DocGeneratorBundle\Entity\DocGeneratorTemplate;
use Chill\DocStoreBundle\Form\StoredObjectType;
use Chill\MainBundle\Form\Type\TranslatableStringFormType; use Chill\MainBundle\Form\Type\TranslatableStringFormType;
use Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodWorkEvaluation;
use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\OptionsResolver\OptionsResolver;
use Chill\DocStoreBundle\Form\StoredObjectType;
use Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodWorkEvaluation;
class DocGeneratorTemplateType extends AbstractType class DocGeneratorTemplateType extends AbstractType
{ {
@ -33,7 +33,7 @@ class DocGeneratorTemplateType extends AbstractType
public function buildForm(FormBuilderInterface $builder, array $options) public function buildForm(FormBuilderInterface $builder, array $options)
{ {
$contexts = \array_flip(\array_map(function (DocGeneratorContextInterface $c) { $contexts = array_flip(array_map(static function (DocGeneratorContextInterface $c) {
return $c->getName(); return $c->getName();
}, $this->contextManager->getContext())); }, $this->contextManager->getContext()));
@ -44,20 +44,19 @@ class DocGeneratorTemplateType extends AbstractType
->add('context', ChoiceType::class, [ ->add('context', ChoiceType::class, [
'required' => true, 'required' => true,
'label' => 'Context', 'label' => 'Context',
'choices' => $contexts 'choices' => $contexts,
]) ])
->add('entities', ChoiceType::class, [ ->add('entities', ChoiceType::class, [
'multiple' => true, 'multiple' => true,
'choices' => [ 'choices' => [
'AccompanyingPeriod' => 'Chill\PersonBundle\Entity\AccompanyingPeriod', 'AccompanyingPeriod' => 'Chill\PersonBundle\Entity\AccompanyingPeriod',
'SocialWork\SocialAction' => 'Chill\PersonBundle\Entity\SocialWork\SocialAction', 'SocialWork\SocialAction' => 'Chill\PersonBundle\Entity\SocialWork\SocialAction',
'AccompanyingPeriod\AccompanyingPeriodWorkEvaluation' => AccompanyingPeriodWorkEvaluation::class 'AccompanyingPeriod\AccompanyingPeriodWorkEvaluation' => AccompanyingPeriodWorkEvaluation::class,
]]) ], ])
->add('description') ->add('description')
->add('file', StoredObjectType::class, [ ->add('file', StoredObjectType::class, [
'error_bubbling' => true 'error_bubbling' => true,
]) ]);
;
} }
public function configureOptions(OptionsResolver $resolver) public function configureOptions(OptionsResolver $resolver)

View File

@ -1,5 +1,12 @@
<?php <?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1); declare(strict_types=1);
namespace Chill\Migrations\DocGenerator; namespace Chill\Migrations\DocGenerator;
@ -8,10 +15,20 @@ use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration; use Doctrine\Migrations\AbstractMigration;
/** /**
* Using DocStore objects inside the DocGenTemplate * Using DocStore objects inside the DocGenTemplate.
*/ */
final class Version20211103111010 extends AbstractMigration final class Version20211103111010 extends AbstractMigration
{ {
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE chill_docgen_template DROP CONSTRAINT FK_49A347E893CB796C');
$this->addSql('DROP INDEX IDX_49A347E893CB796C');
$this->addSql('ALTER TABLE chill_docgen_template ADD file VARCHAR(255) NOT NULL');
$this->addSql('ALTER TABLE chill_docgen_template DROP file_id');
$this->addSql('ALTER TABLE chill_docgen_template ALTER entities DROP NOT NULL');
$this->addSql('ALTER TABLE chill_docgen_template ALTER context DROP NOT NULL');
}
public function getDescription(): string public function getDescription(): string
{ {
return 'Using DocStore objects inside the DocGenTemplate'; return 'Using DocStore objects inside the DocGenTemplate';
@ -26,14 +43,4 @@ final class Version20211103111010 extends AbstractMigration
$this->addSql('ALTER TABLE chill_docgen_template ADD CONSTRAINT FK_49A347E893CB796C FOREIGN KEY (file_id) REFERENCES chill_doc.stored_object (id) NOT DEFERRABLE INITIALLY IMMEDIATE'); $this->addSql('ALTER TABLE chill_docgen_template ADD CONSTRAINT FK_49A347E893CB796C FOREIGN KEY (file_id) REFERENCES chill_doc.stored_object (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
$this->addSql('CREATE INDEX IDX_49A347E893CB796C ON chill_docgen_template (file_id)'); $this->addSql('CREATE INDEX IDX_49A347E893CB796C ON chill_docgen_template (file_id)');
} }
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE chill_docgen_template DROP CONSTRAINT FK_49A347E893CB796C');
$this->addSql('DROP INDEX IDX_49A347E893CB796C');
$this->addSql('ALTER TABLE chill_docgen_template ADD file VARCHAR(255) NOT NULL');
$this->addSql('ALTER TABLE chill_docgen_template DROP file_id');
$this->addSql('ALTER TABLE chill_docgen_template ALTER entities DROP NOT NULL');
$this->addSql('ALTER TABLE chill_docgen_template ALTER context DROP NOT NULL');
}
} }

View File

@ -12,6 +12,7 @@ declare(strict_types=1);
namespace Chill\MainBundle\Security\Resolver; namespace Chill\MainBundle\Security\Resolver;
use Chill\MainBundle\Entity\Scope; use Chill\MainBundle\Entity\Scope;
use Doctrine\Common\Collections\Collection;
final class ScopeResolverDispatcher final class ScopeResolverDispatcher
{ {
@ -45,7 +46,13 @@ final class ScopeResolverDispatcher
{ {
foreach ($this->resolvers as $resolver) { foreach ($this->resolvers as $resolver) {
if ($resolver->supports($entity, $options)) { if ($resolver->supports($entity, $options)) {
return $resolver->resolveScope($entity, $options); $scopes = $resolver->resolveScope($entity, $options);
if ($scopes instanceof Collection) {
return $scopes->toArray();
}
return $scopes;
} }
} }

View File

@ -11,6 +11,7 @@ declare(strict_types=1);
namespace Chill\MainBundle\Templating; namespace Chill\MainBundle\Templating;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Contracts\Translation\TranslatorInterface; use Symfony\Contracts\Translation\TranslatorInterface;
use function array_key_exists; use function array_key_exists;
@ -21,10 +22,13 @@ final class TranslatableStringHelper implements TranslatableStringHelperInterfac
private TranslatorInterface $translator; private TranslatorInterface $translator;
public function __construct(RequestStack $requestStack, TranslatorInterface $translator) private string $defaultLocale;
public function __construct(RequestStack $requestStack, TranslatorInterface $translator, ParameterBagInterface $parameterBag)
{ {
$this->requestStack = $requestStack; $this->requestStack = $requestStack;
$this->translator = $translator; $this->translator = $translator;
$this->defaultLocale = $parameterBag->get('kernel.default_locale');
} }
public function localize(array $translatableStrings): ?string public function localize(array $translatableStrings): ?string
@ -35,11 +39,7 @@ final class TranslatableStringHelper implements TranslatableStringHelperInterfac
$request = $this->requestStack->getCurrentRequest(); $request = $this->requestStack->getCurrentRequest();
if (null === $request) { $language = null === $request ? $this->defaultLocale : $request->getLocale();
return null;
}
$language = $request->getLocale();
if (array_key_exists($language, $translatableStrings)) { if (array_key_exists($language, $translatableStrings)) {
return $translatableStrings[$language]; return $translatableStrings[$language];

View File

@ -117,11 +117,11 @@ class AccompanyingPeriod implements
* @var DateTime * @var DateTime
* *
* @ORM\Column(type="date", nullable=true) * @ORM\Column(type="date", nullable=true)
* @Groups({"read", "write"}) * @Groups({"read", "write", "docgen:read"})
* @Assert\NotBlank(groups={AccompanyingPeriod::STEP_CLOSED}) * @Assert\NotBlank(groups={AccompanyingPeriod::STEP_CLOSED})
* @Assert\GreaterThan(propertyPath="openingDate", groups={AccompanyingPeriod::STEP_CLOSED}) * @Assert\GreaterThan(propertyPath="openingDate", groups={AccompanyingPeriod::STEP_CLOSED})
*/ */
private $closingDate; private ?DateTime $closingDate = null;
/** /**
* @var AccompanyingPeriod\ClosingMotive * @var AccompanyingPeriod\ClosingMotive
@ -132,7 +132,7 @@ class AccompanyingPeriod implements
* @Groups({"read", "write"}) * @Groups({"read", "write"})
* @Assert\NotBlank(groups={AccompanyingPeriod::STEP_CLOSED}) * @Assert\NotBlank(groups={AccompanyingPeriod::STEP_CLOSED})
*/ */
private $closingMotive; private ?ClosingMotive $closingMotive = null;
/** /**
* @var Collection * @var Collection
@ -144,33 +144,34 @@ class AccompanyingPeriod implements
* ) * )
* @Assert\NotBlank(groups={AccompanyingPeriod::STEP_DRAFT}) * @Assert\NotBlank(groups={AccompanyingPeriod::STEP_DRAFT})
*/ */
private $comments; private Collection $comments;
/** /**
* @var bool * @var bool
* @ORM\Column(type="boolean", options={"default": false}) * @ORM\Column(type="boolean", options={"default": false})
* @Groups({"read", "write"}) * @Groups({"read", "write", "docgen:read"})
*/ */
private $confidential = false; private bool $confidential = false;
/** /**
* @ORM\Column(type="datetime", nullable=true, options={"default": NULL}) * @ORM\Column(type="datetime", nullable=true, options={"default": NULL})
* @Groups({"docgen:read"})
*/ */
private DateTimeInterface $createdAt; private ?DateTimeInterface $createdAt = null;
/** /**
* @ORM\ManyToOne(targetEntity=User::class) * @ORM\ManyToOne(targetEntity=User::class)
* @ORM\JoinColumn(nullable=true) * @ORM\JoinColumn(nullable=true)
* @Groups({"read"}) * @Groups({"read", "docgen:read"})
*/ */
private $createdBy; private ?User $createdBy = null;
/** /**
* @var bool * @var bool
* @ORM\Column(type="boolean", options={"default": false}) * @ORM\Column(type="boolean", options={"default": false})
* @Groups({"read", "write"}) * @Groups({"read", "write", "docgen:read"})
*/ */
private $emergency = false; private bool $emergency = false;
/** /**
* @var int * @var int
@ -178,9 +179,9 @@ class AccompanyingPeriod implements
* @ORM\Id * @ORM\Id
* @ORM\Column(name="id", type="integer") * @ORM\Column(name="id", type="integer")
* @ORM\GeneratedValue(strategy="AUTO") * @ORM\GeneratedValue(strategy="AUTO")
* @Groups({"read"}) * @Groups({"read", "docgen:read"})
*/ */
private $id; private ?int $id = null;
/** /**
* @ORM\ManyToOne( * @ORM\ManyToOne(
@ -202,9 +203,9 @@ class AccompanyingPeriod implements
* @var DateTime * @var DateTime
* *
* @ORM\Column(type="date") * @ORM\Column(type="date")
* @Groups({"read", "write"}) * @Groups({"read", "write", "docgen:read"})
*/ */
private $openingDate; private ?DateTime $openingDate = null;
/** /**
* @ORM\ManyToOne(targetEntity=Origin::class) * @ORM\ManyToOne(targetEntity=Origin::class)
@ -212,7 +213,7 @@ class AccompanyingPeriod implements
* @Groups({"read", "write"}) * @Groups({"read", "write"})
* @Assert\NotBlank(groups={AccompanyingPeriod::STEP_CONFIRMED}) * @Assert\NotBlank(groups={AccompanyingPeriod::STEP_CONFIRMED})
*/ */
private $origin; private ?Origin $origin = null;
/** /**
* @var Collection * @var Collection
@ -220,10 +221,10 @@ class AccompanyingPeriod implements
* @ORM\OneToMany(targetEntity=AccompanyingPeriodParticipation::class, * @ORM\OneToMany(targetEntity=AccompanyingPeriodParticipation::class,
* mappedBy="accompanyingPeriod", orphanRemoval=true, * mappedBy="accompanyingPeriod", orphanRemoval=true,
* cascade={"persist", "refresh", "remove", "merge", "detach"}) * cascade={"persist", "refresh", "remove", "merge", "detach"})
* @Groups({"read"}) * @Groups({"read", "docgen:read"})
* @ParticipationOverlap(groups={AccompanyingPeriod::STEP_DRAFT, AccompanyingPeriod::STEP_CONFIRMED}) * @ParticipationOverlap(groups={AccompanyingPeriod::STEP_DRAFT, AccompanyingPeriod::STEP_CONFIRMED})
*/ */
private $participations; private Collection $participations;
/** /**
* @ORM\ManyToOne( * @ORM\ManyToOne(
@ -239,26 +240,26 @@ class AccompanyingPeriod implements
* @ORM\Column(type="text") * @ORM\Column(type="text")
* @Groups({"read", "write"}) * @Groups({"read", "write"})
*/ */
private $remark = ''; private string $remark = '';
/** /**
* @var bool * @var bool
* @ORM\Column(type="boolean", options={"default": false}) * @ORM\Column(type="boolean", options={"default": false})
* @Groups({"read", "write"}) * @Groups({"read", "write", "docgen:read"})
*/ */
private $requestorAnonymous = false; private bool $requestorAnonymous = false;
/** /**
* @ORM\ManyToOne(targetEntity=Person::class, inversedBy="accompanyingPeriodRequested") * @ORM\ManyToOne(targetEntity=Person::class, inversedBy="accompanyingPeriodRequested")
* @ORM\JoinColumn(nullable=true) * @ORM\JoinColumn(nullable=true)
*/ */
private $requestorPerson; private ?Person $requestorPerson = null;
/** /**
* @ORM\ManyToOne(targetEntity=ThirdParty::class) * @ORM\ManyToOne(targetEntity=ThirdParty::class)
* @ORM\JoinColumn(nullable=true) * @ORM\JoinColumn(nullable=true)
*/ */
private $requestorThirdParty; private ?ThirdParty $requestorThirdParty = null;
/** /**
* @var Collection * @var Collection
@ -272,7 +273,7 @@ class AccompanyingPeriod implements
* @Groups({"read"}) * @Groups({"read"})
* @ResourceDuplicateCheck(groups={AccompanyingPeriod::STEP_DRAFT, AccompanyingPeriod::STEP_CONFIRMED, "Default", "default"}) * @ResourceDuplicateCheck(groups={AccompanyingPeriod::STEP_DRAFT, AccompanyingPeriod::STEP_CONFIRMED, "Default", "default"})
*/ */
private $resources; private Collection $resources;
/** /**
* @var Collection * @var Collection
@ -288,7 +289,7 @@ class AccompanyingPeriod implements
* @Groups({"read"}) * @Groups({"read"})
* @Assert\Count(min=1, groups={AccompanyingPeriod::STEP_CONFIRMED}, minMessage="A course must be associated to at least one scope") * @Assert\Count(min=1, groups={AccompanyingPeriod::STEP_CONFIRMED}, minMessage="A course must be associated to at least one scope")
*/ */
private $scopes; private Collection $scopes;
/** /**
* @ORM\ManyToMany( * @ORM\ManyToMany(
@ -297,7 +298,7 @@ class AccompanyingPeriod implements
* @ORM\JoinTable( * @ORM\JoinTable(
* name="chill_person_accompanying_period_social_issues" * name="chill_person_accompanying_period_social_issues"
* ) * )
* @Groups({"read"}) * @Groups({"read", "docgen:read"})
* @Assert\Count(min=1, groups={AccompanyingPeriod::STEP_CONFIRMED}, minMessage="A course must contains at least one social issue") * @Assert\Count(min=1, groups={AccompanyingPeriod::STEP_CONFIRMED}, minMessage="A course must contains at least one social issue")
*/ */
private Collection $socialIssues; private Collection $socialIssues;
@ -307,26 +308,26 @@ class AccompanyingPeriod implements
* @ORM\Column(type="string", length=32, nullable=true) * @ORM\Column(type="string", length=32, nullable=true)
* @Groups({"read"}) * @Groups({"read"})
*/ */
private $step = self::STEP_DRAFT; private string $step = self::STEP_DRAFT;
/** /**
* @ORM\Column(type="datetime", nullable=true, options={"default": NULL}) * @ORM\Column(type="datetime", nullable=true, options={"default": NULL})
*/ */
private DateTimeInterface $updatedAt; private ?DateTimeInterface $updatedAt = null;
/** /**
* @ORM\ManyToOne( * @ORM\ManyToOne(
* targetEntity=User::class * targetEntity=User::class
* ) * )
*/ */
private User $updatedBy; private ?User $updatedBy = null;
/** /**
* @ORM\ManyToOne(targetEntity=User::class) * @ORM\ManyToOne(targetEntity=User::class)
* @ORM\JoinColumn(nullable=true) * @ORM\JoinColumn(nullable=true)
* @Groups({"read", "write"}) * @Groups({"read", "write", "docgen:read"})
*/ */
private $user; private ?User $user = null;
/** /**
* @ORM\OneToMany( * @ORM\OneToMany(
@ -577,6 +578,11 @@ class AccompanyingPeriod implements
}); });
} }
public function getCreatedAt(): ?DateTime
{
return $this->createdAt;
}
public function getCreatedBy(): ?User public function getCreatedBy(): ?User
{ {
return $this->createdBy; return $this->createdBy;
@ -605,7 +611,7 @@ class AccompanyingPeriod implements
* *
* @return int * @return int
*/ */
public function getId() public function getId(): ?int
{ {
return $this->id; return $this->id;
} }
@ -631,7 +637,7 @@ class AccompanyingPeriod implements
public function getLocation(?DateTimeImmutable $at = null): ?Address public function getLocation(?DateTimeImmutable $at = null): ?Address
{ {
if ($this->getPersonLocation() instanceof Person) { if ($this->getPersonLocation() instanceof Person) {
return $this->getPersonLocation()->getCurrentHouseholdAddress($at); return $this->getPersonLocation()->getCurrentPersonAddress();
} }
return $this->getAddressLocation(); return $this->getAddressLocation();
@ -660,7 +666,7 @@ class AccompanyingPeriod implements
* *
* @return DateTime * @return DateTime
*/ */
public function getOpeningDate() public function getOpeningDate(): ?\DateTime
{ {
return $this->openingDate; return $this->openingDate;
} }

View File

@ -33,26 +33,26 @@ class Origin
* @ORM\Column(type="integer") * @ORM\Column(type="integer")
* @Groups({"read"}) * @Groups({"read"})
*/ */
private $id; private ?int $id = null;
/** /**
* @ORM\Column(type="json") * @ORM\Column(type="json")
* @Groups({"read"}) * @Groups({"read"})
*/ */
private $label; private array $label = [];
/** /**
* @ORM\Column(type="date_immutable", nullable=true) * @ORM\Column(type="date_immutable", nullable=true)
* @Groups({"read"}) * @Groups({"read"})
*/ */
private $noActiveAfter; private ?\DateTimeImmutable $noActiveAfter = null;
public function getId(): ?int public function getId(): ?int
{ {
return $this->id; return $this->id;
} }
public function getLabel() public function getLabel(): array
{ {
return $this->label; return $this->label;
} }
@ -62,7 +62,7 @@ class Origin
return $this->noActiveAfter; return $this->noActiveAfter;
} }
public function setLabel(string $label): self public function setLabel(array $label): self
{ {
$this->label = $label; $this->label = $label;

View File

@ -0,0 +1,147 @@
<?php
namespace Chill\PersonBundle\Serializer\Normalizer;
use Chill\MainBundle\Entity\Scope;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Security\Resolver\ScopeResolverDispatcher;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\SocialWork\SocialIssue;
use Chill\PersonBundle\Templating\Entity\ClosingMotiveRender;
use Chill\PersonBundle\Templating\Entity\SocialIssueRender;
use Symfony\Component\Serializer\Exception\CircularReferenceException;
use Symfony\Component\Serializer\Exception\ExceptionInterface;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
use Symfony\Component\Serializer\Exception\LogicException;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Contracts\Translation\TranslatorInterface;
class AccompanyingPeriodDocGenNormalizer implements ContextAwareNormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;
private TranslatorInterface $translator;
private TranslatableStringHelper $translatableStringHelper;
private SocialIssueRender $socialIssueRender;
private ClosingMotiveRender $closingMotiveRender;
private ScopeResolverDispatcher $scopeResolverDispatcher;
private const IGNORE_FIRST_PASS_KEY = 'acc_period_ignore_first_pass';
private const PERIOD_NULL = [
'id' => "",
'closingDate' => \DateTime::class,
'confidential' => "",
'confidentialText' => '',
'createdAt' => \DateTime::class,
'createdBy' => User::class,
'emergency' => "",
'emergencyText' => '',
'openingDate' => \DateTime::class,
'originText' => '',
'requestorAnonymous' => false,
'socialIssues' => [],
'intensity' => '',
'step' => '',
'closingMotiveText' => '',
'socialIssuesText' => '',
'scopes' => [],
'scopesText' => '',
'ref' => User::class,
'participations' => [],
];
public function __construct(
TranslatorInterface $translator,
TranslatableStringHelper $translatableStringHelper,
SocialIssueRender $socialIssueRender,
ClosingMotiveRender $closingMotiveRender,
ScopeResolverDispatcher $scopeResolverDispatcher
) {
$this->translator = $translator;
$this->translatableStringHelper = $translatableStringHelper;
$this->socialIssueRender = $socialIssueRender;
$this->closingMotiveRender = $closingMotiveRender;
$this->scopeResolverDispatcher = $scopeResolverDispatcher;
}
public function supportsNormalization($data, string $format = null, array $context = []): bool
{
if ('docgen' !== $format) {
return false;
}
if ($data instanceof AccompanyingPeriod) {
if (array_key_exists(self::IGNORE_FIRST_PASS_KEY, $context)
&& in_array(spl_object_hash($data), $context[self::IGNORE_FIRST_PASS_KEY])) {
return false;
}
return true;
} elseif (null === $data && ($context['docgen:expects'] ?? null) === AccompanyingPeriod::class) {
return true;
}
return false;
}
/**
* @param AccompanyingPeriod|null $period
*/
public function normalize($period, string $format = null, array $context = [])
{
if ($period instanceof AccompanyingPeriod) {
$ignored = $context[self::IGNORE_FIRST_PASS_KEY] ?? [];
$ignored[] = spl_object_hash($period);
$initial =
$this->normalizer->normalize($period, $format, \array_merge($context,
[self::IGNORE_FIRST_PASS_KEY => $ignored, AbstractNormalizer::GROUPS => 'docgen:read']));
// some transformation
$user = $initial['user'];
unset($initial['user']);
$scopes = $this->scopeResolverDispatcher->isConcerned($period) ? $this->scopeResolverDispatcher->resolveScope($period) : [];
if (!is_array($scopes)) {
$scopes = [$scopes];
}
return array_merge(
// get a first default data
$initial,
// and add data custom
[
'intensity' => $this->translator->trans($period->getIntensity()),
'step' => $this->translator->trans('accompanying_period.'.$period->getStep()),
'emergencyText' => $period->isEmergency() ? $this->translator->trans('accompanying_period.emergency') : '',
'confidentialText' => $period->isConfidential() ? $this->translator->trans('confidential') : '',
'originText' => null !== $period->getOrigin() ? $this->translatableStringHelper->localize($period->getOrigin()->getLabel()) : '',
'closingMotiveText' => null !== $period->getClosingMotive() ?
$this->closingMotiveRender->renderString($period->getClosingMotive(), []) : '',
'ref' => $user,
'socialIssuesText' => implode(', ', array_map(function(SocialIssue $s) {
return $this->socialIssueRender->renderString($s, []);
}, $period->getSocialIssues()->toArray())),
'scopesText' => implode(', ', array_map(function (Scope $s) {
return $this->translatableStringHelper->localize($s->getName());
}, $scopes)),
'scopes' => $scopes,
]
);
} elseif (null === $period) {
return self::PERIOD_NULL;
}
throw new InvalidArgumentException("this neither an accompanying period or null");
}
}

View File

@ -1,10 +1,18 @@
<?php <?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\PersonBundle\Service\DocGenerator; namespace Chill\PersonBundle\Service\DocGenerator;
use Chill\DocGeneratorBundle\Context\DocGeneratorContextInterface; use Chill\DocGeneratorBundle\Context\DocGeneratorContextInterface;
use Chill\DocGeneratorBundle\Context\Exception\UnexpectedTypeException; use Chill\DocGeneratorBundle\Context\Exception\UnexpectedTypeException;
use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\PersonBundle\Entity\AccompanyingPeriod; use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface; use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
@ -12,16 +20,6 @@ class AccompanyingPeriodContext implements DocGeneratorContextInterface
{ {
public NormalizerInterface $normalizer; public NormalizerInterface $normalizer;
public function getName(): string
{
return 'Accompanying Period';
}
public static function getKey(): string
{
return self::class;
}
public function getData($entity): array public function getData($entity): array
{ {
if (!$entity instanceof AccompanyingPeriod) { if (!$entity instanceof AccompanyingPeriod) {
@ -36,6 +34,16 @@ class AccompanyingPeriodContext implements DocGeneratorContextInterface
// TODO: Implement getForm() method. // TODO: Implement getForm() method.
} }
public static function getKey(): string
{
return self::class;
}
public function getName(): string
{
return 'Accompanying Period';
}
public function hasForm(): bool public function hasForm(): bool
{ {
return false; return false;
@ -43,6 +51,6 @@ class AccompanyingPeriodContext implements DocGeneratorContextInterface
public function supports(string $entityClass): bool public function supports(string $entityClass): bool
{ {
return $entityClass === AccompanyingPeriod::class; return AccompanyingPeriod::class === $entityClass;
} }
} }

View File

@ -0,0 +1,109 @@
<?php
namespace Serializer\Normalizer;
use Chill\MainBundle\Entity\Scope;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Entity\SocialWork\SocialIssue;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class AccompanyingPeriodDocGenNormalizerTest extends KernelTestCase
{
private NormalizerInterface $normalizer;
protected function setUp(): void
{
self::bootKernel();
$this->normalizer = self::$container->get(NormalizerInterface::class);
}
public function testNormalize()
{
$period = new AccompanyingPeriod();
$period->setConfidential(true);
$period->setEmergency(true);
$period->setOrigin((new AccompanyingPeriod\Origin())->setLabel(['fr' => 'origin']));
$period->setClosingMotive((new AccompanyingPeriod\ClosingMotive())->setName(['closing']));
$period->addScope((new Scope())->setName(['fr' => 'scope1']));
$period->addScope((new Scope())->setName(['fr' =>'scope2']));
$period->addSocialIssue((new SocialIssue())->setTitle(['fr' => 'issue1']));
$period->addSocialIssue((new SocialIssue())->setTitle(['fr' => 'issue2']));
$data = $this->normalizer->normalize($period, 'docgen', ['docgen:expects' => AccompanyingPeriod::class]);
$expected = [
'id' => null,
'closingDate' => '@ignored',
'confidential' => true,
'confidentialText' => 'confidentiel',
'createdAt' => '@ignored',
'createdBy' => '@ignored',
'emergency' => true,
'emergencyText' => 'Urgent',
'openingDate' => '@ignored',
'originText' => 'origin',
'requestorAnonymous' => false,
'socialIssues' => '@ignored',
'intensity' => 'ponctuel',
'step' => 'Brouillon',
'closingMotiveText' => 'closing',
'socialIssuesText' => 'issue1, issue2',
'scopes' => '@ignored',
'scopesText' => 'scope1, scope2',
'ref' => '@ignored',
'participations' => '@ignored',
];
$this->assertIsArray($data);
$this->assertEqualsCanonicalizing(array_keys($expected), array_keys($data));
foreach ($expected as $key => $item) {
if ($item === '@ignored') {
continue;
}
$this->assertEquals($item, $data[$key]);
}
}
public function testNormalizeNull()
{
$data = $this->normalizer->normalize(null, 'docgen', ['docgen:expects' => AccompanyingPeriod::class]);
$expected = [
'id' => "",
'closingDate' => '@ignored',
'confidential' => "",
'confidentialText' => '',
'createdAt' => '@ignored',
'createdBy' => '@ignored',
'emergency' => "",
'emergencyText' => '',
'openingDate' => '@ignored',
'originText' => '',
'requestorAnonymous' => '',
'socialIssues' => '@ignored',
'intensity' => '',
'step' => '',
'closingMotiveText' => '',
'socialIssuesText' => '',
'scopes' => '@ignored',
'scopesText' => '',
'ref' => '@ignored',
'participations' => '@ignored',
];
$this->assertIsArray($data);
$this->assertEqualsCanonicalizing(array_keys($expected), array_keys($data));
foreach ($expected as $key => $item) {
if ($item === '@ignored') {
continue;
}
$this->assertEquals($item, $data[$key]);
}
}
}

View File

@ -377,9 +377,14 @@ accompanying_period:
dates: Période dates: Période
dates_from_%opening_date%: Ouvert depuis le %opening_date% dates_from_%opening_date%: Ouvert depuis le %opening_date%
dates_from_%opening_date%_to_%closing_date%: Ouvert du %opening_date% au %closing_date% dates_from_%opening_date%_to_%closing_date%: Ouvert du %opening_date% au %closing_date%
DRAFT: Brouillon
CONFIRMED: Confirmé
CLOSED: Clotûré
emergency: Urgent
occasional: ponctuel occasional: ponctuel
regular: régulier regular: régulier
Confidential: confidentiel Confidential: confidentiel
confidential: confidentiel
Draft: brouillon Draft: brouillon
Confirmed: en file active Confirmed: en file active
Closed: Cloturé Closed: Cloturé