Minor: Format code

pull/6006/head
Angel Fernando Quiroz Campos 9 months ago
parent 85547e2b45
commit 2c679c951c
No known key found for this signature in database
GPG Key ID: B284841AE3E562CD
  1. 15
      src/CoreBundle/Controller/ValidationTokenController.php
  2. 2
      src/CoreBundle/DataTransformer/SkillTreeNodeTransformer.php
  3. 7
      src/CoreBundle/Entity/Session.php
  4. 4
      src/CoreBundle/Entity/Skill.php
  5. 14
      src/CoreBundle/Entity/SkillProfile.php
  6. 15
      src/CoreBundle/Entity/ValidationToken.php
  7. 12
      src/CoreBundle/Form/DataTransformer/ResourceToIdentifierTransformer.php
  8. 1
      src/CoreBundle/Repository/TicketRelUserRepository.php
  9. 8
      src/CoreBundle/Repository/TrackEDefaultRepository.php
  10. 12
      src/CoreBundle/Security/Authenticator/OAuth2/AzureAuthenticator.php
  11. 4
      src/CoreBundle/Service/CourseService.php
  12. 6
      src/CoreBundle/ServiceHelper/AuthenticationConfigHelper.php
  13. 5
      src/CoreBundle/ServiceHelper/ValidationTokenHelper.php
  14. 8
      src/CoreBundle/Settings/SettingsManager.php
  15. 4
      src/CoreBundle/Tool/ToolChain.php
  16. 2
      tests/CoreBundle/Repository/SkillRepositoryTest.php

