Merge branch 'docgen/improve-normalizer' into issue321_layout_improvements_actionForm

This commit is contained in:
2021-12-10 11:47:30 +01:00
36 changed files with 868 additions and 167 deletions

View File

@@ -14,10 +14,10 @@ namespace Chill\PersonBundle\Controller;
use Chill\MainBundle\CRUD\Controller\ApiController;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Repository\Relationships\RelationshipRepository;
use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use function array_values;
class RelationshipApiController extends ApiController
{
@@ -36,9 +36,10 @@ class RelationshipApiController extends ApiController
*/
public function getRelationshipsByPerson(Person $person)
{
//TODO: add permissions? (voter?)
$this->denyAccessUnlessGranted(PersonVoter::SEE, $person);
$relationships = $this->repository->findByPerson($person);
return $this->json(array_values($relationships), Response::HTTP_OK, [], ['groups' => ['read']]);
return $this->json($relationships, Response::HTTP_OK, [], ['groups' => ['read']]);
}
}

View File

@@ -65,7 +65,7 @@ class HouseholdMember
* @ORM\Column(type="integer")
* @Serializer\Groups({"read", "docgen:read"})
*/
private $id;
private ?int $id = null;
/**
* @var Person
@@ -73,6 +73,7 @@ class HouseholdMember
* targetEntity="\Chill\PersonBundle\Entity\Person"
* )
* @Serializer\Groups({"read", "docgen:read"})
* @Serializer\Context({"docgen:person:with-household": false})
* @Assert\Valid(groups={"household_memberships"})
* @Assert\NotNull(groups={"household_memberships"})
*/

View File

@@ -35,7 +35,7 @@ class Position
* @ORM\Column(type="integer")
* @Serializer\Groups({"read", "docgen:read"})
*/
private ?int $id;
private ?int $id = null;
/**
* @ORM\Column(type="json")

View File

@@ -588,8 +588,6 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
return $this;
}
// a period opened and another one after it
/**
* Function used for validation that check if the accompanying periods of
* the person are not collapsing (i.e. have not shared days) or having

View File

@@ -19,6 +19,7 @@ use DateTimeImmutable;
use DateTimeInterface;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\DiscriminatorColumn;
use RuntimeException;
use Symfony\Component\Serializer\Annotation as Serializer;
use Symfony\Component\Serializer\Annotation\DiscriminatorMap;
use Symfony\Component\Validator\Constraints as Assert;
@@ -116,6 +117,27 @@ class Relationship implements TrackCreationInterface, TrackUpdateInterface
return $this->id;
}
/**
* Return the opposite person of the @see{counterpart} person.
*
* this is the from person if the given is associated to the To,
* or the To person otherwise.
*
* @throw RuntimeException if the counterpart is neither in the from or to person
*/
public function getOpposite(Person $counterpart): Person
{
if ($this->fromPerson !== $counterpart && $this->toPerson !== $counterpart) {
throw new RuntimeException('the counterpart is neither the from nor to person for this relationship');
}
if ($this->fromPerson === $counterpart) {
return $this->toPerson;
}
return $this->fromPerson;
}
public function getRelation(): ?Relation
{
return $this->relation;

View File

@@ -11,18 +11,31 @@ declare(strict_types=1);
namespace Chill\PersonBundle\Repository\Relationships;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Entity\Relationships\Relationship;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
use Doctrine\Persistence\ObjectRepository;
class RelationshipRepository implements ObjectRepository
{
private EntityManagerInterface $em;
private EntityRepository $repository;
public function __construct(EntityManagerInterface $em)
{
$this->repository = $em->getRepository(Relationship::class);
$this->em = $em;
}
public function countByPerson(Person $person): int
{
return $this->buildQueryByPerson($person)
->select('COUNT(p)')
->getQuery()
->getSingleScalarResult();
}
public function find($id): ?Relationship
@@ -40,15 +53,13 @@ class RelationshipRepository implements ObjectRepository
return $this->repository->findBy($criteria, $orderBy, $limit, $offset);
}
public function findByPerson($personId): array
/**
* @return array|Relationship[]
*/
public function findByPerson(Person $person): array
{
// return all relationships of which person is part? or only where person is the fromPerson?
return $this->repository->createQueryBuilder('r')
->select('r, t') // entity Relationship
->join('r.relation', 't')
->where('r.fromPerson = :val')
->orWhere('r.toPerson = :val')
->setParameter('val', $personId)
return $this->buildQueryByPerson($person)
->select('r')
->getQuery()
->getResult();
}
@@ -62,4 +73,20 @@ class RelationshipRepository implements ObjectRepository
{
return Relationship::class;
}
private function buildQueryByPerson(Person $person): QueryBuilder
{
$qb = $this->em->createQueryBuilder();
$qb
->from(Relationship::class, 'r')
->where(
$qb->expr()->orX(
$qb->expr()->eq('r.fromPerson', ':person'),
$qb->expr()->eq('r.toPerson', ':person')
)
)
->setParameter('person', $person);
return $qb;
}
}

