diff --git a/api/composer.json b/api/composer.json index 6927e56468..21673c626c 100644 --- a/api/composer.json +++ b/api/composer.json @@ -141,7 +141,8 @@ ], "psalm": [ "psalm.phar" - ] + ], + "rector": "vendor/bin/rector" }, "conflict": { "symfony/dependency-injection": "5.3.7", diff --git a/api/rector.php b/api/rector.php index 4ada2bee80..4e4d1f933e 100644 --- a/api/rector.php +++ b/api/rector.php @@ -2,34 +2,57 @@ declare(strict_types=1); -use Rector\Core\Configuration\Option; -use Rector\Doctrine\Set\DoctrineSetList; -use Rector\Php74\Rector\Property\TypedPropertyRector; -use Rector\Set\ValueObject\SetList; -use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; +use Rector\CodeQuality\Rector\Catch_\ThrowWithPreviousExceptionRector; +use Rector\CodeQuality\Rector\ClassMethod\LocallyCalledStaticMethodToNonStaticRector; +use Rector\CodeQuality\Rector\Equal\UseIdenticalOverEqualWithSameTypeRector; +use Rector\CodeQuality\Rector\Identical\FlipTypeControlToUseExclusiveTypeRector; +use Rector\CodeQuality\Rector\If_\CombineIfRector; +use Rector\CodeQuality\Rector\If_\ExplicitBoolCompareRector; +use Rector\CodeQuality\Rector\If_\SimplifyIfElseToTernaryRector; +use Rector\CodeQuality\Rector\If_\SimplifyIfReturnBoolRector; +use Rector\Config\RectorConfig; +use Rector\DeadCode\Rector\If_\RemoveDeadInstanceOfRector; +use Rector\Doctrine\Bundle230\Rector\Class_\AddAnnotationToRepositoryRector; +use Rector\PHPUnit\CodeQuality\Rector\Class_\PreferPHPUnitThisCallRector; +use Rector\PHPUnit\CodeQuality\Rector\ClassMethod\AddInstanceofAssertForNullableInstanceRector; +use Rector\PHPUnit\CodeQuality\Rector\MethodCall\AssertEmptyNullableObjectToAssertInstanceofRector; +use Rector\Privatization\Rector\Class_\FinalizeTestCaseClassRector; +use Rector\Renaming\Rector\FuncCall\RenameFunctionRector; +use Rector\Strict\Rector\Empty_\DisallowedEmptyRuleFixerRector; +use Rector\TypeDeclaration\Rector\StmtsAwareInterface\DeclareStrictTypesRector; -return static function (ContainerConfigurator $containerConfigurator): void { - // get parameters - $parameters = $containerConfigurator->parameters(); - $parameters->set(Option::PATHS, [ +// @noinspection PhpUnhandledExceptionInspection +return RectorConfig::configure() + ->withPaths([ + __DIR__.'/public', + __DIR__.'/config', + __DIR__.'/migrations', __DIR__.'/src', __DIR__.'/tests', - ]); - $parameters->set(Option::AUTO_IMPORT_NAMES, true); - $parameters->set(Option::IMPORT_SHORT_CLASSES, false); - $parameters->set(Option::APPLY_AUTO_IMPORT_NAMES_ON_CHANGED_FILES_ONLY, true); - - // Define what rule sets will be applied - $containerConfigurator->import(DoctrineSetList::ANNOTATIONS_TO_ATTRIBUTES); - - // $containerConfigurator->import(SetList::DEAD_CODE); - // $containerConfigurator->import(SetList::CODE_QUALITY); - // $containerConfigurator->import(SetList::CODING_STYLE); - // $containerConfigurator->import(SetList::PHP_80); - - // get services (needed for register a single rule) - // $services = $containerConfigurator->services(); - - // register a single rule - // $services->set(TypedPropertyRector::class); -}; + ]) + ->withComposerBased(doctrine: true, phpunit: true, symfony: true) + ->withPreparedSets(deadCode: true, codeQuality: true, privatization: true, rectorPreset: true, phpunitCodeQuality: true, symfonyCodeQuality: true) + ->withAttributesSets(all: true) + ->withConfiguredRule(RenameFunctionRector::class, [ + 'implode' => 'join', + 'join' => 'join', + ]) + ->withSkip([ + AddAnnotationToRepositoryRector::class, + AddInstanceofAssertForNullableInstanceRector::class, + AssertEmptyNullableObjectToAssertInstanceofRector::class, + CombineIfRector::class, + DeclareStrictTypesRector::class, + DisallowedEmptyRuleFixerRector::class, + ExplicitBoolCompareRector::class, + FinalizeTestCaseClassRector::class, + FlipTypeControlToUseExclusiveTypeRector::class, + LocallyCalledStaticMethodToNonStaticRector::class, + PreferPHPUnitThisCallRector::class, + RemoveDeadInstanceOfRector::class, + SimplifyIfElseToTernaryRector::class, + SimplifyIfReturnBoolRector::class, + ThrowWithPreviousExceptionRector::class, + UseIdenticalOverEqualWithSameTypeRector::class, + ]) +; diff --git a/api/src/Controller/CevidbController.php b/api/src/Controller/CevidbController.php index 85e8cbdd25..69c0a3ce0e 100644 --- a/api/src/Controller/CevidbController.php +++ b/api/src/Controller/CevidbController.php @@ -12,7 +12,7 @@ class CevidbController extends AbstractController { * Link to this controller to start the "connect" process. */ #[Route('/auth/cevidb', name: 'connect_cevidb_start')] - public function connectAction(Request $request, ClientRegistry $clientRegistry) { + public function connect(Request $request, ClientRegistry $clientRegistry) { return $clientRegistry ->getClient('cevidb') // key used in config/packages/knpu_oauth2_client.yaml ->redirect([], ['additionalData' => ['callback' => $request->get('callback')]]) @@ -25,7 +25,7 @@ public function connectAction(Request $request, ClientRegistry $clientRegistry) * in config/packages/knpu_oauth2_client.yaml. */ #[Route('/auth/cevidb/callback', name: 'connect_cevidb_check')] - public function connectCheckAction(Request $request, ClientRegistry $clientRegistry) { + public function connectCheck(ClientRegistry $clientRegistry) { // ** if you want to *authenticate* the user, then // leave this method blank and create a custom authenticator } diff --git a/api/src/Controller/GoogleController.php b/api/src/Controller/GoogleController.php index 4d06184c6c..17a96b8199 100644 --- a/api/src/Controller/GoogleController.php +++ b/api/src/Controller/GoogleController.php @@ -12,7 +12,7 @@ class GoogleController extends AbstractController { * Link to this controller to start the "connect" process. */ #[Route('/auth/google', name: 'connect_google_start')] - public function connectAction(Request $request, ClientRegistry $clientRegistry) { + public function connect(Request $request, ClientRegistry $clientRegistry) { return $clientRegistry ->getClient('google') // key used in config/packages/knpu_oauth2_client.yaml ->redirect([], ['additionalData' => ['callback' => $request->get('callback')]]) @@ -25,7 +25,7 @@ public function connectAction(Request $request, ClientRegistry $clientRegistry) * in config/packages/knpu_oauth2_client.yaml. */ #[Route('/auth/google/callback', name: 'connect_google_check')] - public function connectCheckAction(Request $request, ClientRegistry $clientRegistry) { + public function connectCheck(ClientRegistry $clientRegistry) { // ** if you want to *authenticate* the user, then // leave this method blank and create a custom authenticator } diff --git a/api/src/Controller/JubladbController.php b/api/src/Controller/JubladbController.php index 9835a8bf58..2a5800340d 100644 --- a/api/src/Controller/JubladbController.php +++ b/api/src/Controller/JubladbController.php @@ -12,7 +12,7 @@ class JubladbController extends AbstractController { * Link to this controller to start the "connect" process. */ #[Route('/auth/jubladb', name: 'connect_jubladb_start')] - public function connectAction(Request $request, ClientRegistry $clientRegistry) { + public function connect(Request $request, ClientRegistry $clientRegistry) { return $clientRegistry ->getClient('jubladb') // key used in config/packages/knpu_oauth2_client.yaml ->redirect([], ['additionalData' => ['callback' => $request->get('callback')]]) @@ -25,7 +25,7 @@ public function connectAction(Request $request, ClientRegistry $clientRegistry) * in config/packages/knpu_oauth2_client.yaml. */ #[Route('/auth/jubladb/callback', name: 'connect_jubladb_check')] - public function connectCheckAction(Request $request, ClientRegistry $clientRegistry) { + public function connectCheck(ClientRegistry $clientRegistry) { // ** if you want to *authenticate* the user, then // leave this method blank and create a custom authenticator } diff --git a/api/src/Controller/PbsmidataController.php b/api/src/Controller/PbsmidataController.php index 4645ac3b67..6a5d35ede3 100644 --- a/api/src/Controller/PbsmidataController.php +++ b/api/src/Controller/PbsmidataController.php @@ -12,7 +12,7 @@ class PbsmidataController extends AbstractController { * Link to this controller to start the "connect" process. */ #[Route('/auth/pbsmidata', name: 'connect_pbsmidata_start')] - public function connectAction(Request $request, ClientRegistry $clientRegistry) { + public function connect(Request $request, ClientRegistry $clientRegistry) { return $clientRegistry ->getClient('pbsmidata') // key used in config/packages/knpu_oauth2_client.yaml ->redirect([], ['additionalData' => ['callback' => $request->get('callback')]]) @@ -25,7 +25,7 @@ public function connectAction(Request $request, ClientRegistry $clientRegistry) * in config/packages/knpu_oauth2_client.yaml. */ #[Route('/auth/pbsmidata/callback', name: 'connect_pbsmidata_check')] - public function connectCheckAction(Request $request, ClientRegistry $clientRegistry) { + public function connectCheck(ClientRegistry $clientRegistry) { // ** if you want to *authenticate* the user, then // leave this method blank and create a custom authenticator } diff --git a/api/src/Doctrine/Filter/ContentNodeCampFilter.php b/api/src/Doctrine/Filter/ContentNodeCampFilter.php index 7241003ca3..69578a45b8 100644 --- a/api/src/Doctrine/Filter/ContentNodeCampFilter.php +++ b/api/src/Doctrine/Filter/ContentNodeCampFilter.php @@ -32,14 +32,11 @@ public function __construct( // This function is only used to hook in documentation generators (supported by Swagger and Hydra) public function getDescription(string $resourceClass): array { - $description = []; - $description['camp'] = [ + return ['camp' => [ 'property' => self::CAMP_QUERY_NAME, 'type' => Type::BUILTIN_TYPE_STRING, 'required' => false, - ]; - - return $description; + ]]; } protected function filterProperty( diff --git a/api/src/Doctrine/Filter/ContentNodeIsRootFilter.php b/api/src/Doctrine/Filter/ContentNodeIsRootFilter.php index 8c217b3a84..fdfa20af65 100644 --- a/api/src/Doctrine/Filter/ContentNodeIsRootFilter.php +++ b/api/src/Doctrine/Filter/ContentNodeIsRootFilter.php @@ -26,14 +26,11 @@ public function __construct( // This function is only used to hook in documentation generators (supported by Swagger and Hydra) public function getDescription(string $resourceClass): array { - $description = []; - $description['isRoot'] = [ + return ['isRoot' => [ 'property' => self::IS_ROOT_QUERY_NAME, 'type' => Type::BUILTIN_TYPE_BOOL, 'required' => false, - ]; - - return $description; + ]]; } protected function filterProperty( diff --git a/api/src/Doctrine/Filter/ContentNodePeriodFilter.php b/api/src/Doctrine/Filter/ContentNodePeriodFilter.php index 3786f99323..57bb9b0f08 100644 --- a/api/src/Doctrine/Filter/ContentNodePeriodFilter.php +++ b/api/src/Doctrine/Filter/ContentNodePeriodFilter.php @@ -33,14 +33,11 @@ public function __construct( // This function is only used to hook in documentation generators (supported by Swagger and Hydra) public function getDescription(string $resourceClass): array { - $description = []; - $description['period'] = [ + return ['period' => [ 'property' => self::PERIOD_QUERY_NAME, 'type' => Type::BUILTIN_TYPE_STRING, 'required' => false, - ]; - - return $description; + ]]; } protected function filterProperty( diff --git a/api/src/Doctrine/Filter/MaterialItemPeriodFilter.php b/api/src/Doctrine/Filter/MaterialItemPeriodFilter.php index fa8a6b1422..e186682a41 100644 --- a/api/src/Doctrine/Filter/MaterialItemPeriodFilter.php +++ b/api/src/Doctrine/Filter/MaterialItemPeriodFilter.php @@ -29,14 +29,11 @@ public function __construct( // This function is only used to hook in documentation generators (supported by Swagger and Hydra) public function getDescription(string $resourceClass): array { - $description = []; - $description['period'] = [ + return ['period' => [ 'property' => self::PERIOD_QUERY_NAME, 'type' => Type::BUILTIN_TYPE_STRING, 'required' => false, - ]; - - return $description; + ]]; } protected function filterProperty( diff --git a/api/src/Entity/Category.php b/api/src/Entity/Category.php index af5d616886..aaf42af080 100644 --- a/api/src/Entity/Category.php +++ b/api/src/Entity/Category.php @@ -303,9 +303,8 @@ private function getAlphaNum($num): string { if ($num >= 26) { $alphaNum .= $this->getAlphaNum(floor($num / 26)); } - $alphaNum .= chr(97 + ($num % 26)); - return $alphaNum; + return $alphaNum.chr(97 + ($num % 26)); } private function getRomanNum($num): string { diff --git a/api/src/Entity/ChecklistItem.php b/api/src/Entity/ChecklistItem.php index 3c7148a00b..954ea10675 100644 --- a/api/src/Entity/ChecklistItem.php +++ b/api/src/Entity/ChecklistItem.php @@ -226,7 +226,7 @@ public function getSubtreeDepth(): int { return 1 + $this->children->reduce(function (int $max, ChecklistItem $child): int { $depth = $child->getSubtreeDepth(); - return ($depth > $max) ? $depth : $max; + return max($depth, $max); }, 0); } diff --git a/api/src/Entity/Period.php b/api/src/Entity/Period.php index 91210bd341..ce631785fa 100644 --- a/api/src/Entity/Period.php +++ b/api/src/Entity/Period.php @@ -329,7 +329,7 @@ public function removeMaterialItem(MaterialItem $materialItem): self { * (based on start and end date). */ public function getPeriodLength(): ?int { - if (isset($this->start, $this->end)) { + if (null !== $this->start && null !== $this->end) { $length = $this->end->getTimestamp() - $this->start->getTimestamp(); return intval(floor($length / 86400)) + 1; diff --git a/api/src/Metadata/Resource/Factory/UriTemplateFactory.php b/api/src/Metadata/Resource/Factory/UriTemplateFactory.php index cca8d1f42f..90dc29c0f9 100644 --- a/api/src/Metadata/Resource/Factory/UriTemplateFactory.php +++ b/api/src/Metadata/Resource/Factory/UriTemplateFactory.php @@ -98,7 +98,7 @@ protected function getIdParameter(ResourceMetadataCollection $resourceMetadataCo protected function getQueryParameters(string $resourceClass, ResourceMetadataCollection $resourceMetadataCollection): string { $parameters = array_merge($this->getFilterParameters($resourceClass, $resourceMetadataCollection), $this->getPaginationParameters($resourceMetadataCollection)); - return empty($parameters) ? '' : '{?'.implode(',', $parameters).'}'; + return [] === $parameters ? '' : '{?'.join(',', $parameters).'}'; } /** diff --git a/api/src/OAuth/Hitobito.php b/api/src/OAuth/Hitobito.php index 7ed36dd05a..6fcd1d4f7d 100644 --- a/api/src/OAuth/Hitobito.php +++ b/api/src/OAuth/Hitobito.php @@ -39,7 +39,7 @@ protected function fetchResourceOwnerDetails(AccessToken $token): mixed { $separator = $this->getScopeSeparator(); $headers = [ - 'X-Scope' => implode($separator, $this->getDefaultScopes()), + 'X-Scope' => join($separator, $this->getDefaultScopes()), ]; $request = $this->getAuthenticatedRequest(self::METHOD_GET, $url, $token, ['headers' => $headers]); diff --git a/api/src/Serializer/Normalizer/ContentTypeNormalizer.php b/api/src/Serializer/Normalizer/ContentTypeNormalizer.php index 8bda22ddb4..abe3e929ac 100644 --- a/api/src/Serializer/Normalizer/ContentTypeNormalizer.php +++ b/api/src/Serializer/Normalizer/ContentTypeNormalizer.php @@ -28,7 +28,7 @@ public function supportsNormalization($data, $format = null, array $context = [] public function normalize($data, $format = null, array $context = []): null|array|\ArrayObject|bool|float|int|string { $normalized_data = $this->decorated->normalize($data, $format, $context); - if ($data instanceof ContentType && isset($data->entityClass)) { + if ($data instanceof ContentType && null !== $data->entityClass) { // get uri for the respective ContentNode entity and add ContentType as query parameter [$uriTemplate, $templated] = $this->uriTemplateFactory->createFromResourceClass($data->entityClass); $uri = $this->uriTemplate->expand($uriTemplate, ['contentType' => $this->iriConverter->getIriFromResource($data)]); diff --git a/api/src/State/ActivityCreateProcessor.php b/api/src/State/ActivityCreateProcessor.php index a1f19bb8af..4906a9007c 100644 --- a/api/src/State/ActivityCreateProcessor.php +++ b/api/src/State/ActivityCreateProcessor.php @@ -30,7 +30,7 @@ public function onBefore($data, Operation $operation, array $uriVariables = [], if (!isset($data->category?->rootContentNode)) { throw new \UnexpectedValueException('Property rootContentNode of provided category is null. Object of type '.ColumnLayout::class.' expected.'); } - if (!is_a($data->category->rootContentNode, ColumnLayout::class)) { + if (!$data->category->rootContentNode instanceof ColumnLayout) { throw new \UnexpectedValueException('Property rootContentNode of provided category is of wrong type. Object of type '.ColumnLayout::class.' expected.'); } diff --git a/api/src/State/CampCreateProcessor.php b/api/src/State/CampCreateProcessor.php index cf33080406..3a72ec822b 100644 --- a/api/src/State/CampCreateProcessor.php +++ b/api/src/State/CampCreateProcessor.php @@ -36,7 +36,7 @@ public function onBefore($data, Operation $operation, array $uriVariables = [], $data->owner = $user; // copy from prototype, if given - if (isset($data->campPrototype)) { + if (null !== $data->campPrototype) { $entityMap = new EntityMap($data); $data->copyFromPrototype($data->campPrototype, $entityMap); } diff --git a/api/src/State/PeriodPersistProcessor.php b/api/src/State/PeriodPersistProcessor.php index 7bfdd862d4..632b30ba02 100644 --- a/api/src/State/PeriodPersistProcessor.php +++ b/api/src/State/PeriodPersistProcessor.php @@ -66,7 +66,7 @@ public static function removeExtraDays(Period $period) { $days = $period->getDays(); foreach ($days as $day) { - if ($day->dayOffset < 0 or $day->dayOffset >= $length) { + if ($day->dayOffset < 0 || $day->dayOffset >= $length) { $period->removeDay($day); } } diff --git a/api/src/State/ProfileUpdateProcessor.php b/api/src/State/ProfileUpdateProcessor.php index bb24bbace6..a3360c32c8 100644 --- a/api/src/State/ProfileUpdateProcessor.php +++ b/api/src/State/ProfileUpdateProcessor.php @@ -43,13 +43,13 @@ public function onBefore($data, Operation $operation, array $uriVariables = [], $this->emailAddressVerificationPerformed = false; /** @var Profile $data */ - if (isset($data->newEmail)) { + if (null !== $data->newEmail) { $verificationKey = IdGenerator::generateRandomHexString(64); $data->untrustedEmail = $data->newEmail; $data->untrustedEmailKey = $verificationKey; $data->untrustedEmailKeyHash = $this->getResetKeyHasher()->hash($verificationKey); - } elseif (isset($data->untrustedEmailKey)) { - if (!isset($data->untrustedEmailKeyHash)) { + } elseif (null !== $data->untrustedEmailKey) { + if (null === $data->untrustedEmailKeyHash) { throw new HttpException(422, 'Email verification failed A'); } @@ -70,7 +70,7 @@ public function onBefore($data, Operation $operation, array $uriVariables = [], public function onAfter($data, Operation $operation, array $uriVariables = [], array $context = []): void { /** @var Profile $data */ - if (isset($data->untrustedEmailKey)) { + if (null !== $data->untrustedEmailKey) { $this->mailService->sendEmailVerificationMail($data->user, $data); $data->untrustedEmailKey = null; } diff --git a/api/src/Validator/AssertBelongsToSameCampValidator.php b/api/src/Validator/AssertBelongsToSameCampValidator.php index 5b6bab405d..b0060ad779 100644 --- a/api/src/Validator/AssertBelongsToSameCampValidator.php +++ b/api/src/Validator/AssertBelongsToSameCampValidator.php @@ -30,11 +30,11 @@ public function validate($value, Constraint $constraint): void { } $object = $this->context->getObject(); - if (!($object instanceof BelongsToCampInterface || $object instanceof BelongsToContentNodeTreeInterface)) { + if (!$object instanceof BelongsToCampInterface && !$object instanceof BelongsToContentNodeTreeInterface) { throw new UnexpectedValueException($value, BelongsToCampInterface::class.' or '.BelongsToContentNodeTreeInterface::class); } - if (!($value instanceof BelongsToCampInterface || $value instanceof BelongsToContentNodeTreeInterface)) { + if (!$value instanceof BelongsToCampInterface && !$value instanceof BelongsToContentNodeTreeInterface) { throw new UnexpectedValueException($value, BelongsToCampInterface::class.' or '.BelongsToContentNodeTreeInterface::class); } diff --git a/api/src/Validator/ContentNode/AssertSlotSupportedByParentValidator.php b/api/src/Validator/ContentNode/AssertSlotSupportedByParentValidator.php index 545d94127a..23dc6ff4e9 100644 --- a/api/src/Validator/ContentNode/AssertSlotSupportedByParentValidator.php +++ b/api/src/Validator/ContentNode/AssertSlotSupportedByParentValidator.php @@ -31,7 +31,7 @@ public function validate($value, Constraint $constraint): void { return; } $supportedSlotNames = $parent->getSupportedSlotNames(); - if (0 === sizeof($supportedSlotNames)) { + if (0 === count($supportedSlotNames)) { $this->context->buildViolation($constraint->parentDoesNotSupportChildrenMessage)->addViolation(); return; diff --git a/api/tests/Api/Activities/CreateActivityTest.php b/api/tests/Api/Activities/CreateActivityTest.php index 8c17c96787..6b34d582b4 100644 --- a/api/tests/Api/Activities/CreateActivityTest.php +++ b/api/tests/Api/Activities/CreateActivityTest.php @@ -354,7 +354,7 @@ public function testCreateActivityCopiesContentFromCategory() { $response = static::createClientWithCredentials()->request('POST', '/activities', ['json' => $this->getExampleWritePayload()]); $id = $response->toArray()['id']; - $newActivity = $this->getEntityManager()->getRepository(Activity::class)->find($id); + $this->getEntityManager()->getRepository(Activity::class)->find($id); $this->assertResponseStatusCodeSame(201); $this->assertJsonContains(['_embedded' => [ diff --git a/api/tests/Api/Activities/ListActivitiesTest.php b/api/tests/Api/Activities/ListActivitiesTest.php index 47f2c2be6c..8832f968d9 100644 --- a/api/tests/Api/Activities/ListActivitiesTest.php +++ b/api/tests/Api/Activities/ListActivitiesTest.php @@ -80,7 +80,7 @@ public function testListActivitiesAsCampSubresourceIsAllowedForCollaborator() { public function testListActivitiesAsCampSubresourceIsDeniedForUnrelatedUser() { $camp = static::getFixture('camp1'); - $response = static::createClientWithCredentials(['email' => static::$fixtures['user4unrelated']->getEmail()])->request('GET', "/camps/{$camp->getId()}/activities"); + static::createClientWithCredentials(['email' => static::$fixtures['user4unrelated']->getEmail()])->request('GET', "/camps/{$camp->getId()}/activities"); $this->assertResponseStatusCodeSame(404); } diff --git a/api/tests/Api/Activities/ReadActivityTest.php b/api/tests/Api/Activities/ReadActivityTest.php index ae501603ec..809b1525f9 100644 --- a/api/tests/Api/Activities/ReadActivityTest.php +++ b/api/tests/Api/Activities/ReadActivityTest.php @@ -90,7 +90,7 @@ public function testGetSingleActivityIsAllowedForMember() { ]); $data = $result->toArray(); - $this->assertEquals(12, count($data['_embedded']['contentNodes'])); + $this->assertCount(12, $data['_embedded']['contentNodes']); } public function testGetSingleActivityIsAllowedForManager() { diff --git a/api/tests/Api/ActivityProgressLabel/ListActivityProgressLabelTest.php b/api/tests/Api/ActivityProgressLabel/ListActivityProgressLabelTest.php index 7f5ad578ac..7cbfd45587 100644 --- a/api/tests/Api/ActivityProgressLabel/ListActivityProgressLabelTest.php +++ b/api/tests/Api/ActivityProgressLabel/ListActivityProgressLabelTest.php @@ -88,7 +88,7 @@ public function testListActivityProgressLabelsAsSubresourceOfCampIsAllowedForCol public function testListActivityProgressLabelsAsSubresourceOfCampIsDeniedForUnrelatedUser() { $camp = static::getFixture('camp1'); - $response = static::createClientWithCredentials(['email' => static::$fixtures['user4unrelated']->getEmail()]) + static::createClientWithCredentials(['email' => static::$fixtures['user4unrelated']->getEmail()]) ->request('GET', "/camps/{$camp->getId()}/activity_progress_labels") ; $this->assertResponseStatusCodeSame(404); diff --git a/api/tests/Api/CampCollaborations/UpdateCampCollaborationTest.php b/api/tests/Api/CampCollaborations/UpdateCampCollaborationTest.php index 51b89f16a2..56413b4bae 100644 --- a/api/tests/Api/CampCollaborations/UpdateCampCollaborationTest.php +++ b/api/tests/Api/CampCollaborations/UpdateCampCollaborationTest.php @@ -399,26 +399,31 @@ public function testRejectsPatchRoleToGuestIfNoManagerWouldBeInCamp(string $user ]); } - public static function usersWhichCanEditCampCollaborations(): array { - return ['user1manager' => ['user1manager'], 'user2member' => ['user2member']]; + public static function usersWhichCanEditCampCollaborations(): \Iterator { + yield 'user1manager' => ['user1manager']; + + yield 'user2member' => ['user2member']; } - public static function invalidAbbreviations(): array { - return [ - ['ABC'], - ['D3C'], - ['🧑🏿‍🚀🙋🏼‍♀️😊'], - ]; + public static function invalidAbbreviations(): \Iterator { + yield ['ABC']; + + yield ['D3C']; + + yield ['🧑🏿‍🚀🙋🏼‍♀️😊']; } - public static function validAbbreviations(): array { - return [ - ['A'], - ['33'], - ['X4'], - ['✅😊'], - ['🧑🏿‍🚀🧑🏼‍🔧'], - ['⚜️'], - ]; + public static function validAbbreviations(): \Iterator { + yield ['A']; + + yield ['33']; + + yield ['X4']; + + yield ['✅😊']; + + yield ['🧑🏿‍🚀🧑🏼‍🔧']; + + yield ['⚜️']; } } diff --git a/api/tests/Api/Categories/ListCategoriesTest.php b/api/tests/Api/Categories/ListCategoriesTest.php index 5458b62cac..6b1b144c25 100644 --- a/api/tests/Api/Categories/ListCategoriesTest.php +++ b/api/tests/Api/Categories/ListCategoriesTest.php @@ -9,7 +9,7 @@ */ class ListCategoriesTest extends ECampApiTestCase { public function testListCategoriesIsDeniedForAnonymousUser() { - $response = static::createBasicClient()->request('GET', '/categories'); + static::createBasicClient()->request('GET', '/categories'); $this->assertResponseStatusCodeSame(401); $this->assertJsonContains([ 'code' => 401, diff --git a/api/tests/Api/Categories/UpdateCategoryTest.php b/api/tests/Api/Categories/UpdateCategoryTest.php index df15957861..4a7853985e 100644 --- a/api/tests/Api/Categories/UpdateCategoryTest.php +++ b/api/tests/Api/Categories/UpdateCategoryTest.php @@ -92,7 +92,7 @@ public function testPatchCategoryIsDeniedForGuest() { public function testPatchCategoryIsAllowedForMember() { $category = static::getFixture('category1'); - $response = static::createClientWithCredentials(['email' => static::$fixtures['user2member']->getEmail()]) + static::createClientWithCredentials(['email' => static::$fixtures['user2member']->getEmail()]) ->request('PATCH', '/categories/'.$category->getId(), ['json' => [ 'short' => 'LP', 'name' => 'Lagerprogramm', @@ -120,7 +120,7 @@ public function testPatchCategoryIsAllowedForMember() { public function testPatchCategoryIsAllowedForManager() { $category = static::getFixture('category1'); - $response = static::createClientWithCredentials()->request('PATCH', '/categories/'.$category->getId(), ['json' => [ + static::createClientWithCredentials()->request('PATCH', '/categories/'.$category->getId(), ['json' => [ 'short' => 'LP', 'name' => 'Lagerprogramm', 'color' => '#FFFF00', @@ -146,7 +146,7 @@ public function testPatchCategoryIsAllowedForManager() { public function testPatchCategoryInCampPrototypeIsDeniedForUnrelatedUser() { $category = static::getFixture('category1campPrototype'); - $response = static::createClientWithCredentials()->request('PATCH', '/categories/'.$category->getId(), ['json' => [ + static::createClientWithCredentials()->request('PATCH', '/categories/'.$category->getId(), ['json' => [ 'short' => 'LP', 'name' => 'Lagerprogramm', 'color' => '#FFFF00', diff --git a/api/tests/Api/ChecklistItems/ListChecklistItemTest.php b/api/tests/Api/ChecklistItems/ListChecklistItemTest.php index 9944a12410..45b015c454 100644 --- a/api/tests/Api/ChecklistItems/ListChecklistItemTest.php +++ b/api/tests/Api/ChecklistItems/ListChecklistItemTest.php @@ -9,7 +9,7 @@ */ class ListChecklistItemTest extends ECampApiTestCase { public function testListChecklistItemsIsDeniedForAnonymousUser() { - $response = static::createBasicClient()->request('GET', '/checklist_items'); + static::createBasicClient()->request('GET', '/checklist_items'); $this->assertResponseStatusCodeSame(401); $this->assertJsonContains([ 'code' => 401, diff --git a/api/tests/Api/ChecklistItems/UpdateChecklistItemTest.php b/api/tests/Api/ChecklistItems/UpdateChecklistItemTest.php index bc1e31cc41..b778266490 100644 --- a/api/tests/Api/ChecklistItems/UpdateChecklistItemTest.php +++ b/api/tests/Api/ChecklistItems/UpdateChecklistItemTest.php @@ -64,7 +64,7 @@ public function testPatchChecklistItemIsDeniedForGuest() { public function testPatchChecklistItemIsAllowedForMember() { $checklistItem = static::getFixture('checklistItem1_1_1'); - $response = static::createClientWithCredentials(['email' => static::$fixtures['user2member']->getEmail()]) + static::createClientWithCredentials(['email' => static::$fixtures['user2member']->getEmail()]) ->request('PATCH', '/checklist_items/'.$checklistItem->getId(), ['json' => [ 'text' => 'Ziel 2', ], 'headers' => ['Content-Type' => 'application/merge-patch+json']]) @@ -77,7 +77,7 @@ public function testPatchChecklistItemIsAllowedForMember() { public function testPatchChecklistItemIsAllowedForManager() { $checklistItem = static::getFixture('checklistItem1_1_1'); - $response = static::createClientWithCredentials()->request('PATCH', '/checklist_items/'.$checklistItem->getId(), ['json' => [ + static::createClientWithCredentials()->request('PATCH', '/checklist_items/'.$checklistItem->getId(), ['json' => [ 'text' => 'Ziel 2', ], 'headers' => ['Content-Type' => 'application/merge-patch+json']]); $this->assertResponseStatusCodeSame(200); @@ -88,7 +88,7 @@ public function testPatchChecklistItemIsAllowedForManager() { public function testPatchChecklistItemInCampPrototypeIsDeniedForUnrelatedUser() { $checklistItem = static::getFixture('checklistItemPrototype_1_1'); - $response = static::createClientWithCredentials()->request('PATCH', '/checklist_items/'.$checklistItem->getId(), ['json' => [ + static::createClientWithCredentials()->request('PATCH', '/checklist_items/'.$checklistItem->getId(), ['json' => [ 'text' => 'Ziel 2', ], 'headers' => ['Content-Type' => 'application/merge-patch+json']]); $this->assertResponseStatusCodeSame(403); diff --git a/api/tests/Api/Checklists/ListChecklistTest.php b/api/tests/Api/Checklists/ListChecklistTest.php index 0450e5d44a..c5f016d3e8 100644 --- a/api/tests/Api/Checklists/ListChecklistTest.php +++ b/api/tests/Api/Checklists/ListChecklistTest.php @@ -9,7 +9,7 @@ */ class ListChecklistTest extends ECampApiTestCase { public function testListChecklistsIsDeniedForAnonymousUser() { - $response = static::createBasicClient()->request('GET', '/checklists'); + static::createBasicClient()->request('GET', '/checklists'); $this->assertResponseStatusCodeSame(401); $this->assertJsonContains([ 'code' => 401, diff --git a/api/tests/Api/Checklists/UpdateChecklistTest.php b/api/tests/Api/Checklists/UpdateChecklistTest.php index 5f681b1a6d..f02c7ae0e3 100644 --- a/api/tests/Api/Checklists/UpdateChecklistTest.php +++ b/api/tests/Api/Checklists/UpdateChecklistTest.php @@ -39,7 +39,7 @@ public function testPatchPrototypeChecklistIsDeniedForUser() { public function testPatchPrototypeChecklistIsAllowedForAdmin() { $checklist = static::getFixture('checklistPrototype'); - $response = static::createClientWithCredentials(['email' => static::$fixtures['admin']->getEmail()]) + static::createClientWithCredentials(['email' => static::$fixtures['admin']->getEmail()]) ->request('PATCH', '/checklists/'.$checklist->getId(), ['json' => [ 'name' => 'ChecklistName', ], 'headers' => ['Content-Type' => 'application/merge-patch+json']]) @@ -108,7 +108,7 @@ public function testPatchChecklistIsDeniedForGuest() { public function testPatchChecklistIsAllowedForMember() { $checklist = static::getFixture('checklist1'); - $response = static::createClientWithCredentials(['email' => static::$fixtures['user2member']->getEmail()]) + static::createClientWithCredentials(['email' => static::$fixtures['user2member']->getEmail()]) ->request('PATCH', '/checklists/'.$checklist->getId(), ['json' => [ 'name' => 'ChecklistName', ], 'headers' => ['Content-Type' => 'application/merge-patch+json']]) @@ -121,7 +121,7 @@ public function testPatchChecklistIsAllowedForMember() { public function testPatchChecklistIsAllowedForManager() { $checklist = static::getFixture('checklist1'); - $response = static::createClientWithCredentials()->request('PATCH', '/checklists/'.$checklist->getId(), ['json' => [ + static::createClientWithCredentials()->request('PATCH', '/checklists/'.$checklist->getId(), ['json' => [ 'name' => 'ChecklistName', ], 'headers' => ['Content-Type' => 'application/merge-patch+json']]); $this->assertResponseStatusCodeSame(200); @@ -132,7 +132,7 @@ public function testPatchChecklistIsAllowedForManager() { public function testPatchChecklistInCampPrototypeIsDeniedForUnrelatedUser() { $checklist = static::getFixture('checklist1campPrototype'); - $response = static::createClientWithCredentials()->request('PATCH', '/checklists/'.$checklist->getId(), ['json' => [ + static::createClientWithCredentials()->request('PATCH', '/checklists/'.$checklist->getId(), ['json' => [ 'name' => 'ChecklistName', ], 'headers' => ['Content-Type' => 'application/merge-patch+json']]); $this->assertResponseStatusCodeSame(403); diff --git a/api/tests/Api/ContentNodes/ChecklistNode/UpdateChecklistNodeTest.php b/api/tests/Api/ContentNodes/ChecklistNode/UpdateChecklistNodeTest.php index 5de49c88b7..d60b1fa319 100644 --- a/api/tests/Api/ContentNodes/ChecklistNode/UpdateChecklistNodeTest.php +++ b/api/tests/Api/ContentNodes/ChecklistNode/UpdateChecklistNodeTest.php @@ -86,7 +86,7 @@ public function testRemoveChecklistItemForMember() { ; $this->assertResponseStatusCodeSame(200); $checklistNode = $this->getEntityManager()->getRepository(ChecklistNode::class)->find($this->defaultEntity->getId()); - $this->assertFalse(in_array($checklistItem, $checklistNode->getChecklistItems())); + $this->assertNotContains($checklistItem, $checklistNode->getChecklistItems()); } public function testRemoveChecklistItemForManager() { @@ -97,7 +97,7 @@ public function testRemoveChecklistItemForManager() { $this->assertResponseStatusCodeSame(200); $checklistNode = $this->getEntityManager()->getRepository(ChecklistNode::class)->find($this->defaultEntity->getId()); - $this->assertFalse(in_array($checklistItem, $checklistNode->getChecklistItems())); + $this->assertNotContains($checklistItem, $checklistNode->getChecklistItems()); } public function testAddChecklistItemOfOtherCampIsDenied() { diff --git a/api/tests/Api/ContentNodes/ColumnLayout/CreateColumnLayoutTest.php b/api/tests/Api/ContentNodes/ColumnLayout/CreateColumnLayoutTest.php index 85ff6e7aa2..5447912374 100644 --- a/api/tests/Api/ContentNodes/ColumnLayout/CreateColumnLayoutTest.php +++ b/api/tests/Api/ContentNodes/ColumnLayout/CreateColumnLayoutTest.php @@ -41,7 +41,7 @@ public function testCreateColumnLayoutAcceptsEmptyJson() { } public function testCreateColumnLayoutAcceptsNonExistingJson() { - $response = $this->create($this->getExampleWritePayload([], ['data'])); + $this->create($this->getExampleWritePayload([], ['data'])); $this->assertResponseStatusCodeSame(201); $this->assertJsonContains(['data' => [ diff --git a/api/tests/Api/ContentNodes/ContentNode/ListContentNodesTest.php b/api/tests/Api/ContentNodes/ContentNode/ListContentNodesTest.php index e56ace1176..7d3084eba9 100644 --- a/api/tests/Api/ContentNodes/ContentNode/ListContentNodesTest.php +++ b/api/tests/Api/ContentNodes/ContentNode/ListContentNodesTest.php @@ -91,7 +91,7 @@ public function testListContentNodesFilteredByPeriodIsAllowedForCollaborator() { public function testListContentNodesFilteredByPeriodIsDeniedForUnrelatedUser() { $period = static::getFixture('period1'); - $response = static::createClientWithCredentials(['email' => static::$fixtures['user4unrelated']->getEmail()]) + static::createClientWithCredentials(['email' => static::$fixtures['user4unrelated']->getEmail()]) ->request('GET', '/content_nodes?period=%2Fperiods%2F'.$period->getId()) ; @@ -105,7 +105,7 @@ public function testListContentNodesFilteredByPeriodIsDeniedForUnrelatedUser() { public function testListContentNodesFilteredByPeriodIsDeniedForInactiveCollaborator() { $period = static::getFixture('period1'); - $response = static::createClientWithCredentials(['email' => static::$fixtures['user5inactive']->getEmail()]) + static::createClientWithCredentials(['email' => static::$fixtures['user5inactive']->getEmail()]) ->request('GET', '/content_nodes?period=%2Fperiods%2F'.$period->getId()) ; diff --git a/api/tests/Api/ContentNodes/CreateContentNodeTestCase.php b/api/tests/Api/ContentNodes/CreateContentNodeTestCase.php index 932b57ed73..e7791915bc 100644 --- a/api/tests/Api/ContentNodes/CreateContentNodeTestCase.php +++ b/api/tests/Api/ContentNodes/CreateContentNodeTestCase.php @@ -268,20 +268,21 @@ public function testCreatePurgesCacheTags() { ], $cacheManager->getInvalidatedTags()); } - public static function getContentNodesWhichCannotHaveChildren(): array { - return [ - ContentNode\MaterialNode::class => [ - 'materialNode1', - ], - ContentNode\MultiSelect::class => [ - 'multiSelect1', - ], - ContentNode\SingleText::class => [ - 'singleText1', - ], - ContentNode\StoryBoard::class => [ - 'storyboard1', - ], + public static function getContentNodesWhichCannotHaveChildren(): \Iterator { + yield ContentNode\MaterialNode::class => [ + 'materialNode1', + ]; + + yield ContentNode\MultiSelect::class => [ + 'multiSelect1', + ]; + + yield ContentNode\SingleText::class => [ + 'singleText1', + ]; + + yield ContentNode\StoryBoard::class => [ + 'storyboard1', ]; } diff --git a/api/tests/Api/ContentNodes/ResponsiveLayout/CreateResponsiveLayoutTest.php b/api/tests/Api/ContentNodes/ResponsiveLayout/CreateResponsiveLayoutTest.php index 0843b9bc0a..0f28a337fc 100644 --- a/api/tests/Api/ContentNodes/ResponsiveLayout/CreateResponsiveLayoutTest.php +++ b/api/tests/Api/ContentNodes/ResponsiveLayout/CreateResponsiveLayoutTest.php @@ -42,7 +42,7 @@ public function testCreateResponsiveLayoutAcceptsEmptyJson() { } public function testCreateResponsiveLayoutAcceptsNonExistingJson() { - $response = $this->create($this->getExampleWritePayload([], ['data'])); + $this->create($this->getExampleWritePayload([], ['data'])); $this->assertResponseStatusCodeSame(201); $this->assertJsonContains(['data' => [ diff --git a/api/tests/Api/ContentNodes/SingleText/CreateSingleTextTest.php b/api/tests/Api/ContentNodes/SingleText/CreateSingleTextTest.php index 39b4974187..7567b77516 100644 --- a/api/tests/Api/ContentNodes/SingleText/CreateSingleTextTest.php +++ b/api/tests/Api/ContentNodes/SingleText/CreateSingleTextTest.php @@ -39,7 +39,7 @@ public function testCreateSingleTextAcceptsEmptyJson() { } public function testCreateSingleTextAcceptsNonExistingJson() { - $response = $this->create($this->getExampleWritePayload([], ['data'])); + $this->create($this->getExampleWritePayload([], ['data'])); $this->assertResponseStatusCodeSame(201); diff --git a/api/tests/Api/ContentNodes/UpdateContentNodeTestCase.php b/api/tests/Api/ContentNodes/UpdateContentNodeTestCase.php index 067d554294..50b7dedb1c 100644 --- a/api/tests/Api/ContentNodes/UpdateContentNodeTestCase.php +++ b/api/tests/Api/ContentNodes/UpdateContentNodeTestCase.php @@ -193,20 +193,21 @@ public function testPatchCleansTextOfInstanceName() { ]); } - public static function getContentNodesWhichCannotHaveChildren(): array { - return [ - ContentNode\MaterialNode::class => [ - 'materialNode1', - ], - ContentNode\MultiSelect::class => [ - 'multiSelect1', - ], - ContentNode\SingleText::class => [ - 'singleText1', - ], - ContentNode\StoryBoard::class => [ - 'storyboard1', - ], + public static function getContentNodesWhichCannotHaveChildren(): \Iterator { + yield ContentNode\MaterialNode::class => [ + 'materialNode1', + ]; + + yield ContentNode\MultiSelect::class => [ + 'multiSelect1', + ]; + + yield ContentNode\SingleText::class => [ + 'singleText1', + ]; + + yield ContentNode\StoryBoard::class => [ + 'storyboard1', ]; } } diff --git a/api/tests/Api/DayResponsibles/ListDayResponsiblesTest.php b/api/tests/Api/DayResponsibles/ListDayResponsiblesTest.php index b7be9a39c5..1902d9fce9 100644 --- a/api/tests/Api/DayResponsibles/ListDayResponsiblesTest.php +++ b/api/tests/Api/DayResponsibles/ListDayResponsiblesTest.php @@ -122,7 +122,7 @@ public function testListDayResponsiblesAsDaySubresourceIsAllowedForCollaborator( public function testListDayResponsiblesAsDaySubresourceIsDeniedForUnrelatedUser() { $day = static::getFixture('day1period1'); - $response = static::createClientWithCredentials(['email' => static::$fixtures['user4unrelated']->getEmail()]) + static::createClientWithCredentials(['email' => static::$fixtures['user4unrelated']->getEmail()]) ->request('GET', '/days/'.$day->getId().'/day_responsibles') ; diff --git a/api/tests/Api/Days/ListDaysTest.php b/api/tests/Api/Days/ListDaysTest.php index 3dfe5b307f..32fbe83558 100644 --- a/api/tests/Api/Days/ListDaysTest.php +++ b/api/tests/Api/Days/ListDaysTest.php @@ -145,7 +145,7 @@ public function testListDaysAsPeriodSubresourceIsAllowedForCollaborator() { public function testListDaysAsPeriodSubresourceIsDeniedForUnrelatedUser() { $period = static::getFixture('period1'); - $response = static::createClientWithCredentials(['email' => static::$fixtures['user4unrelated']->getEmail()]) + static::createClientWithCredentials(['email' => static::$fixtures['user4unrelated']->getEmail()]) ->request('GET', '/periods/'.$period->getId().'/days') ; diff --git a/api/tests/Api/ECampApiTestCase.php b/api/tests/Api/ECampApiTestCase.php index eb5ac00173..029a48a6da 100644 --- a/api/tests/Api/ECampApiTestCase.php +++ b/api/tests/Api/ECampApiTestCase.php @@ -288,7 +288,7 @@ protected function assertJsonContainsItems(ResponseInterface $response, array $i 'totalItems' => count($items), ]); - if (!empty($items)) { + if ([] !== $items) { $this->assertJsonContains([ '_links' => [ 'items' => [], diff --git a/api/tests/Api/Invitations/AcceptInvitationTest.php b/api/tests/Api/Invitations/AcceptInvitationTest.php index 28e9f6bab5..b667eb7450 100644 --- a/api/tests/Api/Invitations/AcceptInvitationTest.php +++ b/api/tests/Api/Invitations/AcceptInvitationTest.php @@ -196,8 +196,16 @@ public function testInvalidRequestWhenWrongMethod(string $method) { $this->assertResponseStatusCodeSame(405); } - public static function invalidMethods(): array { - return ['GET' => ['GET'], 'PUT' => ['PUT'], 'POST' => ['POST'], 'DELETE' => ['DELETE'], 'OPTIONS' => ['OPTIONS']]; + public static function invalidMethods(): \Iterator { + yield 'GET' => ['GET']; + + yield 'PUT' => ['PUT']; + + yield 'POST' => ['POST']; + + yield 'DELETE' => ['DELETE']; + + yield 'OPTIONS' => ['OPTIONS']; } /** diff --git a/api/tests/Api/Invitations/RejectInvitationTest.php b/api/tests/Api/Invitations/RejectInvitationTest.php index 1ab7181358..4e26369696 100644 --- a/api/tests/Api/Invitations/RejectInvitationTest.php +++ b/api/tests/Api/Invitations/RejectInvitationTest.php @@ -161,8 +161,16 @@ public function testInvalidRequestWhenWrongMethod(string $method) { $this->assertResponseStatusCodeSame(405); } - public static function invalidMethods(): array { - return ['GET' => ['GET'], 'PUT' => ['PUT'], 'POST' => ['POST'], 'DELETE' => ['DELETE'], 'OPTIONS' => ['OPTIONS']]; + public static function invalidMethods(): \Iterator { + yield 'GET' => ['GET']; + + yield 'PUT' => ['PUT']; + + yield 'POST' => ['POST']; + + yield 'DELETE' => ['DELETE']; + + yield 'OPTIONS' => ['OPTIONS']; } /** diff --git a/api/tests/Api/MaterialItems/ListMaterialItemsTest.php b/api/tests/Api/MaterialItems/ListMaterialItemsTest.php index dd70d615d6..85cb43d60b 100644 --- a/api/tests/Api/MaterialItems/ListMaterialItemsTest.php +++ b/api/tests/Api/MaterialItems/ListMaterialItemsTest.php @@ -121,7 +121,7 @@ public function testListMaterialItemsFilteredByPeriodIsAllowedForCollaborator() public function testListMaterialItemsFilteredByPeriodIsDeniedForUnrelatedUser() { $period = static::getFixture('period1'); - $response = static::createClientWithCredentials(['email' => static::$fixtures['user4unrelated']->getEmail()]) + static::createClientWithCredentials(['email' => static::$fixtures['user4unrelated']->getEmail()]) ->request('GET', '/material_items?period=%2Fperiods%2F'.$period->getId()) ; @@ -135,7 +135,7 @@ public function testListMaterialItemsFilteredByPeriodIsDeniedForUnrelatedUser() public function testListMaterialItemsFilteredByPeriodIsDeniedForInactiveCollaborator() { $period = static::getFixture('period1'); - $response = static::createClientWithCredentials(['email' => static::$fixtures['user5inactive']->getEmail()]) + static::createClientWithCredentials(['email' => static::$fixtures['user5inactive']->getEmail()]) ->request('GET', '/material_items?period=%2Fperiods%2F'.$period->getId()) ; diff --git a/api/tests/Api/Periods/UpdatePeriodTest.php b/api/tests/Api/Periods/UpdatePeriodTest.php index aeeb789aac..de58d13c37 100644 --- a/api/tests/Api/Periods/UpdatePeriodTest.php +++ b/api/tests/Api/Periods/UpdatePeriodTest.php @@ -411,9 +411,9 @@ public function testPatchPeriodMovePeriodStart() { // Period has now 4 days $this->assertCount(4, $period->days); - $day1 = $this->getEntityManager()->getRepository(Day::class)->find($day1->getId()); - $day2 = $this->getEntityManager()->getRepository(Day::class)->find($day2->getId()); - $day3 = $this->getEntityManager()->getRepository(Day::class)->find($day3->getId()); + $this->getEntityManager()->getRepository(Day::class)->find($day1->getId()); + $this->getEntityManager()->getRepository(Day::class)->find($day2->getId()); + $this->getEntityManager()->getRepository(Day::class)->find($day3->getId()); $day1_resp = $this->getEntityManager()->getRepository(DayResponsible::class)->find($day1_resp->getId()); $day2_resp = $this->getEntityManager()->getRepository(DayResponsible::class)->find($day2_resp->getId()); diff --git a/api/tests/Api/PersonalInvitations/AcceptPersonalInvitationTest.php b/api/tests/Api/PersonalInvitations/AcceptPersonalInvitationTest.php index fd559a3055..2518db3ea0 100644 --- a/api/tests/Api/PersonalInvitations/AcceptPersonalInvitationTest.php +++ b/api/tests/Api/PersonalInvitations/AcceptPersonalInvitationTest.php @@ -166,8 +166,16 @@ public function testInvalidRequestWhenWrongMethod(string $method) { $this->assertResponseStatusCodeSame(405); } - public static function invalidMethods(): array { - return ['GET' => ['GET'], 'PUT' => ['PUT'], 'POST' => ['POST'], 'DELETE' => ['DELETE'], 'OPTIONS' => ['OPTIONS']]; + public static function invalidMethods(): \Iterator { + yield 'GET' => ['GET']; + + yield 'PUT' => ['PUT']; + + yield 'POST' => ['POST']; + + yield 'DELETE' => ['DELETE']; + + yield 'OPTIONS' => ['OPTIONS']; } /** diff --git a/api/tests/Api/PersonalInvitations/RejectPersonalInvitationTest.php b/api/tests/Api/PersonalInvitations/RejectPersonalInvitationTest.php index c00b51a460..8ed8d16369 100644 --- a/api/tests/Api/PersonalInvitations/RejectPersonalInvitationTest.php +++ b/api/tests/Api/PersonalInvitations/RejectPersonalInvitationTest.php @@ -143,8 +143,16 @@ public function testInvalidRequestWhenWrongMethod(string $method) { $this->assertResponseStatusCodeSame(405); } - public static function invalidMethods(): array { - return ['GET' => ['GET'], 'PUT' => ['PUT'], 'POST' => ['POST'], 'DELETE' => ['DELETE'], 'OPTIONS' => ['OPTIONS']]; + public static function invalidMethods(): \Iterator { + yield 'GET' => ['GET']; + + yield 'PUT' => ['PUT']; + + yield 'POST' => ['POST']; + + yield 'DELETE' => ['DELETE']; + + yield 'OPTIONS' => ['OPTIONS']; } /** diff --git a/api/tests/Api/Profiles/UpdateProfileTest.php b/api/tests/Api/Profiles/UpdateProfileTest.php index 2b61dd7330..623eb5c12c 100644 --- a/api/tests/Api/Profiles/UpdateProfileTest.php +++ b/api/tests/Api/Profiles/UpdateProfileTest.php @@ -544,31 +544,35 @@ public function testNotWriteableProperties(string $property) { ]); } - public static function notWriteableProfileProperties(): array { - return [ - 'untrustedEmailKeyHash' => ['untrustedEmailKeyHash'], - 'googleId' => ['googleId'], - 'pbsmidataId' => ['pbsmidataId'], - 'roles' => ['roles'], - 'user' => ['user'], - ]; + public static function notWriteableProfileProperties(): \Iterator { + yield 'untrustedEmailKeyHash' => ['untrustedEmailKeyHash']; + + yield 'googleId' => ['googleId']; + + yield 'pbsmidataId' => ['pbsmidataId']; + + yield 'roles' => ['roles']; + + yield 'user' => ['user']; } - public static function invalidAbbreviations(): array { - return [ - ['ABC'], - ['D3C'], - ['🧑🏿‍🚀🙋🏼‍♀️😊'], - ]; + public static function invalidAbbreviations(): \Iterator { + yield ['ABC']; + + yield ['D3C']; + + yield ['🧑🏿‍🚀🙋🏼‍♀️😊']; } - public static function validAbbreviations(): array { - return [ - ['AB'], - ['33'], - ['X4'], - ['✅😊'], - ['🧑🏿‍🚀🧑🏼‍🔧'], - ]; + public static function validAbbreviations(): \Iterator { + yield ['AB']; + + yield ['33']; + + yield ['X4']; + + yield ['✅😊']; + + yield ['🧑🏿‍🚀🧑🏼‍🔧']; } } diff --git a/api/tests/Api/ScheduleEntries/CreateScheduleEntryTest.php b/api/tests/Api/ScheduleEntries/CreateScheduleEntryTest.php index 6824d77689..432c9b3051 100644 --- a/api/tests/Api/ScheduleEntries/CreateScheduleEntryTest.php +++ b/api/tests/Api/ScheduleEntries/CreateScheduleEntryTest.php @@ -210,7 +210,7 @@ public function testCreateScheduleEntryUsesDefaultForMissingWidth() { } public function testCreateScheduleEntryWithReversedPropertyOrder() { - $result = static::createClientWithCredentials()->request('POST', '/schedule_entries', ['json' => [ + static::createClientWithCredentials()->request('POST', '/schedule_entries', ['json' => [ 'start' => '2023-05-01T04:00:00+00:00', 'end' => '2023-05-01T05:00:00+00:00', 'period' => $this->getIriFor('period1'), diff --git a/api/tests/Api/ScheduleEntries/ListScheduleEntriesTest.php b/api/tests/Api/ScheduleEntries/ListScheduleEntriesTest.php index 340021470a..5ab84c3cc3 100644 --- a/api/tests/Api/ScheduleEntries/ListScheduleEntriesTest.php +++ b/api/tests/Api/ScheduleEntries/ListScheduleEntriesTest.php @@ -398,7 +398,7 @@ public function testListScheduleEntriesAsPeriodSubresourceIsAllowedForCollaborat public function testListScheduleEntriesAsPeriodSubresourceIsDeniedForUnrelatedUser() { $period = static::getFixture('period1'); - $response = static::createClientWithCredentials(['email' => static::$fixtures['user4unrelated']->getEmail()]) + static::createClientWithCredentials(['email' => static::$fixtures['user4unrelated']->getEmail()]) ->request('GET', '/periods/'.$period->getId().'/schedule_entries') ; diff --git a/api/tests/Api/ScheduleEntries/UpdateScheduleEntryTest.php b/api/tests/Api/ScheduleEntries/UpdateScheduleEntryTest.php index 57be07c531..a3747db90a 100644 --- a/api/tests/Api/ScheduleEntries/UpdateScheduleEntryTest.php +++ b/api/tests/Api/ScheduleEntries/UpdateScheduleEntryTest.php @@ -84,7 +84,7 @@ public function testPatchScheduleEntryIsDeniedForGuest() { public function testPatchScheduleEntryIsAllowedForMember() { $scheduleEntry = static::getFixture('scheduleEntry1'); - $response = static::createClientWithCredentials(['email' => static::$fixtures['user2member']->getEmail()]) + static::createClientWithCredentials(['email' => static::$fixtures['user2member']->getEmail()]) ->request('PATCH', '/schedule_entries/'.$scheduleEntry->getId(), ['json' => [ 'period' => $this->getIriFor('period2'), 'start' => '2023-04-15T00:10:00+00:00', @@ -185,7 +185,7 @@ public function testPatchScheduleEntryValidatesMissingStart() { public function testPatchScheduleEntryValidatesStartBeforePeriodStart() { $scheduleEntry = static::getFixture('scheduleEntry1'); - $response = static::createClientWithCredentials()->request('PATCH', '/schedule_entries/'.$scheduleEntry->getId(), ['json' => [ + static::createClientWithCredentials()->request('PATCH', '/schedule_entries/'.$scheduleEntry->getId(), ['json' => [ 'start' => '2023-04-30T23:59:59+00:00', ], 'headers' => ['Content-Type' => 'application/merge-patch+json']]); diff --git a/api/tests/Api/SnapshotTests/EndpointPerformanceTest.php b/api/tests/Api/SnapshotTests/EndpointPerformanceTest.php index 92f4138caa..e58842510a 100644 --- a/api/tests/Api/SnapshotTests/EndpointPerformanceTest.php +++ b/api/tests/Api/SnapshotTests/EndpointPerformanceTest.php @@ -71,7 +71,7 @@ public function testPerformanceDidNotChangeForStableEndpoints() { $this->assertMatchesSnapshot($numberOfQueries, new ECampYamlSnapshotDriver()); if ([] !== $endpointsWithTooLongExecutionTime) { - self::markTestSkipped('Some endpoints have too long execution time, were: '.implode(',', array_keys($endpointsWithTooLongExecutionTime))); + self::markTestSkipped('Some endpoints have too long execution time, were: '.join(',', array_keys($endpointsWithTooLongExecutionTime))); } } @@ -162,7 +162,11 @@ public function measurePerformanceFor(string $collectionEndpoint): array { // times below 0.03. $executionTimeSeconds = max(0.03, round($collector->getTime(), 2)); - return [$statusCode, $queryCount, $executionTimeSeconds]; + return [ + $statusCode, + $queryCount, + $executionTimeSeconds, + ]; } public static function getContentNodeEndpoints(): array { @@ -219,7 +223,8 @@ private static function getCollectionEndpoints() { $responseArray = $response->toArray(); $onlyUrls = array_map(fn (array $item) => $item['href'], $responseArray['_links']); $withoutParameters = array_map(fn (string $uriTemplate) => preg_replace('/\{[^}]*}/', '', $uriTemplate), $onlyUrls); - $normalEndpoints = array_filter($withoutParameters, function (string $endpoint) { + + return array_filter($withoutParameters, function (string $endpoint) { // @noinspection PhpDuplicateMatchArmBodyInspection return match ($endpoint) { '/' => false, @@ -235,8 +240,6 @@ private static function getCollectionEndpoints() { default => true }; }); - - return $normalEndpoints; } private function getPerformanceCriticalUrls(): array { diff --git a/api/tests/Api/Users/CreateUserTest.php b/api/tests/Api/Users/CreateUserTest.php index cc8fc9e124..e0e608a9b9 100644 --- a/api/tests/Api/Users/CreateUserTest.php +++ b/api/tests/Api/Users/CreateUserTest.php @@ -829,11 +829,10 @@ public function testNotWriteableUserProperties(string $property) { ]); } - public static function notWriteableUserProperties(): array { - return [ - 'activationKeyHash' => ['activationKeyHash'], - 'passwordResetKeyHash' => ['passwordResetKeyHash'], - ]; + public static function notWriteableUserProperties(): \Iterator { + yield 'activationKeyHash' => ['activationKeyHash']; + + yield 'passwordResetKeyHash' => ['passwordResetKeyHash']; } #[DataProvider('notWriteableProfileProperties')] @@ -859,15 +858,18 @@ public function testNotWriteableProfileProperties(string $property) { ]); } - public static function notWriteableProfileProperties(): array { - return [ - 'untrustedEmailKey' => ['untrustedEmailKey'], - 'untrustedEmailKeyHash' => ['untrustedEmailKeyHash'], - 'googleId' => ['googleId'], - 'pbsmidataId' => ['pbsmidataId'], - 'roles' => ['roles'], - 'user' => ['user'], - ]; + public static function notWriteableProfileProperties(): \Iterator { + yield 'untrustedEmailKey' => ['untrustedEmailKey']; + + yield 'untrustedEmailKeyHash' => ['untrustedEmailKeyHash']; + + yield 'googleId' => ['googleId']; + + yield 'pbsmidataId' => ['pbsmidataId']; + + yield 'roles' => ['roles']; + + yield 'user' => ['user']; } /** diff --git a/api/tests/Api/Users/UpdateUserTest.php b/api/tests/Api/Users/UpdateUserTest.php index 1ec93388a9..6a595ee60f 100644 --- a/api/tests/Api/Users/UpdateUserTest.php +++ b/api/tests/Api/Users/UpdateUserTest.php @@ -101,10 +101,9 @@ public function testNotWriteableProperties(string $property) { ]); } - public static function notWriteableUserProperties(): array { - return [ - 'activationKeyHash' => ['activationKeyHash'], - 'passwordResetKeyHash' => ['passwordResetKeyHash'], - ]; + public static function notWriteableUserProperties(): \Iterator { + yield 'activationKeyHash' => ['activationKeyHash']; + + yield 'passwordResetKeyHash' => ['passwordResetKeyHash']; } } diff --git a/api/tests/Constraints/CompatibleHalResponseTest.php b/api/tests/Constraints/CompatibleHalResponseTest.php index e5aae6348f..9b9acb9b01 100644 --- a/api/tests/Constraints/CompatibleHalResponseTest.php +++ b/api/tests/Constraints/CompatibleHalResponseTest.php @@ -22,90 +22,93 @@ public function testCompatibleArraysIsCommutative(array $array1, array $array2) assertThat($array2, CompatibleHalResponse::isHalCompatibleWith($array1)); } - public static function compatibleArrays() { - return [ - 'empty' => [[], []], - 'one_key' => [['one' => 1], ['one' => 1]], - 'two_keys' => [ - ['one' => 1, 'two' => 2], - ['one' => 1, 'two' => 2], + public static function compatibleArrays(): \Iterator { + yield 'empty' => [[], []]; + + yield 'one_key' => [['one' => 1], ['one' => 1]]; + + yield 'two_keys' => [ + ['one' => 1, 'two' => 2], + ['one' => 1, 'two' => 2], + ]; + + yield 'different_values' => [['one' => 1], ['one' => 2]]; + + yield 'one_embedded_one_not' => [ + [ + '_links' => [ + 'one' => 'value', + ], ], - 'different_values' => [['one' => 1], ['one' => 2]], - 'one_embedded_one_not' => [ - [ - '_links' => [ - 'one' => 'value', - ], + [ + '_links' => [ + 'one' => 'value', ], - [ - '_links' => [ - 'one' => 'value', - ], - '_embedded' => [ - 'one' => [ - '_links' => [ - 'self' => 1, - ], + '_embedded' => [ + 'one' => [ + '_links' => [ + 'self' => 1, ], ], ], ], - 'recursive' => [ - [ - '_links' => [ - 'one' => 'value', - ], - '_embedded' => [ - 'one' => [ - '_links' => [ - 'self' => 1, - ], - '_embedded' => [ - 'one' => [ - '_links' => [ - 'self' => 1, - ], + ]; + + yield 'recursive' => [ + [ + '_links' => [ + 'one' => 'value', + ], + '_embedded' => [ + 'one' => [ + '_links' => [ + 'self' => 1, + ], + '_embedded' => [ + 'one' => [ + '_links' => [ + 'self' => 1, ], - 'two' => [ - '_links' => [ - 'self' => 1, - ], + ], + 'two' => [ + '_links' => [ + 'self' => 1, ], ], ], - 'two' => [ - '_links' => [ - 'self' => 1, - ], + ], + 'two' => [ + '_links' => [ + 'self' => 1, ], ], ], - [ - '_links' => [ - 'one' => 'value', - ], - '_embedded' => [ - 'one' => [ - '_links' => [ - 'self' => 1, - ], - '_embedded' => [ - 'one' => [ - '_links' => [ - 'self' => 1, - ], + ], + [ + '_links' => [ + 'one' => 'value', + ], + '_embedded' => [ + 'one' => [ + '_links' => [ + 'self' => 1, + ], + '_embedded' => [ + 'one' => [ + '_links' => [ + 'self' => 1, ], - 'two' => [ - '_links' => [ - 'self' => 1, - ], + ], + 'two' => [ + '_links' => [ + 'self' => 1, ], ], ], - 'two' => [ - '_links' => [ - 'self' => 1, - ], + ], + 'two' => [ + '_links' => [ + 'self' => 1, ], ], ], @@ -123,89 +126,91 @@ public function testNotCompatibleArraysIsCommutative(array $array1, array $array assertThat($array2, logicalNot(CompatibleHalResponse::isHalCompatibleWith($array1))); } - public static function notCompatibleArrays() { - return [ - 'empty_and_not_empty' => [[], [2]], - 'one_key' => [['one' => 1], ['two' => 1]], - 'two_keys' => [ - ['one' => 1, 'three' => 2], - ['one' => 1, 'two' => 2], + public static function notCompatibleArrays(): \Iterator { + yield 'empty_and_not_empty' => [[], [2]]; + + yield 'one_key' => [['one' => 1], ['two' => 1]]; + + yield 'two_keys' => [ + ['one' => 1, 'three' => 2], + ['one' => 1, 'two' => 2], + ]; + + yield 'one_embedded_one_not' => [ + [ + '_links' => [ + 'two' => 'value', + ], ], - 'one_embedded_one_not' => [ - [ - '_links' => [ - 'two' => 'value', - ], + [ + '_links' => [ + 'one' => 'value', ], - [ - '_links' => [ - 'one' => 'value', - ], - '_embedded' => [ - 'one' => [ - '_links' => [ - 'self' => 1, - ], + '_embedded' => [ + 'one' => [ + '_links' => [ + 'self' => 1, ], ], ], ], - 'recursive' => [ - [ - '_links' => [ - 'one' => 'value', - ], - '_embedded' => [ - 'one' => [ - '_links' => [ - 'self' => 1, - ], - '_embedded' => [ - 'one' => [ - '_links' => [ - 'self' => 1, - ], + ]; + + yield 'recursive' => [ + [ + '_links' => [ + 'one' => 'value', + ], + '_embedded' => [ + 'one' => [ + '_links' => [ + 'self' => 1, + ], + '_embedded' => [ + 'one' => [ + '_links' => [ + 'self' => 1, ], - 'two' => [ - '_links' => [ - 'self' => 1, - ], + ], + 'two' => [ + '_links' => [ + 'self' => 1, ], ], ], - 'two' => [ - '_links' => [ - 'self' => 1, - ], + ], + 'two' => [ + '_links' => [ + 'self' => 1, ], ], ], - [ - '_links' => [ - 'one' => 'value', - ], - '_embedded' => [ - 'one' => [ - '_links' => [ - 'self' => 1, - ], - '_embedded' => [ - 'one' => [ - '_links' => [ - 'self' => 1, - ], + ], + [ + '_links' => [ + 'one' => 'value', + ], + '_embedded' => [ + 'one' => [ + '_links' => [ + 'self' => 1, + ], + '_embedded' => [ + 'one' => [ + '_links' => [ + 'self' => 1, ], - 'three' => [ - '_links' => [ - 'self' => 1, - ], + ], + 'three' => [ + '_links' => [ + 'self' => 1, ], ], ], - 'two' => [ - '_links' => [ - 'self' => 1, - ], + ], + 'two' => [ + '_links' => [ + 'self' => 1, ], ], ], diff --git a/api/tests/DependencyInjection/JWTOAuthStateCompilerPassTest.php b/api/tests/DependencyInjection/JWTOAuthStateCompilerPassTest.php index 994d2540bf..00e0dc232a 100644 --- a/api/tests/DependencyInjection/JWTOAuthStateCompilerPassTest.php +++ b/api/tests/DependencyInjection/JWTOAuthStateCompilerPassTest.php @@ -37,8 +37,8 @@ public function testProcess() { $compilerPass->process($container); // then - $this->assertEquals(6, count($container->getDefinition('knpu.oauth2.client.test-service')->getArguments())); - $this->assertEquals(1, count($container->getDefinition('knpu.oauth2.client.test-service-2')->getArguments())); - $this->assertEquals(1, count($container->getDefinition('knpu.oauth2.client.test-service-3')->getArguments())); + $this->assertCount(6, $container->getDefinition('knpu.oauth2.client.test-service')->getArguments()); + $this->assertCount(1, $container->getDefinition('knpu.oauth2.client.test-service-2')->getArguments()); + $this->assertCount(1, $container->getDefinition('knpu.oauth2.client.test-service-3')->getArguments()); } } diff --git a/api/tests/Doctrine/Filter/ContentNodePeriodFilterTest.php b/api/tests/Doctrine/Filter/ContentNodePeriodFilterTest.php index bd9ba162a6..a5ed86b554 100644 --- a/api/tests/Doctrine/Filter/ContentNodePeriodFilterTest.php +++ b/api/tests/Doctrine/Filter/ContentNodePeriodFilterTest.php @@ -20,7 +20,6 @@ */ class ContentNodePeriodFilterTest extends TestCase { private ManagerRegistry|MockObject $managerRegistryMock; - private EntityManager|MockObject $entityManagerMock; private MockObject|QueryBuilder $queryBuilderMock; private MockObject|QueryNameGeneratorInterface $queryNameGeneratorInterfaceMock; private IriConverterInterface|MockObject $iriConverterMock; @@ -28,39 +27,34 @@ class ContentNodePeriodFilterTest extends TestCase { public function setUp(): void { parent::setUp(); $this->managerRegistryMock = $this->createMock(ManagerRegistry::class); - $this->entityManagerMock = $this->createMock(EntityManager::class); + $entityManagerMock = $this->createMock(EntityManager::class); $this->queryBuilderMock = $this->createMock(QueryBuilder::class); $this->queryNameGeneratorInterfaceMock = $this->createMock(QueryNameGeneratorInterface::class); $this->iriConverterMock = $this->createMock(IriConverterInterface::class); - $this->entityManagerMock + $entityManagerMock ->method('createQueryBuilder') - ->will($this->returnValue($this->queryBuilderMock)) + ->willReturn($this->queryBuilderMock) ; $this->queryBuilderMock - ->method('from') - ->will($this->returnSelf()) + ->method('from')->willReturnSelf() ; $this->queryBuilderMock - ->method('select') - ->will($this->returnSelf()) + ->method('select')->willReturnSelf() ; $this->queryBuilderMock - ->method('innerJoin') - ->will($this->returnSelf()) + ->method('innerJoin')->willReturnSelf() ; $this->queryBuilderMock - ->method('join') - ->will($this->returnSelf()) + ->method('join')->willReturnSelf() ; $this->queryBuilderMock - ->method('andWhere') - ->will($this->returnSelf()) + ->method('andWhere')->willReturnSelf() ; $this->queryBuilderMock @@ -76,21 +70,21 @@ public function setUp(): void { $expr = new Expr(); $this->queryBuilderMock ->method('expr') - ->will($this->returnValue($expr)) + ->willReturn($expr) ; $this->queryBuilderMock ->method('getEntityManager') - ->will($this->returnValue($this->entityManagerMock)) + ->willReturn($entityManagerMock) ; $this->queryNameGeneratorInterfaceMock ->method('generateParameterName') - ->willReturnCallback(fn ($field) => $field.'_a1') + ->willReturnCallback(fn (string $field): string => $field.'_a1') ; $this->queryNameGeneratorInterfaceMock ->method('generateJoinAlias') - ->willReturnCallback(fn ($field) => $field.'_j1') + ->willReturnCallback(fn (string $field): string => $field.'_j1') ; } @@ -161,7 +155,7 @@ public function testAddsFilterForPeriodProperty() { ->expects($this->once()) ->method('getResourceFromIri') ->with('/period/123') - ->will($this->returnValue($period)) + ->willReturn($period) ; $this->queryBuilderMock diff --git a/api/tests/Doctrine/Filter/ExpressionDateTimeFilterTest.php b/api/tests/Doctrine/Filter/ExpressionDateTimeFilterTest.php index 420d28acd0..1dabdd9100 100644 --- a/api/tests/Doctrine/Filter/ExpressionDateTimeFilterTest.php +++ b/api/tests/Doctrine/Filter/ExpressionDateTimeFilterTest.php @@ -38,11 +38,11 @@ public function setUp(): void { $this->queryNameGeneratorInterfaceMock ->method('generateParameterName') - ->willReturnCallback(fn ($field) => $field.'_a1') + ->willReturnCallback(fn (string $field): string => $field.'_a1') ; $this->queryNameGeneratorInterfaceMock ->method('generateJoinAlias') - ->willReturnCallback(fn ($field) => $field.'_j1') + ->willReturnCallback(fn (string $field): string => $field.'_j1') ; $classMetadata = $this->createStub(ClassMetadata::class); @@ -62,7 +62,7 @@ public function testGetDescriptionDoesNothingWhenNoPropertiesDefined() { $description = $filter->getDescription('Dummy'); // then - $this->assertEquals([], $description); + $this->assertSame([], $description); } public function testGetDescription() { @@ -105,7 +105,7 @@ public function testGetDescriptionDisallowsEmptyExpression() { $description = $filter->getDescription('Dummy'); // then - $this->assertEquals([], $description); + $this->assertSame([], $description); } public function testApplyChecksForDefinedFilters() { @@ -293,12 +293,13 @@ public function testApplyReplacesMultipleInstancesOfTheSameRelationAlias(string ]]); } - public static function getOperators() { - return [ - 'before' => ['before', '<='], - 'strictly_before' => ['strictly_before', '<'], - 'after' => ['after', '>='], - 'strictly_after' => ['strictly_after', '>'], - ]; + public static function getOperators(): \Iterator { + yield 'before' => ['before', '<=']; + + yield 'strictly_before' => ['strictly_before', '<']; + + yield 'after' => ['after', '>=']; + + yield 'strictly_after' => ['strictly_after', '>']; } } diff --git a/api/tests/Doctrine/Filter/MaterialItemPeriodFilterTest.php b/api/tests/Doctrine/Filter/MaterialItemPeriodFilterTest.php index 31c354a10e..6e09063c37 100644 --- a/api/tests/Doctrine/Filter/MaterialItemPeriodFilterTest.php +++ b/api/tests/Doctrine/Filter/MaterialItemPeriodFilterTest.php @@ -21,61 +21,52 @@ */ class MaterialItemPeriodFilterTest extends TestCase { private ManagerRegistry|MockObject $managerRegistryMock; - private EntityRepository|MockObject $materialNodeRepositoryMock; - private MockObject|QueryBuilder $materialNodeQueryBuilderMock; private MockObject|QueryBuilder $queryBuilderMock; - private EntityManager|MockObject $entityManagerMock; private MockObject|QueryNameGeneratorInterface $queryNameGeneratorInterfaceMock; private IriConverterInterface|MockObject $iriConverterMock; public function setUp(): void { parent::setUp(); $this->managerRegistryMock = $this->createMock(ManagerRegistry::class); - $this->materialNodeRepositoryMock = $this->createMock(EntityRepository::class); - $this->materialNodeQueryBuilderMock = $this->createMock(QueryBuilder::class); + $materialNodeRepositoryMock = $this->createMock(EntityRepository::class); + $materialNodeQueryBuilderMock = $this->createMock(QueryBuilder::class); $this->queryBuilderMock = $this->createMock(QueryBuilder::class); - $this->entityManagerMock = $this->createMock(EntityManager::class); + $entityManagerMock = $this->createMock(EntityManager::class); $this->queryNameGeneratorInterfaceMock = $this->createMock(QueryNameGeneratorInterface::class); $this->iriConverterMock = $this->createMock(IriConverterInterface::class); $this->managerRegistryMock ->method('getRepository') - ->will($this->returnValue($this->materialNodeRepositoryMock)) + ->willReturn($materialNodeRepositoryMock) ; - $this->materialNodeRepositoryMock + $materialNodeRepositoryMock ->method('createQueryBuilder') - ->will($this->returnValue($this->materialNodeQueryBuilderMock)) + ->willReturn($materialNodeQueryBuilderMock) ; - $this->materialNodeQueryBuilderMock - ->method('select') - ->will($this->returnSelf()) + $materialNodeQueryBuilderMock + ->method('select')->willReturnSelf() ; - $this->materialNodeQueryBuilderMock - ->method('join') - ->will($this->returnSelf()) + $materialNodeQueryBuilderMock + ->method('join')->willReturnSelf() ; - $this->materialNodeQueryBuilderMock - ->method('where') - ->will($this->returnSelf()) + $materialNodeQueryBuilderMock + ->method('where')->willReturnSelf() ; $this->queryBuilderMock - ->method('from') - ->will($this->returnSelf()) + ->method('from')->willReturnSelf() ; $this->queryBuilderMock - ->method('join') - ->will($this->returnSelf()) + ->method('join')->willReturnSelf() ; $this->queryBuilderMock - ->method('where') - ->will($this->returnSelf()) + ->method('where')->willReturnSelf() ; $this->queryBuilderMock @@ -85,7 +76,7 @@ public function setUp(): void { $this->queryBuilderMock ->method('getEntityManager') - ->will($this->returnValue($this->entityManagerMock)) + ->willReturn($entityManagerMock) ; $this->queryBuilderMock @@ -96,21 +87,21 @@ public function setUp(): void { $expr = new Expr(); $this->queryBuilderMock ->method('expr') - ->will($this->returnValue($expr)) + ->willReturn($expr) ; - $this->entityManagerMock + $entityManagerMock ->method('createQueryBuilder') - ->will($this->returnValue($this->queryBuilderMock)) + ->willReturn($this->queryBuilderMock) ; $this->queryNameGeneratorInterfaceMock ->method('generateParameterName') - ->willReturnCallback(fn ($field) => $field.'_a1') + ->willReturnCallback(fn (string $field): string => $field.'_a1') ; $this->queryNameGeneratorInterfaceMock ->method('generateJoinAlias') - ->willReturnCallback(fn ($field) => $field.'_j1') + ->willReturnCallback(fn (string $field): string => $field.'_j1') ; } @@ -176,7 +167,7 @@ public function testAddsFilterForPeriodProperty() { ->expects($this->once()) ->method('getResourceFromIri') ->with('/period/123') - ->will($this->returnValue($period)) + ->willReturn($period) ; $this->queryBuilderMock diff --git a/api/tests/Entity/CampTest.php b/api/tests/Entity/CampTest.php index 8909dee23b..03075fadb5 100644 --- a/api/tests/Entity/CampTest.php +++ b/api/tests/Entity/CampTest.php @@ -57,7 +57,7 @@ public function testCopyFromPrototype() { $camp = new Camp(); $camp->copyFromPrototype($this->campPrototype, new EntityMap($camp)); - $this->assertEquals($this->campPrototype->getId(), $camp->campPrototypeId); + $this->assertSame($this->campPrototype->getId(), $camp->campPrototypeId); $this->assertCount(1, $camp->categories); diff --git a/api/tests/Entity/PeriodTest.php b/api/tests/Entity/PeriodTest.php index ebb260dcbc..a5a3b4b19a 100644 --- a/api/tests/Entity/PeriodTest.php +++ b/api/tests/Entity/PeriodTest.php @@ -28,7 +28,7 @@ public function testFirstDayNumberInPeriod() { $period2->addDay(new Day()); $period2->addDay(new Day()); - $this->assertEquals(3, $period1->getFirstDayNumber()); - $this->assertEquals(1, $period2->getFirstDayNumber()); + $this->assertSame(3, $period1->getFirstDayNumber()); + $this->assertSame(1, $period2->getFirstDayNumber()); } } diff --git a/api/tests/Entity/ProfileTest.php b/api/tests/Entity/ProfileTest.php index d37b5ca19c..10d2fef1cd 100644 --- a/api/tests/Entity/ProfileTest.php +++ b/api/tests/Entity/ProfileTest.php @@ -27,7 +27,7 @@ public function testDisplayNameUsesNicknameIfPresent() { $displayName = $this->profile->getDisplayName(); // then - $this->assertEquals('Bi-Pi', $displayName); + $this->assertSame('Bi-Pi', $displayName); } public function testDisplayNameUsesFullName() { @@ -38,7 +38,7 @@ public function testDisplayNameUsesFullName() { $displayName = $this->profile->getDisplayName(); // then - $this->assertEquals('Robert Baden-Powell', $displayName); + $this->assertSame('Robert Baden-Powell', $displayName); } public function testDisplayNameUsesFirstname() { @@ -50,7 +50,7 @@ public function testDisplayNameUsesFirstname() { $displayName = $this->profile->getDisplayName(); // then - $this->assertEquals('Robert', $displayName); + $this->assertSame('Robert', $displayName); } public function testDisplayNameUsesEmailHashAsFallback() { @@ -62,7 +62,7 @@ public function testDisplayNameUsesEmailHashAsFallback() { $displayName = $this->profile->getDisplayName(); // then - $this->assertEquals('Noname-b642', $displayName); + $this->assertSame('Noname-b642', $displayName); } public function testLegalNameUsesFullNameIfPresent() { @@ -72,7 +72,7 @@ public function testLegalNameUsesFullNameIfPresent() { $displayName = $this->profile->getLegalName(); // then - $this->assertEquals('Robert Baden-Powell', $displayName); + $this->assertSame('Robert Baden-Powell', $displayName); } public function testLegalNameUsesNicknameWhenFirstnameMissing() { @@ -83,7 +83,7 @@ public function testLegalNameUsesNicknameWhenFirstnameMissing() { $displayName = $this->profile->getLegalName(); // then - $this->assertEquals('Bi-Pi', $displayName); + $this->assertSame('Bi-Pi', $displayName); } public function testLegalNameUsesNicknameWhenSurnameMissing() { @@ -94,7 +94,7 @@ public function testLegalNameUsesNicknameWhenSurnameMissing() { $displayName = $this->profile->getLegalName(); // then - $this->assertEquals('Bi-Pi', $displayName); + $this->assertSame('Bi-Pi', $displayName); } public function testLegalNameUsesEmailHashAsFallback() { @@ -106,6 +106,6 @@ public function testLegalNameUsesEmailHashAsFallback() { $displayName = $this->profile->getLegalName(); // then - $this->assertEquals('Noname-b642', $displayName); + $this->assertSame('Noname-b642', $displayName); } } diff --git a/api/tests/Entity/ScheduleEntryTest.php b/api/tests/Entity/ScheduleEntryTest.php index 1eb2e9d05e..a3be4c480a 100644 --- a/api/tests/Entity/ScheduleEntryTest.php +++ b/api/tests/Entity/ScheduleEntryTest.php @@ -17,7 +17,6 @@ class ScheduleEntryTest extends TestCase { private ScheduleEntry $scheduleEntry1; private ScheduleEntry $scheduleEntry2; private ScheduleEntry $scheduleEntry3; - private Camp $camp; private Period $period; private Day $day1; private Day $day2; @@ -34,8 +33,8 @@ public function setUp(): void { $this->period->addDay($this->day1); $this->period->addDay($this->day2); - $this->camp = new Camp(); - $this->camp->addPeriod($this->period); + $camp = new Camp(); + $camp->addPeriod($this->period); $this->scheduleEntry2 = new ScheduleEntry(); $this->scheduleEntry2->startOffset = 960; @@ -76,21 +75,21 @@ public function testGetEndReturnsNullOnError() { } public function testGetDayNumber() { - $this->assertEquals(1, $this->scheduleEntry1->getDayNumber()); - $this->assertEquals(1, $this->scheduleEntry2->getDayNumber()); - $this->assertEquals(2, $this->scheduleEntry3->getDayNumber()); + $this->assertSame(1, $this->scheduleEntry1->getDayNumber()); + $this->assertSame(1, $this->scheduleEntry2->getDayNumber()); + $this->assertSame(2, $this->scheduleEntry3->getDayNumber()); } public function testGetScheduleEntryNumber() { - $this->assertEquals(1, $this->scheduleEntry1->getScheduleEntryNumber()); - $this->assertEquals(2, $this->scheduleEntry2->getScheduleEntryNumber()); - $this->assertEquals(1, $this->scheduleEntry3->getScheduleEntryNumber()); + $this->assertSame(1, $this->scheduleEntry1->getScheduleEntryNumber()); + $this->assertSame(2, $this->scheduleEntry2->getScheduleEntryNumber()); + $this->assertSame(1, $this->scheduleEntry3->getScheduleEntryNumber()); } public function testGetNumber() { - $this->assertEquals('1.1', $this->scheduleEntry1->getNumber()); - $this->assertEquals('1.2', $this->scheduleEntry2->getNumber()); - $this->assertEquals('2.1', $this->scheduleEntry3->getNumber()); + $this->assertSame('1.1', $this->scheduleEntry1->getNumber()); + $this->assertSame('1.2', $this->scheduleEntry2->getNumber()); + $this->assertSame('2.1', $this->scheduleEntry3->getNumber()); } public function testGetNumberInDifferentNumberingStyle() { @@ -99,9 +98,9 @@ public function testGetNumberInDifferentNumberingStyle() { $activity = new Activity(); $activity->category = $category; $this->scheduleEntry2->activity = $activity; - $this->assertEquals('1.1', $this->scheduleEntry1->getNumber()); - $this->assertEquals('1.i', $this->scheduleEntry2->getNumber()); - $this->assertEquals('2.1', $this->scheduleEntry3->getNumber()); + $this->assertSame('1.1', $this->scheduleEntry1->getNumber()); + $this->assertSame('1.i', $this->scheduleEntry2->getNumber()); + $this->assertSame('2.1', $this->scheduleEntry3->getNumber()); } public function testGetEmptyValueWhenNumberingStyleIsNone() { @@ -110,9 +109,9 @@ public function testGetEmptyValueWhenNumberingStyleIsNone() { $activity = new Activity(); $activity->category = $category; $this->scheduleEntry2->activity = $activity; - $this->assertEquals('1.1', $this->scheduleEntry1->getNumber()); - $this->assertEquals('', $this->scheduleEntry2->getNumber()); - $this->assertEquals('2.1', $this->scheduleEntry3->getNumber()); + $this->assertSame('1.1', $this->scheduleEntry1->getNumber()); + $this->assertSame('', $this->scheduleEntry2->getNumber()); + $this->assertSame('2.1', $this->scheduleEntry3->getNumber()); } public function testGetNumberOrdersSamePeriodOffsetByLeft() { @@ -120,8 +119,8 @@ public function testGetNumberOrdersSamePeriodOffsetByLeft() { $this->scheduleEntry1->left = 0.5; $this->scheduleEntry2->left = 0; - $this->assertEquals('1.1', $this->scheduleEntry2->getNumber()); - $this->assertEquals('1.2', $this->scheduleEntry1->getNumber()); + $this->assertSame('1.1', $this->scheduleEntry2->getNumber()); + $this->assertSame('1.2', $this->scheduleEntry1->getNumber()); } public function testGetNumberOrdersSamePeriodOffsetAndLeftByLength() { @@ -130,8 +129,8 @@ public function testGetNumberOrdersSamePeriodOffsetAndLeftByLength() { $this->scheduleEntry1->endOffset = $this->scheduleEntry1->startOffset + 60; $this->scheduleEntry2->endOffset = $this->scheduleEntry1->startOffset + 120; - $this->assertEquals('1.1', $this->scheduleEntry2->getNumber()); - $this->assertEquals('1.2', $this->scheduleEntry1->getNumber()); + $this->assertSame('1.1', $this->scheduleEntry2->getNumber()); + $this->assertSame('1.2', $this->scheduleEntry1->getNumber()); } public function testGetNumberOrdersSamePeriodOffsetAndLeftAndLengthById() { @@ -140,11 +139,11 @@ public function testGetNumberOrdersSamePeriodOffsetAndLeftAndLengthById() { $this->scheduleEntry1->endOffset = $this->scheduleEntry2->endOffset; if ($this->scheduleEntry1->getId() < $this->scheduleEntry2->getId()) { - $this->assertEquals('1.1', $this->scheduleEntry1->getNumber()); - $this->assertEquals('1.2', $this->scheduleEntry2->getNumber()); + $this->assertSame('1.1', $this->scheduleEntry1->getNumber()); + $this->assertSame('1.2', $this->scheduleEntry2->getNumber()); } else { - $this->assertEquals('1.1', $this->scheduleEntry2->getNumber()); - $this->assertEquals('1.2', $this->scheduleEntry1->getNumber()); + $this->assertSame('1.1', $this->scheduleEntry2->getNumber()); + $this->assertSame('1.2', $this->scheduleEntry1->getNumber()); } } diff --git a/api/tests/EventListener/RequestTransactionListenerTest.php b/api/tests/EventListener/RequestTransactionListenerTest.php index eb907e95b8..5276729142 100644 --- a/api/tests/EventListener/RequestTransactionListenerTest.php +++ b/api/tests/EventListener/RequestTransactionListenerTest.php @@ -200,8 +200,10 @@ public function testIgnoresExceptionsForRequestsWhichDontChangeState(string $met } /** @noinspection PhpArrayShapeAttributeCanBeAddedInspection */ - public static function methodsWhichDontChangeState(): array { - return ['GET' => ['GET'], 'OPTIONS' => ['OPTIONS']]; + public static function methodsWhichDontChangeState(): \Iterator { + yield 'GET' => ['GET']; + + yield 'OPTIONS' => ['OPTIONS']; } /** @@ -231,8 +233,12 @@ public function testRollsBackTransactionForExceptionsForOtherMethods(string $met } /** @noinspection PhpArrayShapeAttributeCanBeAddedInspection */ - public static function methodsWhichChangeState(): array { - return ['PUT' => ['PUT'], 'POST' => ['POST'], 'DELETE' => ['DELETE']]; + public static function methodsWhichChangeState(): \Iterator { + yield 'PUT' => ['PUT']; + + yield 'POST' => ['POST']; + + yield 'DELETE' => ['DELETE']; } /** diff --git a/api/tests/InputFilter/CleanHTMLFilterTest.php b/api/tests/InputFilter/CleanHTMLFilterTest.php index 6114c1cbe5..ed74c582a5 100644 --- a/api/tests/InputFilter/CleanHTMLFilterTest.php +++ b/api/tests/InputFilter/CleanHTMLFilterTest.php @@ -38,19 +38,23 @@ public function testInputFiltering(string $input, string $output) { $result = $this->inputFilter->applyTo($data, 'key'); // then - $this->assertEquals($outputData, $result); + $this->assertSame($outputData, $result); } - public static function getExamples() { - return [ - ['', ''], - ['abc', 'abc'], - ['abc', 'abc'], - ['<3', '<3'], - ['', ''], - ['123', '123'], - ['abc
  • def', 'abcdef'], - ]; + public static function getExamples(): \Iterator { + yield ['', '']; + + yield ['abc', 'abc']; + + yield ['abc', 'abc']; + + yield ['<3', '<3']; + + yield ['', '']; + + yield ['123', '123']; + + yield ['abc
  • def', 'abcdef']; } public function testDoesNothingWhenKeyIsMissing() { @@ -61,7 +65,7 @@ public function testDoesNothingWhenKeyIsMissing() { $result = $this->inputFilter->applyTo($data, 'key'); // then - $this->assertEquals($data, $result); + $this->assertSame($data, $result); } public function testDoesNothingWhenValueIsNull() { @@ -83,6 +87,6 @@ public function testThrowsWhenValueIsNotStringable() { $this->expectException(UnexpectedValueException::class); // when - $result = $this->inputFilter->applyTo($data, 'key'); + $this->inputFilter->applyTo($data, 'key'); } } diff --git a/api/tests/InputFilter/CleanTextFilterTest.php b/api/tests/InputFilter/CleanTextFilterTest.php index f686d99b1e..3fe02049e8 100644 --- a/api/tests/InputFilter/CleanTextFilterTest.php +++ b/api/tests/InputFilter/CleanTextFilterTest.php @@ -30,24 +30,33 @@ public function testInputFiltering(string $input, string $output) { $result = $this->inputFilter->applyTo($data, 'key'); // then - $this->assertEquals($outputData, $result); + $this->assertSame($outputData, $result); } - public static function getExamples() { - return [ - ['', ''], - ['abc', 'abc'], - ['', ''], - ['😀', '😀'], - ['keeps \backslash\ and "double quotes"', 'keeps \backslash\ and "double quotes"'], - ["keeps 'single quotes'", "keeps 'single quotes'"], - ["removes newlines\n, tabs\t, vertical tabs\v and form-feed\f", 'removes newlines, tabs, vertical tabs and form-feed'], - ["removes unicode\u{000A} control\u{0007} caracters", 'removes unicode control caracters'], - ["removes ASCII\x0A control\x07 caracters", 'removes ASCII control caracters'], - ["removes ANSI escape \e[32m sequences", 'removes ANSI escape [32m sequences'], - ["removes bidirectional\u{202E} text control", 'removes bidirectional text control'], - ['removes non-escaped bidirectional‮ text control', 'removes non-escaped bidirectional text control'], - ]; + public static function getExamples(): \Iterator { + yield ['', '']; + + yield ['abc', 'abc']; + + yield ['', '']; + + yield ['😀', '😀']; + + yield ['keeps \backslash\ and "double quotes"', 'keeps \backslash\ and "double quotes"']; + + yield ["keeps 'single quotes'", "keeps 'single quotes'"]; + + yield ["removes newlines\n, tabs\t, vertical tabs\v and form-feed\f", 'removes newlines, tabs, vertical tabs and form-feed']; + + yield ["removes unicode\u{000A} control\u{0007} caracters", 'removes unicode control caracters']; + + yield ["removes ASCII\x0A control\x07 caracters", 'removes ASCII control caracters']; + + yield ["removes ANSI escape \e[32m sequences", 'removes ANSI escape [32m sequences']; + + yield ["removes bidirectional\u{202E} text control", 'removes bidirectional text control']; + + yield ['removes non-escaped bidirectional‮ text control', 'removes non-escaped bidirectional text control']; } public function testDoesNothingWhenKeyIsMissing() { @@ -58,7 +67,7 @@ public function testDoesNothingWhenKeyIsMissing() { $result = $this->inputFilter->applyTo($data, 'key'); // then - $this->assertEquals($data, $result); + $this->assertSame($data, $result); } public function testDoesNothingWhenValueIsNull() { @@ -80,6 +89,6 @@ public function testThrowsWhenValueIsNotStringable() { $this->expectException(UnexpectedValueException::class); // when - $result = $this->inputFilter->applyTo($data, 'key'); + $this->inputFilter->applyTo($data, 'key'); } } diff --git a/api/tests/InputFilter/TrimFilterTest.php b/api/tests/InputFilter/TrimFilterTest.php index 3cf486b9b7..ae91a7fa34 100644 --- a/api/tests/InputFilter/TrimFilterTest.php +++ b/api/tests/InputFilter/TrimFilterTest.php @@ -22,20 +22,25 @@ public function testInputFiltering(string $input, string $output) { $result = $trim->applyTo($data, 'key'); // then - $this->assertEquals($outputData, $result); + $this->assertSame($outputData, $result); } - public static function getExamples() { - return [ - ['', ''], - ['abc', 'abc'], - [' abc', 'abc'], - ['abc def', 'abc def'], - ['abc ', 'abc'], - ["\tabc", 'abc'], - [' abc', 'abc'], - ["\t abc ", 'abc'], - ]; + public static function getExamples(): \Iterator { + yield ['', '']; + + yield ['abc', 'abc']; + + yield [' abc', 'abc']; + + yield ['abc def', 'abc def']; + + yield ['abc ', 'abc']; + + yield ["\tabc", 'abc']; + + yield [' abc', 'abc']; + + yield ["\t abc ", 'abc']; } public function testDoesNothingWhenKeyIsMissing() { @@ -47,7 +52,7 @@ public function testDoesNothingWhenKeyIsMissing() { $result = $trim->applyTo($data, 'key'); // then - $this->assertEquals($data, $result); + $this->assertSame($data, $result); } public function testDoesNothingWhenValueIsNull() { @@ -71,6 +76,6 @@ public function testThrowsWhenValueIsNotStringable() { $this->expectException(UnexpectedValueException::class); // when - $result = $trim->applyTo($data, 'key'); + $trim->applyTo($data, 'key'); } } diff --git a/api/tests/Metadata/Resource/Factory/UriTemplateFactoryTest.php b/api/tests/Metadata/Resource/Factory/UriTemplateFactoryTest.php index 9379bd627f..802993a090 100644 --- a/api/tests/Metadata/Resource/Factory/UriTemplateFactoryTest.php +++ b/api/tests/Metadata/Resource/Factory/UriTemplateFactoryTest.php @@ -51,9 +51,9 @@ protected function setUp(): void { ), ])); - $this->resourceNameCollectionFactory->method('create')->willReturnCallback(fn () => $this->resourceNameCollection); + $this->resourceNameCollectionFactory->method('create')->willReturnCallback(fn (): ResourceNameCollection => $this->resourceNameCollection); $this->resourceMetadataCollectionFactory->method('create')->with('Dummy')->willReturnCallback(fn () => $this->resourceMetadataCollection); - $this->iriConverter->method('getIriFromResource')->willReturnCallback(function ($resourceClass) { + $this->iriConverter->method('getIriFromResource')->willReturnCallback(function (object|string $resourceClass): ?string { return '/'.lcfirst($resourceClass).'s'; }); } diff --git a/api/tests/Metadata/Resource/OperationHelperTest.php b/api/tests/Metadata/Resource/OperationHelperTest.php index 5ca5572004..45b056a332 100644 --- a/api/tests/Metadata/Resource/OperationHelperTest.php +++ b/api/tests/Metadata/Resource/OperationHelperTest.php @@ -39,7 +39,7 @@ public function testFindGet() { $operation = OperationHelper::findOneByType($this->resourceMetadataCollection, Get::class); // then - $this->assertEquals('get', $operation->getName()); + $this->assertSame('get', $operation->getName()); } public function testReturnsNullForMissingOperation() { @@ -75,7 +75,7 @@ public function testFindsFirstOperation() { $operation = OperationHelper::findOneByType($this->resourceMetadataCollection, Get::class); // then - $this->assertEquals('get1', $operation->getName()); + $this->assertSame('get1', $operation->getName()); } public function testFindsOperationInMultipleResources() { @@ -100,7 +100,7 @@ public function testFindsOperationInMultipleResources() { $operation = OperationHelper::findOneByType($this->resourceMetadataCollection, Get::class); // then - $this->assertEquals('get1', $operation->getName()); + $this->assertSame('get1', $operation->getName()); } public function testFindGraphQlOperation() { @@ -115,6 +115,6 @@ public function testFindGraphQlOperation() { $operation = OperationHelper::findOneByType($this->resourceMetadataCollection, QueryCollection::class); // then - $this->assertEquals('queryCollection', $operation->getName()); + $this->assertSame('queryCollection', $operation->getName()); } } diff --git a/api/tests/OAuth/JWTStateOAuth2ClientTest.php b/api/tests/OAuth/JWTStateOAuth2ClientTest.php index 1810ac5c4f..df2c4048b1 100644 --- a/api/tests/OAuth/JWTStateOAuth2ClientTest.php +++ b/api/tests/OAuth/JWTStateOAuth2ClientTest.php @@ -29,7 +29,7 @@ public function testGetCookieName() { $cookieName = JWTStateOAuth2Client::getCookieName('test_com_'); // then - $this->assertEquals('test_com_oauth_state_jwt', $cookieName); + $this->assertSame('test_com_oauth_state_jwt', $cookieName); } public function testRedirect() { @@ -71,7 +71,7 @@ public function testRedirect() { $response = $client->redirect([], ['additionalData' => ['foo' => 'bar']]); // then - $this->assertEquals(1, count($response->headers->getCookies())); + $this->assertCount(1, $response->headers->getCookies()); $this->assertEquals('test_prefix_oauth_state_jwt', $response->headers->getCookies()[0]->getName()); $this->assertEquals('lax', $response->headers->getCookies()[0]->getSameSite()); $this->assertTrue($response->headers->getCookies()[0]->isHttpOnly()); diff --git a/api/tests/Security/Voter/CampIsPrototypeVoterTest.php b/api/tests/Security/Voter/CampIsPrototypeVoterTest.php index 1ab66746d4..a8a57c64f1 100644 --- a/api/tests/Security/Voter/CampIsPrototypeVoterTest.php +++ b/api/tests/Security/Voter/CampIsPrototypeVoterTest.php @@ -42,7 +42,7 @@ public function testDoesntVoteWhenAttributeWrong() { $result = $this->voter->vote($this->token, new Period(), ['CAMP_IS_SOMETHING_ELSE']); // then - $this->assertEquals(VoterInterface::ACCESS_ABSTAIN, $result); + $this->assertSame(VoterInterface::ACCESS_ABSTAIN, $result); } public function testDoesntVoteWhenSubjectDoesNotBelongToCamp() { @@ -52,7 +52,7 @@ public function testDoesntVoteWhenSubjectDoesNotBelongToCamp() { $result = $this->voter->vote($this->token, new CampIsPrototypeVoterTestDummy(), ['CAMP_IS_PROTOTYPE']); // then - $this->assertEquals(VoterInterface::ACCESS_ABSTAIN, $result); + $this->assertSame(VoterInterface::ACCESS_ABSTAIN, $result); } public function testDoesntVoteWhenSubjectIsNull() { @@ -62,7 +62,7 @@ public function testDoesntVoteWhenSubjectIsNull() { $result = $this->voter->vote($this->token, null, ['CAMP_IS_PROTOTYPE']); // then - $this->assertEquals(VoterInterface::ACCESS_ABSTAIN, $result); + $this->assertSame(VoterInterface::ACCESS_ABSTAIN, $result); } public function testDeniesAccessWhenGetCampYieldsNull() { @@ -75,7 +75,7 @@ public function testDeniesAccessWhenGetCampYieldsNull() { $result = $this->voter->vote($this->token, $subject, ['CAMP_IS_PROTOTYPE']); // then - $this->assertEquals(VoterInterface::ACCESS_DENIED, $result); + $this->assertSame(VoterInterface::ACCESS_DENIED, $result); } public function testDeniesAccessWhenCampIsntPrototype() { @@ -92,7 +92,7 @@ public function testDeniesAccessWhenCampIsntPrototype() { $result = $this->voter->vote($this->token, $subject, ['CAMP_IS_PROTOTYPE']); // then - $this->assertEquals(VoterInterface::ACCESS_DENIED, $result); + $this->assertSame(VoterInterface::ACCESS_DENIED, $result); } public function testGrantsAccessViaBelongsToCampInterface() { @@ -111,7 +111,7 @@ public function testGrantsAccessViaBelongsToCampInterface() { $result = $this->voter->vote($this->token, $subject, ['CAMP_IS_PROTOTYPE']); // then - $this->assertEquals(VoterInterface::ACCESS_GRANTED, $result); + $this->assertSame(VoterInterface::ACCESS_GRANTED, $result); } public function testGrantsAccessViaBelongsToContentNodeTreeInterface() { @@ -134,7 +134,7 @@ public function testGrantsAccessViaBelongsToContentNodeTreeInterface() { $result = $this->voter->vote($this->token, $subject, ['CAMP_IS_PROTOTYPE']); // then - $this->assertEquals(VoterInterface::ACCESS_GRANTED, $result); + $this->assertSame(VoterInterface::ACCESS_GRANTED, $result); } } diff --git a/api/tests/Security/Voter/CampRoleVoterTest.php b/api/tests/Security/Voter/CampRoleVoterTest.php index 21a2660b92..d6777c399f 100644 --- a/api/tests/Security/Voter/CampRoleVoterTest.php +++ b/api/tests/Security/Voter/CampRoleVoterTest.php @@ -43,7 +43,7 @@ public function testDoesntVoteWhenAttributeWrong() { $result = $this->voter->vote($this->token, new Period(), ['CAMP_SUPPORTER']); // then - $this->assertEquals(VoterInterface::ACCESS_ABSTAIN, $result); + $this->assertSame(VoterInterface::ACCESS_ABSTAIN, $result); } public function testDoesntVoteWhenSubjectDoesNotBelongToCamp() { @@ -53,7 +53,7 @@ public function testDoesntVoteWhenSubjectDoesNotBelongToCamp() { $result = $this->voter->vote($this->token, new CampRoleVoterTestDummy(), ['CAMP_COLLABORATOR']); // then - $this->assertEquals(VoterInterface::ACCESS_ABSTAIN, $result); + $this->assertSame(VoterInterface::ACCESS_ABSTAIN, $result); } public function testDoesntVoteWhenSubjectIsNull() { @@ -63,7 +63,7 @@ public function testDoesntVoteWhenSubjectIsNull() { $result = $this->voter->vote($this->token, null, ['CAMP_COLLABORATOR']); // then - $this->assertEquals(VoterInterface::ACCESS_ABSTAIN, $result); + $this->assertSame(VoterInterface::ACCESS_ABSTAIN, $result); } public function testDeniesAccessWhenNotLoggedIn() { @@ -74,7 +74,7 @@ public function testDeniesAccessWhenNotLoggedIn() { $result = $this->voter->vote($this->token, new Period(), ['CAMP_COLLABORATOR']); // then - $this->assertEquals(VoterInterface::ACCESS_DENIED, $result); + $this->assertSame(VoterInterface::ACCESS_DENIED, $result); } public function testDeniesAccessWhenGetCampYieldsNull() { @@ -87,7 +87,7 @@ public function testDeniesAccessWhenGetCampYieldsNull() { $result = $this->voter->vote($this->token, $subject, ['CAMP_COLLABORATOR']); // then - $this->assertEquals(VoterInterface::ACCESS_DENIED, $result); + $this->assertSame(VoterInterface::ACCESS_DENIED, $result); } public function testDeniesAccessWhenGetCampYieldsNullAndNotLoggedIn() { @@ -100,7 +100,7 @@ public function testDeniesAccessWhenGetCampYieldsNullAndNotLoggedIn() { $result = $this->voter->vote($this->token, $subject, ['CAMP_COLLABORATOR']); // then - $this->assertEquals(VoterInterface::ACCESS_DENIED, $result); + $this->assertSame(VoterInterface::ACCESS_DENIED, $result); } public function testDeniesAccessWhenNoCampCollaborations() { @@ -116,7 +116,7 @@ public function testDeniesAccessWhenNoCampCollaborations() { $result = $this->voter->vote($this->token, $subject, ['CAMP_COLLABORATOR']); // then - $this->assertEquals(VoterInterface::ACCESS_DENIED, $result); + $this->assertSame(VoterInterface::ACCESS_DENIED, $result); } public function testDeniesAccessWhenNoMatchingCampCollaboration() { @@ -139,7 +139,7 @@ public function testDeniesAccessWhenNoMatchingCampCollaboration() { $result = $this->voter->vote($this->token, $subject, ['CAMP_COLLABORATOR']); // then - $this->assertEquals(VoterInterface::ACCESS_DENIED, $result); + $this->assertSame(VoterInterface::ACCESS_DENIED, $result); } public function testDeniesAccessWhenMatchingCampCollaborationIsInvitation() { @@ -162,7 +162,7 @@ public function testDeniesAccessWhenMatchingCampCollaborationIsInvitation() { $result = $this->voter->vote($this->token, $subject, ['CAMP_COLLABORATOR']); // then - $this->assertEquals(VoterInterface::ACCESS_DENIED, $result); + $this->assertSame(VoterInterface::ACCESS_DENIED, $result); } public function testDeniesAccessWhenMatchingCampCollaborationIsInactive() { @@ -185,7 +185,7 @@ public function testDeniesAccessWhenMatchingCampCollaborationIsInactive() { $result = $this->voter->vote($this->token, $subject, ['CAMP_COLLABORATOR']); // then - $this->assertEquals(VoterInterface::ACCESS_DENIED, $result); + $this->assertSame(VoterInterface::ACCESS_DENIED, $result); } public function testDeniesAccessWhenRolesDontMatch() { @@ -208,7 +208,7 @@ public function testDeniesAccessWhenRolesDontMatch() { $result = $this->voter->vote($this->token, $subject, ['CAMP_MANAGER']); // then - $this->assertEquals(VoterInterface::ACCESS_DENIED, $result); + $this->assertSame(VoterInterface::ACCESS_DENIED, $result); } public function testGrantsAccessViaBelongsToCampInterface() { @@ -233,7 +233,7 @@ public function testGrantsAccessViaBelongsToCampInterface() { $result = $this->voter->vote($this->token, $subject, ['CAMP_COLLABORATOR']); // then - $this->assertEquals(VoterInterface::ACCESS_GRANTED, $result); + $this->assertSame(VoterInterface::ACCESS_GRANTED, $result); } public function testGrantsAccessViaBelongsToContentNodeTreeInterface() { @@ -262,7 +262,7 @@ public function testGrantsAccessViaBelongsToContentNodeTreeInterface() { $result = $this->voter->vote($this->token, $subject, ['CAMP_COLLABORATOR']); // then - $this->assertEquals(VoterInterface::ACCESS_GRANTED, $result); + $this->assertSame(VoterInterface::ACCESS_GRANTED, $result); } } diff --git a/api/tests/Serializer/Denormalizer/InputFilterDenormalizerTest.php b/api/tests/Serializer/Denormalizer/InputFilterDenormalizerTest.php index cd41c9edcc..53ead6b80b 100644 --- a/api/tests/Serializer/Denormalizer/InputFilterDenormalizerTest.php +++ b/api/tests/Serializer/Denormalizer/InputFilterDenormalizerTest.php @@ -25,19 +25,14 @@ class InputFilterDenormalizerTest extends TestCase { */ private $decoratedMock; - /** - * @var MockObject|ServiceLocator - */ - private $inputFilterLocatorMock; - protected function setUp(): void { - $this->inputFilterLocatorMock = $this->createMock(ServiceLocator::class); - $this->inputFilterLocatorMock->method('get')->willReturnCallback(function ($name) { + $inputFilterLocatorMock = $this->createMock(ServiceLocator::class); + $inputFilterLocatorMock->method('get')->willReturnCallback(function (string $name): mixed { return new $name(); }); $this->decoratedMock = $this->createMock(DenormalizerInterface::class); - $this->denormalizer = new InputFilterDenormalizer($this->inputFilterLocatorMock); + $this->denormalizer = new InputFilterDenormalizer($inputFilterLocatorMock); $this->denormalizer->setDenormalizer($this->decoratedMock); } diff --git a/api/tests/Serializer/Normalizer/CollectionItemsNormalizerTest.php b/api/tests/Serializer/Normalizer/CollectionItemsNormalizerTest.php index 4453f1388d..fe25cecc11 100644 --- a/api/tests/Serializer/Normalizer/CollectionItemsNormalizerTest.php +++ b/api/tests/Serializer/Normalizer/CollectionItemsNormalizerTest.php @@ -54,7 +54,7 @@ public function testDelegatesNormalizeToDecorated() { $result = $this->normalizer->normalize($resource, null, []); // then - $this->assertEquals($delegatedResult, $result); + $this->assertSame($delegatedResult, $result); } public function testNormalizeReplacesEmbeddedAndLinkedItemWithItems() { @@ -66,7 +66,7 @@ public function testNormalizeReplacesEmbeddedAndLinkedItemWithItems() { $result = $this->normalizer->normalize($resource, null, []); // then - $this->assertEquals([ + $this->assertSame([ 'hello' => 'world', '_links' => [ 'items' => [ @@ -99,7 +99,7 @@ public function testNormalizeAddsEmptyEmbeddedItemsIfTotalItemsIsZero() { $result = $this->normalizer->normalize($resource, null, []); // then - $this->assertEquals([ + $this->assertSame([ 'hello' => 'world', 'totalItems' => 0, '_links' => [ diff --git a/api/tests/Serializer/Normalizer/ContentTypeNormalizerTest.php b/api/tests/Serializer/Normalizer/ContentTypeNormalizerTest.php index 62314d5232..ed27c46843 100644 --- a/api/tests/Serializer/Normalizer/ContentTypeNormalizerTest.php +++ b/api/tests/Serializer/Normalizer/ContentTypeNormalizerTest.php @@ -19,14 +19,13 @@ class ContentTypeNormalizerTest extends TestCase { private ContentTypeNormalizer $normalizer; private MockObject|NormalizerInterface $decoratedMock; - private IriConverterInterface|MockObject $iriConverter; private MockObject|UriTemplate $uriTemplate; private MockObject|UriTemplateFactory $uriTemplateFactory; protected function setUp(): void { $this->decoratedMock = $this->createMock(NormalizerInterface::class); - $this->iriConverter = $this->createMock(IriConverterInterface::class); + $iriConverter = $this->createMock(IriConverterInterface::class); $this->uriTemplate = $this->createMock(UriTemplate::class); $this->uriTemplateFactory = $this->createMock(UriTemplateFactory::class); @@ -34,7 +33,7 @@ protected function setUp(): void { $this->decoratedMock, $this->uriTemplate, $this->uriTemplateFactory, - $this->iriConverter, + $iriConverter, ); $this->normalizer->setSerializer($this->createMock(SerializerInterface::class)); } @@ -65,7 +64,7 @@ public function testDelegatesNormalizeToDecorated() { $result = $this->normalizer->normalize($resource, null, ['resource_class' => \stdClass::class]); // then - $this->assertEquals($delegatedResult, $result); + $this->assertSame($delegatedResult, $result); } public function testNormalizeAddsEntityPath() { @@ -102,6 +101,6 @@ public function testNormalizeAddsEntityPath() { ], ], ]; - $this->assertEquals($expectedResult, $result); + $this->assertSame($expectedResult, $result); } } diff --git a/api/tests/Serializer/Normalizer/Error/TranslationInfoOfConstraintViolationTest.php b/api/tests/Serializer/Normalizer/Error/TranslationInfoOfConstraintViolationTest.php index 1f781485d3..e7695fa808 100644 --- a/api/tests/Serializer/Normalizer/Error/TranslationInfoOfConstraintViolationTest.php +++ b/api/tests/Serializer/Normalizer/Error/TranslationInfoOfConstraintViolationTest.php @@ -32,50 +32,50 @@ public function testExtractsTranslationInfoFromConstraintViolation(ConstraintVio assertThat($translationInfo->parameters, equalTo($parametersWithoutCurlyBraces)); } - public static function constraintViolations(): array { - return [ - AssertAllowTransitions::class => [ - 'violation' => new ConstraintViolation( - message: 'value must be one of inactive, was established', - messageTemplate: 'value must be one of {{ to }}, was {{ value }}', - parameters: ['{{ to }}' => 'inactive', '{{ value }}' => 'established'], - root: new CampCollaboration(), - propertyPath: 'status', - invalidValue: 'established', - plural: null, - code: null, - constraint: new AssertAllowTransitions(transitions: []) - ), - 'key' => 'app.validator.allowtransition.assertallowtransitions', - ], - NotBlank::class => [ - 'violation' => new ConstraintViolation( - message: 'This value should not be blank.', - messageTemplate: 'This value should not be blank.', - parameters: ['{{ value }}' => '""'], - root: new CampCollaboration(), - propertyPath: 'name', - invalidValue: '', - plural: null, - code: 'c1051bb4-d103-4f74-8988-acbcafc7fdc3', - constraint: new NotBlank() - ), - 'key' => 'symfony.component.validator.constraints.notblank', - ], - NotBlank::class.' without parameters' => [ - 'violation' => new ConstraintViolation( - message: 'This value should not be blank.', - messageTemplate: 'This value should not be blank.', - parameters: [], - root: new CampCollaboration(), - propertyPath: 'name', - invalidValue: '', - plural: null, - code: 'c1051bb4-d103-4f74-8988-acbcafc7fdc3', - constraint: new NotBlank() - ), - 'key' => 'symfony.component.validator.constraints.notblank', - ], + public static function constraintViolations(): \Iterator { + yield AssertAllowTransitions::class => [ + new ConstraintViolation( + message: 'value must be one of inactive, was established', + messageTemplate: 'value must be one of {{ to }}, was {{ value }}', + parameters: ['{{ to }}' => 'inactive', '{{ value }}' => 'established'], + root: new CampCollaboration(), + propertyPath: 'status', + invalidValue: 'established', + plural: null, + code: null, + constraint: new AssertAllowTransitions(transitions: []) + ), + 'app.validator.allowtransition.assertallowtransitions', + ]; + + yield NotBlank::class => [ + new ConstraintViolation( + message: 'This value should not be blank.', + messageTemplate: 'This value should not be blank.', + parameters: ['{{ value }}' => '""'], + root: new CampCollaboration(), + propertyPath: 'name', + invalidValue: '', + plural: null, + code: 'c1051bb4-d103-4f74-8988-acbcafc7fdc3', + constraint: new NotBlank() + ), + 'symfony.component.validator.constraints.notblank', + ]; + + yield NotBlank::class.' without parameters' => [ + new ConstraintViolation( + message: 'This value should not be blank.', + messageTemplate: 'This value should not be blank.', + parameters: [], + root: new CampCollaboration(), + propertyPath: 'name', + invalidValue: '', + plural: null, + code: 'c1051bb4-d103-4f74-8988-acbcafc7fdc3', + constraint: new NotBlank() + ), + 'symfony.component.validator.constraints.notblank', ]; } } diff --git a/api/tests/Serializer/Normalizer/RelatedCollectionLinkNormalizerTest.php b/api/tests/Serializer/Normalizer/RelatedCollectionLinkNormalizerTest.php index d7f8ff12df..97deaa03bb 100644 --- a/api/tests/Serializer/Normalizer/RelatedCollectionLinkNormalizerTest.php +++ b/api/tests/Serializer/Normalizer/RelatedCollectionLinkNormalizerTest.php @@ -38,7 +38,6 @@ class RelatedCollectionLinkNormalizerTest extends TestCase { private RelatedCollectionLinkNormalizer $normalizer; private MockObject|NormalizerInterface $decoratedMock; - private MockObject|ServiceLocator $filterLocatorMock; private MockObject|NameConverterInterface $nameConverterMock; private MockObject|UriTemplate $uriTemplate; private MockObject|UriTemplateFactory $uriTemplateFactory; @@ -52,8 +51,8 @@ class RelatedCollectionLinkNormalizerTest extends TestCase { private null|DateFilter|SearchFilterInterface $filterInstance; protected function setUp(): void { - $this->filterLocatorMock = $this->createMock(ServiceLocator::class); - $this->filterLocatorMock->method('get')->willReturnCallback(function ($name) { + $filterLocatorMock = $this->createMock(ServiceLocator::class); + $filterLocatorMock->method('get')->willReturnCallback(function (string $name): mixed { return $this->filterInstance; }); @@ -73,7 +72,7 @@ protected function setUp(): void { $this->normalizer = new RelatedCollectionLinkNormalizer( $this->decoratedMock, - $this->filterLocatorMock, + $filterLocatorMock, $this->nameConverterMock, $this->uriTemplate, $this->uriTemplateFactory, @@ -115,7 +114,7 @@ public function testDelegatesNormalizeToDecorated() { $result = $this->normalizer->normalize($resource, null, ['resource_class' => ParentEntity::class]); // then - $this->assertEquals($delegatedResult, $result); + $this->assertSame($delegatedResult, $result); } public function testHandlesDecoratedNormalizerReturningAnIRIString() { @@ -131,7 +130,7 @@ public function testHandlesDecoratedNormalizerReturningAnIRIString() { $result = $this->normalizer->normalize($resource, null, ['resource_class' => ParentEntity::class]); // then - $this->assertEquals($delegatedResult, $result); + $this->assertSame($delegatedResult, $result); } public function testFallsBackToObjectClassWhenResourceClassIsMissingInContext() { @@ -152,7 +151,7 @@ public function testFallsBackToObjectClassWhenResourceClassIsMissingInContext() $result = $this->normalizer->normalize($resource, null, []); // then - $this->assertEquals($delegatedResult, $result); + $this->assertSame($delegatedResult, $result); } public function testNormalizeReplacesLinkArrayWithSingleFilteredCollectionLink() { @@ -210,7 +209,7 @@ public function testNormalizeReplacesLinkArrayWithSingleFilteredCollectionLinkBa $result = $this->normalizer->normalize($resource, null, ['resource_class' => ParentEntity::class]); // then - $this->assertEquals([ + $this->assertSame([ 'hello' => 'world', '_links' => [ 'relatedEntities' => ['href' => '/relatedEntities?test_param=value'], @@ -250,7 +249,7 @@ public function testNormalizeReplacesSerializedNameLinkArray() { $result = $this->normalizer->normalize($resource, null, ['resource_class' => ParentEntity::class]); // then - $this->assertEquals([ + $this->assertSame([ 'hello' => 'world', '_links' => [ 'childrenWithSerializedName' => ['href' => '/children?parent=%2Fparents%2F123'], @@ -531,10 +530,6 @@ protected function mockGeneratedRoute($generated = '/children?parent=%2Fparents% } class ParentEntity { - private string $id = '123'; - - private string $hello = 'world'; - #[ORM\OneToMany(targetEntity: Child::class, mappedBy: 'parent')] private Collection $children; diff --git a/api/tests/Serializer/Normalizer/UriTemplateNormalizerTest.php b/api/tests/Serializer/Normalizer/UriTemplateNormalizerTest.php index b65177a8e2..a56114b449 100644 --- a/api/tests/Serializer/Normalizer/UriTemplateNormalizerTest.php +++ b/api/tests/Serializer/Normalizer/UriTemplateNormalizerTest.php @@ -21,15 +21,14 @@ class UriTemplateNormalizerTest extends TestCase { private UriTemplateNormalizer $uriTemplateNormalizer; private MockObject|NormalizerInterface $decorated; private MockObject|UriTemplateFactory $uriTemplateFactory; - private EnglishInflector $englishInflector; private array $loginAndOauthLinks; protected function setUp(): void { $this->decorated = $this->createMock(NormalizerInterface::class); $this->uriTemplateFactory = $this->createMock(UriTemplateFactory::class); - $this->englishInflector = new EnglishInflector(); + $englishInflector = new EnglishInflector(); $urlGenerator = $this->createMock(UrlGeneratorInterface::class); - $urlGenerator->method('generate')->willReturnCallback(function (string $arg) { + $urlGenerator->method('generate')->willReturnCallback(function (string $arg): string { switch ($arg) { case 'authentication_token': return '/authentication_token'; @@ -59,7 +58,7 @@ protected function setUp(): void { $this->uriTemplateNormalizer = new UriTemplateNormalizer( $this->decorated, - $this->englishInflector, + $englishInflector, $this->uriTemplateFactory, $urlGenerator, ); diff --git a/api/tests/Service/ClaimInvitationServiceTest.php b/api/tests/Service/ClaimInvitationServiceTest.php index 75488d53d0..4e236e1d53 100644 --- a/api/tests/Service/ClaimInvitationServiceTest.php +++ b/api/tests/Service/ClaimInvitationServiceTest.php @@ -76,7 +76,7 @@ public function testClaimsInvitation() { // then $this->assertEquals($invitation->user, $this->user); $this->assertNull($invitation->inviteEmail); - $this->assertEquals($invitation->inviteKeyHash, 'asdfasdfasdf'); + $this->assertSame('asdfasdfasdf', $invitation->inviteKeyHash); $this->assertEquals($invitation->camp, $camp); } @@ -119,8 +119,8 @@ public function testIgnoresInvitationWhenUserAlreadyPartOfCamp() { // then $this->assertNull($invitation->user); - $this->assertEquals($invitation->inviteEmail, 'new@example.com'); - $this->assertEquals($invitation->inviteKeyHash, 'asdfasdfasdf'); + $this->assertSame('new@example.com', $invitation->inviteEmail); + $this->assertSame('asdfasdfasdf', $invitation->inviteKeyHash); $this->assertEquals($invitation->camp, $camp); } @@ -163,8 +163,8 @@ public function testIgnoresInvitationWhenUserWasPreviouslyPartOfCamp() { // then $this->assertNull($invitation->user); - $this->assertEquals($invitation->inviteEmail, 'new@example.com'); - $this->assertEquals($invitation->inviteKeyHash, 'asdfasdfasdf'); + $this->assertSame('new@example.com', $invitation->inviteEmail); + $this->assertSame('asdfasdfasdf', $invitation->inviteKeyHash); $this->assertEquals($invitation->camp, $camp); } @@ -220,7 +220,7 @@ public function testHandlesUniqueConstraintViolationWhenUserAlreadyPartOfCamp() // then $this->assertEquals($invitation2->user, $this->user); $this->assertNull($invitation2->inviteEmail); - $this->assertEquals($invitation2->inviteKeyHash, 'asdfasdfasdf'); + $this->assertSame('asdfasdfasdf', $invitation2->inviteKeyHash); $this->assertEquals($invitation2->camp, $camp); } } diff --git a/api/tests/State/ActivityCreateProcessorTest.php b/api/tests/State/ActivityCreateProcessorTest.php index 2584debb64..cdb83c7344 100644 --- a/api/tests/State/ActivityCreateProcessorTest.php +++ b/api/tests/State/ActivityCreateProcessorTest.php @@ -12,7 +12,6 @@ use App\State\ActivityCreateProcessor; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityRepository; -use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** @@ -21,11 +20,10 @@ class ActivityCreateProcessorTest extends TestCase { private ActivityCreateProcessor $processor; private Activity $activity; - private EntityManagerInterface|MockObject $em; protected function setUp(): void { $decoratedProcessor = $this->createMock(ProcessorInterface::class); - $this->em = $this->createMock(EntityManagerInterface::class); + $em = $this->createMock(EntityManagerInterface::class); $this->activity = new Activity(); $this->activity->category = new Category(); @@ -43,10 +41,10 @@ protected function setUp(): void { // EntityManager $repository = $this->createMock(EntityRepository::class); - $this->em->method('getRepository')->willReturn($repository); + $em->method('getRepository')->willReturn($repository); $repository->method('findOneBy')->willReturn($contentType); - $this->processor = new ActivityCreateProcessor($decoratedProcessor, $this->em); + $this->processor = new ActivityCreateProcessor($decoratedProcessor, $em); } public function testSetsCampFromCategory() { @@ -78,7 +76,7 @@ public function testPostFailsForMissingCategoryRootContentNode() { $this->expectException(\UnexpectedValueException::class); // when - /** @var Activity $data */ - $data = $this->processor->onBefore($this->activity, new Post()); + // @var Activity $data + $this->processor->onBefore($this->activity, new Post()); } } diff --git a/api/tests/State/CampCollaborationCreateProcessorTest.php b/api/tests/State/CampCollaborationCreateProcessorTest.php index 3bc8ff899f..f860144d8c 100644 --- a/api/tests/State/CampCollaborationCreateProcessorTest.php +++ b/api/tests/State/CampCollaborationCreateProcessorTest.php @@ -20,7 +20,6 @@ use PHPUnit\Framework\TestCase; use Symfony\Bundle\SecurityBundle\Security; use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactory; -use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactoryInterface; /** * @internal @@ -41,7 +40,6 @@ class CampCollaborationCreateProcessorTest extends TestCase { private EntityManagerInterface|MockObject $em; private MockObject|Security $security; - private MockObject|PasswordHasherFactoryInterface $pwHashFactory; private MailService|MockObject $mailService; private CampCollaborationCreateProcessor $processor; @@ -68,7 +66,7 @@ protected function setUp(): void { $decoratedProcessor = $this->createMock(ProcessorInterface::class); $this->security = $this->createMock(Security::class); $this->security->expects(self::any())->method('getUser')->willReturn($this->user); - $this->pwHashFactory = $this->createMock(PasswordHasherFactory::class); + $pwHashFactory = $this->createMock(PasswordHasherFactory::class); $this->profileRepository = $this->createMock(ProfileRepository::class); $this->em = $this->createMock(EntityManagerInterface::class); $this->mailService = $this->createMock(MailService::class); @@ -77,7 +75,7 @@ protected function setUp(): void { $this->processor = new CampCollaborationCreateProcessor( $decoratedProcessor, $this->security, - $this->pwHashFactory, + $pwHashFactory, $this->profileRepository, $this->em, $this->mailService, diff --git a/api/tests/State/CampCollaborationResendInvitationProcessorTest.php b/api/tests/State/CampCollaborationResendInvitationProcessorTest.php index ff2f1103b8..a3c6399317 100644 --- a/api/tests/State/CampCollaborationResendInvitationProcessorTest.php +++ b/api/tests/State/CampCollaborationResendInvitationProcessorTest.php @@ -15,7 +15,6 @@ use PHPUnit\Framework\TestCase; use Symfony\Bundle\SecurityBundle\Security; use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactory; -use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactoryInterface; /** * @internal @@ -29,11 +28,6 @@ class CampCollaborationResendInvitationProcessorTest extends TestCase { private CampCollaboration $campCollaboration; private User $user; - private Profile $profile; - private Camp $camp; - - private MockObject|Security $security; - private MockObject|PasswordHasherFactoryInterface $pwHashFactory; private MailService|MockObject $mailService; private CampCollaborationResendInvitationProcessor $processor; @@ -42,31 +36,31 @@ class CampCollaborationResendInvitationProcessorTest extends TestCase { * @throws \ReflectionException */ protected function setUp(): void { - $this->camp = new Camp(); - $this->camp->title = 'title'; + $camp = new Camp(); + $camp->title = 'title'; $this->campCollaboration = new CampCollaboration(); $this->campCollaboration->user = self::INITIAL_USER; $this->campCollaboration->inviteEmail = self::INITIAL_INVITE_EMAIL; $this->campCollaboration->inviteKey = self::INITIAL_INVITE_KEY; - $this->campCollaboration->camp = $this->camp; + $this->campCollaboration->camp = $camp; - $this->profile = new Profile(); - $this->profile->email = 'e@mail.com'; + $profile = new Profile(); + $profile->email = 'e@mail.com'; $this->user = new User(); - $this->profile->user = $this->user; - $this->user->profile = $this->profile; + $profile->user = $this->user; + $this->user->profile = $profile; $decoratedProcessor = $this->createMock(ProcessorInterface::class); - $this->security = $this->createMock(Security::class); - $this->security->expects(self::any())->method('getUser')->willReturn($this->user); - $this->pwHashFactory = $this->createMock(PasswordHasherFactory::class); + $security = $this->createMock(Security::class); + $security->expects(self::any())->method('getUser')->willReturn($this->user); + $pwHashFactory = $this->createMock(PasswordHasherFactory::class); $this->mailService = $this->createMock(MailService::class); $this->processor = new CampCollaborationResendInvitationProcessor( $decoratedProcessor, - $this->security, - $this->pwHashFactory, + $security, + $pwHashFactory, $this->mailService, ); } diff --git a/api/tests/State/CategoryCreateProcessorTest.php b/api/tests/State/CategoryCreateProcessorTest.php index 694c9d405f..c937de5816 100644 --- a/api/tests/State/CategoryCreateProcessorTest.php +++ b/api/tests/State/CategoryCreateProcessorTest.php @@ -34,7 +34,7 @@ protected function setUp(): void { public function testCreatesNewContentNodeBeforeCreate() { // given $repositoryMock = $this->createMock(EntityRepository::class); - $repositoryMock->method('findOneBy')->willReturnCallback(function ($criteria) { + $repositoryMock->method('findOneBy')->willReturnCallback(function (array $criteria): ?object { $result = new ContentType(); $result->name = $criteria['name']; diff --git a/api/tests/State/ContentNodes/MultiSelectCreateProcessorTest.php b/api/tests/State/ContentNodes/MultiSelectCreateProcessorTest.php index 7fda36d3ac..56279dce5f 100644 --- a/api/tests/State/ContentNodes/MultiSelectCreateProcessorTest.php +++ b/api/tests/State/ContentNodes/MultiSelectCreateProcessorTest.php @@ -59,10 +59,10 @@ public function testCopyMultiSelectOptionsFromContentTypeOnCreate() { $options = $data->data['options']; $this->assertArrayHasKey('key1', $options); - $this->assertEquals($options['key1']['checked'], false); + $this->assertEquals(false, $options['key1']['checked']); $this->assertArrayHasKey('key2', $options); - $this->assertEquals($options['key2']['checked'], false); + $this->assertEquals(false, $options['key2']['checked']); } public function testDoesNotSetRootFromParentOnUpdate() { diff --git a/api/tests/State/ContentNodes/SingleTextPersistProcessorTest.php b/api/tests/State/ContentNodes/SingleTextPersistProcessorTest.php index 29dec5e7d4..cf061217c5 100644 --- a/api/tests/State/ContentNodes/SingleTextPersistProcessorTest.php +++ b/api/tests/State/ContentNodes/SingleTextPersistProcessorTest.php @@ -31,7 +31,7 @@ protected function setUp(): void { $decoratedProcessor = $this->createMock(ProcessorInterface::class); $cleanHTMLFilter = $this->createMock(CleanHTMLFilter::class); $cleanHTMLFilter->method('applyTo')->willReturnCallback( - function ($object, $property) { + function (array $object, string $property): array { $object[$property] = '***sanitizedHTML***'; return $object; diff --git a/api/tests/State/ContentNodes/StoryboardPersistProcessorTest.php b/api/tests/State/ContentNodes/StoryboardPersistProcessorTest.php index 07c362afec..c9aa7a8e1d 100644 --- a/api/tests/State/ContentNodes/StoryboardPersistProcessorTest.php +++ b/api/tests/State/ContentNodes/StoryboardPersistProcessorTest.php @@ -10,7 +10,6 @@ use App\InputFilter\CleanHTMLFilter; use App\InputFilter\CleanTextFilter; use App\State\ContentNode\StoryboardPersistProcessor; -use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** @@ -18,34 +17,28 @@ */ class StoryboardPersistProcessorTest extends TestCase { private StoryboardPersistProcessor $processor; - private CleanHTMLFilter|MockObject $cleanHTMLFilter; - private CleanTextFilter|MockObject $cleanTextFilter; private ColumnLayout $root; private Storyboard $contentNode; protected function setUp(): void { $decoratedProcessor = $this->createMock(ProcessorInterface::class); - $this->cleanHTMLFilter = $this->createMock(CleanHTMLFilter::class); - $this->cleanHTMLFilter->method('applyTo')->will( - $this->returnCallback( - function ($object, $property) { - $object[$property] = '***sanitizedHTML***'; + $cleanHTMLFilter = $this->createMock(CleanHTMLFilter::class); + $cleanHTMLFilter->method('applyTo')->willReturnCallback( + function (array $object, string $property): array { + $object[$property] = '***sanitizedHTML***'; - return $object; - } - ) + return $object; + } ); - $this->cleanTextFilter = $this->createMock(CleanTextFilter::class); - $this->cleanTextFilter->method('applyTo')->will( - $this->returnCallback( - function ($object, $property) { - $object[$property] = '***sanitizedText***'; + $cleanTextFilter = $this->createMock(CleanTextFilter::class); + $cleanTextFilter->method('applyTo')->willReturnCallback( + function (array $object, string $property): array { + $object[$property] = '***sanitizedText***'; - return $object; - } - ) + return $object; + } ); $this->contentNode = new Storyboard(); @@ -68,7 +61,7 @@ function ($object, $property) { $this->contentNode->parent = new ColumnLayout(); $this->contentNode->parent->root = $this->root; - $this->processor = new StoryboardPersistProcessor($decoratedProcessor, $this->cleanHTMLFilter, $this->cleanTextFilter); + $this->processor = new StoryboardPersistProcessor($decoratedProcessor, $cleanHTMLFilter, $cleanTextFilter); } public function testSetsRootFromParentOnCreate() { diff --git a/api/tests/State/InvitationRejectProcessorTest.php b/api/tests/State/InvitationRejectProcessorTest.php index 75456bb547..dd3f4d79bc 100644 --- a/api/tests/State/InvitationRejectProcessorTest.php +++ b/api/tests/State/InvitationRejectProcessorTest.php @@ -5,7 +5,6 @@ use ApiPlatform\Metadata\Patch; use App\DTO\Invitation; use App\Entity\CampCollaboration; -use App\Entity\User; use App\Repository\CampCollaborationRepository; use App\State\InvitationRejectProcessor; use Doctrine\ORM\EntityManagerInterface; @@ -24,7 +23,6 @@ class InvitationRejectProcessorTest extends TestCase { private Invitation $invitation; private CampCollaboration $campCollaboration; - private User $user; private CampCollaborationRepository|MockObject $collaborationRepository; private MockObject|PasswordHasherFactoryInterface $pwHasherFactory; @@ -38,7 +36,6 @@ class InvitationRejectProcessorTest extends TestCase { protected function setUp(): void { $this->invitation = new Invitation(self::INVITEKEY, '', '', '', false); $this->campCollaboration = new CampCollaboration(); - $this->user = new User(); $this->collaborationRepository = $this->createMock(CampCollaborationRepository::class); $this->pwHasherFactory = $this->createMock(PasswordHasherFactory::class); diff --git a/api/tests/State/PeriodPersistProcessorTest.php b/api/tests/State/PeriodPersistProcessorTest.php index d996cf1425..08e557253d 100644 --- a/api/tests/State/PeriodPersistProcessorTest.php +++ b/api/tests/State/PeriodPersistProcessorTest.php @@ -75,7 +75,7 @@ public function testAddDayAtStartMoveData() { $this->processor->onBefore($patchData, new Patch(), [], ['previous_data' => $this->period]); // then - $this->assertEquals(1440 + 600, $this->scheduleEntry->startOffset); + $this->assertSame(1440 + 600, $this->scheduleEntry->startOffset); $this->assertEquals(1, $this->dayResponsible->day->dayOffset); $days = $this->period->getDaysSorted(); @@ -96,7 +96,7 @@ public function testAddDayAtStartNoMoveData() { $this->processor->onBefore($patchData, new Patch(), [], ['previous_data' => $this->period]); // then - $this->assertEquals(1440 + 1440 + 600, $this->scheduleEntry->startOffset); + $this->assertSame(1440 + 1440 + 600, $this->scheduleEntry->startOffset); $this->assertEquals(2, $this->dayResponsible->day->dayOffset); $days = $this->period->getDaysSorted(); @@ -117,7 +117,7 @@ public function testRemoveDayAtStartMoveData() { $this->processor->onBefore($patchData, new Patch(), [], ['previous_data' => $this->period]); // then - $this->assertEquals(1440 + 600, $this->scheduleEntry->startOffset); + $this->assertSame(1440 + 600, $this->scheduleEntry->startOffset); $this->assertEquals(1, $this->dayResponsible->day->dayOffset); $days = $this->period->getDaysSorted(); @@ -136,7 +136,7 @@ public function testRemoveDayAtStartNoMoveData() { $this->processor->onBefore($patchData, new Patch(), [], ['previous_data' => $this->period]); // then - $this->assertEquals(600, $this->scheduleEntry->startOffset); + $this->assertSame(600, $this->scheduleEntry->startOffset); $this->assertEquals(0, $this->dayResponsible->day->dayOffset); $days = $this->period->getDaysSorted(); diff --git a/api/tests/State/ProfileUpdateProcessorTest.php b/api/tests/State/ProfileUpdateProcessorTest.php index 31a7710d54..a19d6c8cbc 100644 --- a/api/tests/State/ProfileUpdateProcessorTest.php +++ b/api/tests/State/ProfileUpdateProcessorTest.php @@ -21,7 +21,6 @@ */ class ProfileUpdateProcessorTest extends TestCase { private ProfileUpdateProcessor $processor; - private MockObject|PasswordHasherFactoryInterface $pwHasherFactory; private MockObject|PasswordHasherInterface $pwHasher; private MailService|MockObject $mailService; private Profile $profile; @@ -33,19 +32,19 @@ protected function setUp(): void { $this->profile = new Profile(); $this->profile->user = new User(); - $this->pwHasherFactory = $this->createMock(PasswordHasherFactoryInterface::class); + $pwHasherFactory = $this->createMock(PasswordHasherFactoryInterface::class); $this->pwHasher = $this->createMock(PasswordHasherInterface::class); $this->mailService = $this->createMock(MailService::class); $decoratedProcessor = $this->createMock(ProcessorInterface::class); - $this->pwHasherFactory->expects(self::any()) + $pwHasherFactory->expects(self::any()) ->method('getPasswordHasher') ->willReturn($this->pwHasher) ; $this->processor = new ProfileUpdateProcessor( $decoratedProcessor, - $this->pwHasherFactory, + $pwHasherFactory, $this->mailService, $this->createMock(Security::class), $this->createMock(UserRepository::class), @@ -65,7 +64,7 @@ public function testSetNewEmail() { $this->processor->onBefore($this->profile, new Patch()); // then - $this->assertEquals('new@mail.com', $this->profile->untrustedEmail); + $this->assertSame('new@mail.com', $this->profile->untrustedEmail); $this->assertNotNull($this->profile->untrustedEmailKey); $this->assertNotNull($this->profile->untrustedEmailKeyHash); } @@ -97,7 +96,7 @@ public function testChangeEmail() { $this->processor->onBefore($this->profile, new Patch()); // then - $this->assertEquals('new@mail.com', $this->profile->email); + $this->assertSame('new@mail.com', $this->profile->email); $this->assertNull($this->profile->untrustedEmail); $this->assertNull($this->profile->untrustedEmailKey); $this->assertNull($this->profile->untrustedEmailKeyHash); diff --git a/api/tests/State/ResetPasswordCreateProcessorTest.php b/api/tests/State/ResetPasswordCreateProcessorTest.php index bfc2e65d83..547d25329a 100644 --- a/api/tests/State/ResetPasswordCreateProcessorTest.php +++ b/api/tests/State/ResetPasswordCreateProcessorTest.php @@ -14,7 +14,6 @@ use PHPUnit\Framework\TestCase; use ReCaptcha\Response; use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactory; -use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactoryInterface; use Symfony\Component\PasswordHasher\PasswordHasherInterface; /** @@ -25,12 +24,8 @@ class ResetPasswordCreateProcessorTest extends TestCase { public const EMAILBASE64 = 'YUBiLmNvbQ=='; private ResetPassword $resetPassword; - - private MockObject|ReCaptchaWrapper $recaptcha; private MockObject|Response $recaptchaResponse; - private EntityManagerInterface|MockObject $entityManager; private MockObject|UserRepository $userRepository; - private MockObject|PasswordHasherFactoryInterface $pwHasherFactory; private MockObject|PasswordHasherInterface $pwHasher; private MailService|MockObject $mailService; private ResetPasswordCreateProcessor $processor; @@ -42,28 +37,28 @@ protected function setUp(): void { $this->resetPassword = new ResetPassword(); $this->recaptchaResponse = $this->createMock(Response::class); - $this->recaptcha = $this->createMock(ReCaptchaWrapper::class); - $this->entityManager = $this->createMock(EntityManagerInterface::class); + $recaptcha = $this->createMock(ReCaptchaWrapper::class); + $entityManager = $this->createMock(EntityManagerInterface::class); $this->userRepository = $this->createMock(UserRepository::class); - $this->pwHasherFactory = $this->createMock(PasswordHasherFactory::class); + $pwHasherFactory = $this->createMock(PasswordHasherFactory::class); $this->pwHasher = $this->createMock(PasswordHasherInterface::class); $this->mailService = $this->createMock(MailService::class); - $this->recaptcha->expects(self::any()) + $recaptcha->expects(self::any()) ->method('verify') ->willReturn($this->recaptchaResponse) ; - $this->pwHasherFactory->expects(self::any()) + $pwHasherFactory->expects(self::any()) ->method('getPasswordHasher') ->willReturn($this->pwHasher) ; $this->processor = new ResetPasswordCreateProcessor( - $this->recaptcha, - $this->entityManager, + $recaptcha, + $entityManager, $this->userRepository, - $this->pwHasherFactory, + $pwHasherFactory, $this->mailService ); } diff --git a/api/tests/State/ResetPasswordUpdateProcessorTest.php b/api/tests/State/ResetPasswordUpdateProcessorTest.php index d171061f3b..8c6ccc1e5b 100644 --- a/api/tests/State/ResetPasswordUpdateProcessorTest.php +++ b/api/tests/State/ResetPasswordUpdateProcessorTest.php @@ -14,7 +14,6 @@ use PHPUnit\Framework\TestCase; use ReCaptcha\Response; use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactory; -use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactoryInterface; use Symfony\Component\PasswordHasher\PasswordHasherInterface; /** @@ -25,12 +24,8 @@ class ResetPasswordUpdateProcessorTest extends TestCase { public const EMAILBASE64 = 'YUBiLmNvbQ=='; private ResetPassword $resetPassword; - - private MockObject|ReCaptchaWrapper $recaptcha; private MockObject|Response $recaptchaResponse; - private EntityManagerInterface|MockObject $entityManager; private MockObject|UserRepository $userRepository; - private MockObject|PasswordHasherFactoryInterface $pwHasherFactory; private MockObject|PasswordHasherInterface $pwHasher; private ResetPasswordUpdateProcessor $processor; @@ -42,27 +37,27 @@ protected function setUp(): void { $this->resetPassword = new ResetPassword(); $this->recaptchaResponse = $this->createMock(Response::class); - $this->recaptcha = $this->createMock(ReCaptchaWrapper::class); - $this->entityManager = $this->createMock(EntityManagerInterface::class); + $recaptcha = $this->createMock(ReCaptchaWrapper::class); + $entityManager = $this->createMock(EntityManagerInterface::class); $this->userRepository = $this->createMock(UserRepository::class); - $this->pwHasherFactory = $this->createMock(PasswordHasherFactory::class); + $pwHasherFactory = $this->createMock(PasswordHasherFactory::class); $this->pwHasher = $this->createMock(PasswordHasherInterface::class); - $this->recaptcha->expects(self::any()) + $recaptcha->expects(self::any()) ->method('verify') ->willReturn($this->recaptchaResponse) ; - $this->pwHasherFactory->expects(self::any()) + $pwHasherFactory->expects(self::any()) ->method('getPasswordHasher') ->willReturn($this->pwHasher) ; $this->processor = new ResetPasswordUpdateProcessor( - $this->recaptcha, - $this->entityManager, + $recaptcha, + $entityManager, $this->userRepository, - $this->pwHasherFactory + $pwHasherFactory ); } diff --git a/api/tests/State/UserCreateProcessorTest.php b/api/tests/State/UserCreateProcessorTest.php index 7902619b80..f0be086ec1 100644 --- a/api/tests/State/UserCreateProcessorTest.php +++ b/api/tests/State/UserCreateProcessorTest.php @@ -19,7 +19,6 @@ */ class UserCreateProcessorTest extends TestCase { private UserCreateProcessor $processor; - private MockObject|ReCaptchaWrapper $recaptcha; private MockObject|Response $recaptchaResponse; private MockObject|UserPasswordHasherInterface $userPasswordHasher; private MailService|MockObject $mailService; @@ -32,8 +31,8 @@ protected function setUp(): void { $this->user = new User(); $this->recaptchaResponse = $this->createMock(Response::class); - $this->recaptcha = $this->createMock(ReCaptchaWrapper::class); - $this->recaptcha->expects(self::any()) + $recaptcha = $this->createMock(ReCaptchaWrapper::class); + $recaptcha->expects(self::any()) ->method('verify') ->willReturn($this->recaptchaResponse) ; @@ -43,7 +42,7 @@ protected function setUp(): void { $decoratedProcessor = $this->createMock(ProcessorInterface::class); $this->processor = new UserCreateProcessor( $decoratedProcessor, - $this->recaptcha, + $recaptcha, $this->userPasswordHasher, $this->mailService ); diff --git a/api/tests/Types/Doctrine/BaseDateTypeTestCase.php b/api/tests/Types/Doctrine/BaseDateTypeTestCase.php index 0e2152468d..fdb66973ae 100644 --- a/api/tests/Types/Doctrine/BaseDateTypeTestCase.php +++ b/api/tests/Types/Doctrine/BaseDateTypeTestCase.php @@ -50,21 +50,30 @@ public function testConvertDateTimeToPHPValue(): void { self::assertSame($date, $this->type->convertToPHPValue($date, $this->platform)); } - /** @return mixed[][] */ - public static function invalidPHPValuesProvider(): iterable { - return [ - [0], - [''], - ['foo'], - ['10:11:12'], - ['2015-01-31'], - ['2015-01-31 10:11:12'], - [new \stdClass()], - [27], - [-1], - [1.2], - [[]], - [['an array']], - ]; + /** @return \Iterator<(int | string), array> */ + public static function invalidPHPValuesProvider(): \Iterator { + yield [0]; + + yield ['']; + + yield ['foo']; + + yield ['10:11:12']; + + yield ['2015-01-31']; + + yield ['2015-01-31 10:11:12']; + + yield [new \stdClass()]; + + yield [27]; + + yield [-1]; + + yield [1.2]; + + yield [[]]; + + yield [['an array']]; } } diff --git a/api/tests/Types/Doctrine/UTCDateTimeTypeTest.php b/api/tests/Types/Doctrine/UTCDateTimeTypeTest.php index 1acc11fd9c..bc49f3032a 100644 --- a/api/tests/Types/Doctrine/UTCDateTimeTypeTest.php +++ b/api/tests/Types/Doctrine/UTCDateTimeTypeTest.php @@ -32,7 +32,7 @@ public function testDateTimeConvertsToPHPValue(): void { // Birthday of jwage and also birthday of Doctrine. Send him a present ;) $date = $this->type->convertToPHPValue('1985-09-01 00:00:00', $this->platform); self::assertInstanceOf(\DateTime::class, $date); - self::assertEquals('1985-09-01 00:00:00', $date->format('Y-m-d H:i:s')); + self::assertSame('1985-09-01 00:00:00', $date->format('Y-m-d H:i:s')); } public function testInvalidDateTimeFormatConversion(): void { @@ -61,6 +61,6 @@ public function testInterpretsDatabaseValueAsUTC(): void { $date = $this->type->convertToPHPValue('1985-09-01 00:00:00', $this->platform); self::assertInstanceOf(\DateTime::class, $date); - self::assertEquals('1985-09-01T00:00:00+00:00', $date->format('c')); + self::assertSame('1985-09-01T00:00:00+00:00', $date->format('c')); } } diff --git a/api/tests/Util/ArrayDeepSortTest.php b/api/tests/Util/ArrayDeepSortTest.php index e0de8fc78d..d94e60938a 100644 --- a/api/tests/Util/ArrayDeepSortTest.php +++ b/api/tests/Util/ArrayDeepSortTest.php @@ -26,12 +26,12 @@ public function testSortsJson1AlwaysTheSame(string $jsonFileName) { $this->assertMatchesJsonSnapshot($sortedArray); } - public static function getJsonFiles() { - return [ - 'json_to_sort_1.json' => ['json_to_sort_1.json'], - 'json_to_sort_2.json' => ['json_to_sort_2.json'], - 'json_to_sort_3.json' => ['json_to_sort_3.json'], - ]; + public static function getJsonFiles(): \Iterator { + yield 'json_to_sort_1.json' => ['json_to_sort_1.json']; + + yield 'json_to_sort_2.json' => ['json_to_sort_2.json']; + + yield 'json_to_sort_3.json' => ['json_to_sort_3.json']; } public function testSortsAssocArrayByKey() { diff --git a/api/tests/Util/CamelPascalNamingStrategyTest.php b/api/tests/Util/CamelPascalNamingStrategyTest.php index f5b58c8ab1..5711c6cbd0 100644 --- a/api/tests/Util/CamelPascalNamingStrategyTest.php +++ b/api/tests/Util/CamelPascalNamingStrategyTest.php @@ -23,16 +23,17 @@ public function testClassToTableName(string $className, string $output) { $result = $strategy->classToTableName($className); // then - $this->assertEquals($output, $result); + $this->assertSame($output, $result); } - public static function getTableNameExamples() { - return [ - ['', ''], - [User::class, 'user'], - [CampCollaboration::class, 'camp_collaboration'], - ['CampCollaboration', 'camp_collaboration'], - ]; + public static function getTableNameExamples(): \Iterator { + yield ['', '']; + + yield [User::class, 'user']; + + yield [CampCollaboration::class, 'camp_collaboration']; + + yield ['CampCollaboration', 'camp_collaboration']; } #[DataProvider('getPropertyExamples')] @@ -44,15 +45,15 @@ public function testPropertyToColumnName(string $input, string $output) { $result = $strategy->propertyToColumnName($input, ''); // then - $this->assertEquals($output, $result); + $this->assertSame($output, $result); } - public static function getPropertyExamples() { - return [ - ['', ''], - ['camp', 'camp'], - ['campCollaboration', 'campCollaboration'], - ]; + public static function getPropertyExamples(): \Iterator { + yield ['', '']; + + yield ['camp', 'camp']; + + yield ['campCollaboration', 'campCollaboration']; } #[DataProvider('getEmbeddedFieldExamples')] @@ -64,14 +65,13 @@ public function testEmbeddedFieldToColumnName(string $propertyName, string $embe $result = $strategy->embeddedFieldToColumnName($propertyName, $embeddedColumnName); // then - $this->assertEquals($output, $result); + $this->assertSame($output, $result); } - public static function getEmbeddedFieldExamples() { - return [ - ['', '', ''], - ['address', 'street', 'addressStreet'], - ]; + public static function getEmbeddedFieldExamples(): \Iterator { + yield ['', '', '']; + + yield ['address', 'street', 'addressStreet']; } #[DataProvider('getJoinColumnExamples')] @@ -83,15 +83,15 @@ public function testJoinColumnName(string $propertyName, string $output) { $result = $strategy->joinColumnName($propertyName); // then - $this->assertEquals($output, $result); + $this->assertSame($output, $result); } - public static function getJoinColumnExamples() { - return [ - ['', 'Id'], - ['camp', 'campId'], - ['campCollaboration', 'campCollaborationId'], - ]; + public static function getJoinColumnExamples(): \Iterator { + yield ['', 'Id']; + + yield ['camp', 'campId']; + + yield ['campCollaboration', 'campCollaborationId']; } #[DataProvider('getJoinKeyColumnExamples')] @@ -103,17 +103,20 @@ public function testJoinKeyColumnName(string $entityName, ?string $referencedCol $result = $strategy->joinKeyColumnName($entityName, $referencedColumnName); // then - $this->assertEquals($output, $result); + $this->assertSame($output, $result); } - public static function getJoinKeyColumnExamples() { - return [ - ['', null, 'Id'], - ['', 'email', 'Email'], - [Camp::class, null, 'campId'], - [CampCollaboration::class, null, 'campCollaborationId'], - [User::class, 'name', 'userName'], - [DayResponsible::class, 'name', 'dayResponsibleName'], - ]; + public static function getJoinKeyColumnExamples(): \Iterator { + yield ['', null, 'Id']; + + yield ['', 'email', 'Email']; + + yield [Camp::class, null, 'campId']; + + yield [CampCollaboration::class, null, 'campCollaborationId']; + + yield [User::class, 'name', 'userName']; + + yield [DayResponsible::class, 'name', 'dayResponsibleName']; } } diff --git a/api/tests/Util/QueryBuilderHelperTest.php b/api/tests/Util/QueryBuilderHelperTest.php index f4acb9936d..b6f2b8dd9a 100644 --- a/api/tests/Util/QueryBuilderHelperTest.php +++ b/api/tests/Util/QueryBuilderHelperTest.php @@ -24,7 +24,7 @@ protected function setUp(): void { $this->queryNameGeneratorInterfaceMock ->method('generateJoinAlias') - ->willReturnCallback(fn ($field) => $field.'_alias') + ->willReturnCallback(fn (string $field): string => $field.'_alias') ; } diff --git a/api/tests/Validator/AssertBelongsToSameCampValidatorTest.php b/api/tests/Validator/AssertBelongsToSameCampValidatorTest.php index e31de57004..3f5a492104 100644 --- a/api/tests/Validator/AssertBelongsToSameCampValidatorTest.php +++ b/api/tests/Validator/AssertBelongsToSameCampValidatorTest.php @@ -177,7 +177,7 @@ class ParentTestClass extends BaseEntity implements BelongsToCampInterface { #[AssertBelongsToSameCamp] public ?ChildTestClass $child; - public function __construct(public Camp $camp, ?ChildTestClass $child = null) {} + public function __construct(public Camp $camp) {} public function getCamp(): ?Camp { return $this->camp; diff --git a/api/tests/Validator/ContentNode/AssertNoRootChangeValidatorTest.php b/api/tests/Validator/ContentNode/AssertNoRootChangeValidatorTest.php index 51e8219282..e3085de645 100644 --- a/api/tests/Validator/ContentNode/AssertNoRootChangeValidatorTest.php +++ b/api/tests/Validator/ContentNode/AssertNoRootChangeValidatorTest.php @@ -147,7 +147,7 @@ class ParentTestClass extends BaseEntity implements BelongsToCampInterface { #[AssertNoRootChange] public ChildTestClass $child; - public function __construct(public Camp $camp, ChildTestClass $child) {} + public function __construct(public Camp $camp) {} public function getCamp(): ?Camp { return $this->camp;