@ -14,12 +14,13 @@ use Chamilo\CoreBundle\Repository\TicketRepository;
use Chamilo\CoreBundle\Repository\TrackEDefaultRepository; use Chamilo\CoreBundle\Repository\TrackEDefaultRepository;
use Chamilo\CoreBundle\Repository\ValidationTokenRepository; use Chamilo\CoreBundle\Repository\ValidationTokenRepository;
use Chamilo\CoreBundle\ServiceHelper\ValidationTokenHelper; use Chamilo\CoreBundle\ServiceHelper\ValidationTokenHelper;
use InvalidArgumentException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use \Symfony\Component\Routing\Generator\UrlGeneratorInterface;
#[Route('/validate')] #[Route('/validate')]
class ValidationTokenController extends AbstractController class ValidationTokenController extends AbstractController
@ -39,11 +40,11 @@ class ValidationTokenController extends AbstractController
public function validate(string $type, string $hash): Response public function validate(string $type, string $hash): Response
{ {
$userId = $this->requestStack->getCurrentRequest()->query->get('user_id'); $userId = $this->requestStack->getCurrentRequest()->query->get('user_id');
$userId = $userId !== null ? (int) $userId : null; $userId = null !== $userId ? (int) $userId : null;
$token = $this->tokenRepository->findOneBy([ $token = $this->tokenRepository->findOneBy([
'type' => $this->validationTokenHelper->getTypeId($type), 'type' => $this->validationTokenHelper->getTypeId($type),
'hash' => $hash 'hash' => $hash,
]); ]);
if (!$token) { if (!$token) {
@ -61,7 +62,8 @@ class ValidationTokenController extends AbstractController
if ('ticket' === $type) { if ('ticket' === $type) {
$ticketId = $token->getResourceId(); $ticketId = $token->getResourceId();
return $this->redirect('/main/ticket/ticket_details.php?ticket_id=' . $ticketId);
return $this->redirect('/main/ticket/ticket_details.php?ticket_id='.$ticketId);
} }
return $this->render('@ChamiloCore/Validation/success.html.twig', [ return $this->render('@ChamiloCore/Validation/success.html.twig', [
@ -92,9 +94,11 @@ class ValidationTokenController extends AbstractController
switch ($token->getType()) { switch ($token->getType()) {
case ValidationTokenHelper::TYPE_TICKET: case ValidationTokenHelper::TYPE_TICKET:
$this->unsubscribeUserFromTicket($token->getResourceId(), $userId); $this->unsubscribeUserFromTicket($token->getResourceId(), $userId);
break; break;
default: default:
throw new \InvalidArgumentException('Unrecognized token type'); throw new InvalidArgumentException('Unrecognized token type');
} }
} }
@ -133,6 +137,7 @@ class ValidationTokenController extends AbstractController
private function getUserId(): ?int private function getUserId(): ?int
{ {
$user = $this->tokenStorage->getToken()?->getUser(); $user = $this->tokenStorage->getToken()?->getUser();
return $user instanceof User ? $user->getId() : null; return $user instanceof User ? $user->getId() : null;
} }
} }

@ -35,7 +35,7 @@ readonly class SkillTreeNodeTransformer implements DataTransformerInterface
} }
$skillNode->children = $object->getChildSkills() $skillNode->children = $object->getChildSkills()
->map(fn(Skill $childSkill) => $this->transform($childSkill, $to, $context)) ->map(fn (Skill $childSkill) => $this->transform($childSkill, $to, $context))
->toArray() ->toArray()
; ;

@ -812,8 +812,8 @@ class Session implements ResourceWithAccessUrlInterface, Stringable
{ {
foreach ($this->getUsers() as $existingSubscription) { foreach ($this->getUsers() as $existingSubscription) {
if ( if (
$existingSubscription->getUser()->getId() === $user->getId() && $existingSubscription->getUser()->getId() === $user->getId()
$existingSubscription->getRelationType() === $relationType && $existingSubscription->getRelationType() === $relationType
) { ) {
return $this; return $this;
} }
@ -821,7 +821,8 @@ class Session implements ResourceWithAccessUrlInterface, Stringable
$sessionRelUser = (new SessionRelUser()) $sessionRelUser = (new SessionRelUser())
->setUser($user) ->setUser($user)
->setRelationType($relationType); ->setRelationType($relationType)
;
$this->addUserSubscription($sessionRelUser); $this->addUserSubscription($sessionRelUser);
return $this; return $this;

@ -38,7 +38,7 @@ use Symfony\Component\Validator\Constraints as Assert;
uriTemplate: '/skills/tree.{_format}', uriTemplate: '/skills/tree.{_format}',
paginationEnabled: false, paginationEnabled: false,
normalizationContext: [ normalizationContext: [
'groups' => ['skill:tree:read'] 'groups' => ['skill:tree:read'],
], ],
output: SkillTreeNode::class, output: SkillTreeNode::class,
provider: SkillTreeStateProvider::class provider: SkillTreeStateProvider::class
@ -467,7 +467,7 @@ class Skill implements Stringable, Translatable
{ {
return $this return $this
->getSkills() ->getSkills()
->map(fn(SkillRelSkill $skillRelSkill): Skill => $skillRelSkill->getSkill()) ->map(fn (SkillRelSkill $skillRelSkill): Skill => $skillRelSkill->getSkill())
; ;
} }

@ -7,11 +7,6 @@ declare(strict_types=1);
namespace Chamilo\CoreBundle\Entity; namespace Chamilo\CoreBundle\Entity;
use ApiPlatform\Metadata\ApiResource; use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Metadata\Put;
use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection; use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
@ -65,9 +60,6 @@ class SkillProfile
return $this; return $this;
} }
/**
* Get title.
*/
public function getTitle(): string public function getTitle(): string
{ {
return $this->title; return $this->title;
@ -80,17 +72,11 @@ class SkillProfile
return $this; return $this;
} }
/**
* Get description.
*/
public function getDescription(): string public function getDescription(): string
{ {
return $this->description; return $this->description;
} }
/**
* Get id.
*/
public function getId(): ?int public function getId(): ?int
{ {
return $this->id; return $this->id;

@ -7,6 +7,7 @@ declare(strict_types=1);
namespace Chamilo\CoreBundle\Entity; namespace Chamilo\CoreBundle\Entity;
use Chamilo\CoreBundle\Repository\ValidationTokenRepository; use Chamilo\CoreBundle\Repository\ValidationTokenRepository;
use DateTime;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
/** /**
@ -32,14 +33,14 @@ class ValidationToken
protected string $hash; protected string $hash;
#[ORM\Column(type: 'datetime')] #[ORM\Column(type: 'datetime')]
protected \DateTime $createdAt; protected DateTime $createdAt;
public function __construct(int $type, int $resourceId) public function __construct(int $type, int $resourceId)
{ {
$this->type = $type; $this->type = $type;
$this->resourceId = $resourceId; $this->resourceId = $resourceId;
$this->hash = hash('sha256', uniqid((string) rand(), true)); $this->hash = hash('sha256', uniqid((string) rand(), true));
$this->createdAt = new \DateTime(); $this->createdAt = new DateTime();
} }
public function getId(): ?int public function getId(): ?int
@ -55,6 +56,7 @@ class ValidationToken
public function setType(int $type): self public function setType(int $type): self
{ {
$this->type = $type; $this->type = $type;
return $this; return $this;
} }
@ -66,6 +68,7 @@ class ValidationToken
public function setResourceId(int $resourceId): self public function setResourceId(int $resourceId): self
{ {
$this->resourceId = $resourceId; $this->resourceId = $resourceId;
return $this; return $this;
} }
@ -74,14 +77,15 @@ class ValidationToken
return $this->hash; return $this->hash;
} }
public function getCreatedAt(): \DateTime public function getCreatedAt(): DateTime
{ {
return $this->createdAt; return $this->createdAt;
} }
public function setCreatedAt(\DateTime $createdAt): self public function setCreatedAt(DateTime $createdAt): self
{ {
$this->createdAt = $createdAt; $this->createdAt = $createdAt;
return $this; return $this;
} }
@ -91,6 +95,7 @@ class ValidationToken
public static function generateLink(int $type, int $resourceId): string public static function generateLink(int $type, int $resourceId): string
{ {
$token = new self($type, $resourceId); $token = new self($type, $resourceId);
return '/validate/' . $type . '/' . $token->getHash();
return '/validate/'.$type.'/'.$token->getHash();
} }
} }

@ -7,8 +7,6 @@ namespace Chamilo\CoreBundle\Form\DataTransformer;
use Doctrine\Persistence\ObjectRepository; use Doctrine\Persistence\ObjectRepository;
use Symfony\Component\Form\DataTransformerInterface; use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Webmozart\Assert\Assert;
/** /**
* @template-implements DataTransformerInterface<object, int|string> * @template-implements DataTransformerInterface<object, int|string>
@ -31,7 +29,7 @@ final class ResourceToIdentifierTransformer implements DataTransformerInterface
return null; return null;
} }
if (is_object($value) && method_exists($value, 'getId')) { if (\is_object($value) && method_exists($value, 'getId')) {
return $value; return $value;
} }
@ -48,17 +46,13 @@ final class ResourceToIdentifierTransformer implements DataTransformerInterface
return null; return null;
} }
if (is_object($value) && method_exists($value, 'getId')) { if (\is_object($value) && method_exists($value, 'getId')) {
return $value; return $value;
} }
$resource = $this->repository->find($value); $resource = $this->repository->find($value);
if (null === $resource) { if (null === $resource) {
throw new TransformationFailedException(sprintf( throw new TransformationFailedException(\sprintf('Object "%s" with identifier "%s" does not exist.', $this->repository->getClassName(), $value));
'Object "%s" with identifier "%s" does not exist.',
$this->repository->getClassName(),
$value
));
} }
return $resource; return $resource;

@ -14,7 +14,6 @@ use Doctrine\Persistence\ManagerRegistry;
class TicketRelUserRepository extends ServiceEntityRepository class TicketRelUserRepository extends ServiceEntityRepository
{ {
public function __construct(ManagerRegistry $registry) public function __construct(ManagerRegistry $registry)
{ {
parent::__construct($registry, TicketRelUser::class); parent::__construct($registry, TicketRelUser::class);

@ -75,10 +75,10 @@ class TrackEDefaultRepository extends ServiceEntityRepository
$event = new TrackEDefault(); $event = new TrackEDefault();
$event->setDefaultUserId($userId ?? 0); $event->setDefaultUserId($userId ?? 0);
$event->setCId(null); $event->setCId(null);
$event->setDefaultDate(new \DateTime()); $event->setDefaultDate(new DateTime());
$event->setDefaultEventType('VALIDATION_TOKEN_USED'); $event->setDefaultEventType('VALIDATION_TOKEN_USED');
$event->setDefaultValueType('validation_token'); $event->setDefaultValueType('validation_token');
$event->setDefaultValue(\json_encode(['hash' => $token->getHash()])); $event->setDefaultValue(json_encode(['hash' => $token->getHash()]));
$event->setSessionId(null); $event->setSessionId(null);
$this->_em->persist($event); $this->_em->persist($event);
@ -93,10 +93,10 @@ class TrackEDefaultRepository extends ServiceEntityRepository
$event = new TrackEDefault(); $event = new TrackEDefault();
$event->setDefaultUserId($userId); $event->setDefaultUserId($userId);
$event->setCId($ticketId); $event->setCId($ticketId);
$event->setDefaultDate(new \DateTime()); $event->setDefaultDate(new DateTime());
$event->setDefaultEventType('ticket_unsubscribe'); $event->setDefaultEventType('ticket_unsubscribe');
$event->setDefaultValueType('ticket_event'); $event->setDefaultValueType('ticket_event');
$event->setDefaultValue(\json_encode(['user_id' => $userId, 'ticket_id' => $ticketId, 'action' => 'unsubscribe'])); $event->setDefaultValue(json_encode(['user_id' => $userId, 'ticket_id' => $ticketId, 'action' => 'unsubscribe']));
$event->setSessionId(null); $event->setSessionId(null);
$this->_em->persist($event); $this->_em->persist($event);

@ -59,21 +59,15 @@ class AzureAuthenticator extends AbstractAuthenticator
$me = $provider->get('/me', $accessToken); $me = $provider->get('/me', $accessToken);
if (empty($me['mail'])) { if (empty($me['mail'])) {
throw new UnauthorizedHttpException( throw new UnauthorizedHttpException('The mail field is empty in Azure AD and is needed to set the organisation email for this user.');
'The mail field is empty in Azure AD and is needed to set the organisation email for this user.'
);
} }
if (empty($me['mailNickname'])) { if (empty($me['mailNickname'])) {
throw new UnauthorizedHttpException( throw new UnauthorizedHttpException('The mailNickname field is empty in Azure AD and is needed to set the unique username for this user.');
'The mailNickname field is empty in Azure AD and is needed to set the unique username for this user.'
);
} }
if (empty($me['objectId'])) { if (empty($me['objectId'])) {
throw new UnauthorizedHttpException( throw new UnauthorizedHttpException('The id field is empty in Azure AD and is needed to set the unique Azure ID for this user.');
'The id field is empty in Azure AD and is needed to set the unique Azure ID for this user.'
);
} }
$userId = $this->azureHelper->registerUser($me); $userId = $this->azureHelper->registerUser($me);

@ -647,9 +647,9 @@ class CourseService
$cr->set_file_option(); $cr->set_file_option();
$cr->restore($courseCode); $cr->restore($courseCode);
} catch (Exception $e) { } catch (Exception $e) {
error_log('Error during course template application: ' . $e->getMessage()); error_log('Error during course template application: '.$e->getMessage());
} catch (Throwable $t) { } catch (Throwable $t) {
error_log('Unexpected error during course template application: ' . $t->getMessage()); error_log('Unexpected error during course template application: '.$t->getMessage());
} }
} }
} }

@ -50,7 +50,7 @@ readonly class AuthenticationConfigHelper
$enabledProviders[] = [ $enabledProviders[] = [
'name' => $providerName, 'name' => $providerName,
'title' => $providerParams['title'] ?? u($providerName)->title(), 'title' => $providerParams['title'] ?? u($providerName)->title(),
'url' => $this->urlGenerator->generate(sprintf("chamilo.oauth2_%s_start", $providerName)), 'url' => $this->urlGenerator->generate(\sprintf('chamilo.oauth2_%s_start', $providerName)),
]; ];
} }
} }
@ -77,7 +77,7 @@ readonly class AuthenticationConfigHelper
public function getProviderOptions(string $providerType, array $config): array public function getProviderOptions(string $providerType, array $config): array
{ {
$defaults = match($providerType) { $defaults = match ($providerType) {
'generic' => [ 'generic' => [
'clientId' => $config['client_id'], 'clientId' => $config['client_id'],
'clientSecret' => $config['client_secret'], 'clientSecret' => $config['client_secret'],
@ -126,6 +126,6 @@ readonly class AuthenticationConfigHelper
], ],
}; };
return array_filter($defaults, fn($value) => $value !== null); return array_filter($defaults, fn ($value) => null !== $value);
} }
} }

@ -8,6 +8,7 @@ namespace Chamilo\CoreBundle\ServiceHelper;
use Chamilo\CoreBundle\Entity\ValidationToken; use Chamilo\CoreBundle\Entity\ValidationToken;
use Chamilo\CoreBundle\Repository\ValidationTokenRepository; use Chamilo\CoreBundle\Repository\ValidationTokenRepository;
use InvalidArgumentException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class ValidationTokenHelper class ValidationTokenHelper
@ -38,7 +39,7 @@ class ValidationTokenHelper
return match ($type) { return match ($type) {
'ticket' => self::TYPE_TICKET, 'ticket' => self::TYPE_TICKET,
'user' => self::TYPE_USER, 'user' => self::TYPE_USER,
default => throw new \InvalidArgumentException('Unrecognized validation type'), default => throw new InvalidArgumentException('Unrecognized validation type'),
}; };
} }
@ -47,7 +48,7 @@ class ValidationTokenHelper
return match ($type) { return match ($type) {
self::TYPE_TICKET => 'ticket', self::TYPE_TICKET => 'ticket',
self::TYPE_USER => 'user', self::TYPE_USER => 'user',
default => throw new \InvalidArgumentException('Unrecognized validation type'), default => throw new InvalidArgumentException('Unrecognized validation type'),
}; };
} }
} }

@ -12,7 +12,6 @@ use Chamilo\CoreBundle\Entity\SettingsCurrent;
use Doctrine\ORM\EntityManager; use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityRepository; use Doctrine\ORM\EntityRepository;
use InvalidArgumentException; use InvalidArgumentException;
use Sylius\Bundle\SettingsBundle\Event\SettingsEvent;
use Sylius\Bundle\SettingsBundle\Manager\SettingsManagerInterface; use Sylius\Bundle\SettingsBundle\Manager\SettingsManagerInterface;
use Sylius\Bundle\SettingsBundle\Model\Settings; use Sylius\Bundle\SettingsBundle\Model\Settings;
use Sylius\Bundle\SettingsBundle\Model\SettingsInterface; use Sylius\Bundle\SettingsBundle\Model\SettingsInterface;
@ -21,7 +20,6 @@ use Sylius\Bundle\SettingsBundle\Schema\SchemaInterface;
use Sylius\Bundle\SettingsBundle\Schema\SettingsBuilder; use Sylius\Bundle\SettingsBundle\Schema\SettingsBuilder;
use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Validator\ConstraintViolationListInterface;
use Symfony\Component\Validator\Exception\ValidatorException; use Symfony\Component\Validator\Exception\ValidatorException;
use const ARRAY_FILTER_USE_KEY; use const ARRAY_FILTER_USE_KEY;
@ -994,7 +992,7 @@ class SettingsManager implements SettingsManagerInterface
private function transformToString($value): string private function transformToString($value): string
{ {
if (is_array($value)) { if (\is_array($value)) {
return implode(',', $value); return implode(',', $value);
} }
@ -1002,11 +1000,11 @@ class SettingsManager implements SettingsManagerInterface
return (string) $value->getId(); return (string) $value->getId();
} }
if (is_bool($value)) { if (\is_bool($value)) {
return $value ? 'true' : 'false'; return $value ? 'true' : 'false';
} }
if (is_null($value)) { if (null === $value) {
return ''; return '';
} }

@ -177,10 +177,10 @@ class ToolChain
continue; continue;
} }
$visibility = in_array($tool->getTitle(), $activeToolsOnCreate, true); $visibility = \in_array($tool->getTitle(), $activeToolsOnCreate, true);
$linkVisibility = $visibility ? ResourceLink::VISIBILITY_PUBLISHED : ResourceLink::VISIBILITY_DRAFT; $linkVisibility = $visibility ? ResourceLink::VISIBILITY_PUBLISHED : ResourceLink::VISIBILITY_DRAFT;
if (in_array($tool->getTitle(), ['course_setting', 'course_maintenance'])) { if (\in_array($tool->getTitle(), ['course_setting', 'course_maintenance'])) {
$linkVisibility = ResourceLink::VISIBILITY_DRAFT; $linkVisibility = ResourceLink::VISIBILITY_DRAFT;
} }

@ -9,8 +9,8 @@ namespace Chamilo\Tests\CoreBundle\Repository;
use Chamilo\CoreBundle\Entity\Asset; use Chamilo\CoreBundle\Entity\Asset;
use Chamilo\CoreBundle\Entity\GradebookCategory; use Chamilo\CoreBundle\Entity\GradebookCategory;
use Chamilo\CoreBundle\Entity\Level; use Chamilo\CoreBundle\Entity\Level;
use Chamilo\CoreBundle\Entity\SkillLevelProfile;
use Chamilo\CoreBundle\Entity\Skill; use Chamilo\CoreBundle\Entity\Skill;
use Chamilo\CoreBundle\Entity\SkillLevelProfile;
use Chamilo\CoreBundle\Entity\SkillProfile; use Chamilo\CoreBundle\Entity\SkillProfile;
use Chamilo\CoreBundle\Entity\SkillRelCourse; use Chamilo\CoreBundle\Entity\SkillRelCourse;
use Chamilo\CoreBundle\Entity\SkillRelGradebook; use Chamilo\CoreBundle\Entity\SkillRelGradebook;

Loading…
Cancel
Save