View File

@@ -16,6 +16,8 @@ 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\AccompanyingPeriodParticipation;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Entity\SocialWork\SocialIssue;
use Chill\PersonBundle\Templating\Entity\ClosingMotiveRender;
use Chill\PersonBundle\Templating\Entity\SocialIssueRender;
@@ -89,17 +91,6 @@ class AccompanyingPeriodDocGenNormalizer implements ContextAwareNormalizerInterf
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) : [];
@@ -107,28 +98,45 @@ class AccompanyingPeriodDocGenNormalizer implements ContextAwareNormalizerInterf
$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,
]
);
$dateContext = array_merge($context, ['docgen:expects' => DateTime::class, 'groups' => 'docgen:read']);
$userContext = array_merge($context, ['docgen:expects' => User::class, 'groups' => 'docgen:read']);
$participationContext = array_merge($context, ['docgen:expects' => AccompanyingPeriodParticipation::class, 'groups' => 'docgen:read']);
return [
'id' => $period->getId(),
'closingDate' => $this->normalizer->normalize($period->getClosingDate(), $format, $dateContext),
'confidential' => $period->isConfidential(),
'createdAt' => $this->normalizer->normalize($period->getCreatedAt(), $format, $dateContext),
'createdBy' => $this->normalizer->normalize($period->getCreatedBy(), $format, $userContext),
'emergency' => $period->isEmergency(),
'openingDate' => $this->normalizer->normalize($period->getOpeningDate(), $format, $dateContext),
'origin' => $this->normalizer->normalize($period->getOrigin(), $format, array_merge($context, ['docgen:expects' => AccompanyingPeriod\Origin::class])),
'participations' => $this->normalizer->normalize($period->getParticipations(), $format, $participationContext),
'currentParticipations' => $this->normalizer->normalize($period->getCurrentParticipations(), $format, $participationContext),
'requestorAnonymous' => $period->isRequestorAnonymous(),
'requestor' => $this->normalizer->normalize($period->getRequestor(), $format, array_merge($context, ['docgen:expects' => Person::class])),
'resources' => $this->normalizer->normalize($period->getResources(), $format, $context),
'scopes' => $this->normalizer->normalize($period->getScopes(), $format, array_merge($context, ['docgen:expects' => Scope::class, 'groups' => 'docgen:read'])),
'socialIssues' => $this->normalizer->normalize($period->getSocialIssues(), $format, $context),
'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()) : '',
'isClosed' => $period->getClosingDate() !== null,
'closingMotiveText' => null !== $period->getClosingMotive() ?
$this->closingMotiveRender->renderString($period->getClosingMotive(), []) : '',
'ref' => $this->normalizer->normalize($period->getUser(), $format, $userContext),
'hasRef' => $period->getUser() !== null,
'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,
'hasRequestor' => $period->getRequestor() !== null,
];
} elseif (null === $period) {
return self::PERIOD_NULL;
}
@@ -143,10 +151,10 @@ class AccompanyingPeriodDocGenNormalizer implements ContextAwareNormalizerInterf
}
if ($data instanceof AccompanyingPeriod) {
if (array_key_exists(self::IGNORE_FIRST_PASS_KEY, $context)
/*if (array_key_exists(self::IGNORE_FIRST_PASS_KEY, $context)
&& in_array(spl_object_hash($data), $context[self::IGNORE_FIRST_PASS_KEY], true)) {
return false;
}
}*/
return true;
}

View File

@@ -13,8 +13,10 @@ namespace Chill\PersonBundle\Serializer\Normalizer;
use Chill\DocGeneratorBundle\Serializer\Helper\NormalizeNullValueHelper;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Chill\PersonBundle\Entity\Household\Household;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Entity\PersonAltName;
use Chill\PersonBundle\Repository\Relationships\RelationshipRepository;
use Chill\PersonBundle\Templating\Entity\PersonRender;
use DateTimeInterface;
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
@@ -33,16 +35,20 @@ class PersonDocGenNormalizer implements
private PersonRender $personRender;
private RelationshipRepository $relationshipRepository;
private TranslatableStringHelper $translatableStringHelper;
private TranslatorInterface $translator;
public function __construct(
PersonRender $personRender,
RelationshipRepository $relationshipRepository,
TranslatorInterface $translator,
TranslatableStringHelper $translatableStringHelper
) {
$this->personRender = $personRender;
$this->relationshipRepository = $relationshipRepository;
$this->translator = $translator;
$this->translatableStringHelper = $translatableStringHelper;
}
@@ -57,7 +63,8 @@ class PersonDocGenNormalizer implements
return $this->normalizeNullValue($format, $context);
}
return [
$data = [
'kind' => 'person',
'firstname' => $person->getFirstName(),
'lastname' => $person->getLastName(),
'altNames' => implode(
@@ -84,6 +91,28 @@ class PersonDocGenNormalizer implements
'memo' => $person->getMemo(),
'numberOfChildren' => (string) $person->getNumberOfChildren(),
];
if ($context['docgen:person:with-household'] ?? false) {
$data['household'] = $this->normalizer->normalize(
$person->getCurrentHousehold(),
$format,
array_merge($context, ['docgen:expects' => Household::class])
);
}
if ($context['docgen:person:with-relations'] ?? false) {
$data['relations'] = $this->normalizer->normalize(
$this->relationshipRepository->findByPerson($person),
$format,
array_merge($context, [
'docgen:person:with-household' => false,
'docgen:person:with-relation' => false,
'docgen:relationship:counterpart' => $person,
])
);
}
return $data;
}
public function supportsNormalization($data, ?string $format = null, array $context = [])

View File

@@ -0,0 +1,90 @@
<?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\Serializer\Normalizer;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Entity\Relationships\Relationship;
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
class RelationshipDocGenNormalizer implements ContextAwareNormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;
private TranslatableStringHelperInterface $translatableStringHelper;
public function __construct(TranslatableStringHelperInterface $translatableStringHelper)
{
$this->translatableStringHelper = $translatableStringHelper;
}
/**
* @param Relationship $relation
*/
public function normalize($relation, ?string $format = null, array $context = [])
{
$counterpart = $context['docgen:relationship:counterpart'] ?? null;
$contextPerson = array_merge($context, [
'docgen:person:with-relation' => false,
'docgen:relationship:counterpart' => null,
'docgen:expects' => Person::class,
]);
if (null !== $counterpart) {
$opposite = $relation->getOpposite($counterpart);
} else {
$opposite = null;
}
if (null === $relation) {
return [
'id' => '',
'fromPerson' => $nullPerson = $this->normalizer->normalize(null, $format, $contextPerson),
'toPerson' => $nullPerson,
'opposite' => $nullPerson,
'text' => '',
'relationId' => '',
];
}
return [
'id' => $relation->getId(),
'fromPerson' => $this->normalizer->normalize(
$relation->getFromPerson(),
$format,
$contextPerson
),
'toPerson' => $this->normalizer->normalize(
$relation->getToPerson(),
$format,
$contextPerson
),
'text' => $relation->getReverse() ?
$this->translatableStringHelper->localize($relation->getRelation()->getReverseTitle()) :
$this->translatableStringHelper->localize($relation->getRelation()->getTitle()),
'opposite' => $this->normalizer->normalize($opposite, $format, $contextPerson),
'relationId' => $relation->getRelation()->getId(),
];
}
public function supportsNormalization($data, ?string $format = null, array $context = [])
{
if ('docgen' !== $format) {
return false;
}
return $data instanceof Relationship || (null === $data
&& Relationship::class === ($context['docgen:expects'] ?? null));
}
}

