Skip to content

Commit

Permalink
feat: Using interfaces from core (related to novosga/novosga#385)
Browse files Browse the repository at this point in the history
  • Loading branch information
rogeriolino committed Oct 21, 2024
1 parent f1b09dc commit 17c5f26
Show file tree
Hide file tree
Showing 16 changed files with 284 additions and 233 deletions.
13 changes: 13 additions & 0 deletions .github/ISSUE_TEMPLATE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
| Q | A
| ---------------- | -----
| Bug report? | yes/no
| Feature request? | yes/no
| Novo SGA version | x.y.z
| PHP version | x.y.z
| Database version | MySQL 5.7/PostgreSQL 15
| Platform/OS | Linux/Windows

<!--
- Please fill in this template according to your issue.
- Replace this comment by the description of your issue.
-->
24 changes: 24 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: CI

on: [push]

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: shivammathur/[email protected]
with:
php-version: 8.2

- name: Install dependencies
run: composer install

- name: PHP Code Standards
run: vendor/bin/phpcs

- name: PHP Code Analysis
run: vendor/bin/phpstan

- name: PHP Unit Tests
run: vendor/bin/phpunit
1 change: 1 addition & 0 deletions .phpunit.result.cache
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"version":1,"defects":[],"times":[]}
23 changes: 23 additions & 0 deletions phpcs.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>

<ruleset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/squizlabs/php_codesniffer/phpcs.xsd">

<config name="installed_paths" value="../../slevomat/coding-standard"/>

<arg name="basepath" value="."/>
<arg name="cache" value=".phpcs-cache"/>
<arg name="colors"/>
<arg name="extensions" value="php"/>

<rule ref="PSR12"/>
<rule ref="SlevomatCodingStandard.Namespaces.UnusedUses">
<properties>
<property name="searchAnnotations" value="true" />
</properties>
</rule>

<file>src/</file>
<file>tests/</file>

</ruleset>
5 changes: 5 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
parameters:
level: 6
paths:
- src/
- tests/
31 changes: 31 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>

<!-- https://phpunit.readthedocs.io/en/latest/configuration.html -->
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
backupGlobals="false"
colors="true"
convertDeprecationsToExceptions="false"
>
<php>
<ini name="display_errors" value="1" />
<ini name="error_reporting" value="-1" />
<server name="APP_ENV" value="test" force="true" />
<server name="SHELL_VERBOSITY" value="-1" />
</php>

<testsuites>
<testsuite name="Project Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>

<coverage processUncoveredFiles="true">
<include>
<directory suffix=".php">src</directory>
</include>
</coverage>