View File

@@ -36,8 +36,8 @@ class SocialActionNormalizer implements NormalizerAwareInterface, NormalizerInte
'id' => $socialAction->getId(),
'type' => 'social_work_social_action',
'text' => $this->render->renderString($socialAction, []),
'parent' => $this->normalizer->normalize($socialAction->getParent()),
'desactivationDate' => $this->normalizer->normalize($socialAction->getDesactivationDate()),
'parent' => $this->normalizer->normalize($socialAction->getParent(), $format, $context),
'desactivationDate' => $this->normalizer->normalize($socialAction->getDesactivationDate(), $format, $context),
'title' => $socialAction->getTitle(),
];

View File

@@ -68,6 +68,8 @@ class AccompanyingPeriodContext implements
public function adminFormReverseTransform(array $data): array
{
dump($data);
if (array_key_exists('category', $data)) {
$data['category'] = [
'idInsideBundle' => $data['category']->getIdInsideBundle(),
@@ -80,7 +82,7 @@ class AccompanyingPeriodContext implements
public function adminFormTransform(array $data): array
{
$data = [
$r = [
'mainPerson' => $data['mainPerson'] ?? false,
'mainPersonLabel' => $data['mainPersonLabel'] ?? $this->translator->trans('docgen.Main person'),
'person1' => $data['person1'] ?? false,
@@ -90,11 +92,11 @@ class AccompanyingPeriodContext implements
];
if (array_key_exists('category', $data)) {
$data['category'] = array_key_exists('category', $data) ?
$r['category'] = array_key_exists('category', $data) ?
$this->documentCategoryRepository->find($data['category']) : null;
}
return $data;
return $r;
}
public function buildAdminForm(FormBuilderInterface $builder): void
@@ -169,11 +171,11 @@ class AccompanyingPeriodContext implements
$options = $template->getOptions();
$data = [];
$data['course'] = $this->normalizer->normalize($entity, 'docgen', ['docgen:expects' => AccompanyingPeriod::class]);
$data['course'] = $this->normalizer->normalize($entity, 'docgen', ['docgen:expects' => AccompanyingPeriod::class, 'groups' => 'docgen:read']);
foreach (['mainPerson', 'person1', 'person2'] as $k) {
if ($options[$k]) {
$data[$k] = $this->normalizer->normalize($contextGenerationData[$k], 'docgen', ['docgen:expects' => Person::class]);
$data[$k] = $this->normalizer->normalize($contextGenerationData[$k], 'docgen', ['docgen:expects' => Person::class, 'groups' => 'docgen:read']);
}
}
@@ -204,7 +206,7 @@ class AccompanyingPeriodContext implements
public function getName(): string
{
return 'Accompanying Period basic';
return 'docgen.Accompanying Period basic';
}
public function hasAdminForm(): bool
@@ -231,7 +233,7 @@ class AccompanyingPeriodContext implements
->setCourse($entity)
->setObject($storedObject);
if (array_key_exists('category', $template->getOptions()['category'])) {
if (array_key_exists('category', $template->getOptions())) {
$doc
->setCategory(
$this->documentCategoryRepository->find(

View File

@@ -102,7 +102,7 @@ class AccompanyingPeriodWorkContext implements
public function getName(): string
{
return 'Accompanying period work';
return 'docgen.Accompanying period work';
}
public function hasAdminForm(): bool

View File

@@ -153,7 +153,7 @@ class AccompanyingPeriodWorkEvaluationContext implements
public function getName(): string
{
return 'Accompanying period work context';
return 'docgen.Accompanying period work context';
}
public function hasAdminForm(): bool

View File

@@ -388,7 +388,7 @@ final class AccompanyingCourseApiControllerTest extends WebTestCase
$this->assertTrue(in_array($this->client->getResponse()->getStatusCode(), [200, 422], true));
if ($response->getStatusCode() === 422) {
if ($this->client->getResponse()->getStatusCode() === 422) {
$this->markTestSkipped('the next tests should appears only on valid accompanying period');
}
@@ -522,7 +522,7 @@ final class AccompanyingCourseApiControllerTest extends WebTestCase
$this->assertTrue(in_array($this->client->getResponse()->getStatusCode(), [200, 422], true));
if ($response->getStatusCode() === 422) {
if ($this->client->getResponse()->getStatusCode() === 422) {
$this->markTestSkipped('the next tests should appears only on valid accompanying period');
}

View File

@@ -11,9 +11,21 @@ declare(strict_types=1);
namespace Serializer\Normalizer;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Chill\PersonBundle\Entity\Household\Household;
use Chill\PersonBundle\Entity\Household\HouseholdMember;
use Chill\PersonBundle\Entity\Household\Position;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Entity\Relationships\Relation;
use Chill\PersonBundle\Entity\Relationships\Relationship;
use Chill\PersonBundle\Repository\Relationships\RelationshipRepository;
use Chill\PersonBundle\Serializer\Normalizer\PersonDocGenNormalizer;
use Chill\PersonBundle\Templating\Entity\PersonRender;
use Prophecy\Argument;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use function array_merge;
/**
@@ -77,8 +89,124 @@ final class PersonDocGenNormalizerTest extends KernelTestCase
*/
public function testNormalize(?Person $person, $expected, $msg)
{
$normalized = $this->normalizer->normalize($person, 'docgen', ['docgen:expects' => Person::class]);
$normalized = $this->normalizer->normalize($person, 'docgen', [
'docgen:expects' => Person::class,
'groups' => 'docgen:read',
]);
$this->assertEquals($expected, $normalized, $msg);
}
public function testNormalizePersonWithHousehold()
{
$household = new Household();
$person = new Person();
$person
->setFirstName('Renaud')
->setLastName('Mégane');
$householdMember = new HouseholdMember();
$householdMember
->setPosition((new Position())->setAllowHolder(true)->setLabel(['fr' => 'position'])
->setShareHousehold(true))
->setHolder(true);
$person->addHouseholdParticipation($householdMember);
$household->addMember($householdMember);
$person = new Person();
$person
->setFirstName('Citroen')
->setLastName('Xsara');
$householdMember = new HouseholdMember();
$householdMember
->setPosition((new Position())->setAllowHolder(true)->setLabel(['fr' => 'position2'])
->setShareHousehold(true))
->setHolder(false);
$person->addHouseholdParticipation($householdMember);
$household->addMember($householdMember);
$actual = $this->normalizer->normalize($person, 'docgen', [
'groups' => 'docgen:read',
'docgen:expects' => Person::class,
'docgen:person:with-household' => true,
]);
$this->assertCount(2, $household->getMembers());
$this->assertIsArray($actual);
$this->assertArrayHasKey('household', $actual);
$this->assertCount(2, $actual['household']['currentMembers']);
$this->assertCount(2, $actual['household']['members']);
}
public function testNormalizePersonWithRelationships()
{
$person = (new Person())->setFirstName('Renaud')->setLastName('megane');
$father = (new Person())->setFirstName('Clément')->setLastName('megane');
$mother = (new Person())->setFirstName('Mireille')->setLastName('Mathieu');
$sister = (new Person())->setFirstName('Callie')->setLastName('megane');
$relations = [
(new Relationship())->setFromPerson($person)->setToPerson($father)
->setReverse(false)->setRelation((new Relation())->setTitle(['fr' => 'Père'])
->setReverseTitle(['fr' => 'Fils'])),
(new Relationship())->setFromPerson($person)->setToPerson($mother)
->setReverse(false)->setRelation((new Relation())->setTitle(['fr' => 'Mère'])
->setReverseTitle(['fr' => 'Fils'])),
(new Relationship())->setFromPerson($person)->setToPerson($sister)
->setReverse(true)->setRelation((new Relation())->setTitle(['fr' => 'Frère'])
->setReverseTitle(['fr' => 'Soeur'])),
];
$repository = $this->prophesize(RelationshipRepository::class);
$repository->findByPerson($person)->willReturn($relations);
$normalizer = $this->buildPersonNormalizer(null, $repository->reveal(), null, null);
$actual = $normalizer->normalize($person, 'docgen', [
'groups' => 'docgen:read',
'docgen:expects' => Person::class,
'docgen:person:with-relations' => true,
]);
$this->assertIsArray($actual);
$this->assertArrayHasKey('relations', $actual);
$this->assertCount(3, $actual['relations']);
}
private function buildPersonNormalizer(
?PersonRender $personRender = null,
?RelationshipRepository $relationshipRepository = null,
?TranslatorInterface $translator = null,
?TranslatableStringHelper $translatableStringHelper = null
): PersonDocGenNormalizer {
$normalizer = new PersonDocGenNormalizer(
$personRender ?? self::$container->get(PersonRender::class),
$relationshipRepository ?? self::$container->get(RelationshipRepository::class),
$translator ?? self::$container->get(TranslatorInterface::class),
$translatableStringHelper ?? self::$container->get(TranslatableStringHelperInterface::class)
);
$normalizerManager = $this->prophesize(NormalizerInterface::class);
$normalizerManager->supportsNormalization(Argument::any(), 'docgen', Argument::any())->willReturn(true);
$normalizerManager->normalize(Argument::type(Person::class), 'docgen', Argument::any())
->will(static function ($args) use ($normalizer) {
return $normalizer->normalize($args[0], $args[1], $args[2]);
});
$normalizerManager->normalize(Argument::any(), 'docgen', Argument::any())->will(
static function ($args) {
if (is_iterable($args[0])) {
$r = [];
foreach ($args[0] as $i) {
$r[] = ['fake' => true, 'hash' => spl_object_hash($i)];
}
return $r;
}
return ['fake' => true, 'hash' => null !== $args[0] ? spl_object_hash($args[0]) : null];
}
);
$normalizer->setNormalizer($normalizerManager->reveal());
return $normalizer;
}
}

View File

@@ -0,0 +1,158 @@
<?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 Serializer\Normalizer;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Entity\Relationships\Relation;
use Chill\PersonBundle\Entity\Relationships\Relationship;
use Chill\PersonBundle\Serializer\Normalizer\RelationshipDocGenNormalizer;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use function is_object;
/**
* @internal
* @coversNothing
*/
final class RelationshipDocGenNormalizerTest extends TestCase
{
public function testNormalizeRelationshipNull()
{
$relationship = null;
$normalizer = $this->buildNormalizer();
$this->assertTrue($normalizer->supportsNormalization($relationship, 'docgen', [
'docgen:expects' => Relationship::class,
]));
$this->assertFalse($normalizer->supportsNormalization($relationship, 'docgen', [
'docgen:expects' => Person::class,
]));
$actual = $normalizer->normalize($relationship, 'docgen', [
'docgen:expects' => Relationship::class,
]);
$this->assertIsArray($actual);
$this->assertEqualsCanonicalizing(
['fromPerson', 'toPerson', 'id', 'relationId', 'text', 'opposite'],
array_keys($actual),
'check that the expected keys are present'
);
}
public function testNormalizeRelationshipWithCounterPart()
{
$relationship = new Relationship();
$relationship
->setFromPerson($person1 = new Person())
->setToPerson($person2 = new Person())
->setRelation(
(new Relation())->setTitle(['fr' => 'title'])
->setReverseTitle(['fr' => 'reverse title'])
)
->setReverse(false);
$normalizer = $this->buildNormalizer();
$this->assertTrue($normalizer->supportsNormalization($relationship, 'docgen', []));
$this->assertFalse($normalizer->supportsNormalization($person1, 'docgen', []));
$actual = $normalizer->normalize($relationship, 'docgen', [
'docgen:expects' => Relationship::class,
'docgen:relationship:counterpart' => $person1,
]);
$this->assertIsArray($actual);
$this->assertEqualsCanonicalizing(
['fromPerson', 'toPerson', 'id', 'relationId', 'text', 'opposite'],
array_keys($actual),
'check that the expected keys are present'
);
$this->assertEquals(spl_object_hash($person2), $actual['opposite']['hash']);
}
public function testNormalizeRelationshipWithoutCounterPart()
{
$relationship = new Relationship();
$relationship
->setFromPerson($person1 = new Person())
->setToPerson($person2 = new Person())
->setRelation(
(new Relation())->setTitle(['fr' => 'title'])
->setReverseTitle(['fr' => 'reverse title'])
)
->setReverse(false);
$normalizer = $this->buildNormalizer();
$this->assertTrue($normalizer->supportsNormalization($relationship, 'docgen', []));
$this->assertFalse($normalizer->supportsNormalization($person1, 'docgen', []));
$actual = $normalizer->normalize($relationship, 'docgen', [
'docgen:expects' => Relationship::class,
]);
$this->assertIsArray($actual);
$this->assertEqualsCanonicalizing(
['fromPerson', 'toPerson', 'id', 'relationId', 'text', 'opposite'],
array_keys($actual),
'check that the expected keys are present'
);
$this->assertEquals(null, $actual['opposite']);
}
private function buildNormalizer(): RelationshipDocGenNormalizer
{
$translatableStringHelper = $this->prophesize(TranslatableStringHelperInterface::class);
$translatableStringHelper->localize(Argument::type('array'))->will(
static function ($args) { return $args[0][array_keys($args[0])[0]]; }
);
$normalizer = new RelationshipDocGenNormalizer(
$translatableStringHelper->reveal()
);
$normalizerManager = $this->prophesize(NormalizerInterface::class);
$normalizerManager->supportsNormalization(Argument::any(), 'docgen', Argument::any())->willReturn(true);
$normalizerManager->normalize(Argument::type(Relationship::class), 'docgen', Argument::any())
->will(static function ($args) use ($normalizer) {
return $normalizer->normalize($args[0], $args[1], $args[2]);
});
$normalizerManager->normalize(Argument::any(), 'docgen', Argument::any())->will(
static function ($args) {
if (null === $args[0]) {
return null;
}
if (is_iterable($args[0])) {
$r = [];
foreach ($args[0] as $i) {
$r[] = ['fake' => true, 'hash' => spl_object_hash($i)];
}
return $r;
}
if (is_object($args[0])) {
return ['fake' => true, 'hash' => null !== $args[0] ? spl_object_hash($args[0]) : null];
}
return $args[0];
}
);
$normalizer->setNormalizer($normalizerManager->reveal());
return $normalizer;
}
}

View File

@@ -455,13 +455,15 @@ see social issues: Voir les problématiques sociales
see persons associated: Voir les usagers concernés
docgen:
Accompanying Period basic: "Parcours d'accompagnement (basique)"
Accompanying period work: "Action d'accompagnement"
Accompanying period work context: "Evaluation des actions d'accompagnement"
Main person: Personne principale
person 1: Première personne
person 2: Seconde personne
Ask for main person: Demander à l'utilisateur de préciser la personne principale
Ask for person 1: Demander à l'utilisateur de préciser la première personne
Ask for person 2: Demander à l'utilisateur de préciser la seconde personne
Accompanying period work: Actions
A basic context for accompanying period: Contexte pour les parcours
A context for accompanying period work: Contexte pour les actions d'accompagnement
A context for accompanying period work evaluation: Contexte pour les évaluations dans les actions d'accompagnement