<extensions>
</extensions>
</phpunit>
45 changes: 28 additions & 17 deletions src/Controller/DefaultController.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public function index(
UsuarioRepositoryInterface $repository,
): Response {
$search = $request->get('q');
/** @var Usuario */
/** @var UsuarioInterface */
$usuario = $this->getUser();
$unidade = $usuario->getLotacao()->getUnidade();

Expand Down Expand Up @@ -188,6 +188,7 @@ private function form(
): Response {
/** @var UsuarioInterface */
$currentUser = $this->getUser();
$unidade = $currentUser->getLotacao()->getUnidade();
$unidades = $unidadeRepository->findByUsuario($currentUser);
$isAdmin = $currentUser->isAdmin();

Expand All @@ -211,7 +212,7 @@ private function form(
throw new Exception($error);
}
}

$lotacoesRemovidas = [];
if ($form->isSubmitted() && $form->isValid()) {
try {
Expand All @@ -226,7 +227,7 @@ private function form(
$error = $translator->trans('error.remove_lotation_permission_denied', [
'%unidade%' => $lotacao->getUnidade(),
], NovosgaUsersBundle::getDomain());

throw new Exception($error);
}
$lotacoesRemovidas[] = $lotacao;
Expand All @@ -246,15 +247,16 @@ private function form(

if ($unidade && $perfil) {
if (!$isAdmin && !in_array($unidade, $unidades)) {
$error = $translator->trans('error.add_lotation_permission_denied', [
'%unidade%' => $lotacao->getUnidade(),
], NovosgaUsersBundle::getDomain());

$error = $translator->trans(
'error.add_lotation_permission_denied',
[ '%unidade%' => $unidade ],
NovosgaUsersBundle::getDomain(),
);
throw new Exception($error);
}

$lotacao = null;

// tenta reaproveitar uma lotacao da mesma unidade
foreach ($lotacoesRemovidas as $l) {
if ($l->getUnidade()->getId() === $unidade->getId()) {
Expand All @@ -264,9 +266,10 @@ private function form(
}

if (!$lotacao) {
$lotacao = $lotacaoService->build();
$lotacao->setUnidade($unidade);
$lotacao->setUsuario($entity);
$lotacao = $lotacaoService
->build()
->setUnidade($unidade)
->setUsuario($entity);
}

$lotacao->setPerfil($perfil);
Expand All @@ -283,7 +286,11 @@ private function form(
$unidadesMap = [];
foreach ($entity->getLotacoes() as $lotacao) {
if (isset($unidadesMap[$lotacao->getUnidade()->getId()])) {
throw new Exception($translator->trans('error.more_than_one_lotation', [], NovosgaUsersBundle::getDomain()));
throw new Exception($translator->trans(
'error.more_than_one_lotation',
[],
NovosgaUsersBundle::getDomain(),
));
}
$unidadesMap[$lotacao->getUnidade()->getId()] = true;
}
Expand All @@ -299,12 +306,12 @@ private function form(
$entity
->setSenha($encoded)
->setAtivo(true)
->setAdmin(false);
->setAdmin(false);
}

$em->persist($entity);
$em->flush();

if (!$isNew) {
$lotacoes = $entity->getLotacoes()->toArray();
$lotacao = end($lotacoes);
Expand All @@ -315,7 +322,11 @@ private function form(
);
}

$this->addFlash('success', $translator->trans('label.add_success', [], NovosgaUsersBundle::getDomain()));
$this->addFlash('success', $translator->trans(
'label.add_success',
[],
NovosgaUsersBundle::getDomain(),
));

return $this->redirectToRoute('novosga_users_edit', [ 'id' => $entity->getId() ]);
} catch (Exception $e) {
Expand Down
2 changes: 1 addition & 1 deletion src/DependencyInjection/NovosgaUsersExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class NovosgaUsersExtension extends Extension
*/
public function load(array $configs, ContainerBuilder $container)
{
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('services.yml');
}
}
16 changes: 6 additions & 10 deletions src/Form/ChangePasswordType.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,7 @@

class ChangePasswordType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
/** {@inheritDoc} */
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
Expand All @@ -44,8 +41,8 @@ public function buildForm(FormBuilderInterface $builder, array $options)
'constraints' => [
new Length([ 'min' => 6 ]),
new Callback(function ($object, ExecutionContextInterface $context, $payload) {
$form = $context->getRoot();
$senha = $form->get('senha');
$form = $context->getRoot();
$senha = $form->get('senha');
$confirmacao = $form->get('confirmacaoSenha');

if ($senha->getData() !== $confirmacao->getData()) {
Expand All @@ -61,16 +58,15 @@ public function buildForm(FormBuilderInterface $builder, array $options)
]);
}

/**
* {@inheritdoc}
*/
/** {@inheritDoc} */
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'translation_domain' => 'NovosgaUsersBundle',
]);
}


/** {@inheritDoc} */
public function getBlockPrefix()
{
return '';
Expand Down
84 changes: 34 additions & 50 deletions src/Form/LotacaoType.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,80 +13,64 @@

namespace Novosga\UsersBundle\Form;

use Doctrine\ORM\EntityRepository;
use App\Entity\Perfil;
use App\Entity\Lotacao;
use App\Entity\Unidade;
use App\Entity\Usuario;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Novosga\Entity\LotacaoInterface;
use Novosga\Entity\PerfilInterface;
use Novosga\Entity\UnidadeInterface;
use Novosga\Entity\UsuarioInterface;
use Novosga\Repository\PerfilRepositoryInterface;
use Novosga\Repository\UnidadeRepositoryInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class LotacaoType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function __construct(
private readonly UnidadeRepositoryInterface $unidadeRepository,
private readonly PerfilRepositoryInterface $perfilRepository,
) {
}

/** {@inheritDoc} */
public function buildForm(FormBuilderInterface $builder, array $options)
{
$ignore = $options['ignore'];
$ignoreList = (array) $options['ignore'];
$usuario = $options['usuario'];

$unidadesUsuario = $this->unidadeRepository->findByUsuario($usuario);
$unidadesDisponiveis = array_values(array_filter(
$unidadesUsuario,
fn (UnidadeInterface $unidade) => !in_array($unidade->getId(), $ignoreList),
));

$builder
->add('unidade', EntityType::class, [
'class' => Unidade::class,
->add('unidade', ChoiceType::class, [
'placeholder' => '',
'query_builder' => function (EntityRepository $er) use ($usuario, $ignore) {
$qb = $er
->createQueryBuilder('e')
->where('e.deletedAt IS NULL')
->orderBy('e.nome', 'ASC');

if (!$usuario->isAdmin()) {
$qb
->join(Lotacao::class, 'l', 'WITH', 'l.unidade = e')
->andWhere('l.usuario = :usuario')
->andWhere('e.deletedAt IS NULL')
->setParameter('usuario', $usuario);
}

if (count($ignore)) {
$qb
->andWhere('e.id NOT IN (:ignore)')
->setParameter('ignore', $ignore);
}

return $qb;
},
'choice_value' => fn (?UnidadeInterface $value) => $value?->getId(),
'choice_label' => fn (?UnidadeInterface $value) => $value?->getNome(),
'choices' => $unidadesDisponiveis,
'label' => 'form.lotacao.unidade',
])
->add('perfil', EntityType::class, [
'class' => Perfil::class,
->add('perfil', ChoiceType::class, [
'placeholder' => '',
'query_builder' => function (EntityRepository $er) {
return $er
->createQueryBuilder('e')
->orderBy('e.nome', 'ASC');
},
'choice_value' => fn (?PerfilInterface $value) => $value?->getId(),
'choice_label' => fn (?PerfilInterface $value) => $value?->getNome(),
'choices' => $this->perfilRepository->findAll(),
'label' => 'form.lotacao.perfil',
])
;
}

/**
*
* @param OptionsResolver $resolver
*/

/** {@inheritDoc} */
public function configureOptions(OptionsResolver $resolver)
{
$resolver
->setDefaults([
'data_class' => Lotacao::class,
'data_class' => LotacaoInterface::class,
'translation_domain' => 'NovosgaUsersBundle',
])
->setRequired(['usuario', 'ignore'])
->setAllowedTypes('usuario', [ Usuario::class ]);
->setAllowedTypes('ignore', [ 'array' ])
->setAllowedTypes('usuario', [ UsuarioInterface::class ]);
}
}
Loading

0 comments on commit 17c5f26

Please sign in to comment.