diff --git a/app/V1Module/presenters/AssignmentSolutionReviewsPresenter.php b/app/V1Module/presenters/AssignmentSolutionReviewsPresenter.php index 53c26b039..9e55c6389 100644 --- a/app/V1Module/presenters/AssignmentSolutionReviewsPresenter.php +++ b/app/V1Module/presenters/AssignmentSolutionReviewsPresenter.php @@ -7,6 +7,7 @@ use App\Helpers\MetaFormats\Validators\VBool; use App\Helpers\MetaFormats\Validators\VInt; use App\Helpers\MetaFormats\Validators\VString; +use App\Helpers\MetaFormats\Validators\VUuid; use App\Exceptions\BadRequestException; use App\Exceptions\InternalServerException; use App\Exceptions\ForbiddenRequestException; @@ -90,7 +91,7 @@ public function checkDefault(string $id) * @GET * @throws InternalServerException */ - #[Path("id", new VString(), "identifier of the solution", required: true)] + #[Path("id", new VUuid(), "identifier of the solution", required: true)] public function actionDefault(string $id) { $solution = $this->assignmentSolutions->findOrThrow($id); @@ -114,7 +115,7 @@ public function checkUpdate(string $id) * @throws InternalServerException */ #[Post("close", new VBool(), "If true, the review is closed. If false, the review is (re)opened.")] - #[Path("id", new VString(), "identifier of the solution", required: true)] + #[Path("id", new VUuid(), "identifier of the solution", required: true)] public function actionUpdate(string $id) { $solution = $this->assignmentSolutions->findOrThrow($id); @@ -183,7 +184,7 @@ public function checkRemove(string $id) * @DELETE * @throws InternalServerException */ - #[Path("id", new VString(), "identifier of the solution", required: true)] + #[Path("id", new VUuid(), "identifier of the solution", required: true)] public function actionRemove(string $id) { $solution = $this->assignmentSolutions->findOrThrow($id); @@ -272,7 +273,7 @@ private function verifyCodeLocation(AssignmentSolution $solution, string $file, "If true, no email notification will be sent (only applies when the review has been closed)", required: false, )] - #[Path("id", new VString(), "identifier of the solution", required: true)] + #[Path("id", new VUuid(), "identifier of the solution", required: true)] public function actionNewComment(string $id) { $solution = $this->assignmentSolutions->findOrThrow($id); @@ -299,7 +300,7 @@ public function actionNewComment(string $id) $this->reviewComments->persist($comment); if ($solution->getReviewedAt() !== null) { - // review is already closed, this needs special treatement + // review is already closed, this needs special treatment if ($issue) { $solution->setIssuesCount($solution->getIssuesCount() + 1); $this->assignmentSolutions->persist($solution); @@ -345,7 +346,7 @@ public function checkEditComment(string $id, string $commentId) "If true, no email notification will be sent (only applies when the review has been closed)", required: false, )] - #[Path("id", new VString(), "identifier of the solution", required: true)] + #[Path("id", new VUuid(), "identifier of the solution", required: true)] #[Path("commentId", new VString(), "identifier of the review comment", required: true)] public function actionEditComment(string $id, string $commentId) { @@ -372,7 +373,7 @@ public function actionEditComment(string $id, string $commentId) $this->reviewComments->persist($comment); if ($solution->getReviewedAt() !== null) { - // review is already closed, this needs special treatement + // review is already closed, this needs special treatment if ($issueChanged) { $solution->setIssuesCount($solution->getIssuesCount() + ($issue ? 1 : -1)); $this->assignmentSolutions->persist($solution); @@ -405,7 +406,7 @@ public function checkDeleteComment(string $id, string $commentId) * Remove one comment from a review. * @DELETE */ - #[Path("id", new VString(), "identifier of the solution", required: true)] + #[Path("id", new VUuid(), "identifier of the solution", required: true)] #[Path("commentId", new VString(), "identifier of the review comment", required: true)] public function actionDeleteComment(string $id, string $commentId) { @@ -415,7 +416,7 @@ public function actionDeleteComment(string $id, string $commentId) $solution = $this->assignmentSolutions->findOrThrow($id); if ($solution->getReviewedAt() !== null) { - // review is already closed, this needs special treatement + // review is already closed, this needs special treatment if ($isIssue) { $solution->setIssuesCount($solution->getIssuesCount() - 1); $this->assignmentSolutions->persist($solution); @@ -441,7 +442,7 @@ public function checkPending(string $id) * Along with that it returns all assignment entities of the corresponding solutions. * @GET */ - #[Path("id", new VString(), "of the user whose pending reviews are listed", required: true)] + #[Path("id", new VUuid(), "of the user whose pending reviews are listed", required: true)] public function actionPending(string $id) { $user = $this->users->findOrThrow($id); diff --git a/app/V1Module/presenters/AssignmentSolutionsPresenter.php b/app/V1Module/presenters/AssignmentSolutionsPresenter.php index 8b7bf5231..c2007fc93 100644 --- a/app/V1Module/presenters/AssignmentSolutionsPresenter.php +++ b/app/V1Module/presenters/AssignmentSolutionsPresenter.php @@ -3,17 +3,11 @@ namespace App\V1Module\Presenters; use App\Helpers\MetaFormats\Attributes\Post; -use App\Helpers\MetaFormats\Attributes\Query; use App\Helpers\MetaFormats\Attributes\Path; -use App\Helpers\MetaFormats\Type; -use App\Helpers\MetaFormats\Validators\VArray; use App\Helpers\MetaFormats\Validators\VBool; -use App\Helpers\MetaFormats\Validators\VDouble; -use App\Helpers\MetaFormats\Validators\VEmail; use App\Helpers\MetaFormats\Validators\VInt; use App\Helpers\MetaFormats\Validators\VMixed; use App\Helpers\MetaFormats\Validators\VString; -use App\Helpers\MetaFormats\Validators\VTimestamp; use App\Helpers\MetaFormats\Validators\VUuid; use App\Exceptions\BadRequestException; use App\Exceptions\InternalServerException; @@ -157,7 +151,7 @@ public function checkSolution(string $id) * @GET * @throws InternalServerException */ - #[Path("id", new VString(), "Identifier of the solution", required: true)] + #[Path("id", new VUuid(), "Identifier of the solution", required: true)] public function actionSolution(string $id) { $solution = $this->assignmentSolutions->findOrThrow($id); @@ -189,7 +183,7 @@ public function checkUpdateSolution(string $id) * @throws InternalServerException */ #[Post("note", new VString(0, 1024), "A note by the author of the solution")] - #[Path("id", new VString(), "Identifier of the solution", required: true)] + #[Path("id", new VUuid(), "Identifier of the solution", required: true)] public function actionUpdateSolution(string $id) { $req = $this->getRequest(); @@ -213,7 +207,7 @@ public function checkDeleteSolution(string $id) * @DELETE * @throws ForbiddenRequestException */ - #[Path("id", new VString(), "identifier of assignment solution", required: true)] + #[Path("id", new VUuid(), "identifier of assignment solution", required: true)] public function actionDeleteSolution(string $id) { $solution = $this->assignmentSolutions->findOrThrow($id); @@ -250,7 +244,7 @@ public function checkSubmissions(string $id) * Get list of all submissions of a solution * @GET */ - #[Path("id", new VString(), "Identifier of the solution", required: true)] + #[Path("id", new VUuid(), "Identifier of the solution", required: true)] public function actionSubmissions(string $id) { $solution = $this->assignmentSolutions->findOrThrow($id); @@ -352,28 +346,28 @@ public function checkSetBonusPoints(string $id) required: false, nullable: true, )] - #[Path("id", new VString(), "Identifier of the solution", required: true)] + #[Path("id", new VUuid(), "Identifier of the solution", required: true)] public function actionSetBonusPoints(string $id) { $solution = $this->assignmentSolutions->findOrThrow($id); $assignment = $solution->getAssignment(); $author = $solution->getSolution()->getAuthor(); $oldBonusPoints = $solution->getBonusPoints(); - $oldOverridenPoints = $solution->getOverriddenPoints(); + $oldOverriddenPoints = $solution->getOverriddenPoints(); $newBonusPoints = $this->getRequest()->getPost("bonusPoints"); $overriddenPoints = $this->getRequest()->getPost("overriddenPoints"); // remember, who was the best in case the new points will change that $oldBest = null; - if ($assignment && ($oldBonusPoints !== $newBonusPoints || $oldOverridenPoints !== $overriddenPoints)) { + if ($assignment && ($oldBonusPoints !== $newBonusPoints || $oldOverriddenPoints !== $overriddenPoints)) { $oldBest = $this->assignmentSolutions->findBestSolution($assignment, $author); } $solution->setBonusPoints($newBonusPoints); - // TODO: validations 'null|numericint' for overridenPoints cannot be used, because null is converted to empty - // TODO: string which immediately breaks stated validation... in the future, this behaviour has to change + // TODO: validations 'null|numericint' for overriddenPoints cannot be used, because null is converted to empty + // TODO: string which immediately breaks stated validation... in the future, this behavior has to change // TODO: lucky third TODO if (Validators::isNumericInt($overriddenPoints)) { $solution->setOverriddenPoints($overriddenPoints); @@ -382,7 +376,7 @@ public function actionSetBonusPoints(string $id) $solution->setOverriddenPoints(null); } else { throw new InvalidApiArgumentException( - 'overridenPoints', + 'overriddenPoints', "The value '$overriddenPoints' is not null|numericint" ); } @@ -391,7 +385,7 @@ public function actionSetBonusPoints(string $id) $this->assignmentSolutions->flush(); $changedSolutions = []; // list of changed solutions reported back in payload - if ($oldBonusPoints !== $newBonusPoints || $oldOverridenPoints !== $overriddenPoints) { + if ($oldBonusPoints !== $newBonusPoints || $oldOverriddenPoints !== $overriddenPoints) { $this->pointsChangedEmailsSender->solutionPointsUpdated($solution); $changedSolutions[] = $this->assignmentSolutionViewFactory->getSolutionData($solution); if ($assignment) { @@ -445,7 +439,7 @@ public function checkSetFlag(string $id, string $flag) * @throws \Exception */ #[Post("value", new VBool(), "True or false which should be set to given flag name", required: true)] - #[Path("id", new VString(), "identifier of the solution", required: true)] + #[Path("id", new VUuid(), "identifier of the solution", required: true)] #[Path("flag", new VString(), "name of the flag which should to be changed", required: true)] public function actionSetFlag(string $id, string $flag) { @@ -484,7 +478,7 @@ public function actionSetFlag(string $id, string $flag) ); // handle unique flags - $resetedSolution = null; // remeber original holder of a unique flag (for an email notification) + $previousHolder = null; // remember original holder of a unique flag (for an email notification) /* @phpstan-ignore-next-line */ if ($unique && $value) { // flag has to be set to false for all other solutions of a user @@ -494,7 +488,7 @@ public function actionSetFlag(string $id, string $flag) ); foreach ($assignmentSolutions as $assignmentSolution) { if ($assignmentSolution->getFlag($flag)) { - $resetedSolution = $assignmentSolution; + $previousHolder = $assignmentSolution; } $assignmentSolution->setFlag($flag, false); } @@ -513,11 +507,11 @@ public function actionSetFlag(string $id, string $flag) $this->getCurrentUser(), $solution, $value, - $resetedSolution + $previousHolder ); } - // assemble response (all entites and stats that may have changed) + // assemble response (all entities and stats that may have changed) $assignmentId = $solution->getAssignment()->getId(); $groupOfSolution = $solution->getAssignment()->getGroup(); if ($groupOfSolution === null) { @@ -525,9 +519,9 @@ public function actionSetFlag(string $id, string $flag) } $resSolutions = [$id => $this->assignmentSolutionViewFactory->getSolutionData($solution)]; - if ($resetedSolution) { - $resSolutions[$resetedSolution->getId()] = - $this->assignmentSolutionViewFactory->getSolutionData($resetedSolution); + if ($previousHolder) { + $resSolutions[$previousHolder->getId()] = + $this->assignmentSolutionViewFactory->getSolutionData($previousHolder); } $bestSolution = $this->assignmentSolutions->findBestSolution( @@ -567,7 +561,7 @@ public function checkDownloadSolutionArchive(string $id) * @throws \Nette\Application\BadRequestException * @throws \Nette\Application\AbortException */ - #[Path("id", new VString(), "of assignment solution", required: true)] + #[Path("id", new VUuid(), "of assignment solution", required: true)] public function actionDownloadSolutionArchive(string $id) { $solution = $this->assignmentSolutions->findOrThrow($id); @@ -592,7 +586,7 @@ public function checkFiles(string $id) * @throws ForbiddenRequestException * @throws NotFoundException */ - #[Path("id", new VString(), "of assignment solution", required: true)] + #[Path("id", new VUuid(), "of assignment solution", required: true)] public function actionFiles(string $id) { $solution = $this->assignmentSolutions->findOrThrow($id)->getSolution(); @@ -672,7 +666,7 @@ public function checkReviewRequests(string $id) * Along with that it returns all assignment entities of the corresponding solutions. * @GET */ - #[Path("id", new VString(), "of the user whose solutions with requested reviews are listed", required: true)] + #[Path("id", new VUuid(), "of the user whose solutions with requested reviews are listed", required: true)] public function actionReviewRequests(string $id) { $user = $this->users->findOrThrow($id); diff --git a/app/V1Module/presenters/AssignmentSolversPresenter.php b/app/V1Module/presenters/AssignmentSolversPresenter.php index 48385c815..3c642f55b 100644 --- a/app/V1Module/presenters/AssignmentSolversPresenter.php +++ b/app/V1Module/presenters/AssignmentSolversPresenter.php @@ -2,21 +2,9 @@ namespace App\V1Module\Presenters; -use App\Helpers\MetaFormats\Attributes\Post; use App\Helpers\MetaFormats\Attributes\Query; -use App\Helpers\MetaFormats\Attributes\Path; -use App\Helpers\MetaFormats\Type; -use App\Helpers\MetaFormats\Validators\VArray; -use App\Helpers\MetaFormats\Validators\VBool; -use App\Helpers\MetaFormats\Validators\VDouble; -use App\Helpers\MetaFormats\Validators\VEmail; -use App\Helpers\MetaFormats\Validators\VInt; -use App\Helpers\MetaFormats\Validators\VMixed; -use App\Helpers\MetaFormats\Validators\VString; -use App\Helpers\MetaFormats\Validators\VTimestamp; use App\Helpers\MetaFormats\Validators\VUuid; use App\Exceptions\BadRequestException; -use App\Model\Entity\AssignmentSolutionSubmission; use App\Model\Repository\Assignments; use App\Model\Repository\AssignmentSolvers; use App\Model\Repository\Users; diff --git a/app/V1Module/presenters/AssignmentsPresenter.php b/app/V1Module/presenters/AssignmentsPresenter.php index 81c0c8951..20aef9420 100644 --- a/app/V1Module/presenters/AssignmentsPresenter.php +++ b/app/V1Module/presenters/AssignmentsPresenter.php @@ -11,6 +11,7 @@ use App\Helpers\MetaFormats\Validators\VMixed; use App\Helpers\MetaFormats\Validators\VString; use App\Helpers\MetaFormats\Validators\VTimestamp; +use App\Helpers\MetaFormats\Validators\VUuid; use App\Exceptions\BadRequestException; use App\Exceptions\ForbiddenRequestException; use App\Exceptions\InvalidApiArgumentException; @@ -187,7 +188,7 @@ public function checkDetail(string $id) * Get details of an assignment * @GET */ - #[Path("id", new VString(), "Identifier of the assignment", required: true)] + #[Path("id", new VUuid(), "Identifier of the assignment", required: true)] public function actionDetail(string $id) { $this->sendSuccessResponse($this->assignmentViewFactory->getAssignment($this->assignments->findOrThrow($id))); @@ -283,10 +284,10 @@ public function checkUpdateDetail(string $id) #[Post( "isExam", new VBool(), - "This assignemnt is dedicated for an exam (should be solved in exam mode)", + "This assignment is dedicated for an exam (should be solved in exam mode)", required: false, )] - #[Path("id", new VString(), "Identifier of the updated assignment", required: true)] + #[Path("id", new VUuid(), "Identifier of the updated assignment", required: true)] public function actionUpdateDetail(string $id) { $assignment = $this->assignments->findOrThrow($id); @@ -352,7 +353,6 @@ public function actionUpdateDetail(string $id) $allowSecondDeadline = filter_var($req->getPost("allowSecondDeadline"), FILTER_VALIDATE_BOOLEAN); $secondDeadlineTimestamp = (int)$req->getPost("secondDeadline") ?: 0; $oldVisibleFrom = $assignment->getVisibleFrom(); - $oldVisibleFromTimestamp = $oldVisibleFrom ? $oldVisibleFrom->getTimestamp() : null; $visibleFromTimestamp = (int)$req->getPost("visibleFrom"); $visibleFrom = $visibleFromTimestamp ? DateTime::createFromFormat('U', $visibleFromTimestamp) : null; $maxPointsDeadlineInterpolation = filter_var( @@ -366,7 +366,7 @@ public function actionUpdateDetail(string $id) $sendNotification = $sendNotification !== null ? filter_var($sendNotification, FILTER_VALIDATE_BOOLEAN) : true; $sendNotification = $sendNotification && !$isExam; // exam assignments don't send notifications - // basic constrain checks and sanitizations + // basic constrain checks and sanitization if (!$allowSecondDeadline) { $secondDeadlineTimestamp = 0; } @@ -520,7 +520,7 @@ public function checkValidate(string $id) * @throws ForbiddenRequestException */ #[Post("version", new VInt(), "Version of the assignment.")] - #[Path("id", new VString(), "Identifier of the assignment", required: true)] + #[Path("id", new VUuid(), "Identifier of the assignment", required: true)] public function actionValidate($id) { $assignment = $this->assignments->findOrThrow($id); @@ -623,7 +623,7 @@ public function checkRemove(string $id) * Delete an assignment * @DELETE */ - #[Path("id", new VString(), "Identifier of the assignment to be removed", required: true)] + #[Path("id", new VUuid(), "Identifier of the assignment to be removed", required: true)] public function actionRemove(string $id) { $this->assignments->remove($this->assignments->findOrThrow($id)); @@ -644,7 +644,7 @@ public function checkSyncWithExercise(string $id) * @throws BadRequestException * @throws NotFoundException */ - #[Path("id", new VString(), "Identifier of the assignment that should be synchronized", required: true)] + #[Path("id", new VUuid(), "Identifier of the assignment that should be synchronized", required: true)] public function actionSyncWithExercise($id) { $assignment = $this->assignments->findOrThrow($id); @@ -679,7 +679,7 @@ public function checkSolutions(string $id) * @GET * @throws NotFoundException */ - #[Path("id", new VString(), "Identifier of the assignment", required: true)] + #[Path("id", new VUuid(), "Identifier of the assignment", required: true)] public function actionSolutions(string $id) { $assignment = $this->assignments->findOrThrow($id); @@ -712,7 +712,7 @@ public function checkUserSolutions(string $id, string $userId) * Get a list of solutions created by a user of an assignment * @GET */ - #[Path("id", new VString(), "Identifier of the assignment", required: true)] + #[Path("id", new VUuid(), "Identifier of the assignment", required: true)] #[Path("userId", new VString(), "Identifier of the user", required: true)] public function actionUserSolutions(string $id, string $userId) { @@ -756,7 +756,7 @@ public function checkBestSolution(string $id, string $userId) * @GET * @throws ForbiddenRequestException */ - #[Path("id", new VString(), "Identifier of the assignment", required: true)] + #[Path("id", new VUuid(), "Identifier of the assignment", required: true)] #[Path("userId", new VString(), "Identifier of the user", required: true)] public function actionBestSolution(string $id, string $userId) { @@ -786,7 +786,7 @@ public function checkBestSolutions(string $id) * @GET * @throws NotFoundException */ - #[Path("id", new VString(), "Identifier of the assignment", required: true)] + #[Path("id", new VUuid(), "Identifier of the assignment", required: true)] public function actionBestSolutions(string $id) { $assignment = $this->assignments->findOrThrow($id); @@ -832,7 +832,7 @@ public function checkDownloadBestSolutionsArchive(string $id) * @throws \Nette\Application\AbortException * @throws \Nette\Application\BadRequestException */ - #[Path("id", new VString(), "Identifier of the assignment", required: true)] + #[Path("id", new VUuid(), "Identifier of the assignment", required: true)] public function actionDownloadBestSolutionsArchive(string $id) { $assignment = $this->assignments->findOrThrow($id); diff --git a/app/V1Module/presenters/AsyncJobsPresenter.php b/app/V1Module/presenters/AsyncJobsPresenter.php index 5b4602ad9..189e8a8dc 100644 --- a/app/V1Module/presenters/AsyncJobsPresenter.php +++ b/app/V1Module/presenters/AsyncJobsPresenter.php @@ -5,22 +5,13 @@ use App\Helpers\MetaFormats\Attributes\Post; use App\Helpers\MetaFormats\Attributes\Query; use App\Helpers\MetaFormats\Attributes\Path; -use App\Helpers\MetaFormats\Type; -use App\Helpers\MetaFormats\Validators\VArray; use App\Helpers\MetaFormats\Validators\VBool; -use App\Helpers\MetaFormats\Validators\VDouble; -use App\Helpers\MetaFormats\Validators\VEmail; use App\Helpers\MetaFormats\Validators\VInt; -use App\Helpers\MetaFormats\Validators\VMixed; -use App\Helpers\MetaFormats\Validators\VString; -use App\Helpers\MetaFormats\Validators\VTimestamp; use App\Helpers\MetaFormats\Validators\VUuid; use App\Async\Dispatcher; use App\Async\Handler\PingAsyncJobHandler; use App\Model\Repository\Assignments; use App\Model\Repository\AsyncJobs; -use App\Model\Entity\Assignment; -use App\Model\Entity\AsyncJob; use App\Security\ACL\IAssignmentPermissions; use App\Security\ACL\IAsyncJobPermissions; use App\Exceptions\NotFoundException; @@ -80,7 +71,7 @@ public function checkDefault(string $id) * @GET * @throws NotFoundException */ - #[Path("id", new VString(), "job identifier", required: true)] + #[Path("id", new VUuid(), "job identifier", required: true)] public function actionDefault(string $id) { $asyncJob = $this->asyncJobs->findOrThrow($id); @@ -119,7 +110,7 @@ public function actionList(?int $ageThreshold, ?bool $includeScheduled) throw new BadRequestException("Age threshold must not be negative."); } - // criterium for termination (either pending or within threshold) + // criteria for termination (either pending or within threshold) $finishedAt = Criteria::expr()->eq('finishedAt', null); if ($ageThreshold) { $thresholdDate = new DateTime(); @@ -138,7 +129,7 @@ public function actionList(?int $ageThreshold, ?bool $includeScheduled) Criteria::expr()->eq('scheduledAt', null) ) ); - $criteria->orderBy([ 'createdAt' => 'ASC' ]); + $criteria->orderBy(['createdAt' => 'ASC']); $jobs = $this->asyncJobs->matching($criteria)->toArray(); $jobs = array_filter($jobs, function ($job) { @@ -161,7 +152,7 @@ public function checkAbort(string $id) * @POST * @throws NotFoundException */ - #[Path("id", new VString(), "job identifier", required: true)] + #[Path("id", new VUuid(), "job identifier", required: true)] public function actionAbort(string $id) { $this->asyncJobs->beginTransaction(); @@ -213,7 +204,7 @@ public function checkAssignmentJobs($id) * Get all pending async jobs related to a particular assignment. * @GET */ - #[Path("id", new VString(), required: true)] + #[Path("id", new VUuid(), required: true)] public function actionAssignmentJobs($id) { $asyncJobs = $this->asyncJobs->findAssignmentJobs($id); diff --git a/app/V1Module/presenters/BrokerPresenter.php b/app/V1Module/presenters/BrokerPresenter.php index a28f16087..ba2806662 100644 --- a/app/V1Module/presenters/BrokerPresenter.php +++ b/app/V1Module/presenters/BrokerPresenter.php @@ -3,18 +3,6 @@ namespace App\V1Module\Presenters; use App\Helpers\MetaFormats\Attributes\Post; -use App\Helpers\MetaFormats\Attributes\Query; -use App\Helpers\MetaFormats\Attributes\Path; -use App\Helpers\MetaFormats\Type; -use App\Helpers\MetaFormats\Validators\VArray; -use App\Helpers\MetaFormats\Validators\VBool; -use App\Helpers\MetaFormats\Validators\VDouble; -use App\Helpers\MetaFormats\Validators\VEmail; -use App\Helpers\MetaFormats\Validators\VInt; -use App\Helpers\MetaFormats\Validators\VMixed; -use App\Helpers\MetaFormats\Validators\VString; -use App\Helpers\MetaFormats\Validators\VTimestamp; -use App\Helpers\MetaFormats\Validators\VUuid; use App\Exceptions\ForbiddenRequestException; use App\Exceptions\InvalidStateException; use App\Helpers\BrokerProxy; @@ -26,7 +14,6 @@ */ class BrokerPresenter extends BasePresenter { - /** * @var IBrokerPermissions * @inject diff --git a/app/V1Module/presenters/BrokerReportsPresenter.php b/app/V1Module/presenters/BrokerReportsPresenter.php index 8978d9e33..c1a185c48 100644 --- a/app/V1Module/presenters/BrokerReportsPresenter.php +++ b/app/V1Module/presenters/BrokerReportsPresenter.php @@ -3,18 +3,9 @@ namespace App\V1Module\Presenters; use App\Helpers\MetaFormats\Attributes\Post; -use App\Helpers\MetaFormats\Attributes\Query; use App\Helpers\MetaFormats\Attributes\Path; -use App\Helpers\MetaFormats\Type; -use App\Helpers\MetaFormats\Validators\VArray; -use App\Helpers\MetaFormats\Validators\VBool; -use App\Helpers\MetaFormats\Validators\VDouble; -use App\Helpers\MetaFormats\Validators\VEmail; -use App\Helpers\MetaFormats\Validators\VInt; use App\Helpers\MetaFormats\Validators\VMixed; use App\Helpers\MetaFormats\Validators\VString; -use App\Helpers\MetaFormats\Validators\VTimestamp; -use App\Helpers\MetaFormats\Validators\VUuid; use App\Exceptions\HttpBasicAuthException; use App\Exceptions\InternalServerException; use App\Exceptions\InvalidStateException; @@ -131,7 +122,7 @@ private function reportFailure(JobId $job, string $message) if (!$submissionRepository) { return; } - + $failureReport = SubmissionFailure::create(SubmissionFailure::TYPE_EVALUATION_FAILURE, $message); $submission = $submissionRepository->findOrThrow($job->getId()); @@ -155,7 +146,8 @@ private function processJobCompletion(JobId $job) $submission = $submissionRepository->findOrThrow($job->getId()); if (!$this->evaluationLoadingHelper->loadEvaluation($submission)) { - $reportMessage = "Broker reports job {$job->getId()} (type: '{$job->getType()}') completion, but job results file is missing."; + $reportMessage = "Broker reports job {$job->getId()} (type: '{$job->getType()}')" + . " completion, but job results file is missing."; $this->reportFailure($job, $reportMessage); return; } @@ -173,7 +165,7 @@ private function processJobCompletion(JobId $job) private function processJobFailure(JobId $job) { $message = $this->getRequest()->getPost("message") ?: ""; - $reportMessage = "Broker reports job {$job->getId()} (type: '{$job->getType()}') processing failure: $message"; + $message = "Broker reports job {$job->getId()} (type: '{$job->getType()}') processing failure: $message"; $this->reportFailure($job, $message); } diff --git a/app/V1Module/presenters/CommentsPresenter.php b/app/V1Module/presenters/CommentsPresenter.php index 5f4396b24..6d1f5b6d5 100644 --- a/app/V1Module/presenters/CommentsPresenter.php +++ b/app/V1Module/presenters/CommentsPresenter.php @@ -3,17 +3,9 @@ namespace App\V1Module\Presenters; use App\Helpers\MetaFormats\Attributes\Post; -use App\Helpers\MetaFormats\Attributes\Query; use App\Helpers\MetaFormats\Attributes\Path; -use App\Helpers\MetaFormats\Type; -use App\Helpers\MetaFormats\Validators\VArray; use App\Helpers\MetaFormats\Validators\VBool; -use App\Helpers\MetaFormats\Validators\VDouble; -use App\Helpers\MetaFormats\Validators\VEmail; -use App\Helpers\MetaFormats\Validators\VInt; -use App\Helpers\MetaFormats\Validators\VMixed; use App\Helpers\MetaFormats\Validators\VString; -use App\Helpers\MetaFormats\Validators\VTimestamp; use App\Helpers\MetaFormats\Validators\VUuid; use App\Exceptions\ForbiddenRequestException; use App\Exceptions\NotFoundException; @@ -110,7 +102,7 @@ public function checkDefault($id) * @GET * @throws ForbiddenRequestException */ - #[Path("id", new VString(), "Identifier of the comment thread", required: true)] + #[Path("id", new VUuid(), "Identifier of the comment thread", required: true)] public function actionDefault($id) { $thread = $this->findThreadOrCreateIt($id); @@ -140,7 +132,7 @@ public function checkAddComment(string $id) */ #[Post("text", new VString(1, 65535), "Text of the comment")] #[Post("isPrivate", new VBool(), "True if the comment is private", required: false)] - #[Path("id", new VString(), "Identifier of the comment thread", required: true)] + #[Path("id", new VUuid(), "Identifier of the comment thread", required: true)] public function actionAddComment(string $id) { $thread = $this->findThreadOrCreateIt($id); diff --git a/app/V1Module/presenters/DefaultPresenter.php b/app/V1Module/presenters/DefaultPresenter.php index 2e4525cc7..8babc92f1 100644 --- a/app/V1Module/presenters/DefaultPresenter.php +++ b/app/V1Module/presenters/DefaultPresenter.php @@ -2,24 +2,10 @@ namespace App\V1Module\Presenters; -use App\Helpers\MetaFormats\Attributes\Post; -use App\Helpers\MetaFormats\Attributes\Query; -use App\Helpers\MetaFormats\Attributes\Path; -use App\Helpers\MetaFormats\Type; -use App\Helpers\MetaFormats\Validators\VArray; -use App\Helpers\MetaFormats\Validators\VBool; -use App\Helpers\MetaFormats\Validators\VDouble; -use App\Helpers\MetaFormats\Validators\VEmail; -use App\Helpers\MetaFormats\Validators\VInt; -use App\Helpers\MetaFormats\Validators\VMixed; -use App\Helpers\MetaFormats\Validators\VString; -use App\Helpers\MetaFormats\Validators\VTimestamp; -use App\Helpers\MetaFormats\Validators\VUuid; use App\Helpers\ApiConfig; class DefaultPresenter extends BasePresenter { - /** * @var ApiConfig * @inject diff --git a/app/V1Module/presenters/EmailVerificationPresenter.php b/app/V1Module/presenters/EmailVerificationPresenter.php index 2c8946d4a..032a56fe9 100644 --- a/app/V1Module/presenters/EmailVerificationPresenter.php +++ b/app/V1Module/presenters/EmailVerificationPresenter.php @@ -3,18 +3,6 @@ namespace App\V1Module\Presenters; use App\Helpers\MetaFormats\Attributes\Post; -use App\Helpers\MetaFormats\Attributes\Query; -use App\Helpers\MetaFormats\Attributes\Path; -use App\Helpers\MetaFormats\Type; -use App\Helpers\MetaFormats\Validators\VArray; -use App\Helpers\MetaFormats\Validators\VBool; -use App\Helpers\MetaFormats\Validators\VDouble; -use App\Helpers\MetaFormats\Validators\VEmail; -use App\Helpers\MetaFormats\Validators\VInt; -use App\Helpers\MetaFormats\Validators\VMixed; -use App\Helpers\MetaFormats\Validators\VString; -use App\Helpers\MetaFormats\Validators\VTimestamp; -use App\Helpers\MetaFormats\Validators\VUuid; use App\Exceptions\ForbiddenRequestException; use App\Helpers\EmailVerificationHelper; use App\Security\Identity; @@ -24,7 +12,6 @@ */ class EmailVerificationPresenter extends BasePresenter { - /** * @var EmailVerificationHelper * @inject diff --git a/app/V1Module/presenters/EmailsPresenter.php b/app/V1Module/presenters/EmailsPresenter.php index 2e683f5fb..78c93995f 100644 --- a/app/V1Module/presenters/EmailsPresenter.php +++ b/app/V1Module/presenters/EmailsPresenter.php @@ -3,18 +3,9 @@ namespace App\V1Module\Presenters; use App\Helpers\MetaFormats\Attributes\Post; -use App\Helpers\MetaFormats\Attributes\Query; use App\Helpers\MetaFormats\Attributes\Path; -use App\Helpers\MetaFormats\Type; -use App\Helpers\MetaFormats\Validators\VArray; use App\Helpers\MetaFormats\Validators\VBool; -use App\Helpers\MetaFormats\Validators\VDouble; -use App\Helpers\MetaFormats\Validators\VEmail; -use App\Helpers\MetaFormats\Validators\VInt; -use App\Helpers\MetaFormats\Validators\VMixed; use App\Helpers\MetaFormats\Validators\VString; -use App\Helpers\MetaFormats\Validators\VTimestamp; -use App\Helpers\MetaFormats\Validators\VUuid; use App\Exceptions\ForbiddenRequestException; use App\Exceptions\NotFoundException; use App\Helpers\EmailHelper; diff --git a/app/V1Module/presenters/ExerciseFilesPresenter.php b/app/V1Module/presenters/ExerciseFilesPresenter.php index 45f0619cc..85b7611fc 100644 --- a/app/V1Module/presenters/ExerciseFilesPresenter.php +++ b/app/V1Module/presenters/ExerciseFilesPresenter.php @@ -6,6 +6,7 @@ use App\Helpers\MetaFormats\Attributes\Path; use App\Helpers\MetaFormats\Validators\VMixed; use App\Helpers\MetaFormats\Validators\VString; +use App\Helpers\MetaFormats\Validators\VUuid; use App\Exceptions\ForbiddenRequestException; use App\Exceptions\InvalidApiArgumentException; use App\Exceptions\NotFoundException; @@ -94,7 +95,7 @@ public function checkUploadSupplementaryFiles(string $id) * @throws SubmissionFailedException */ #[Post("files", new VMixed(), "Identifiers of supplementary files", nullable: true)] - #[Path("id", new VString(), "identification of exercise", required: true)] + #[Path("id", new VUuid(), "identification of exercise", required: true)] public function actionUploadSupplementaryFiles(string $id) { $exercise = $this->exercises->findOrThrow($id); @@ -175,7 +176,7 @@ public function checkGetSupplementaryFiles(string $id) * Get list of all supplementary files for an exercise * @GET */ - #[Path("id", new VString(), "identification of exercise", required: true)] + #[Path("id", new VUuid(), "identification of exercise", required: true)] public function actionGetSupplementaryFiles(string $id) { $exercise = $this->exercises->findOrThrow($id); @@ -195,7 +196,7 @@ public function checkDeleteSupplementaryFile(string $id, string $fileId) * @DELETE * @throws ForbiddenRequestException */ - #[Path("id", new VString(), "identification of exercise", required: true)] + #[Path("id", new VUuid(), "identification of exercise", required: true)] #[Path("fileId", new VString(), "identification of file", required: true)] public function actionDeleteSupplementaryFile(string $id, string $fileId) { @@ -228,7 +229,7 @@ public function checkDownloadSupplementaryFilesArchive(string $id) * @throws \Nette\Application\BadRequestException * @throws \Nette\Application\AbortException */ - #[Path("id", new VString(), "of exercise", required: true)] + #[Path("id", new VUuid(), "of exercise", required: true)] public function actionDownloadSupplementaryFilesArchive(string $id) { $exercise = $this->exercises->findOrThrow($id); @@ -255,7 +256,7 @@ public function checkUploadAttachmentFiles(string $id) * @throws ForbiddenRequestException */ #[Post("files", new VMixed(), "Identifiers of attachment files", nullable: true)] - #[Path("id", new VString(), "identification of exercise", required: true)] + #[Path("id", new VUuid(), "identification of exercise", required: true)] public function actionUploadAttachmentFiles(string $id) { $exercise = $this->exercises->findOrThrow($id); @@ -310,7 +311,7 @@ public function checkGetAttachmentFiles(string $id) * @GET * @throws ForbiddenRequestException */ - #[Path("id", new VString(), "identification of exercise", required: true)] + #[Path("id", new VUuid(), "identification of exercise", required: true)] public function actionGetAttachmentFiles(string $id) { /** @var Exercise $exercise */ @@ -333,7 +334,7 @@ public function checkDeleteAttachmentFile(string $id, string $fileId) * @throws ForbiddenRequestException * @throws NotFoundException */ - #[Path("id", new VString(), "identification of exercise", required: true)] + #[Path("id", new VUuid(), "identification of exercise", required: true)] #[Path("fileId", new VString(), "identification of file", required: true)] public function actionDeleteAttachmentFile(string $id, string $fileId) { @@ -364,7 +365,7 @@ public function checkDownloadAttachmentFilesArchive(string $id) * @throws \Nette\Application\BadRequestException * @throws \Nette\Application\AbortException */ - #[Path("id", new VString(), "of exercise", required: true)] + #[Path("id", new VUuid(), "of exercise", required: true)] public function actionDownloadAttachmentFilesArchive(string $id) { $exercise = $this->exercises->findOrThrow($id); diff --git a/app/V1Module/presenters/ExercisesConfigPresenter.php b/app/V1Module/presenters/ExercisesConfigPresenter.php index dfdb5a0fb..536ef851e 100644 --- a/app/V1Module/presenters/ExercisesConfigPresenter.php +++ b/app/V1Module/presenters/ExercisesConfigPresenter.php @@ -7,6 +7,7 @@ use App\Helpers\MetaFormats\Validators\VArray; use App\Helpers\MetaFormats\Validators\VMixed; use App\Helpers\MetaFormats\Validators\VString; +use App\Helpers\MetaFormats\Validators\VUuid; use App\Exceptions\ApiException; use App\Exceptions\ExerciseCompilationException; use App\Exceptions\ExerciseConfigException; @@ -166,7 +167,7 @@ private function getEnvironmentConfigs(Exercise $exercise) * @GET * @throws NotFoundException */ - #[Path("id", new VString(), "Identifier of the exercise", required: true)] + #[Path("id", new VUuid(), "Identifier of the exercise", required: true)] public function actionGetEnvironmentConfigs(string $id) { /** @var Exercise $exercise */ @@ -194,7 +195,7 @@ public function checkUpdateEnvironmentConfigs(string $id) * @throws NotFoundException */ #[Post("environmentConfigs", new VArray(), "Environment configurations for the exercise")] - #[Path("id", new VString(), "identification of exercise", required: true)] + #[Path("id", new VUuid(), "identification of exercise", required: true)] public function actionUpdateEnvironmentConfigs(string $id) { /** @var Exercise $exercise */ @@ -279,7 +280,7 @@ public function checkGetConfiguration(string $id) * @throws NotFoundException * @throws ExerciseConfigException */ - #[Path("id", new VString(), "Identifier of the exercise", required: true)] + #[Path("id", new VUuid(), "Identifier of the exercise", required: true)] public function actionGetConfiguration(string $id) { /** @var Exercise $exercise */ @@ -316,7 +317,7 @@ public function checkSetConfiguration(string $id) * @throws ParseException */ #[Post("config", new VArray(), "A list of basic high level exercise configuration")] - #[Path("id", new VString(), "Identifier of the exercise", required: true)] + #[Path("id", new VUuid(), "Identifier of the exercise", required: true)] public function actionSetConfiguration(string $id) { $exercise = $this->exercises->findOrThrow($id); @@ -370,7 +371,7 @@ public function checkGetVariablesForExerciseConfig(string $id) */ #[Post("runtimeEnvironmentId", new VString(1), "Environment identifier", required: false)] #[Post("pipelinesIds", new VArray(), "Identifiers of selected pipelines for one test")] - #[Path("id", new VString(), "Identifier of the exercise", required: true)] + #[Path("id", new VUuid(), "Identifier of the exercise", required: true)] public function actionGetVariablesForExerciseConfig(string $id) { // get request data @@ -414,7 +415,7 @@ public function checkGetHardwareGroupLimits(string $id, string $runtimeEnvironme * @throws NotFoundException * @throws ExerciseConfigException */ - #[Path("id", new VString(), "Identifier of the exercise", required: true)] + #[Path("id", new VUuid(), "Identifier of the exercise", required: true)] #[Path("runtimeEnvironmentId", new VString(), required: true)] #[Path("hwGroupId", new VString(), required: true)] public function actionGetHardwareGroupLimits(string $id, string $runtimeEnvironmentId, string $hwGroupId) @@ -463,7 +464,7 @@ public function checkSetHardwareGroupLimits(string $id, string $runtimeEnvironme * @throws ExerciseCompilationException */ #[Post("limits", new VArray(), "A list of resource limits for the given environment and hardware group")] - #[Path("id", new VString(), "Identifier of the exercise", required: true)] + #[Path("id", new VUuid(), "Identifier of the exercise", required: true)] #[Path("runtimeEnvironmentId", new VString(), required: true)] #[Path("hwGroupId", new VString(), required: true)] public function actionSetHardwareGroupLimits(string $id, string $runtimeEnvironmentId, string $hwGroupId) @@ -527,7 +528,7 @@ public function checkRemoveHardwareGroupLimits(string $id, string $runtimeEnviro * @DELETE * @throws NotFoundException */ - #[Path("id", new VString(), "Identifier of the exercise", required: true)] + #[Path("id", new VUuid(), "Identifier of the exercise", required: true)] #[Path("runtimeEnvironmentId", new VString(), required: true)] #[Path("hwGroupId", new VString(), required: true)] public function actionRemoveHardwareGroupLimits(string $id, string $runtimeEnvironmentId, string $hwGroupId) @@ -571,7 +572,7 @@ public function checkGetLimits(string $id) * @throws ForbiddenRequestException * @throws NotFoundException */ - #[Path("id", new VString(), "Identifier of the exercise", required: true)] + #[Path("id", new VUuid(), "Identifier of the exercise", required: true)] public function actionGetLimits(string $id) { /** @var Exercise $exercise */ @@ -613,7 +614,7 @@ public function checkSetLimits(string $id) * @throws ExerciseConfigException */ #[Post("limits", new VArray(), "A list of resource limits in the same format as getLimits endpoint yields.")] - #[Path("id", new VString(), "Identifier of the exercise", required: true)] + #[Path("id", new VUuid(), "Identifier of the exercise", required: true)] public function actionSetLimits(string $id) { /** @var Exercise $exercise */ @@ -672,7 +673,7 @@ public function checkGetScoreConfig(string $id) * Get score configuration for exercise based on given identification. * @GET */ - #[Path("id", new VString(), "Identifier of the exercise", required: true)] + #[Path("id", new VUuid(), "Identifier of the exercise", required: true)] public function actionGetScoreConfig(string $id) { $exercise = $this->exercises->findOrThrow($id); @@ -701,7 +702,7 @@ public function checkSetScoreConfig(string $id) "A configuration of the score calculator (the format depends on the calculator type)", nullable: true, )] - #[Path("id", new VString(), "Identifier of the exercise", required: true)] + #[Path("id", new VUuid(), "Identifier of the exercise", required: true)] public function actionSetScoreConfig(string $id) { $exercise = $this->exercises->findOrThrow($id); @@ -740,7 +741,7 @@ public function checkGetTests(string $id) * Get tests for exercise based on given identification. * @GET */ - #[Path("id", new VString(), "Identifier of the exercise", required: true)] + #[Path("id", new VUuid(), "Identifier of the exercise", required: true)] public function actionGetTests(string $id) { $exercise = $this->exercises->findOrThrow($id); @@ -765,7 +766,7 @@ public function checkSetTests(string $id) * @throws ExerciseConfigException */ #[Post("tests", new VArray(), "An array of tests which will belong to exercise")] - #[Path("id", new VString(), "Identifier of the exercise", required: true)] + #[Path("id", new VUuid(), "Identifier of the exercise", required: true)] public function actionSetTests(string $id) { $exercise = $this->exercises->findOrThrow($id); diff --git a/app/V1Module/presenters/ExercisesPresenter.php b/app/V1Module/presenters/ExercisesPresenter.php index b0b0b569c..585629279 100644 --- a/app/V1Module/presenters/ExercisesPresenter.php +++ b/app/V1Module/presenters/ExercisesPresenter.php @@ -211,10 +211,10 @@ public function checkDefault() )] public function actionDefault( int $offset = 0, - int $limit = null, - string $orderBy = null, - array $filters = null, - string $locale = null + ?int $limit = null, + ?string $orderBy = null, + ?array $filters = null, + ?string $locale = null ) { $pagination = $this->getPagination( $offset, @@ -266,7 +266,7 @@ public function checkAuthors() required: false, nullable: true, )] - public function actionAuthors(string $instanceId = null, string $groupId = null) + public function actionAuthors(?string $instanceId = null, ?string $groupId = null) { $authors = $this->exercises->getAuthors($instanceId, $groupId, $this->groups); $this->sendSuccessResponse($this->userViewFactory->getUsers($authors)); @@ -309,7 +309,7 @@ public function checkDetail(string $id) * Get details of an exercise * @GET */ - #[Path("id", new VString(), "identification of exercise", required: true)] + #[Path("id", new VUuid(), "identification of exercise", required: true)] public function actionDetail(string $id) { /** @var Exercise $exercise */ @@ -364,7 +364,7 @@ public function checkUpdateDetail(string $id) nullable: true, )] #[Post("mergeJudgeLogs", new VBool(), "If true, judge stderr will be merged into stdout (default for assignments)")] - #[Path("id", new VString(), "identification of exercise", required: true)] + #[Path("id", new VUuid(), "identification of exercise", required: true)] public function actionUpdateDetail(string $id) { $req = $this->getRequest(); @@ -484,7 +484,7 @@ public function checkValidate($id) * @POST */ #[Post("version", new VInt(), "Version of the exercise.")] - #[Path("id", new VString(), "Identifier of the exercise", required: true)] + #[Path("id", new VUuid(), "Identifier of the exercise", required: true)] public function actionValidate($id) { $exercise = $this->exercises->findOrThrow($id); @@ -513,7 +513,7 @@ public function checkAssignments(string $id) * @GET * @throws NotFoundException */ - #[Path("id", new VString(), "Identifier of the exercise", required: true)] + #[Path("id", new VUuid(), "Identifier of the exercise", required: true)] #[Query("archived", new VBool(), "Include also archived groups in the result", required: false)] public function actionAssignments(string $id, bool $archived = false) { @@ -590,7 +590,7 @@ public function checkHardwareGroups(string $id) * @throws NotFoundException */ #[Post("hwGroups", new VArray(), "List of hardware groups identifications to which exercise belongs to")] - #[Path("id", new VString(), "identifier of exercise", required: true)] + #[Path("id", new VUuid(), "identifier of exercise", required: true)] public function actionHardwareGroups(string $id) { $exercise = $this->exercises->findOrThrow($id); @@ -634,7 +634,7 @@ public function checkRemove(string $id) * Delete an exercise * @DELETE */ - #[Path("id", new VString(), required: true)] + #[Path("id", new VUuid(), "Identifier of the exercise", required: true)] public function actionRemove(string $id) { /** @var Exercise $exercise */ @@ -653,7 +653,7 @@ public function actionRemove(string $id) * @throws ParseException */ #[Post("groupId", new VMixed(), "Identifier of the group to which exercise will be forked", nullable: true)] - #[Path("id", new VString(), "Identifier of the exercise", required: true)] + #[Path("id", new VUuid(), "Identifier of the exercise", required: true)] public function actionForkFrom(string $id) { $user = $this->getCurrentUser(); @@ -694,7 +694,7 @@ public function checkAttachGroup(string $id, string $groupId) * @POST * @throws InvalidApiArgumentException */ - #[Path("id", new VString(), "Identifier of the exercise", required: true)] + #[Path("id", new VUuid(), "Identifier of the exercise", required: true)] #[Path("groupId", new VString(), "Identifier of the group to which exercise should be attached", required: true)] public function actionAttachGroup(string $id, string $groupId) { @@ -728,7 +728,7 @@ public function checkDetachGroup(string $id, string $groupId) * @DELETE * @throws InvalidApiArgumentException */ - #[Path("id", new VString(), "Identifier of the exercise", required: true)] + #[Path("id", new VUuid(), "Identifier of the exercise", required: true)] #[Path("groupId", new VString(), "Identifier of the group which should be detached from exercise", required: true)] public function actionDetachGroup(string $id, string $groupId) { @@ -803,7 +803,7 @@ public function checkTagsUpdateGlobal(string $tag) required: false, )] #[Path("tag", new VString(), "Tag to be updated", required: true)] - public function actionTagsUpdateGlobal(string $tag, string $renameTo = null, bool $force = false) + public function actionTagsUpdateGlobal(string $tag, ?string $renameTo = null, bool $force = false) { // Check whether at least one modification action is present (so far, we have only renameTo) if ($renameTo === null) { @@ -871,7 +871,7 @@ public function checkAddTag(string $id) * @throws ForbiddenRequestException * @throws InvalidApiArgumentException */ - #[Path("id", new VString(), required: true)] + #[Path("id", new VUuid(), "Identifier of the exercise", required: true)] #[Path("name", new VString(1, 32), "Name of the newly added tag to given exercise", required: true)] public function actionAddTag(string $id, string $name) { @@ -904,7 +904,7 @@ public function checkRemoveTag(string $id) * @DELETE * @throws NotFoundException */ - #[Path("id", new VString(), required: true)] + #[Path("id", new VUuid(), "Identifier of the exercise", required: true)] #[Path("name", new VString(), required: true)] public function actionRemoveTag(string $id, string $name) { @@ -933,7 +933,7 @@ public function checkSetArchived(string $id) * @throws NotFoundException */ #[Post("archived", new VBool(), "Whether the exercise should be marked or unmarked", required: true)] - #[Path("id", new VString(), "identifier of the exercise", required: true)] + #[Path("id", new VUuid(), "Identifier of the exercise", required: true)] public function actionSetArchived(string $id) { $exercise = $this->exercises->findOrThrow($id); @@ -963,7 +963,7 @@ public function checkSetAuthor(string $id) * @throws ForbiddenRequestException */ #[Post("author", new VUuid(), "Id of the new author of the exercise.", required: true)] - #[Path("id", new VString(), "identifier of the exercise", required: true)] + #[Path("id", new VUuid(), "identifier of the exercise", required: true)] public function actionSetAuthor(string $id) { $exercise = $this->exercises->findOrThrow($id); @@ -1000,7 +1000,7 @@ public function checkSetAdmins(string $id) * @throws NotFoundException */ #[Post("admins", new VArray(), "List of user IDs.", required: true)] - #[Path("id", new VString(), "identifier of the exercise", required: true)] + #[Path("id", new VUuid(), "identifier of the exercise", required: true)] public function actionSetAdmins(string $id) { $exercise = $this->exercises->findOrThrow($id); @@ -1059,7 +1059,7 @@ public function checkSendNotification(string $id) * @POST */ #[Post("message", new VString(), "Message sent to notified users.")] - #[Path("id", new VString(), "identifier of the exercise", required: true)] + #[Path("id", new VUuid(), "identifier of the exercise", required: true)] public function actionSendNotification(string $id) { $exercise = $this->exercises->findOrThrow($id); diff --git a/app/V1Module/presenters/ExtensionsPresenter.php b/app/V1Module/presenters/ExtensionsPresenter.php index 727f7caa8..90eaf9254 100644 --- a/app/V1Module/presenters/ExtensionsPresenter.php +++ b/app/V1Module/presenters/ExtensionsPresenter.php @@ -5,16 +5,7 @@ use App\Helpers\MetaFormats\Attributes\Post; use App\Helpers\MetaFormats\Attributes\Query; use App\Helpers\MetaFormats\Attributes\Path; -use App\Helpers\MetaFormats\Type; -use App\Helpers\MetaFormats\Validators\VArray; -use App\Helpers\MetaFormats\Validators\VBool; -use App\Helpers\MetaFormats\Validators\VDouble; -use App\Helpers\MetaFormats\Validators\VEmail; -use App\Helpers\MetaFormats\Validators\VInt; -use App\Helpers\MetaFormats\Validators\VMixed; use App\Helpers\MetaFormats\Validators\VString; -use App\Helpers\MetaFormats\Validators\VTimestamp; -use App\Helpers\MetaFormats\Validators\VUuid; use App\Exceptions\ForbiddenRequestException; use App\Exceptions\BadRequestException; use App\Model\Repository\Instances; @@ -70,7 +61,7 @@ public function checkUrl(string $extId, string $instanceId) } /** - * Return URL refering to the extension with properly injected temporary JWT token. + * Return URL referring to the extension with properly injected temporary JWT token. * @GET */ #[Query("locale", new VString(2, 2), required: false)] @@ -100,7 +91,7 @@ public function actionUrl(string $extId, string $instanceId, ?string $locale, ?s public function checkToken(string $extId) { /* - * This checker does not employ traditional ACLs for permission checks since it is trvial and it is better + * This checker does not employ traditional ACLs for permission checks since it is trivial and it is better * to keep everything here (in one place). However, this may change in the future should the presenter get * more complex. * This action expects to be authenticated by temporary token generated in 'url' action. diff --git a/app/V1Module/presenters/ForgottenPasswordPresenter.php b/app/V1Module/presenters/ForgottenPasswordPresenter.php index 51a8fbd8c..111664497 100644 --- a/app/V1Module/presenters/ForgottenPasswordPresenter.php +++ b/app/V1Module/presenters/ForgottenPasswordPresenter.php @@ -3,26 +3,14 @@ namespace App\V1Module\Presenters; use App\Helpers\MetaFormats\Attributes\Post; -use App\Helpers\MetaFormats\Attributes\Query; -use App\Helpers\MetaFormats\Attributes\Path; -use App\Helpers\MetaFormats\Type; -use App\Helpers\MetaFormats\Validators\VArray; -use App\Helpers\MetaFormats\Validators\VBool; -use App\Helpers\MetaFormats\Validators\VDouble; -use App\Helpers\MetaFormats\Validators\VEmail; -use App\Helpers\MetaFormats\Validators\VInt; use App\Helpers\MetaFormats\Validators\VMixed; use App\Helpers\MetaFormats\Validators\VString; -use App\Helpers\MetaFormats\Validators\VTimestamp; -use App\Helpers\MetaFormats\Validators\VUuid; use App\Exceptions\ForbiddenRequestException; use App\Exceptions\NotFoundException; use App\Helpers\ForgottenPasswordHelper; use App\Model\Repository\Logins; use App\Model\Repository\SecurityEvents; -use App\Model\Entity\Login; use App\Model\Entity\SecurityEvent; -use App\Security\AccessToken; use App\Security\TokenScope; use Nette\Security\Passwords; use ZxcvbnPhp\Zxcvbn; @@ -98,7 +86,7 @@ public function actionChange() $this->logins->persist($login); $this->logins->flush(); - $event = SecurityEvent::createChangePasswoedEvent( + $event = SecurityEvent::createChangePasswordEvent( $this->getHttpRequest()->getRemoteAddress(), $login->getUser() ); diff --git a/app/V1Module/presenters/GroupExternalAttributesPresenter.php b/app/V1Module/presenters/GroupExternalAttributesPresenter.php index 809106c36..0cdd3df80 100644 --- a/app/V1Module/presenters/GroupExternalAttributesPresenter.php +++ b/app/V1Module/presenters/GroupExternalAttributesPresenter.php @@ -5,15 +5,7 @@ use App\Helpers\MetaFormats\Attributes\Post; use App\Helpers\MetaFormats\Attributes\Query; use App\Helpers\MetaFormats\Attributes\Path; -use App\Helpers\MetaFormats\Type; -use App\Helpers\MetaFormats\Validators\VArray; -use App\Helpers\MetaFormats\Validators\VBool; -use App\Helpers\MetaFormats\Validators\VDouble; -use App\Helpers\MetaFormats\Validators\VEmail; -use App\Helpers\MetaFormats\Validators\VInt; -use App\Helpers\MetaFormats\Validators\VMixed; use App\Helpers\MetaFormats\Validators\VString; -use App\Helpers\MetaFormats\Validators\VTimestamp; use App\Helpers\MetaFormats\Validators\VUuid; use App\Exceptions\ForbiddenRequestException; use App\Exceptions\BadRequestException; @@ -22,11 +14,10 @@ use App\Model\Entity\GroupExternalAttribute; use App\Model\View\GroupViewFactory; use App\Security\ACL\IGroupPermissions; -use DateTime; use InvalidArgumentException; /** - * Additional attributes used by 3rd parties to keep relations between groups and entites in external systems. + * Additional attributes used by 3rd parties to keep relations between groups and entities in external systems. * In case of a university, the attributes may hold things like course/semester/student-group identifiers. */ class GroupExternalAttributesPresenter extends BasePresenter @@ -66,10 +57,10 @@ public function checkDefault() * Return all attributes that correspond to given filtering parameters. * @GET * - * The filter is encocded as array of objects (logically represented as disjunction of clauses) + * The filter is encoded as array of objects (logically represented as disjunction of clauses) * -- i.e., [clause1 OR clause2 ...]. Each clause is an object with the following keys: * "group", "service", "key", "value" that match properties of GroupExternalAttribute entity. - * The values are expected values matched with == in the search. Any of the keys may be ommitted or null + * The values are expected values matched with == in the search. Any of the keys may be omitted or null * which indicate it should not be matched in the particular clause. * A clause must contain at least one of the four keys. * @@ -142,7 +133,7 @@ public function checkRemove() * Remove selected attribute * @DELETE */ - #[Path("id", new VString(), required: true)] + #[Path("id", new VUuid(), "Identifier of the external attribute.", required: true)] public function actionRemove(string $id) { $attribute = $this->groupExternalAttributes->findOrThrow($id); diff --git a/app/V1Module/presenters/GroupInvitationsPresenter.php b/app/V1Module/presenters/GroupInvitationsPresenter.php index d537233ce..37d986cfb 100644 --- a/app/V1Module/presenters/GroupInvitationsPresenter.php +++ b/app/V1Module/presenters/GroupInvitationsPresenter.php @@ -3,14 +3,7 @@ namespace App\V1Module\Presenters; use App\Helpers\MetaFormats\Attributes\Post; -use App\Helpers\MetaFormats\Attributes\Query; use App\Helpers\MetaFormats\Attributes\Path; -use App\Helpers\MetaFormats\Type; -use App\Helpers\MetaFormats\Validators\VArray; -use App\Helpers\MetaFormats\Validators\VBool; -use App\Helpers\MetaFormats\Validators\VDouble; -use App\Helpers\MetaFormats\Validators\VEmail; -use App\Helpers\MetaFormats\Validators\VInt; use App\Helpers\MetaFormats\Validators\VMixed; use App\Helpers\MetaFormats\Validators\VString; use App\Helpers\MetaFormats\Validators\VTimestamp; @@ -64,11 +57,11 @@ public function checkDefault($id) * Return invitation details including all relevant group entities (so a name can be constructed). * @GET */ - #[Path("id", new VString(), required: true)] + #[Path("id", new VUuid(), "Identifier of the group invitation", required: true)] public function actionDefault($id) { $invitation = $this->groupInvitations->findOrThrow($id); - $groups = $this->groups->groupsAncestralClosure([ $invitation->getGroup() ]); + $groups = $this->groups->groupsAncestralClosure([$invitation->getGroup()]); $this->sendSuccessResponse([ "invitation" => $invitation, "groups" => $this->groupViewFactory->getGroups($groups), @@ -89,7 +82,7 @@ public function checkUpdate($id) */ #[Post("expireAt", new VTimestamp(), "When the invitation expires.", nullable: true)] #[Post("note", new VMixed(), "Note for the students who wish to use the invitation link.", nullable: true)] - #[Path("id", new VString(), required: true)] + #[Path("id", new VUuid(), "Identifier of the group invitation", required: true)] public function actionUpdate($id) { $req = $this->getRequest(); @@ -112,7 +105,7 @@ public function checkRemove($id) /** * @DELETE */ - #[Path("id", new VString(), required: true)] + #[Path("id", new VUuid(), "Identifier of the group invitation", required: true)] public function actionRemove($id) { $invitation = $this->groupInvitations->findOrThrow($id); @@ -137,7 +130,7 @@ public function checkAccept($id) * Allow the current user to join the corresponding group using the invitation. * @POST */ - #[Path("id", new VString(), required: true)] + #[Path("id", new VUuid(), "Identifier of the group invitation", required: true)] public function actionAccept($id) { $invitation = $this->groupInvitations->findOrThrow($id); diff --git a/app/V1Module/presenters/GroupsPresenter.php b/app/V1Module/presenters/GroupsPresenter.php index 025ef4071..a00a16f85 100644 --- a/app/V1Module/presenters/GroupsPresenter.php +++ b/app/V1Module/presenters/GroupsPresenter.php @@ -393,7 +393,7 @@ public function checkUpdateGroup(string $id) #[Post( "externalId", new VMixed(), - "An informative, human readable indentifier of the group", + "An informative, human readable identifier of the group", required: false, nullable: true, )] @@ -403,7 +403,7 @@ public function checkUpdateGroup(string $id) #[Post("threshold", new VInt(), "A minimum percentage of points needed to pass the course", required: false)] #[Post("pointsLimit", new VInt(), "A minimum of (absolute) points needed to pass the course", required: false)] #[Post("localizedTexts", new VArray(), "Localized names and descriptions")] - #[Path("id", new VString(), "An identifier of the updated group", required: true)] + #[Path("id", new VUuid(), "An identifier of the updated group", required: true)] public function actionUpdateGroup(string $id) { $req = $this->getRequest(); @@ -444,7 +444,7 @@ public function checkSetOrganizational(string $id) * @throws NotFoundException */ #[Post("value", new VBool(), "The value of the flag", required: true)] - #[Path("id", new VString(), "An identifier of the updated group", required: true)] + #[Path("id", new VUuid(), "An identifier of the updated group", required: true)] public function actionSetOrganizational(string $id) { $group = $this->groups->findOrThrow($id); @@ -480,7 +480,7 @@ public function checkSetArchived(string $id) * @throws NotFoundException */ #[Post("value", new VBool(), "The value of the flag", required: true)] - #[Path("id", new VString(), "An identifier of the updated group", required: true)] + #[Path("id", new VUuid(), "An identifier of the updated group", required: true)] public function actionSetArchived(string $id) { $group = $this->groups->findOrThrow($id); @@ -492,7 +492,7 @@ public function actionSetArchived(string $id) // snapshot the inherited membership-relations $typePriorities = array_flip(GroupMembership::INHERITABLE_TYPES); - // this is actually a hack for PHP Stan (can be removed when there will be more than 1 interitable type) + // this is actually a hack for PHP Stan (can be removed when there will be more than 1 inheritable type) $typePriorities[''] = -1; // adding a fake priority for fake type $membershipsToInherit = []; // aggregated memberships from all ancestors, key is user ID @@ -562,7 +562,7 @@ public function checkSetExam(string $id) * @throws NotFoundException */ #[Post("value", new VBool(), "The value of the flag", required: true)] - #[Path("id", new VString(), "An identifier of the updated group", required: true)] + #[Path("id", new VUuid(), "An identifier of the updated group", required: true)] public function actionSetExam(string $id) { $group = $this->groups->findOrThrow($id); @@ -584,7 +584,7 @@ public function checkSetExamPeriod(string $id) * Set an examination period (in the future) when the group will be secured for submitting. * Only locked students may submit solutions in the group during this period. * This endpoint is also used to update already planned exam period, but only dates in the future - * can be editted (e.g., once an exam begins, the beginning may no longer be updated). + * can be edited (e.g., once an exam begins, the beginning may no longer be updated). * @POST * @throws NotFoundException */ @@ -602,7 +602,7 @@ public function checkSetExamPeriod(string $id) required: true, )] #[Post("strict", new VBool(), "Whether locked users are prevented from accessing other groups.", required: false)] - #[Path("id", new VString(), "An identifier of the updated group", required: true)] + #[Path("id", new VUuid(), "An identifier of the updated group", required: true)] public function actionSetExamPeriod(string $id) { $group = $this->groups->findOrThrow($id); @@ -715,7 +715,7 @@ public function checkRemoveExamPeriod(string $id) * @DELETE * @throws NotFoundException */ - #[Path("id", new VString(), "An identifier of the updated group", required: true)] + #[Path("id", new VUuid(), "An identifier of the updated group", required: true)] public function actionRemoveExamPeriod(string $id) { $group = $this->groups->findOrThrow($id); @@ -764,7 +764,7 @@ public function checkGetExamLocks(string $id, string $examId) * Retrieve a list of locks for given exam * @GET */ - #[Path("id", new VString(), "An identifier of the related group", required: true)] + #[Path("id", new VUuid(), "An identifier of the related group", required: true)] #[Path("examId", new VInt(), "An identifier of the exam", required: true)] public function actionGetExamLocks(string $id, string $examId) { @@ -780,7 +780,7 @@ public function actionGetExamLocks(string $id, string $examId) * @throws NotFoundException * @throws BadRequestException */ - #[Path("id", new VString(), "An identifier of the relocated group", required: true)] + #[Path("id", new VUuid(), "An identifier of the relocated group", required: true)] #[Path("newParentId", new VString(), "An identifier of the new parent group", required: true)] public function actionRelocate(string $id, string $newParentId) { @@ -838,7 +838,7 @@ public function checkRemoveGroup(string $id) * Delete a group * @DELETE */ - #[Path("id", new VString(), "Identifier of the group", required: true)] + #[Path("id", new VUuid(), "Identifier of the group", required: true)] public function actionRemoveGroup(string $id) { $group = $this->groups->findOrThrow($id); @@ -861,7 +861,7 @@ public function checkDetail(string $id) * Get details of a group * @GET */ - #[Path("id", new VString(), "Identifier of the group", required: true)] + #[Path("id", new VUuid(), "Identifier of the group", required: true)] public function actionDetail(string $id) { $group = $this->groups->findOrThrow($id); @@ -881,9 +881,9 @@ public function checkSubgroups(string $id) /** * Get a list of subgroups of a group * @GET - * @DEPRECTATED Subgroup list is part of group view. + * @DEPRECATED Subgroup list is part of group view. */ - #[Path("id", new VString(), "Identifier of the group", required: true)] + #[Path("id", new VUuid(), "Identifier of the group", required: true)] public function actionSubgroups(string $id) { /** @var Group $group */ @@ -914,7 +914,7 @@ public function checkMembers(string $id) * @GET * @DEPRECATED Members are listed in group view. */ - #[Path("id", new VString(), "Identifier of the group", required: true)] + #[Path("id", new VUuid(), "Identifier of the group", required: true)] public function actionMembers(string $id) { $group = $this->groups->findOrThrow($id); @@ -948,7 +948,7 @@ public function checkAddMember(string $id, string $userId) * @POST */ #[Post("type", new VString(1), "Identifier of membership type (admin, supervisor, ...)", required: true)] - #[Path("id", new VString(), "Identifier of the group", required: true)] + #[Path("id", new VUuid(), "Identifier of the group", required: true)] #[Path("userId", new VString(), "Identifier of the supervisor", required: true)] public function actionAddMember(string $id, string $userId) { @@ -994,7 +994,7 @@ public function checkRemoveMember(string $id, string $userId) * Remove a member (other than student) from a group * @DELETE */ - #[Path("id", new VString(), "Identifier of the group", required: true)] + #[Path("id", new VUuid(), "Identifier of the group", required: true)] #[Path("userId", new VString(), "Identifier of the supervisor", required: true)] public function actionRemoveMember(string $id, string $userId) { @@ -1033,7 +1033,7 @@ public function checkAssignments(string $id) * Get all exercise assignments for a group * @GET */ - #[Path("id", new VString(), "Identifier of the group", required: true)] + #[Path("id", new VUuid(), "Identifier of the group", required: true)] public function actionAssignments(string $id) { /** @var Group $group */ @@ -1067,7 +1067,7 @@ public function checkShadowAssignments(string $id) * Get all shadow assignments for a group * @GET */ - #[Path("id", new VString(), "Identifier of the group", required: true)] + #[Path("id", new VUuid(), "Identifier of the group", required: true)] public function actionShadowAssignments(string $id) { /** @var Group $group */ @@ -1106,7 +1106,7 @@ public function checkStats(string $id) * @GET * @throws ForbiddenRequestException */ - #[Path("id", new VString(), "Identifier of the group", required: true)] + #[Path("id", new VUuid(), "Identifier of the group", required: true)] public function actionStats(string $id) { $group = $this->groups->findOrThrow($id); @@ -1135,7 +1135,7 @@ public function checkStudentsStats(string $id, string $userId) * @GET * @throws BadRequestException */ - #[Path("id", new VString(), "Identifier of the group", required: true)] + #[Path("id", new VUuid(), "Identifier of the group", required: true)] #[Path("userId", new VString(), "Identifier of the student", required: true)] public function actionStudentsStats(string $id, string $userId) { @@ -1165,7 +1165,7 @@ public function checkStudentsSolutions(string $id, string $userId) * @GET * @throws BadRequestException */ - #[Path("id", new VString(), "Identifier of the group", required: true)] + #[Path("id", new VUuid(), "Identifier of the group", required: true)] #[Path("userId", new VString(), "Identifier of the student", required: true)] public function actionStudentsSolutions(string $id, string $userId) { @@ -1212,7 +1212,7 @@ public function checkAddStudent(string $id, string $userId) * Add a student to a group * @POST */ - #[Path("id", new VString(), "Identifier of the group", required: true)] + #[Path("id", new VUuid(), "Identifier of the group", required: true)] #[Path("userId", new VString(), "Identifier of the student", required: true)] public function actionAddStudent(string $id, string $userId) { @@ -1243,7 +1243,7 @@ public function checkRemoveStudent(string $id, string $userId) * Remove a student from a group * @DELETE */ - #[Path("id", new VString(), "Identifier of the group", required: true)] + #[Path("id", new VUuid(), "Identifier of the group", required: true)] #[Path("userId", new VString(), "Identifier of the student", required: true)] public function actionRemoveStudent(string $id, string $userId) { @@ -1275,7 +1275,7 @@ public function checkLockStudent(string $id, string $userId) * Lock student in a group and with an IP from which the request was made. * @POST */ - #[Path("id", new VString(), "Identifier of the group", required: true)] + #[Path("id", new VUuid(), "Identifier of the group", required: true)] #[Path("userId", new VString(), "Identifier of the student", required: true)] public function actionLockStudent(string $id, string $userId) { @@ -1315,7 +1315,7 @@ public function checkUnlockStudent(string $id, string $userId) * Unlock a student currently locked in a group. * @DELETE */ - #[Path("id", new VString(), "Identifier of the group", required: true)] + #[Path("id", new VUuid(), "Identifier of the group", required: true)] #[Path("userId", new VString(), "Identifier of the student", required: true)] public function actionUnlockStudent(string $id, string $userId) { diff --git a/app/V1Module/presenters/HardwareGroupsPresenter.php b/app/V1Module/presenters/HardwareGroupsPresenter.php index a930499b3..226599ef1 100644 --- a/app/V1Module/presenters/HardwareGroupsPresenter.php +++ b/app/V1Module/presenters/HardwareGroupsPresenter.php @@ -2,19 +2,6 @@ namespace App\V1Module\Presenters; -use App\Helpers\MetaFormats\Attributes\Post; -use App\Helpers\MetaFormats\Attributes\Query; -use App\Helpers\MetaFormats\Attributes\Path; -use App\Helpers\MetaFormats\Type; -use App\Helpers\MetaFormats\Validators\VArray; -use App\Helpers\MetaFormats\Validators\VBool; -use App\Helpers\MetaFormats\Validators\VDouble; -use App\Helpers\MetaFormats\Validators\VEmail; -use App\Helpers\MetaFormats\Validators\VInt; -use App\Helpers\MetaFormats\Validators\VMixed; -use App\Helpers\MetaFormats\Validators\VString; -use App\Helpers\MetaFormats\Validators\VTimestamp; -use App\Helpers\MetaFormats\Validators\VUuid; use App\Exceptions\ForbiddenRequestException; use App\Model\Repository\HardwareGroups; use App\Security\ACL\IHardwareGroupPermissions; @@ -24,7 +11,6 @@ */ class HardwareGroupsPresenter extends BasePresenter { - /** * @var HardwareGroups * @inject diff --git a/app/V1Module/presenters/InstancesPresenter.php b/app/V1Module/presenters/InstancesPresenter.php index 18b80c2a8..35b0f453d 100644 --- a/app/V1Module/presenters/InstancesPresenter.php +++ b/app/V1Module/presenters/InstancesPresenter.php @@ -8,6 +8,7 @@ use App\Helpers\MetaFormats\Validators\VMixed; use App\Helpers\MetaFormats\Validators\VString; use App\Helpers\MetaFormats\Validators\VTimestamp; +use App\Helpers\MetaFormats\Validators\VUuid; use App\Exceptions\ForbiddenRequestException; use App\Exceptions\NotFoundException; use App\Model\Entity\LocalizedGroup; @@ -134,7 +135,7 @@ public function actionCreateInstance() $this->instances->persist($instance->getRootGroup(), false); $this->instances->persist($localizedRootGroup, false); $this->instances->persist($instance); - $this->sendSuccessResponse($this->instanceViewFactory->getInstance($instance, $user), IResponse::S201_CREATED); + $this->sendSuccessResponse($this->instanceViewFactory->getInstance($instance, $user), IResponse::S201_Created); } public function checkUpdateInstance(string $id) @@ -151,7 +152,7 @@ public function checkUpdateInstance(string $id) * @POST */ #[Post("isOpen", new VBool(), "Should the instance be open for registration?", required: false)] - #[Path("id", new VString(), "An identifier of the updated instance", required: true)] + #[Path("id", new VUuid(), "An identifier of the updated instance", required: true)] public function actionUpdateInstance(string $id) { $instance = $this->instances->findOrThrow($id); @@ -177,7 +178,7 @@ public function checkDeleteInstance(string $id) * Delete an instance * @DELETE */ - #[Path("id", new VString(), "An identifier of the instance to be deleted", required: true)] + #[Path("id", new VUuid(), "An identifier of the instance to be deleted", required: true)] public function actionDeleteInstance(string $id) { $instance = $this->instances->findOrThrow($id); @@ -207,7 +208,7 @@ public function checkDetail(string $id) * Get details of an instance * @GET */ - #[Path("id", new VString(), "An identifier of the instance", required: true)] + #[Path("id", new VUuid(), "An identifier of the instance", required: true)] public function actionDetail(string $id) { $instance = $this->instances->findOrThrow($id); @@ -226,7 +227,7 @@ public function checkLicences(string $id) * Get a list of licenses associated with an instance * @GET */ - #[Path("id", new VString(), "An identifier of the instance", required: true)] + #[Path("id", new VUuid(), "An identifier of the instance", required: true)] public function actionLicences(string $id) { $instance = $this->instances->findOrThrow($id); @@ -247,7 +248,7 @@ public function checkCreateLicence(string $id) */ #[Post("note", new VString(2), "A note for users or administrators")] #[Post("validUntil", new VTimestamp(), "Expiration date of the license")] - #[Path("id", new VString(), "An identifier of the instance", required: true)] + #[Path("id", new VUuid(), "An identifier of the instance", required: true)] public function actionCreateLicence(string $id) { $instance = $this->instances->findOrThrow($id); @@ -275,8 +276,8 @@ public function checkUpdateLicence(string $licenceId) */ #[Post("note", new VString(2, 255), "A note for users or administrators", required: false)] #[Post("validUntil", new VString(), "Expiration date of the license", required: false)] - #[Post("isValid", new VBool(), "Administrator switch to toggle licence validity", required: false)] - #[Path("licenceId", new VString(), "Identifier of the licence", required: true)] + #[Post("isValid", new VBool(), "Administrator switch to toggle license validity", required: false)] + #[Path("licenceId", new VString(), "Identifier of the license", required: true)] public function actionUpdateLicence(string $licenceId) { $licence = $this->licences->findOrThrow($licenceId); @@ -310,7 +311,7 @@ public function checkDeleteLicence(string $licenceId) * @DELETE * @throws NotFoundException */ - #[Path("licenceId", new VString(), "Identifier of the licence", required: true)] + #[Path("licenceId", new VString(), "Identifier of the license", required: true)] public function actionDeleteLicence(string $licenceId) { $licence = $this->licences->findOrThrow($licenceId); diff --git a/app/V1Module/presenters/NotificationsPresenter.php b/app/V1Module/presenters/NotificationsPresenter.php index 67a590d51..27bd3f693 100644 --- a/app/V1Module/presenters/NotificationsPresenter.php +++ b/app/V1Module/presenters/NotificationsPresenter.php @@ -8,6 +8,7 @@ use App\Helpers\MetaFormats\Validators\VArray; use App\Helpers\MetaFormats\Validators\VString; use App\Helpers\MetaFormats\Validators\VTimestamp; +use App\Helpers\MetaFormats\Validators\VUuid; use App\Exceptions\ForbiddenRequestException; use App\Exceptions\InvalidApiArgumentException; use App\Exceptions\NotFoundException; @@ -232,7 +233,7 @@ public function checkUpdate(string $id) #[Post("role", new VString(1), "Users with this role and its children can see notification")] #[Post("type", new VString(), "Type of the notification (custom)")] #[Post("localizedTexts", new VArray(), "Text of notification")] - #[Path("id", new VString(), required: true)] + #[Path("id", new VUuid(), required: true)] public function actionUpdate(string $id) { $notification = $this->notifications->findOrThrow($id); @@ -254,7 +255,7 @@ public function checkRemove(string $id) * @DELETE * @throws NotFoundException */ - #[Path("id", new VString(), required: true)] + #[Path("id", new VUuid(), required: true)] public function actionRemove(string $id) { $notification = $this->notifications->findOrThrow($id); diff --git a/app/V1Module/presenters/PipelinesPresenter.php b/app/V1Module/presenters/PipelinesPresenter.php index d2f797e77..8eba2bd63 100644 --- a/app/V1Module/presenters/PipelinesPresenter.php +++ b/app/V1Module/presenters/PipelinesPresenter.php @@ -10,6 +10,7 @@ use App\Helpers\MetaFormats\Validators\VInt; use App\Helpers\MetaFormats\Validators\VMixed; use App\Helpers\MetaFormats\Validators\VString; +use App\Helpers\MetaFormats\Validators\VUuid; use App\Exceptions\BadRequestException; use App\Exceptions\ExerciseConfigException; use App\Exceptions\ForbiddenRequestException; @@ -168,10 +169,10 @@ public function checkDefault(string $search = null) )] public function actionDefault( int $offset = 0, - int $limit = null, - string $orderBy = null, - array $filters = null, - string $locale = null + ?int $limit = null, + ?string $orderBy = null, + ?array $filters = null, + ?string $locale = null ) { $pagination = $this->getPagination( $offset, @@ -237,7 +238,7 @@ public function actionCreatePipeline() "Whether the pipeline is global (has no author, is used in generic runtimes)", required: false, )] - #[Path("id", new VString(), "identification of pipeline to be copied", required: true)] + #[Path("id", new VUuid(), "identification of pipeline to be copied", required: true)] public function actionForkPipeline(string $id) { $req = $this->getRequest(); @@ -272,7 +273,7 @@ public function checkRemovePipeline(string $id) * @DELETE * @throws NotFoundException */ - #[Path("id", new VString(), required: true)] + #[Path("id", new VUuid(), "Identifier of the pipeline", required: true)] public function actionRemovePipeline(string $id) { $pipeline = $this->pipelines->findOrThrow($id); @@ -294,7 +295,7 @@ public function checkGetPipeline(string $id) * @GET * @throws NotFoundException */ - #[Path("id", new VString(), "Identifier of the pipeline", required: true)] + #[Path("id", new VUuid(), "Identifier of the pipeline", required: true)] public function actionGetPipeline(string $id) { /** @var Pipeline $pipeline */ @@ -331,7 +332,7 @@ public function checkUpdatePipeline(string $id) "Whether the pipeline is global (has no author, is used in generic runtimes)", required: false, )] - #[Path("id", new VString(), "Identifier of the pipeline", required: true)] + #[Path("id", new VUuid(), "Identifier of the pipeline", required: true)] public function actionUpdatePipeline(string $id) { /** @var Pipeline $pipeline */ @@ -410,7 +411,7 @@ public function checkUpdateRuntimeEnvironments(string $id) * @throws ForbiddenRequestException * @throws NotFoundException */ - #[Path("id", new VString(), "Identifier of the pipeline", required: true)] + #[Path("id", new VUuid(), "Identifier of the pipeline", required: true)] public function actionUpdateRuntimeEnvironments(string $id) { /** @var Pipeline $pipeline */ @@ -433,7 +434,7 @@ public function actionUpdateRuntimeEnvironments(string $id) * @throws NotFoundException */ #[Post("version", new VInt(), "Version of the pipeline.")] - #[Path("id", new VString(), "Identifier of the pipeline", required: true)] + #[Path("id", new VUuid(), "Identifier of the pipeline", required: true)] public function actionValidatePipeline(string $id) { $pipeline = $this->pipelines->findOrThrow($id); @@ -468,7 +469,7 @@ public function checkUploadSupplementaryFiles(string $id) * @throws NotFoundException */ #[Post("files", new VMixed(), "Identifiers of supplementary files", nullable: true)] - #[Path("id", new VString(), "identification of pipeline", required: true)] + #[Path("id", new VUuid(), "identification of pipeline", required: true)] public function actionUploadSupplementaryFiles(string $id) { $pipeline = $this->pipelines->findOrThrow($id); @@ -521,7 +522,7 @@ public function checkGetSupplementaryFiles(string $id) * @GET * @throws NotFoundException */ - #[Path("id", new VString(), "identification of pipeline", required: true)] + #[Path("id", new VUuid(), "identification of pipeline", required: true)] public function actionGetSupplementaryFiles(string $id) { $pipeline = $this->pipelines->findOrThrow($id); @@ -541,7 +542,7 @@ public function checkDeleteSupplementaryFile(string $id, string $fileId) * @DELETE * @throws NotFoundException */ - #[Path("id", new VString(), "identification of pipeline", required: true)] + #[Path("id", new VUuid(), "identification of pipeline", required: true)] #[Path("fileId", new VString(), "identification of file", required: true)] public function actionDeleteSupplementaryFile(string $id, string $fileId) { @@ -571,7 +572,7 @@ public function checkGetPipelineExercises(string $id) * @GET * @throws NotFoundException */ - #[Path("id", new VString(), "Identifier of the pipeline", required: true)] + #[Path("id", new VUuid(), "Identifier of the pipeline", required: true)] public function actionGetPipelineExercises(string $id) { $exercises = $this->exercises->getPipelineExercises($id); diff --git a/app/V1Module/presenters/PlagiarismPresenter.php b/app/V1Module/presenters/PlagiarismPresenter.php index d8959c430..9965d478d 100644 --- a/app/V1Module/presenters/PlagiarismPresenter.php +++ b/app/V1Module/presenters/PlagiarismPresenter.php @@ -5,22 +5,15 @@ use App\Helpers\MetaFormats\Attributes\Post; use App\Helpers\MetaFormats\Attributes\Query; use App\Helpers\MetaFormats\Attributes\Path; -use App\Helpers\MetaFormats\Type; use App\Helpers\MetaFormats\Validators\VArray; use App\Helpers\MetaFormats\Validators\VBool; use App\Helpers\MetaFormats\Validators\VDouble; -use App\Helpers\MetaFormats\Validators\VEmail; -use App\Helpers\MetaFormats\Validators\VInt; -use App\Helpers\MetaFormats\Validators\VMixed; use App\Helpers\MetaFormats\Validators\VString; -use App\Helpers\MetaFormats\Validators\VTimestamp; use App\Helpers\MetaFormats\Validators\VUuid; use App\Exceptions\BadRequestException; use App\Exceptions\ForbiddenRequestException; use App\Exceptions\ParseException; use App\Exceptions\FrontendErrorMappings; -use App\Model\Entity\AssignmentSolution; -use App\Model\Entity\User; use App\Model\Entity\PlagiarismDetectionBatch; use App\Model\Entity\PlagiarismDetectedSimilarity; use App\Model\Entity\PlagiarismDetectedSimilarFile; @@ -33,7 +26,6 @@ use App\Security\ACL\IPlagiarismPermissions; use App\Security\ACL\IAssignmentSolutionPermissions; use App\Model\View\PlagiarismViewFactory; -use DateTime; /** * Presenter handling plagiarism-related stuff (similarity records and their presentation) @@ -86,7 +78,7 @@ class PlagiarismPresenter extends BasePresenter * @var PlagiarismViewFactory * @inject */ - public $plagiarismViewFatory; + public $plagiarismViewFactory; public function checkListBatches(?string $detectionTool, ?string $solutionId): void { @@ -129,7 +121,7 @@ public function checkBatchDetail(string $id): void * Fetch a detail of a particular batch record. * @GET */ - #[Path("id", new VString(), required: true)] + #[Path("id", new VUuid(), "Identification of the detection batch", required: true)] public function actionBatchDetail(string $id): void { $batch = $this->detectionBatches->findOrThrow($id); @@ -173,11 +165,11 @@ public function checkUpdateBatch(string $id): void } /** - * Update dectection bath record. At the momeny, only the uploadCompletedAt can be changed. + * Update detection bath record. At the moment, only the uploadCompletedAt can be changed. * @POST */ #[Post("uploadCompleted", new VBool(), "Whether the upload of the batch data is completed or not.")] - #[Path("id", new VString(), required: true)] + #[Path("id", new VUuid(), "Identification of the detection batch", required: true)] public function actionUpdateBatch(string $id): void { $req = $this->getRequest(); @@ -201,14 +193,14 @@ public function checkGetSimilarities(string $id, string $solutionId): void * Returns a list of detected similarities entities (similar file records are nested within). * @GET */ - #[Path("id", new VString(), required: true)] + #[Path("id", new VUuid(), "Identification of the detection batch", required: true)] #[Path("solutionId", new VString(), required: true)] public function actionGetSimilarities(string $id, string $solutionId): void { $batch = $this->detectionBatches->findOrThrow($id); $solution = $this->assignmentSolutions->findOrThrow($solutionId); $similarities = array_map( - [$this->plagiarismViewFatory, 'getPlagiarismSimilarityData'], + [$this->plagiarismViewFactory, 'getPlagiarismSimilarityData'], $this->detectedSimilarities->getSolutionSimilarities($batch, $solution) ); $this->sendSuccessResponse($similarities); @@ -224,7 +216,7 @@ public function checkAddSimilarities(string $id, string $solutionId): void /** * Appends one detected similarity record (similarities associated with one file and one other author) - * into a detected batch. This division was selected to make the appends relatively small and managable. + * into a detected batch. This division was selected to make the appends relatively small and manageable. * @POST */ #[Post("solutionFileId", new VUuid(), "Id of the uploaded solution file.")] @@ -237,7 +229,7 @@ public function checkAddSimilarities(string $id, string $solutionId): void #[Post("authorId", new VUuid(), "Id of the author of the similar solutions/files.")] #[Post("similarity", new VDouble(), "Relative similarity of the records associated with selected author [0-1].")] #[Post("files", new VArray(), "List of similar files and their records.")] - #[Path("id", new VString(), required: true)] + #[Path("id", new VUuid(), "Identification of the detection batch", required: true)] #[Path("solutionId", new VString(), required: true)] public function actionAddSimilarities(string $id, string $solutionId): void { @@ -280,10 +272,11 @@ public function actionAddSimilarities(string $id, string $solutionId): void } if ( $similarFile && (!($similarFile instanceof SolutionFile) || !$similarSolution - || $similarFile->getSolution()->getId() !== $similarSolution->getSolution()->getId()) + || $similarFile->getSolution()->getId() !== $similarSolution->getSolution()->getId()) ) { throw new BadRequestException( - "In the similar files record, every solutionFileId must refer to a file related to the corresponding selected solution." + "In the similar files record, every solutionFileId must refer " + . "to a file related to the corresponding selected solution." ); } @@ -309,6 +302,6 @@ public function actionAddSimilarities(string $id, string $solutionId): void $this->detectedSimilarities->persist($detectedSimilarity, false); $solution->setPlagiarismBatch($batch); $this->assignmentSolutions->persist($solution); - $this->sendSuccessResponse($this->plagiarismViewFatory->getPlagiarismSimilarityData($detectedSimilarity)); + $this->sendSuccessResponse($this->plagiarismViewFactory->getPlagiarismSimilarityData($detectedSimilarity)); } } diff --git a/app/V1Module/presenters/ReferenceExerciseSolutionsPresenter.php b/app/V1Module/presenters/ReferenceExerciseSolutionsPresenter.php index 80401894b..cc8bdde90 100644 --- a/app/V1Module/presenters/ReferenceExerciseSolutionsPresenter.php +++ b/app/V1Module/presenters/ReferenceExerciseSolutionsPresenter.php @@ -9,6 +9,7 @@ use App\Helpers\MetaFormats\Validators\VInt; use App\Helpers\MetaFormats\Validators\VMixed; use App\Helpers\MetaFormats\Validators\VString; +use App\Helpers\MetaFormats\Validators\VUuid; use App\Exceptions\BadRequestException; use App\Exceptions\ExerciseCompilationException; use App\Exceptions\ExerciseConfigException; @@ -468,7 +469,7 @@ public function checkResubmit(string $id) * @throws BadRequestException */ #[Post("debug", new VBool(), "Debugging evaluation with all logs and outputs", required: false)] - #[Path("id", new VString(), "Identifier of the reference solution", required: true)] + #[Path("id", new VUuid(), "Identifier of the reference solution", required: true)] public function actionResubmit(string $id) { $req = $this->getRequest(); @@ -635,7 +636,7 @@ public function checkFiles(string $id) * @throws ForbiddenRequestException * @throws NotFoundException */ - #[Path("id", new VString(), "of reference solution", required: true)] + #[Path("id", new VUuid(), "of reference solution", required: true)] public function actionFiles(string $id) { $solution = $this->referenceSolutions->findOrThrow($id)->getSolution(); diff --git a/app/V1Module/presenters/RegistrationPresenter.php b/app/V1Module/presenters/RegistrationPresenter.php index a8b299806..eebe4a408 100644 --- a/app/V1Module/presenters/RegistrationPresenter.php +++ b/app/V1Module/presenters/RegistrationPresenter.php @@ -140,7 +140,7 @@ protected function getInstance(string $instanceId): Instance public function checkCreateAccount() { if (!$this->registrationConfig->isEnabled()) { - // If the registration is not enabled in general, creator must be logged in and have priviledges. + // If the registration is not enabled in general, creator must be logged in and have privileges. if (!$this->userAcl->canCreate()) { throw new ForbiddenRequestException(); } @@ -220,7 +220,7 @@ public function actionCreateAccount() "user" => $this->userViewFactory->getFullUser($user), "accessToken" => $this->accessManager->issueToken($user) ], - IResponse::S201_CREATED + IResponse::S201_Created ); } @@ -398,7 +398,7 @@ public function actionAcceptInvitation() "user" => $this->userViewFactory->getFullUser($user), "accessToken" => $this->accessManager->issueToken($user), ], - IResponse::S201_CREATED + IResponse::S201_Created ); } } diff --git a/app/V1Module/presenters/RuntimeEnvironmentsPresenter.php b/app/V1Module/presenters/RuntimeEnvironmentsPresenter.php index 5799d6761..c57e187a2 100644 --- a/app/V1Module/presenters/RuntimeEnvironmentsPresenter.php +++ b/app/V1Module/presenters/RuntimeEnvironmentsPresenter.php @@ -2,19 +2,6 @@ namespace App\V1Module\Presenters; -use App\Helpers\MetaFormats\Attributes\Post; -use App\Helpers\MetaFormats\Attributes\Query; -use App\Helpers\MetaFormats\Attributes\Path; -use App\Helpers\MetaFormats\Type; -use App\Helpers\MetaFormats\Validators\VArray; -use App\Helpers\MetaFormats\Validators\VBool; -use App\Helpers\MetaFormats\Validators\VDouble; -use App\Helpers\MetaFormats\Validators\VEmail; -use App\Helpers\MetaFormats\Validators\VInt; -use App\Helpers\MetaFormats\Validators\VMixed; -use App\Helpers\MetaFormats\Validators\VString; -use App\Helpers\MetaFormats\Validators\VTimestamp; -use App\Helpers\MetaFormats\Validators\VUuid; use App\Exceptions\ForbiddenRequestException; use App\Model\Repository\RuntimeEnvironments; use App\Security\ACL\IRuntimeEnvironmentPermissions; @@ -24,7 +11,6 @@ */ class RuntimeEnvironmentsPresenter extends BasePresenter { - /** * @var RuntimeEnvironments * @inject diff --git a/app/V1Module/presenters/SecurityPresenter.php b/app/V1Module/presenters/SecurityPresenter.php index 5b543aef1..cd3dd3662 100644 --- a/app/V1Module/presenters/SecurityPresenter.php +++ b/app/V1Module/presenters/SecurityPresenter.php @@ -58,7 +58,7 @@ public function actionCheck() return; } - $action = $requestParams["action"] ?? Presenter::DEFAULT_ACTION; + $action = $requestParams["action"] ?? Presenter::DefaultAction; $methodName = $presenter->formatPermissionCheckMethod($action); if (!method_exists($presenter, $methodName)) { $this->checkFailed(); diff --git a/app/V1Module/presenters/ShadowAssignmentsPresenter.php b/app/V1Module/presenters/ShadowAssignmentsPresenter.php index 36ef5cdb5..ede8bdebb 100644 --- a/app/V1Module/presenters/ShadowAssignmentsPresenter.php +++ b/app/V1Module/presenters/ShadowAssignmentsPresenter.php @@ -10,6 +10,7 @@ use App\Helpers\MetaFormats\Validators\VMixed; use App\Helpers\MetaFormats\Validators\VString; use App\Helpers\MetaFormats\Validators\VTimestamp; +use App\Helpers\MetaFormats\Validators\VUuid; use App\Exceptions\BadRequestException; use App\Exceptions\ForbiddenRequestException; use App\Exceptions\InvalidApiArgumentException; @@ -100,7 +101,7 @@ public function checkDetail(string $id) * @GET * @throws NotFoundException */ - #[Path("id", new VString(), "Identifier of the assignment", required: true)] + #[Path("id", new VUuid(), "Identifier of the assignment", required: true)] public function actionDetail(string $id) { $assignment = $this->shadowAssignments->findOrThrow($id); @@ -121,7 +122,7 @@ public function checkValidate(string $id) * @throws ForbiddenRequestException */ #[Post("version", new VInt(), "Version of the shadow assignment.")] - #[Path("id", new VString(), "Identifier of the shadow assignment", required: true)] + #[Path("id", new VUuid(), "Identifier of the shadow assignment", required: true)] public function actionValidate($id) { $assignment = $this->shadowAssignments->findOrThrow($id); @@ -165,7 +166,7 @@ public function checkUpdateDetail(string $id) required: false, nullable: true, )] - #[Path("id", new VString(), "Identifier of the updated assignment", required: true)] + #[Path("id", new VUuid(), "Identifier of the updated assignment", required: true)] public function actionUpdateDetail(string $id) { $assignment = $this->shadowAssignments->findOrThrow($id); @@ -293,7 +294,7 @@ public function checkRemove(string $id) * @DELETE * @throws NotFoundException */ - #[Path("id", new VString(), "Identifier of the assignment to be removed", required: true)] + #[Path("id", new VUuid(), "Identifier of the assignment to be removed", required: true)] public function actionRemove(string $id) { $assignment = $this->shadowAssignments->findOrThrow($id); @@ -326,7 +327,7 @@ public function checkCreatePoints(string $id) "Datetime when the points were awarded, whatever that means", required: false, )] - #[Path("id", new VString(), "Identifier of the shadow assignment", required: true)] + #[Path("id", new VUuid(), "Identifier of the shadow assignment", required: true)] public function actionCreatePoints(string $id) { $req = $this->getRequest(); diff --git a/app/V1Module/presenters/SubmissionFailuresPresenter.php b/app/V1Module/presenters/SubmissionFailuresPresenter.php index 96b33e2e5..aea958b94 100644 --- a/app/V1Module/presenters/SubmissionFailuresPresenter.php +++ b/app/V1Module/presenters/SubmissionFailuresPresenter.php @@ -3,19 +3,10 @@ namespace App\V1Module\Presenters; use App\Helpers\MetaFormats\Attributes\Post; -use App\Helpers\MetaFormats\Attributes\Query; use App\Helpers\MetaFormats\Attributes\Path; -use App\Helpers\MetaFormats\Type; -use App\Helpers\MetaFormats\Validators\VArray; use App\Helpers\MetaFormats\Validators\VBool; -use App\Helpers\MetaFormats\Validators\VDouble; -use App\Helpers\MetaFormats\Validators\VEmail; -use App\Helpers\MetaFormats\Validators\VInt; -use App\Helpers\MetaFormats\Validators\VMixed; use App\Helpers\MetaFormats\Validators\VString; -use App\Helpers\MetaFormats\Validators\VTimestamp; use App\Helpers\MetaFormats\Validators\VUuid; -use App\Exceptions\BadRequestException; use App\Exceptions\ForbiddenRequestException; use App\Helpers\Notifications\FailureResolutionEmailsSender; use App\Model\Repository\AssignmentSolutionSubmissions; @@ -29,7 +20,6 @@ */ class SubmissionFailuresPresenter extends BasePresenter { - /** * @var SubmissionFailures * @inject @@ -98,7 +88,7 @@ public function checkDetail(string $id) * Get details of a failure * @GET */ - #[Path("id", new VString(), "An identifier of the failure", required: true)] + #[Path("id", new VUuid(), "An identifier of the failure", required: true)] public function actionDetail(string $id) { $failure = $this->submissionFailures->findOrThrow($id); @@ -119,7 +109,7 @@ public function checkResolve(string $id) */ #[Post("note", new VString(0, 255), "Brief description of how the failure was resolved", required: false)] #[Post("sendEmail", new VBool(), "True if email should be sent to the author of submission")] - #[Path("id", new VString(), "An identifier of the failure", required: true)] + #[Path("id", new VUuid(), "An identifier of the failure", required: true)] public function actionResolve(string $id) { $failure = $this->submissionFailures->findOrThrow($id); diff --git a/app/V1Module/presenters/SubmitPresenter.php b/app/V1Module/presenters/SubmitPresenter.php index 2cb922237..2feda4be1 100644 --- a/app/V1Module/presenters/SubmitPresenter.php +++ b/app/V1Module/presenters/SubmitPresenter.php @@ -9,6 +9,7 @@ use App\Helpers\MetaFormats\Validators\VBool; use App\Helpers\MetaFormats\Validators\VMixed; use App\Helpers\MetaFormats\Validators\VString; +use App\Helpers\MetaFormats\Validators\VUuid; use App\Exceptions\ExerciseConfigException; use App\Exceptions\ForbiddenRequestException; use App\Exceptions\ParseException; @@ -168,12 +169,12 @@ class SubmitPresenter extends BasePresenter * @param User|null $user * @return bool */ - private function canReceiveSubmissions(Assignment $assignment, User $user = null) + private function canReceiveSubmissions(Assignment $assignment, ?User $user = null) { return $this->assignmentAcl->canSubmit($assignment, $user) && $assignment->isVisibleToStudents() && $assignment->getGroup() && - $assignment->getGroup()->hasValidLicence() && + $assignment->getGroup()->hasValidLicense() && $user !== null && count( $this->assignmentSolutions->findValidSolutions($assignment, $user) @@ -192,7 +193,7 @@ private function getUserOrCurrent(?string $userId): User return $userId !== null ? $this->users->findOrThrow($userId) : $this->getCurrentUser(); } - public function checkCanSubmit(string $id, string $userId = null) + public function checkCanSubmit(string $id) { $assignment = $this->assignments->findOrThrow($id); @@ -207,9 +208,9 @@ public function checkCanSubmit(string $id, string $userId = null) * @throws ForbiddenRequestException * @throws NotFoundException */ - #[Path("id", new VString(), "Identifier of the assignment", required: true)] + #[Path("id", new VUuid(), "Identifier of the assignment", required: true)] #[Query("userId", new VString(), "Identification of the user", required: false, nullable: true)] - public function actionCanSubmit(string $id, string $userId = null) + public function actionCanSubmit(string $id, ?string $userId = null) { $assignment = $this->assignments->findOrThrow($id); $user = $this->getUserOrCurrent($userId); @@ -243,7 +244,7 @@ public function actionCanSubmit(string $id, string $userId = null) nullable: true, )] #[Post("solutionParams", new VMixed(), "Solution parameters", required: false, nullable: true)] - #[Path("id", new VString(), "Identifier of the assignment", required: true)] + #[Path("id", new VUuid(), "Identifier of the assignment", required: true)] public function actionSubmit(string $id) { $this->assignments->beginTransaction(); @@ -346,7 +347,7 @@ public function checkResubmit(string $id) * @throws ParseException */ #[Post("debug", new VBool(), "Debugging resubmit with all logs and outputs", required: false)] - #[Path("id", new VString(), "Identifier of the solution", required: true)] + #[Path("id", new VUuid(), "Identifier of the solution", required: true)] public function actionResubmit(string $id) { $req = $this->getRequest(); @@ -366,12 +367,12 @@ public function checkResubmitAllAsyncJobStatus(string $id) /** * Return a list of all pending resubmit async jobs associated with given assignment. - * Under normal circumstances, the list shoul be either empty, or contian only one job. + * Under normal circumstances, the list should be either empty, or contain only one job. * @GET * @throws ForbiddenRequestException * @throws NotFoundException */ - #[Path("id", new VString(), "Identifier of the assignment", required: true)] + #[Path("id", new VUuid(), "Identifier of the assignment", required: true)] public function actionResubmitAllAsyncJobStatus(string $id) { $assignment = $this->assignments->findOrThrow($id); @@ -396,7 +397,7 @@ public function checkResubmitAll(string $id) * @throws ForbiddenRequestException * @throws NotFoundException */ - #[Path("id", new VString(), "Identifier of the assignment", required: true)] + #[Path("id", new VUuid(), "Identifier of the assignment", required: true)] public function actionResubmitAll(string $id) { $assignment = $this->assignments->findOrThrow($id); @@ -414,7 +415,7 @@ public function actionResubmitAll(string $id) $this->sendSuccessResponse(['pending' => $asyncJobs, 'failed' => $failedJobs]); } - public function checkPreSubmit(string $id, string $userId = null) + public function checkPreSubmit(string $id, ?string $userId = null) { $assignment = $this->assignments->findOrThrow($id); $user = $this->getUserOrCurrent($userId); @@ -435,7 +436,7 @@ public function checkPreSubmit(string $id, string $userId = null) * @throws NotFoundException */ #[Post("files", new VArray())] - #[Path("id", new VString(), "identifier of assignment", required: true)] + #[Path("id", new VUuid(), "identifier of assignment", required: true)] #[Query("userId", new VString(), "Identifier of the submission author", required: false, nullable: true)] public function actionPreSubmit(string $id, string $userId = null) { diff --git a/app/V1Module/presenters/UploadedFilesPresenter.php b/app/V1Module/presenters/UploadedFilesPresenter.php index caf5b5b9e..351e175c6 100644 --- a/app/V1Module/presenters/UploadedFilesPresenter.php +++ b/app/V1Module/presenters/UploadedFilesPresenter.php @@ -129,7 +129,7 @@ public function checkDetail(string $id) * @GET * @LoggedIn */ - #[Path("id", new VString(), "Identifier of the uploaded file", required: true)] + #[Path("id", new VUuid(), "Identifier of the uploaded file", required: true)] public function actionDetail(string $id) { $file = $this->uploadedFiles->findOrThrow($id); @@ -145,7 +145,7 @@ public function checkDownload(string $id, ?string $entry = null, ?string $simila if ($file instanceof SolutionFile && $similarSolutionId) { // special check using similar solution hint - // similar solution refers to anoter solution which has detected similarities in this file + // similar solution refers to another solution which has detected similarities in this file // (so whoever can see plagiarisms of the original solution may see this file) $similarSolution = $this->assignmentSolutions->findOrThrow($similarSolutionId); $fileSolution = $this->assignmentSolutions->findOneBy(['solution' => $file->getSolution()]); @@ -186,7 +186,7 @@ public function checkDownload(string $id, ?string $entry = null, ?string $simila . "This is basically a shortcut (hint) for ACLs.", required: false, )] - #[Path("id", new VString(), "Identifier of the file", required: true)] + #[Path("id", new VUuid(), "Identifier of the file", required: true)] public function actionDownload(string $id, ?string $entry = null) { $fileEntity = $this->uploadedFiles->findOrThrow($id); @@ -234,7 +234,7 @@ public function checkContent(string $id, ?string $entry = null, ?string $similar . "This is basically a shortcut (hint) for ACLs.", required: false, )] - #[Path("id", new VString(), "Identifier of the file", required: true)] + #[Path("id", new VUuid(), "Identifier of the file", required: true)] public function actionContent(string $id, ?string $entry = null) { $fileEntity = $this->uploadedFiles->findOrThrow($id); @@ -289,7 +289,7 @@ public function checkDigest(string $id) * In the future, we might want to add algorithm selection via query parameter (default is SHA1). * @GET */ - #[Path("id", new VString(), "Identifier of the file", required: true)] + #[Path("id", new VUuid(), "Identifier of the file", required: true)] public function actionDigest(string $id) { $fileEntity = $this->uploadedFiles->findOrThrow($id); @@ -334,7 +334,7 @@ public function actionUpload() if (!$file->isOk()) { throw new CannotReceiveUploadedFileException( sprintf("Cannot receive uploaded file '%s' due to '%d'", $file->getName(), $file->getError()), - IResponse::S500_INTERNAL_SERVER_ERROR, + IResponse::S500_InternalServerError, FrontendErrorMappings::E500_001__CANNOT_RECEIVE_FILE, ["filename" => $file->getName(), "errorCode" => $file->getError()] ); @@ -343,7 +343,7 @@ public function actionUpload() if (!Strings::match($file->getName(), self::FILENAME_PATTERN)) { throw new CannotReceiveUploadedFileException( sprintf("File name '%s' contains invalid characters", $file->getName()), - IResponse::S400_BAD_REQUEST, + IResponse::S400_BadRequest, FrontendErrorMappings::E400_003__UPLOADED_FILE_INVALID_CHARACTERS, ["filename" => $file->getName(), "pattern" => self::FILENAME_PATTERN] ); @@ -396,7 +396,7 @@ public function actionStartPartial() if (!Strings::match($name, self::FILENAME_PATTERN)) { throw new CannotReceiveUploadedFileException( "File name '$name' contains invalid characters", - IResponse::S400_BAD_REQUEST, + IResponse::S400_BadRequest, FrontendErrorMappings::E400_003__UPLOADED_FILE_INVALID_CHARACTERS, ["filename" => $name, "pattern" => self::FILENAME_PATTERN] ); @@ -407,7 +407,7 @@ public function actionStartPartial() // TODO: in the future, we might want to employ more sophisticated quota checking throw new CannotReceiveUploadedFileException( "Invalid declared file size ($size) for per-partes upload", - IResponse::S400_BAD_REQUEST, + IResponse::S400_BadRequest, FrontendErrorMappings::E400_004__UPLOADED_FILE_INVALID_SIZE, ["size" => $size, "maximum" => $maxSize] ); @@ -438,7 +438,7 @@ public function checkAppendPartial(string $id) * @throws InternalServerException */ #[Query("offset", new VInt(), "Offset of the chunk for verification", required: true)] - #[Path("id", new VString(), "Identifier of the file", required: true)] + #[Path("id", new VUuid(), "Identifier of the partial file", required: true)] public function actionAppendPartial(string $id, int $offset) { $partialFile = $this->uploadedPartialFiles->findOrThrow($id); @@ -483,7 +483,7 @@ public function checkCancelPartial(string $id) * Cancel partial upload and remove all uploaded chunks. * @DELETE */ - #[Path("id", new VString(), required: true)] + #[Path("id", new VUuid(), "Identifier of the partial file", required: true)] public function actionCancelPartial(string $id) { $partialFile = $this->uploadedPartialFiles->findOrThrow($id); @@ -527,14 +527,14 @@ public function checkCompletePartial(string $id) * All data chunks are extracted from the store, assembled into one file, and is moved back into the store. * @POST */ - #[Path("id", new VString(), required: true)] + #[Path("id", new VUuid(), "Identifier of the partial file", required: true)] public function actionCompletePartial(string $id) { $partialFile = $this->uploadedPartialFiles->findOrThrow($id); if (!$partialFile->isUploadComplete()) { throw new CannotReceiveUploadedFileException( "Unable to finalize incomplete per-partes upload.", - IResponse::S400_BAD_REQUEST, + IResponse::S400_BadRequest, FrontendErrorMappings::E400_005__UPLOADED_FILE_PARTIAL, [ "chunks" => $partialFile->getChunks(), @@ -593,7 +593,7 @@ public function checkDownloadSupplementaryFile(string $id) * @throws NotFoundException * @throws \Nette\Application\AbortException */ - #[Path("id", new VString(), "Identifier of the file", required: true)] + #[Path("id", new VUuid(), "Identifier of the file", required: true)] public function actionDownloadSupplementaryFile(string $id) { $fileEntity = $this->supplementaryFiles->findOrThrow($id); diff --git a/app/V1Module/presenters/UserCalendarsPresenter.php b/app/V1Module/presenters/UserCalendarsPresenter.php index 7f6090115..ac9d2aea3 100644 --- a/app/V1Module/presenters/UserCalendarsPresenter.php +++ b/app/V1Module/presenters/UserCalendarsPresenter.php @@ -3,17 +3,8 @@ namespace App\V1Module\Presenters; use App\Helpers\MetaFormats\Attributes\Post; -use App\Helpers\MetaFormats\Attributes\Query; use App\Helpers\MetaFormats\Attributes\Path; -use App\Helpers\MetaFormats\Type; -use App\Helpers\MetaFormats\Validators\VArray; -use App\Helpers\MetaFormats\Validators\VBool; -use App\Helpers\MetaFormats\Validators\VDouble; -use App\Helpers\MetaFormats\Validators\VEmail; -use App\Helpers\MetaFormats\Validators\VInt; -use App\Helpers\MetaFormats\Validators\VMixed; use App\Helpers\MetaFormats\Validators\VString; -use App\Helpers\MetaFormats\Validators\VTimestamp; use App\Helpers\MetaFormats\Validators\VUuid; use App\Exceptions\BadRequestException; use App\Exceptions\ForbiddenRequestException; @@ -34,7 +25,6 @@ use Eluceo\iCal\Domain\Entity\Calendar; use Eluceo\iCal\Presentation\Factory\CalendarFactory; use Eluceo\iCal\Domain\ValueObject; -use DateTime; /** * User iCal management endpoints @@ -83,7 +73,7 @@ class UserCalendarsPresenter extends BasePresenter * @param string $lang identifier * @return mixed */ - private static function getBestLoale(array $texts, string $lang): mixed + private static function getBestLocale(array $texts, string $lang): mixed { return !empty($texts[$lang]) ? $texts[$lang] : (!empty($texts['en']) ? $texts['en'] : reset($texts)); } @@ -97,7 +87,7 @@ private static function getBestLoale(array $texts, string $lang): mixed */ private function createDeadlineEvent(User $user, Assignment $assignment, string $lang): Event { - $id = [ 'recodex', $user->getId(), $assignment->getId() ]; + $id = ['recodex', $user->getId(), $assignment->getId()]; $event = new Event(new ValueObject\UniqueIdentifier(join('/', $id))); // time @@ -105,7 +95,7 @@ private function createDeadlineEvent(User $user, Assignment $assignment, string $event->setOccurrence(new ValueObject\TimeSpan($deadline, $deadline)); // capion - $texts = self::getBestLoale($assignment->getLocalizedTextsAssocArray(), $lang); + $texts = self::getBestLocale($assignment->getLocalizedTextsAssocArray(), $lang); if ($texts) { $event->setSummary('ReCodEx deadline: ' . $texts->getName()); } @@ -117,7 +107,7 @@ private function createDeadlineEvent(User $user, Assignment $assignment, string // location $group = $assignment->getGroup(); if ($group) { - $groupTexts = self::getBestLoale($group->getLocalizedTextsAssocArray(), $lang); + $groupTexts = self::getBestLocale($group->getLocalizedTextsAssocArray(), $lang); if ($groupTexts) { $location = new ValueObject\Location($groupTexts->getName()); $event->setLocation($location); @@ -193,11 +183,11 @@ public function checkUserCalendars(string $id) * Get all iCal tokens of one user (including expired ones). * @GET */ - #[Path("id", new VString(), "of the user", required: true)] + #[Path("id", new VUuid(), "of the user", required: true)] public function actionUserCalendars(string $id) { $user = $this->users->findOrThrow($id); - $calendars = $this->userCalendars->findBy([ 'user' => $user ], [ 'createdAt' => 'DESC' ]); + $calendars = $this->userCalendars->findBy(['user' => $user], ['createdAt' => 'DESC']); $this->sendSuccessResponse($calendars); } @@ -213,7 +203,7 @@ public function checkCreateCalendar(string $id) * Create new iCal token for a particular user. * @POST */ - #[Path("id", new VString(), "of the user", required: true)] + #[Path("id", new VUuid(), "of the user", required: true)] public function actionCreateCalendar(string $id) { $user = $this->users->findOrThrow($id); diff --git a/app/V1Module/presenters/UsersPresenter.php b/app/V1Module/presenters/UsersPresenter.php index f0d49d9e5..aa7c07a66 100644 --- a/app/V1Module/presenters/UsersPresenter.php +++ b/app/V1Module/presenters/UsersPresenter.php @@ -11,6 +11,7 @@ use App\Helpers\MetaFormats\Validators\VInt; use App\Helpers\MetaFormats\Validators\VMixed; use App\Helpers\MetaFormats\Validators\VString; +use App\Helpers\MetaFormats\Validators\VUuid; use App\Exceptions\ForbiddenRequestException; use App\Exceptions\FrontendErrorMappings; use App\Exceptions\InvalidApiArgumentException; @@ -139,10 +140,10 @@ public function checkDefault() )] public function actionDefault( int $offset = 0, - int $limit = null, - string $orderBy = null, - array $filters = null, - string $locale = null + ?int $limit = null, + ?string $orderBy = null, + ?array $filters = null, + ?string $locale = null ) { $pagination = $this->getPagination( $offset, @@ -198,7 +199,7 @@ public function checkDetail(string $id) * Get details of a user account * @GET */ - #[Path("id", new VString(), "Identifier of the user", required: true)] + #[Path("id", new VUuid(), "Identifier of the user", required: true)] public function actionDetail(string $id) { $user = $this->users->findOrThrow($id); @@ -218,7 +219,7 @@ public function checkDelete(string $id) * @DELETE * @throws ForbiddenRequestException */ - #[Path("id", new VString(), "Identifier of the user", required: true)] + #[Path("id", new VUuid(), "Identifier of the user", required: true)] public function actionDelete(string $id) { $user = $this->users->findOrThrow($id); @@ -254,7 +255,7 @@ public function checkUpdateProfile(string $id) #[Post("password", new VString(1), "New password of current user", required: false)] #[Post("passwordConfirm", new VString(1), "Confirmation of new password of current user", required: false)] #[Post("gravatarUrlEnabled", new VBool(), "Enable or disable gravatar profile image", required: false)] - #[Path("id", new VString(), "Identifier of the user", required: true)] + #[Path("id", new VUuid(), "Identifier of the user", required: true)] public function actionUpdateProfile(string $id) { $req = $this->getRequest(); @@ -339,7 +340,7 @@ private function changeUserEmail(User $user, ?string $email) } /** - * Change firstname and second name and check if user can change them. + * Change first name and last name and check if user can change them. * @param User $user * @param null|string $titlesBefore * @param null|string $firstname @@ -419,7 +420,7 @@ private function changeUserPassword( $login->changePassword($password, $this->passwordsService); $login->getUser()->setTokenValidityThreshold(new DateTime()); - $event = SecurityEvent::createChangePasswoedEvent( + $event = SecurityEvent::createChangePasswordEvent( $this->getHttpRequest()->getRemoteAddress(), $login->getUser() ); @@ -518,7 +519,7 @@ public function checkUpdateSettings(string $id) . "in a supervised/admin-ed group.", required: false, )] - #[Path("id", new VString(), "Identifier of the user", required: true)] + #[Path("id", new VUuid(), "Identifier of the user", required: true)] public function actionUpdateSettings(string $id) { $req = $this->getRequest(); @@ -574,10 +575,10 @@ public function checkUpdateUiData(string $id) #[Post( "overwrite", new VBool(), - "Flag indicating that uiData should be overwritten completelly (instead of regular merge)", + "Flag indicating that uiData should be overwritten completely (instead of regular merge)", required: false, )] - #[Path("id", new VString(), "Identifier of the user", required: true)] + #[Path("id", new VUuid(), "Identifier of the user", required: true)] public function actionUpdateUiData(string $id) { $req = $this->getRequest(); @@ -633,7 +634,7 @@ public function checkCreateLocalAccount(string $id) * @POST * @throws InvalidApiArgumentException */ - #[Path("id", new VString(), required: true)] + #[Path("id", new VUuid(), "Identifier of the user", required: true)] public function actionCreateLocalAccount(string $id) { $user = $this->users->findOrThrow($id); @@ -656,7 +657,7 @@ public function checkGroups(string $id) * Get a list of non-archived groups for a user * @GET */ - #[Path("id", new VString(), "Identifier of the user", required: true)] + #[Path("id", new VUuid(), "Identifier of the user", required: true)] public function actionGroups(string $id) { $user = $this->users->findOrThrow($id); @@ -699,7 +700,7 @@ public function checkAllGroups(string $id) * Get a list of all groups for a user * @GET */ - #[Path("id", new VString(), "Identifier of the user", required: true)] + #[Path("id", new VUuid(), "Identifier of the user", required: true)] public function actionAllGroups(string $id) { $user = $this->users->findOrThrow($id); @@ -725,7 +726,7 @@ public function checkInstances(string $id) * @GET * @throws NotFoundException */ - #[Path("id", new VString(), "Identifier of the user", required: true)] + #[Path("id", new VUuid(), "Identifier of the user", required: true)] public function actionInstances(string $id) { $user = $this->users->findOrThrow($id); @@ -755,7 +756,7 @@ public function checkSetRole(string $id) * @throws NotFoundException */ #[Post("role", new VString(1), "Role which should be assigned to the user")] - #[Path("id", new VString(), "Identifier of the user", required: true)] + #[Path("id", new VUuid(), "Identifier of the user", required: true)] public function actionSetRole(string $id) { $user = $this->users->findOrThrow($id); @@ -785,7 +786,7 @@ public function checkInvalidateTokens(string $id) * @throws ForbiddenRequestException * @throws NotFoundException */ - #[Path("id", new VString(), "Identifier of the user", required: true)] + #[Path("id", new VUuid(), "Identifier of the user", required: true)] public function actionInvalidateTokens(string $id) { $user = $this->users->findOrThrow($id); @@ -825,7 +826,7 @@ public function checkSetAllowed(string $id) * @throws NotFoundException */ #[Post("isAllowed", new VBool(), "Whether the user is allowed (active) or not.")] - #[Path("id", new VString(), "Identifier of the user", required: true)] + #[Path("id", new VUuid(), "Identifier of the user", required: true)] public function actionSetAllowed(string $id) { $user = $this->users->findOrThrow($id); @@ -851,7 +852,7 @@ public function checkUpdateExternalLogin(string $id, string $service) * @throws InvalidApiArgumentException */ #[Post("externalId", new VString(1, 128))] - #[Path("id", new VString(), "identifier of the user", required: true)] + #[Path("id", new VUuid(), "identifier of the user", required: true)] #[Path("service", new VString(), "identifier of the authentication service (login type)", required: true)] public function actionUpdateExternalLogin(string $id, string $service) { @@ -862,7 +863,7 @@ public function actionUpdateExternalLogin(string $id, string $service) $anotherUser = $this->externalLogins->getUser($service, $externalId); if ($anotherUser) { if ($anotherUser->getId() !== $id) { - // oopsie, this external ID is alreay used for a different user + // oopsie, this external ID is already used for a different user throw new InvalidApiArgumentException('externalId', "This ID is already used by another user."); } // otherwise the external ID is already set to this user, so there is nothing to change... @@ -896,7 +897,7 @@ public function checkRemoveExternalLogin(string $id, string $service) * Remove external ID of given authentication service. * @DELETE */ - #[Path("id", new VString(), "identifier of the user", required: true)] + #[Path("id", new VUuid(), "identifier of the user", required: true)] #[Path("service", new VString(), "identifier of the authentication service (login type)", required: true)] public function actionRemoveExternalLogin(string $id, string $service) { diff --git a/app/V1Module/presenters/base/ApiErrorPresenter.php b/app/V1Module/presenters/base/ApiErrorPresenter.php index e295c430c..ffef95277 100644 --- a/app/V1Module/presenters/base/ApiErrorPresenter.php +++ b/app/V1Module/presenters/base/ApiErrorPresenter.php @@ -51,10 +51,10 @@ public function renderDefault($exception) FrontendErrorMappings::E400_000__BAD_REQUEST ); } elseif ($exception instanceof ConnectionException) { - $this->sendErrorResponse(IResponse::S500_INTERNAL_SERVER_ERROR, "Database is offline"); + $this->sendErrorResponse(IResponse::S500_InternalServerError, "Database is offline"); } else { $type = get_class($exception); - $this->sendErrorResponse(IResponse::S500_INTERNAL_SERVER_ERROR, "Unexpected Error {$type}"); + $this->sendErrorResponse(IResponse::S500_InternalServerError, "Unexpected Error {$type}"); } } diff --git a/app/V1Module/presenters/base/BasePresenter.php b/app/V1Module/presenters/base/BasePresenter.php index e2d87e631..59242990f 100644 --- a/app/V1Module/presenters/base/BasePresenter.php +++ b/app/V1Module/presenters/base/BasePresenter.php @@ -90,7 +90,7 @@ protected function verifyUserIpLock(User $user) if (!$remoteAddr || !$user->verifyIpLock($remoteAddr)) { throw new ForbiddenRequestException( "Forbidden Request - User is not allowed access from IP '$remoteAddr'.", - IResponse::S403_FORBIDDEN, + IResponse::S403_Forbidden, FrontendErrorMappings::E403_003__USER_IP_LOCKED, [ 'remoteAddress' => $remoteAddr, @@ -361,7 +361,7 @@ protected function logUserAction($code = IResponse::S200_OK) if ($this->getUser()->isLoggedIn()) { $remoteAddr = $this->getHttpRequest()->getRemoteAddress(); $params = $this->getRequest()->getParameters(); - unset($params[self::ACTION_KEY]); + unset($params[self::ActionKey]); $this->userActions->log($this->getAction(true), $remoteAddr, $params, $code); } } @@ -394,7 +394,7 @@ protected function sendPaginationSuccessResponse( array $items, Pagination $pagination, bool $sliceItems = false, - int $totalCount = null, + ?int $totalCount = null, $code = IResponse::S200_OK ) { $this->sendSuccessResponse( @@ -431,7 +431,7 @@ protected function getPagination(...$params): Pagination protected function sendStorageFileResponse( IImmutableFile $file, string $name, - string $contentType = null, + ?string $contentType = null, bool $forceDownload = true ) { $this->logUserAction(200); @@ -445,7 +445,7 @@ protected function sendStorageFileResponse( * @param string|null $name * @param bool $forceDownload */ - protected function sendZipFilesResponse(array $files, string $name = null, bool $forceDownload = true) + protected function sendZipFilesResponse(array $files, ?string $name = null, bool $forceDownload = true) { $this->logUserAction(200); $this->sendResponse(new ZipFilesResponse($files, $name, $forceDownload)); diff --git a/app/V1Module/router/MethodRoute.php b/app/V1Module/router/MethodRoute.php index 03ffe4776..20fe96ebe 100644 --- a/app/V1Module/router/MethodRoute.php +++ b/app/V1Module/router/MethodRoute.php @@ -3,14 +3,13 @@ namespace App\V1Module\Router; use Nette\Http\IRequest; -use Nette\Application\Request; use Nette\Application\Routers\Route; use Nette\Http\UrlScript; use Nette\Routing\Router; /** * Base class of all module routes which construct URLs. And also does all - * checkings of HTTP request method against the one given during construction. + * checking of HTTP request method against the one given during construction. */ class MethodRoute implements Router { diff --git a/app/async/Dispatcher.php b/app/async/Dispatcher.php index 3633538eb..75e703e1f 100644 --- a/app/async/Dispatcher.php +++ b/app/async/Dispatcher.php @@ -84,7 +84,7 @@ public function unschedule(AsyncJob $job): bool try { $rows = 0; - $this->entityManager->transactional(function ($em) use ($job, &$rows) { + $this->entityManager->wrapInTransaction(function ($em) use ($job, &$rows) { $qb = $em->createQueryBuilder(); $qb->delete(AsyncJob::class, 'aj') ->where($qb->expr()->isNull("aj.startedAt")) diff --git a/app/async/IAsyncJobHandler.php b/app/async/IAsyncJobHandler.php index e3d225938..ed5de26e7 100644 --- a/app/async/IAsyncJobHandler.php +++ b/app/async/IAsyncJobHandler.php @@ -3,8 +3,6 @@ namespace App\Async; use App\Model\Entity\AsyncJob; -use Nette\Utils\Arrays; -use Nette; /** * Interface implemented by all asynchronous job handlers. @@ -25,14 +23,14 @@ public function getId(): string; public function checkArgs(array $args): bool; /** - * The main method of the async job does what the job is ment to do. + * The main method of the async job does what the job is meant to do. * @param AsyncJob $job entity to be executed */ public function execute(AsyncJob $job); /** * Called by signal handler to terminate the job asap (but gracefully). - * If the job is not interruptable, this function should be implemented with empty body. + * If the job is not interrupt-able, this function should be implemented with empty body. */ public function cancel(): void; } diff --git a/app/async/Notify.php b/app/async/Notify.php index 06ed3d7d2..79a65c5f6 100644 --- a/app/async/Notify.php +++ b/app/async/Notify.php @@ -19,7 +19,7 @@ class Notify */ public static function isAvailable(): bool { - $requirements = [ 'inotify_init', 'inotify_add_watch', 'inotify_read', 'inotify_queue_len', 'stream_select' ]; + $requirements = ['inotify_init', 'inotify_add_watch', 'inotify_read', 'inotify_queue_len', 'stream_select']; foreach ($requirements as $reqFnc) { if (!function_exists($reqFnc)) { return false; @@ -118,7 +118,7 @@ public function isNotified(): bool } /** - * Wait (block) until a nofitication is risen or timeout is breached. + * Wait (block) until a notification is risen or timeout is breached. * @param int $timeout maximal waiting time in seconds * @return bool true if notifications were collected, false on timeout * @throws LogicException @@ -136,7 +136,7 @@ public function waitForNotification(int $timeout = 1): bool ); } - $streams = [ $this->inotifyStream ]; + $streams = [$this->inotifyStream]; @stream_select($streams, $streams, $streams, $timeout); // will block until event or timeout return $this->isNotifiedInternal(); } diff --git a/app/async/Worker.php b/app/async/Worker.php index 7a2c1bd55..b3c9294b2 100644 --- a/app/async/Worker.php +++ b/app/async/Worker.php @@ -56,7 +56,7 @@ class Worker private $timeToRestart = null; /** - * @var int number of jobs remainig to process (once it reaches zero, the worker terminates so it can be restarted) + * @var int number of jobs remaining to process (once it reaches zero, the worker terminates so it can be restarted) */ private $jobsRemaining = 1; @@ -93,7 +93,7 @@ public function __construct(array $config, Dispatcher $dispatcher, AsyncJobs $as $this->quiet = (bool)Arrays::get($config, "quiet", false); - // setup signal handling (try to terminate gracefuly on these signals) + // setup signal handling (try to terminate gracefully on these signals) if (function_exists('pcntl_async_signals') && function_exists('pcntl_signal')) { pcntl_async_signals(true); pcntl_signal(SIGINT, [$this, 'terminate']); @@ -112,7 +112,7 @@ public function terminate(): void /** * Test whether the worker shall process jobs further, or whether it should go for restart. - * @return bool true if it shoud continue + * @return bool true if it should continue */ private function shallContinue(): bool { @@ -195,7 +195,7 @@ private function dispatchJob(AsyncJob $job) ); } - // we need to relaod the job since the dispatcher might cleared the caches... + // we need to reload the job since the dispatcher might cleared the caches... $jobReloaded = $this->asyncJobs->get($id); if ($jobReloaded) { if ($error) { @@ -209,12 +209,12 @@ private function dispatchJob(AsyncJob $job) /** * Main method of the worker that actually processes the async job. - * This method is blockinig, once it terminates the worker process should also terminate. + * This method is blocking, once it terminates the worker process should also terminate. * @param string $workerId identifier of the worker (should be gathered from the CLI arguments) */ public function run(string $workerId) { - $this->notify->init(); // start listeining for notifications + $this->notify->init(); // start listening for notifications while ($this->shallContinue()) { // just a precaution so the worker will not run forever // allocate and mark the best suitable job (null = none available) diff --git a/app/async/handlers/AssignmentNotificationJobHandler.php b/app/async/handlers/AssignmentNotificationJobHandler.php index bb99baf57..a83f80b0e 100644 --- a/app/async/handlers/AssignmentNotificationJobHandler.php +++ b/app/async/handlers/AssignmentNotificationJobHandler.php @@ -5,11 +5,9 @@ use App\Model\Entity\AsyncJob; use App\Model\Entity\User; use App\Model\Entity\Assignment; -use App\Model\Repository\Assignments; use App\Async\IAsyncJobHandler; use App\Async\Dispatcher; use App\Helpers\Notifications\AssignmentEmailsSender; -use InvalidArgumentException; /** * Scheduled job that sends email notifications when the assignment becomes visible. diff --git a/app/async/handlers/PingAsyncJobHandler.php b/app/async/handlers/PingAsyncJobHandler.php index bfbe2631b..52df4ddfc 100644 --- a/app/async/handlers/PingAsyncJobHandler.php +++ b/app/async/handlers/PingAsyncJobHandler.php @@ -44,6 +44,6 @@ public static function dispatchAsyncJob(Dispatcher $dispatcher, ?User $user): As public function cancel(): void { - // ping is not interruptable, nothing to do here + // ping is not interrupt-able, nothing to do here } } diff --git a/app/commands/BaseCommand.php b/app/commands/BaseCommand.php index 9af24d219..2183743fd 100644 --- a/app/commands/BaseCommand.php +++ b/app/commands/BaseCommand.php @@ -84,8 +84,8 @@ private static function indexToLetters(int $idx): string } /** - * Perform a select inquery so the user chooses from given options. - * @param string $text of the inquery + * Perform a select inquiry so the user chooses from given options. + * @param string $text of the inquiry * @param array $options to choose from * @param callable|null $renderer explicit to-string converter for options * @return mixed selected option value @@ -102,7 +102,7 @@ protected function select(string $text, array $options, ?callable $renderer = nu if ($this->nonInteractive) { throw new RuntimeException( - "Unable preform the '$text' inquery in non-interactive mode. Operation aborted." + "Unable preform the '$text' inquiry in non-interactive mode. Operation aborted." ); } @@ -115,7 +115,7 @@ protected function select(string $text, array $options, ?callable $renderer = nu $translateBack[$key] = $option; } - // make the inquery + // make the inquiry QuestionHelper::disableStty(); /** @var QuestionHelper */ $helper = $this->getHelper('question'); diff --git a/app/commands/DoctrineFixtures.php b/app/commands/DoctrineFixtures.php index 2166273cb..886d8bc0d 100644 --- a/app/commands/DoctrineFixtures.php +++ b/app/commands/DoctrineFixtures.php @@ -98,7 +98,10 @@ protected function execute(InputInterface $input, OutputInterface $output) $groupFiles = []; /** @var SplFileInfo $file */ - foreach (Finder::findFiles("*.neon", "*.yml", "*.yaml", "*.json")->in($fixtureDir . "/" . $group) as $file) { + foreach ( + Finder::findFiles("*.neon", "*.yml", "*.yaml", "*.json") + ->in($fixtureDir . "/" . $group) as $file + ) { $groupFiles[] = $file->getRealPath(); } diff --git a/app/commands/ExportDatabase.php b/app/commands/ExportDatabase.php index 62f22b71a..197e6e9d2 100644 --- a/app/commands/ExportDatabase.php +++ b/app/commands/ExportDatabase.php @@ -9,7 +9,6 @@ use App\Model\Repository\HardwareGroups; use App\Model\Repository\Pipelines; use App\Model\Repository\RuntimeEnvironments; -use Nette\Neon\Encoder; use Nette\Neon\Neon; use Nette\Utils\FileSystem; use Symfony\Component\Console\Command\Command; @@ -95,7 +94,7 @@ protected function execute(InputInterface $input, OutputInterface $output) */ private function encodeResult($content): string { - return Neon::encode($content, Encoder::BLOCK); + return Neon::encode($content, true); } /** diff --git a/app/commands/GeneralStatsNotification.php b/app/commands/GeneralStatsNotification.php index d6a8bec47..2088614c2 100644 --- a/app/commands/GeneralStatsNotification.php +++ b/app/commands/GeneralStatsNotification.php @@ -4,10 +4,7 @@ use App\Helpers\Notifications\GeneralStatsEmailsSender; use App\Helpers\GeneralStatsHelper; -use App\Model\Repository\Assignments; -use DateTime; use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; diff --git a/app/commands/PlagiarismDetectionAccessToken.php b/app/commands/PlagiarismDetectionAccessToken.php index 9a1002eb8..2522ecc5a 100644 --- a/app/commands/PlagiarismDetectionAccessToken.php +++ b/app/commands/PlagiarismDetectionAccessToken.php @@ -38,7 +38,7 @@ public function __construct(AccessManager $accessManager, Users $users) protected function configure() { $this->setName(self::$defaultName) - ->setDescription('Generate token restricted for plagiarsim scope (for 3rd party tools).'); + ->setDescription('Generate token restricted for plagiarism scope (for 3rd party tools).'); $this->addArgument('userId', InputArgument::REQUIRED, 'ID of the admin owning the token.'); $this->addOption( 'expiration', diff --git a/app/commands/RemoveInactiveUsers.php b/app/commands/RemoveInactiveUsers.php index f33ae1659..8935fe7a2 100644 --- a/app/commands/RemoveInactiveUsers.php +++ b/app/commands/RemoveInactiveUsers.php @@ -2,12 +2,10 @@ namespace App\Console; -use App\Model\Entity\User; use App\Model\Repository\Users; use App\Helpers\AnonymizationHelper; use DateTime; use DateInterval; -use Exception; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; @@ -92,7 +90,8 @@ protected function execute(InputInterface $input, OutputInterface $output) if (!$silent) { if ($this->roles) { - $output->writeln("The cleanup aims only at users with the following roles: " . join(', ', $this->roles)); + $output->writeln("The cleanup aims only at users with the following roles: " + . join(', ', $this->roles)); } if ($this->disableThreshold) { $output->writeln("Disabling users not authenticated since: " @@ -152,7 +151,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $this->users->persist($user, false); } - // delete uers + // delete users foreach ($usersToDelete as $user) { $this->anonymizationHelper->prepareUserForSoftDelete($user); $this->users->remove($user, false); diff --git a/app/commands/SendPendingReviewsNotification.php b/app/commands/SendPendingReviewsNotification.php index cbdaa4c70..7e612f9a6 100644 --- a/app/commands/SendPendingReviewsNotification.php +++ b/app/commands/SendPendingReviewsNotification.php @@ -5,9 +5,7 @@ use App\Helpers\Notifications\ReviewsEmailsSender; use App\Model\Repository\AssignmentSolutions; use App\Model\Entity\Group; -use App\Model\Entity\User; use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use DateTime; diff --git a/app/commands/SwaggerAnnotator.php b/app/commands/SwaggerAnnotator.php index 5f052d536..ce6cd2d17 100644 --- a/app/commands/SwaggerAnnotator.php +++ b/app/commands/SwaggerAnnotator.php @@ -4,14 +4,10 @@ use App\Helpers\Swagger\TempAnnotationFileBuilder; use App\Helpers\Swagger\AnnotationHelper; -use App\V1Module\Router\MethodRoute; -use Nette\Routing\RouteList; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Exception; -use ReflectionException; -use ReflectionClass; /** * Command that creates a temporary file for swagger documentation generation. @@ -28,7 +24,7 @@ protected function configure(): void $filePath = self::$autogeneratedAnnotationFilePath; $this->setName(self::$defaultName)->setDescription( "Extracts endpoint method annotations and puts them into a temporary file that can be used to generate" - . " an OpenAPI documentation. The file is located at {$filePath}" + . " an OpenAPI documentation. The file is located at {$filePath}" ); } diff --git a/app/commands/cleanup/CleanupExerciseConfigs.php b/app/commands/cleanup/CleanupExerciseConfigs.php index 85e165aa4..0131e8efb 100644 --- a/app/commands/cleanup/CleanupExerciseConfigs.php +++ b/app/commands/cleanup/CleanupExerciseConfigs.php @@ -2,13 +2,10 @@ namespace App\Console; -use App\Model\Entity\Assignment; -use App\Model\Entity\Exercise; -use App\Model\Entity\SolutionEvaluation; use App\Model\Repository\Exercises; use DateTime; use Exception; -use Doctrine\DBAL\Connection; +use Doctrine\DBAL\ArrayParameterType; use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; @@ -60,7 +57,7 @@ private function cleanupEnvironmentConfigs(DateTime $limit): int $deleteQuery = $this->entityManager->createQuery( 'DELETE FROM App\Model\Entity\ExerciseEnvironmentConfig c WHERE c.id IN (:ids)' ); - $deleteQuery->setParameter("ids", $ids, Connection::PARAM_STR_ARRAY); + $deleteQuery->setParameter("ids", $ids, ArrayParameterType::STRING); return $deleteQuery->execute(); } @@ -115,7 +112,7 @@ private function cleanupLimits(DateTime $limit): int $deleteQuery = $this->entityManager->createQuery( 'DELETE FROM App\Model\Entity\ExerciseLimits l WHERE l.id IN (:ids)' ); - $deleteQuery->setParameter("ids", $ids, Connection::PARAM_STR_ARRAY); + $deleteQuery->setParameter("ids", $ids, ArrayParameterType::STRING); return $deleteQuery->execute(); } @@ -137,7 +134,7 @@ private function cleanupTests(DateTime $limit): int $deleteQuery = $this->entityManager->createQuery( 'DELETE FROM App\Model\Entity\ExerciseTest t WHERE t.id IN (:ids)' ); - $deleteQuery->setParameter("ids", $ids, Connection::PARAM_STR_ARRAY); + $deleteQuery->setParameter("ids", $ids, ArrayParameterType::STRING); return $deleteQuery->execute(); } @@ -152,7 +149,7 @@ protected function executeUnsafe(DateTime $limit, OutputInterface $output) 'Tests', ]; - $report = [ 'Removed:' ]; + $report = ['Removed:']; foreach ($toDelete as $key) { $method = "cleanup$key"; $deletedCount = $this->$method($limit); diff --git a/app/commands/cleanup/CleanupExerciseFiles.php b/app/commands/cleanup/CleanupExerciseFiles.php index c6b2efc6f..513fd365e 100644 --- a/app/commands/cleanup/CleanupExerciseFiles.php +++ b/app/commands/cleanup/CleanupExerciseFiles.php @@ -52,7 +52,8 @@ public function __construct( protected function configure() { $this->setName('db:cleanup:exercise-files') - ->setDescription('Remove unused supplementary and attachment files (only DB records are removed in case of supplementary files).'); + ->setDescription('Remove unused supplementary and attachment files " + . "(only DB records are removed in case of supplementary files).'); } private function removeUnusedSupplementaryFiles(OutputInterface $output) diff --git a/app/commands/cleanup/CleanupLocalizedTexts.php b/app/commands/cleanup/CleanupLocalizedTexts.php index c829e6ca3..b6e65dfa8 100644 --- a/app/commands/cleanup/CleanupLocalizedTexts.php +++ b/app/commands/cleanup/CleanupLocalizedTexts.php @@ -7,7 +7,7 @@ use App\Model\Repository\Assignments; use App\Model\Repository\Exercises; use DateTime; -use Doctrine\DBAL\Connection; +use Doctrine\DBAL\ArrayParameterType; use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; @@ -75,7 +75,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $limit->modify("-14 days"); $deleteQuery->setParameter("date", $limit); - $deleteQuery->setParameter("ids", $usedTexts, Connection::PARAM_STR_ARRAY); + $deleteQuery->setParameter("ids", $usedTexts, ArrayParameterType::STRING); $deleted += $deleteQuery->execute(); diff --git a/app/commands/cleanup/CleanupPipelineConfigs.php b/app/commands/cleanup/CleanupPipelineConfigs.php index dd309b275..4fd133077 100644 --- a/app/commands/cleanup/CleanupPipelineConfigs.php +++ b/app/commands/cleanup/CleanupPipelineConfigs.php @@ -5,7 +5,7 @@ use App\Model\Entity\Pipeline; use App\Model\Repository\Pipelines; use DateTime; -use Doctrine\DBAL\Connection; +use Doctrine\DBAL\ArrayParameterType; use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; @@ -60,7 +60,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $limit->modify("-14 days"); $deleteQuery->setParameter("date", $limit); - $deleteQuery->setParameter("ids", $usedConfigs, Connection::PARAM_STR_ARRAY); + $deleteQuery->setParameter("ids", $usedConfigs, ArrayParameterType::STRING); $deleted += $deleteQuery->execute(); $output->writeln(sprintf("Removed %d unused pipeline config entities", $deleted)); diff --git a/app/commands/cleanup/CleanupUploads.php b/app/commands/cleanup/CleanupUploads.php index 095920640..7a75705cb 100644 --- a/app/commands/cleanup/CleanupUploads.php +++ b/app/commands/cleanup/CleanupUploads.php @@ -67,9 +67,9 @@ protected function configure() /** * Wrapper function for deleting a list of files, computing basic stats, and printing out job results. - * @param array $files list of files to be delted + * @param array $files list of files to be deleted * @param BaseRepository $fileRepository related repository from which the $files entities are - * @param OutputInterface $output console acces for printing the info + * @param OutputInterface $output console access for printing the info * @param callable $deleteFile the actual function that can delete the physical file */ protected function removeOldFiles( diff --git a/app/commands/runtimes/FixConfigVariables.php b/app/commands/runtimes/FixConfigVariables.php index a33e7da04..b7ebf1550 100644 --- a/app/commands/runtimes/FixConfigVariables.php +++ b/app/commands/runtimes/FixConfigVariables.php @@ -68,26 +68,26 @@ protected function configure() { $this->setName(self::$defaultName)->setDescription( 'Scan exercise configs of given runtime environment and attempt to fix the variables. ' . - 'The variables lists are extracted from pipelines, new variables are added (with defaults), ' . - 'unidentified variables are removed.' + 'The variables lists are extracted from pipelines, new variables are added (with defaults), ' . + 'unidentified variables are removed.' ) - ->addArgument( - 'runtime', - InputArgument::REQUIRED, - 'Identifier of the runtime environment of which the exercises will be updated.' - ) - ->addOption( - 'yes', - 'y', - InputOption::VALUE_NONE, - "Assume 'yes' to all inquiries (run in non-interactive mode)" - ) - ->addOption( - 'silent', - 's', - InputOption::VALUE_NONE, - "Silent mode (no outputs except for errors)" - ); + ->addArgument( + 'runtime', + InputArgument::REQUIRED, + 'Identifier of the runtime environment of which the exercises will be updated.' + ) + ->addOption( + 'yes', + 'y', + InputOption::VALUE_NONE, + "Assume 'yes' to all inquiries (run in non-interactive mode)" + ) + ->addOption( + 'silent', + 's', + InputOption::VALUE_NONE, + "Silent mode (no outputs except for errors)" + ); } private function writeln(...$lines): void @@ -121,7 +121,7 @@ private function loadPipelines(RuntimeEnvironment $runtime): array } /** - * Join given pipelines and extract expected variabled for that particular configuration. + * Join given pipelines and extract expected variables for that particular configuration. * @param string[] $pipelineIds list of pipeline ids to participate * @param VariablesTable $environmentVariables variables already defined in the environment * @return array pipeline id => [ name => Variable ] @@ -276,9 +276,9 @@ private function fixTestsPipelines(array &$tests, string $runtimeId, array $expe $errors ); } - unset($pipeline); // just to make sure a reference is not accidentaly used + unset($pipeline); // just to make sure a reference is not accidentally used } - unset($test); // just to make sure a reference is not accidentaly used + unset($test); // just to make sure a reference is not accidentally used // consolidate update statistics foreach ($adds as $pid => $names) { @@ -320,7 +320,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $runtime = $this->runtimeEnvironments->findOrThrow($runtimeId); $expectedVariables = $this->getExpectedVariables($runtime); - // take all configs one by one regardles of their exercises + // take all configs one by one regardless of their exercises $configs = $this->exerciseConfigs->findAll(); $updated = $failed = 0; foreach ($configs as $configEntity) { diff --git a/app/commands/runtimes/FixExerciseConfigs.php b/app/commands/runtimes/FixExerciseConfigs.php index 9fc115da4..192adb00c 100644 --- a/app/commands/runtimes/FixExerciseConfigs.php +++ b/app/commands/runtimes/FixExerciseConfigs.php @@ -53,25 +53,25 @@ protected function configure() { $this->setName(self::$defaultName)->setDescription( 'Scan exercise configs of given runtime environment and attempts to fix them. ' . - 'This feature may be used when runtime was updated and some of its pipelines replaced.' + 'This feature may be used when runtime was updated and some of its pipelines replaced.' ) - ->addArgument( - 'runtime', - InputArgument::REQUIRED, - 'Identifier of the runtime environment of which the exercises will be updated.' - ) - ->addOption( - 'yes', - 'y', - InputOption::VALUE_NONE, - "Assume 'yes' to all inquiries (run in non-interactive mode)" - ) - ->addOption( - 'silent', - 's', - InputOption::VALUE_NONE, - "Silent mode (no outputs except for errors)" - ); + ->addArgument( + 'runtime', + InputArgument::REQUIRED, + 'Identifier of the runtime environment of which the exercises will be updated.' + ) + ->addOption( + 'yes', + 'y', + InputOption::VALUE_NONE, + "Assume 'yes' to all inquiries (run in non-interactive mode)" + ) + ->addOption( + 'silent', + 's', + InputOption::VALUE_NONE, + "Silent mode (no outputs except for errors)" + ); } private function writeln(...$lines): void @@ -190,9 +190,9 @@ private function fixTestsPipelines(array &$tests, string $runtimeId) $pipeline['name'] = $newId; $changes[$oldId] = $newId; } - unset($pipeline); // just to make sure a reference is not accidentaly used + unset($pipeline); // just to make sure a reference is not accidentally used } - unset($test); // just to make sure a reference is not accidentaly used + unset($test); // just to make sure a reference is not accidentally used return $changes; } @@ -221,7 +221,7 @@ protected function execute(InputInterface $input, OutputInterface $output) // make sure internal pipeline caches are populated $this->loadPipelines($runtimeId); - // take all configs one by one regardles of their exercises + // take all configs one by one regardless of their exercises $configs = $this->exerciseConfigs->findAll(); $updated = $failed = 0; foreach ($configs as $configEntity) { @@ -235,7 +235,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $changes = $this->fixTestsPipelines($config['tests'], $runtimeId); if ($changes === false) { - // error occured + // error occurred $this->writeln("Cannot fix exercise config $configId, pipelines cannot be matched."); ++$failed; } elseif ($changes) { diff --git a/app/commands/runtimes/RuntimeExport.php b/app/commands/runtimes/RuntimeExport.php index a9d66ee45..5b6fc4768 100644 --- a/app/commands/runtimes/RuntimeExport.php +++ b/app/commands/runtimes/RuntimeExport.php @@ -4,7 +4,6 @@ use App\Model\Repository\RuntimeEnvironments; use App\Model\Repository\Pipelines; -use App\Model\Entity\RuntimeEnvironment; use App\Model\Entity\Pipeline; use App\Helpers\FileStorageManager; use ZipArchive; @@ -46,7 +45,7 @@ protected function configure() $this->setName(self::$defaultName)->setDescription( 'Export runtime environment and its pipelines into a ZIP package.' )->addArgument('runtime', InputArgument::REQUIRED, 'ID of the runtime environment to be exported.') - ->addArgument('saveAs', InputArgument::REQUIRED, 'Path to the output ZIP archive.'); + ->addArgument('saveAs', InputArgument::REQUIRED, 'Path to the output ZIP archive.'); } protected static function preprocessPipeline(Pipeline $pipeline) @@ -125,7 +124,7 @@ protected function execute(InputInterface $input, OutputInterface $output) self::addJsonFile($zip, $pipeline->getId() . ".json", $config); } - // Add suplementary pipeline files + // Add supplementary pipeline files foreach ($pipelines as $pipeline) { $files = $pipeline->getSupplementaryEvaluationFiles()->getValues(); foreach ($files as $supFile) { diff --git a/app/commands/runtimes/RuntimeImport.php b/app/commands/runtimes/RuntimeImport.php index 4fe629767..b6495ef30 100644 --- a/app/commands/runtimes/RuntimeImport.php +++ b/app/commands/runtimes/RuntimeImport.php @@ -78,23 +78,23 @@ protected function configure() $this->setName(self::$defaultName)->setDescription( 'Import runtime environment and its pipelines from a ZIP package.' ) - ->addArgument( - 'zipFile', - InputArgument::REQUIRED, - 'Path to the ZIP package from which the data will be loaded.' - ) - ->addOption( - 'yes', - 'y', - InputOption::VALUE_NONE, - "Assume 'yes' to all inquiries (run in non-interactive mode)" - ) - ->addOption( - 'silent', - 's', - InputOption::VALUE_NONE, - "Silent mode (no outputs except for errors)" - ); + ->addArgument( + 'zipFile', + InputArgument::REQUIRED, + 'Path to the ZIP package from which the data will be loaded.' + ) + ->addOption( + 'yes', + 'y', + InputOption::VALUE_NONE, + "Assume 'yes' to all inquiries (run in non-interactive mode)" + ) + ->addOption( + 'silent', + 's', + InputOption::VALUE_NONE, + "Silent mode (no outputs except for errors)" + ); } /* @@ -278,7 +278,7 @@ protected function printRuntimeUpdateInfo(array $data): void 'platform' => $runtime->getPlatform(), 'description' => $runtime->getDescription(), ]; - $this->output->writeln("Runtime $id already exists, the followig fields will be updated:"); + $this->output->writeln("Runtime $id already exists, the following fields will be updated:"); foreach ($old as $key => $value) { if ($value !== $data[$key]) { $this->output->writeln("\t[$key]: $value => $data[$key]"); @@ -318,7 +318,7 @@ private static function renderPipelineStr(?Pipeline $pipeline): string /** * List the pipelines to be written and how they affect existing pipelines. * @param array $pipelines loaded pipeline metadata - * @param array $targetPipelines matched existing pipeline entites + * @param array $targetPipelines matched existing pipeline entities */ protected function printPipelineUpdateInfo(array $pipelines, array $targetPipelines): void { @@ -410,7 +410,7 @@ protected function updatePipeline(?Pipeline $pipeline, array $data, RuntimeEnvir /** * Find out existing pipeline entity that corresponds to given loaded record. - * If ambigous, the user is interactively prompted to select the right pipeline. + * If ambiguous, the user is interactively prompted to select the right pipeline. * @param array $data pipeline structure loaded from manifest * @return Pipeline|null matching DB entity or null, if no match is found */ diff --git a/app/commands/security/ListExamEvents.php b/app/commands/security/ListExamEvents.php index c5c6be54a..8e5f0943e 100644 --- a/app/commands/security/ListExamEvents.php +++ b/app/commands/security/ListExamEvents.php @@ -4,7 +4,6 @@ use App\Model\Entity\GroupExamLock; use App\Model\Repository\GroupExamLocks; -use DateTime; use Exception; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; @@ -12,7 +11,7 @@ use Symfony\Component\Console\Input\InputOption; /** - * Lists all group exam lock records that occured in given time interval. + * Lists all group exam lock records that occurred in given time interval. * Locks are listed with related data in CSV format on the stdout. */ class ListExamEvents extends BaseCommand diff --git a/app/commands/security/ListSecurityEvents.php b/app/commands/security/ListSecurityEvents.php index c8e55c24d..07e2a8c4d 100644 --- a/app/commands/security/ListSecurityEvents.php +++ b/app/commands/security/ListSecurityEvents.php @@ -4,7 +4,6 @@ use App\Model\Entity\SecurityEvent; use App\Model\Repository\SecurityEvents; -use DateTime; use Exception; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; diff --git a/app/config/config.neon b/app/config/config.neon index 3c8b17da3..571fd0706 100644 --- a/app/config/config.neon +++ b/app/config/config.neon @@ -114,7 +114,7 @@ parameters: exerciseUrl: "%webapp.address%/app/exercises/{id}" shadowAssignmentUrl: "%webapp.address%/app/shadow-assignment/{id}" solutionUrl: "%webapp.address%/app/assignment/{assignmentId}/solution/{solutionId}" - referenceSolutiontUrl: "%webapp.address%/app/exercises/{exerciseId}/reference-solution/{solutionId}" + referenceSolutionUrl: "%webapp.address%/app/exercises/{exerciseId}/reference-solution/{solutionId}" forgottenPasswordUrl: "%webapp.address%/forgotten-password/change?{token}" # URL of web application where the password can be changed emailVerificationUrl: "%webapp.address%/email-verification?{token}" invitationUrl: "%webapp.address%/accept-invitation?{token}" diff --git a/app/exceptions/ApiException.php b/app/exceptions/ApiException.php index 0bdef4ed3..15e6d587f 100644 --- a/app/exceptions/ApiException.php +++ b/app/exceptions/ApiException.php @@ -13,7 +13,6 @@ */ class ApiException extends Exception { - /** @var string */ private $frontendErrorCode; /** @var array|null */ @@ -29,7 +28,7 @@ class ApiException extends Exception */ public function __construct( $msg = "Unexpected API error", - $code = IResponse::S500_INTERNAL_SERVER_ERROR, + $code = IResponse::S500_InternalServerError, $frontendErrorCode = FrontendErrorMappings::E500_000__INTERNAL_SERVER_ERROR, $frontendErrorParams = null, $previous = null diff --git a/app/exceptions/BadRequestException.php b/app/exceptions/BadRequestException.php index 182206941..f47c52873 100644 --- a/app/exceptions/BadRequestException.php +++ b/app/exceptions/BadRequestException.php @@ -23,11 +23,11 @@ public function __construct( string $msg = 'one or more parameters are missing', string $frontendErrorCode = FrontendErrorMappings::E400_000__BAD_REQUEST, $frontendErrorParams = null, - Exception $previous = null + ?Exception $previous = null ) { parent::__construct( "Bad Request - $msg", - IResponse::S400_BAD_REQUEST, + IResponse::S400_BadRequest, $frontendErrorCode, $frontendErrorParams, $previous diff --git a/app/exceptions/CASMissingInfoException.php b/app/exceptions/CASMissingInfoException.php index 247068a78..f442654a2 100644 --- a/app/exceptions/CASMissingInfoException.php +++ b/app/exceptions/CASMissingInfoException.php @@ -20,6 +20,6 @@ public function __construct( string $frontendErrorCode = FrontendErrorMappings::E409_000__CONFLICT, $frontendErrorParams = null ) { - parent::__construct($msg, IResponse::S409_CONFLICT, $frontendErrorCode, $frontendErrorParams); + parent::__construct($msg, IResponse::S409_Conflict, $frontendErrorCode, $frontendErrorParams); } } diff --git a/app/exceptions/CannotReceiveUploadedFileException.php b/app/exceptions/CannotReceiveUploadedFileException.php index a03417cae..fb8a30ea0 100644 --- a/app/exceptions/CannotReceiveUploadedFileException.php +++ b/app/exceptions/CannotReceiveUploadedFileException.php @@ -19,7 +19,7 @@ class CannotReceiveUploadedFileException extends ApiException */ public function __construct( string $message, - int $code = IResponse::S500_INTERNAL_SERVER_ERROR, + int $code = IResponse::S500_InternalServerError, string $frontendCode = FrontendErrorMappings::E500_001__CANNOT_RECEIVE_FILE, $frontendErrorParams = null ) { diff --git a/app/exceptions/ConfigException.php b/app/exceptions/ConfigException.php index 68acc4135..59e7e0119 100644 --- a/app/exceptions/ConfigException.php +++ b/app/exceptions/ConfigException.php @@ -6,7 +6,7 @@ use Nette\Http\IResponse; /** - * Exception concerning core module confugration. + * Exception concerning core module configuration. */ class ConfigException extends ApiException { diff --git a/app/exceptions/ExerciseCompilationException.php b/app/exceptions/ExerciseCompilationException.php index dc825ccef..c21112b2e 100644 --- a/app/exceptions/ExerciseCompilationException.php +++ b/app/exceptions/ExerciseCompilationException.php @@ -10,7 +10,6 @@ */ class ExerciseCompilationException extends ApiException { - /** * Create instance with further description. * @param string $msg description @@ -20,7 +19,7 @@ class ExerciseCompilationException extends ApiException */ public function __construct( string $msg = 'Please, check the exercise instructions', - $code = IResponse::S500_INTERNAL_SERVER_ERROR, + $code = IResponse::S500_InternalServerError, string $frontendErrorCode = FrontendErrorMappings::E500_300__EXERCISE_COMPILATION, $frontendErrorParams = null ) { diff --git a/app/exceptions/ExerciseCompilationSoftException.php b/app/exceptions/ExerciseCompilationSoftException.php index 6ddd00a9d..6327c91ab 100644 --- a/app/exceptions/ExerciseCompilationSoftException.php +++ b/app/exceptions/ExerciseCompilationSoftException.php @@ -10,7 +10,6 @@ */ class ExerciseCompilationSoftException extends ExerciseCompilationException { - /** * Constructor. * @param string $msg description @@ -22,6 +21,6 @@ public function __construct( string $frontendErrorCode = FrontendErrorMappings::E400_400__EXERCISE_COMPILATION, $frontendErrorParams = null ) { - parent::__construct($msg, IResponse::S400_BAD_REQUEST, $frontendErrorCode, $frontendErrorParams); + parent::__construct($msg, IResponse::S400_BadRequest, $frontendErrorCode, $frontendErrorParams); } } diff --git a/app/exceptions/ExerciseConfigException.php b/app/exceptions/ExerciseConfigException.php index 0506bfc13..722fc27b6 100644 --- a/app/exceptions/ExerciseConfigException.php +++ b/app/exceptions/ExerciseConfigException.php @@ -23,7 +23,7 @@ public function __construct( ) { parent::__construct( "Exercise configuration error - $msg", - IResponse::S400_BAD_REQUEST, + IResponse::S400_BadRequest, $frontendErrorCode, $frontendErrorParams ); diff --git a/app/exceptions/ForbiddenRequestException.php b/app/exceptions/ForbiddenRequestException.php index 4d0f10031..c62a36ce6 100644 --- a/app/exceptions/ForbiddenRequestException.php +++ b/app/exceptions/ForbiddenRequestException.php @@ -20,7 +20,7 @@ class ForbiddenRequestException extends ApiException */ public function __construct( string $msg = "Forbidden Request - Access denied", - $code = IResponse::S403_FORBIDDEN, + $code = IResponse::S403_Forbidden, string $frontendErrorCode = FrontendErrorMappings::E403_000__FORBIDDEN, $frontendErrorParams = null ) { diff --git a/app/exceptions/FrontendErrorMappings.php b/app/exceptions/FrontendErrorMappings.php index 9333d7232..8e3449f1b 100644 --- a/app/exceptions/FrontendErrorMappings.php +++ b/app/exceptions/FrontendErrorMappings.php @@ -19,7 +19,7 @@ class FrontendErrorMappings public const E400_004__UPLOADED_FILE_INVALID_SIZE = "400-004"; /** Per-partes upload is not completed yet */ public const E400_005__UPLOADED_FILE_PARTIAL = "400-005"; - /** Entity version is too old (concurrent edits occured) */ + /** Entity version is too old (concurrent edits occurred) */ public const E400_010__ENTITY_VERSION_TOO_OLD = "400-010"; /** Invalid credentials */ diff --git a/app/exceptions/InternalServerException.php b/app/exceptions/InternalServerException.php index abd3fd4b4..f6ce1e457 100644 --- a/app/exceptions/InternalServerException.php +++ b/app/exceptions/InternalServerException.php @@ -26,7 +26,7 @@ public function __construct( ) { parent::__construct( "Internal Server Error - $details", - IResponse::S500_INTERNAL_SERVER_ERROR, + IResponse::S500_InternalServerError, $frontendErrorCode, $frontendErrorParams, $previous diff --git a/app/exceptions/InvalidAccessTokenException.php b/app/exceptions/InvalidAccessTokenException.php index b83de9e46..86b03801c 100644 --- a/app/exceptions/InvalidAccessTokenException.php +++ b/app/exceptions/InvalidAccessTokenException.php @@ -17,7 +17,7 @@ public function __construct($token, $previous = null) { parent::__construct( "Access token '$token' is not valid.", - IResponse::S401_UNAUTHORIZED, + IResponse::S401_Unauthorized, FrontendErrorMappings::E401_002__INVALID_TOKEN, ["token" => $token], $previous diff --git a/app/exceptions/InvalidArgumentException.php b/app/exceptions/InvalidArgumentException.php index 017fceb05..974b51cfa 100644 --- a/app/exceptions/InvalidArgumentException.php +++ b/app/exceptions/InvalidArgumentException.php @@ -23,7 +23,7 @@ public function __construct( ) { parent::__construct( "Invalid Argument '$argument' - $msg", - IResponse::S400_BAD_REQUEST, + IResponse::S400_BadRequest, $frontendErrorCode, ["argument" => $argument] ); diff --git a/app/exceptions/InvalidExternalTokenException.php b/app/exceptions/InvalidExternalTokenException.php index b4f263a8d..6136af15f 100644 --- a/app/exceptions/InvalidExternalTokenException.php +++ b/app/exceptions/InvalidExternalTokenException.php @@ -24,7 +24,7 @@ public function __construct(string $token, string $reason = '', $previous = null parent::__construct( $message, - IResponse::S401_UNAUTHORIZED, + IResponse::S401_Unauthorized, FrontendErrorMappings::E401_002__INVALID_TOKEN, ["token" => $token], $previous diff --git a/app/exceptions/InvalidMembershipException.php b/app/exceptions/InvalidMembershipException.php index 4e7d8b778..312ca0470 100644 --- a/app/exceptions/InvalidMembershipException.php +++ b/app/exceptions/InvalidMembershipException.php @@ -22,7 +22,7 @@ public function __construct( ) { parent::__construct( "Invalid Membership Request - $msg", - IResponse::S400_BAD_REQUEST, + IResponse::S400_BadRequest, $frontendErrorCode, $frontendErrorParams ); diff --git a/app/exceptions/InvalidStateException.php b/app/exceptions/InvalidStateException.php index 8878c3794..fbb900a9b 100644 --- a/app/exceptions/InvalidStateException.php +++ b/app/exceptions/InvalidStateException.php @@ -22,7 +22,7 @@ public function __construct( ) { parent::__construct( "Invalid State - $msg", - IResponse::S500_INTERNAL_SERVER_ERROR, + IResponse::S500_InternalServerError, $frontendErrorCode, $frontendErrorParams ); diff --git a/app/exceptions/JobConfigLoadingException.php b/app/exceptions/JobConfigLoadingException.php index 7ae812170..34a553653 100644 --- a/app/exceptions/JobConfigLoadingException.php +++ b/app/exceptions/JobConfigLoadingException.php @@ -23,7 +23,7 @@ public function __construct( ) { parent::__construct( "Job configuration file cannot be opened or parsed - $msg", - IResponse::S400_BAD_REQUEST, + IResponse::S400_BadRequest, $frontendErrorCode, $frontendErrorParams ); diff --git a/app/exceptions/LdapConnectException.php b/app/exceptions/LdapConnectException.php index 584ba41eb..2dd59dd9d 100644 --- a/app/exceptions/LdapConnectException.php +++ b/app/exceptions/LdapConnectException.php @@ -16,7 +16,7 @@ public function __construct() { parent::__construct( 'Cannot connect to LDAP server. Please check your configuration.', - IResponse::S500_INTERNAL_SERVER_ERROR, + IResponse::S500_InternalServerError, FrontendErrorMappings::E500_002__LDAP_CONNECTION ); } diff --git a/app/exceptions/NoAccessTokenException.php b/app/exceptions/NoAccessTokenException.php index c1c812165..2858b245e 100644 --- a/app/exceptions/NoAccessTokenException.php +++ b/app/exceptions/NoAccessTokenException.php @@ -17,7 +17,7 @@ public function __construct() { parent::__construct( "You must provide an access token for this action.", - IResponse::S401_UNAUTHORIZED, + IResponse::S401_Unauthorized, FrontendErrorMappings::E401_001__NO_TOKEN ); } diff --git a/app/exceptions/NotFoundException.php b/app/exceptions/NotFoundException.php index 919e54b40..e2e964f97 100644 --- a/app/exceptions/NotFoundException.php +++ b/app/exceptions/NotFoundException.php @@ -25,7 +25,7 @@ public function __construct( ) { parent::__construct( "Not Found - $msg", - IResponse::S404_NOT_FOUND, + IResponse::S404_NotFound, $frontendErrorCode, $frontendErrorParams, $previous diff --git a/app/exceptions/NotImplementedException.php b/app/exceptions/NotImplementedException.php index 87d651e99..47d871956 100644 --- a/app/exceptions/NotImplementedException.php +++ b/app/exceptions/NotImplementedException.php @@ -5,7 +5,7 @@ use Nette\Http\IResponse; /** - * Actually not used for debbuging purposes but used in production and thrown + * Actually not used for debugging purposes but used in production and thrown * if user requested non-existing application route. */ class NotImplementedException extends ApiException @@ -16,8 +16,8 @@ class NotImplementedException extends ApiException public function __construct() { parent::__construct( - "This feature is not implemented. Contact the authors of the API for more information about the status of the API.", - IResponse::S501_NOT_IMPLEMENTED, + "This feature is not implemented. Contact the authors of the API for more information.", + IResponse::S501_NotImplemented, FrontendErrorMappings::E501_000__NOT_IMPLEMENTED ); } diff --git a/app/exceptions/NotReadyException.php b/app/exceptions/NotReadyException.php index dca89bd31..753bbc0ce 100644 --- a/app/exceptions/NotReadyException.php +++ b/app/exceptions/NotReadyException.php @@ -6,10 +6,9 @@ class NotReadyException extends ApiException { - public function __construct( $msg = "The resource is not ready yet", - $code = IResponse::S202_ACCEPTED, + $code = IResponse::S202_Accepted, string $frontendErrorCode = FrontendErrorMappings::E202_000__ACCEPTED, $frontendErrorParams = null, $previous = null diff --git a/app/exceptions/ParseException.php b/app/exceptions/ParseException.php index 8c3f723f5..e887e85a3 100644 --- a/app/exceptions/ParseException.php +++ b/app/exceptions/ParseException.php @@ -22,7 +22,7 @@ public function __construct( ) { parent::__construct( "Parsing error - $msg", - IResponse::S400_BAD_REQUEST, + IResponse::S400_BadRequest, $frontendErrorCode, $frontendErrorParams ); diff --git a/app/exceptions/SubmissionEvaluationFailedException.php b/app/exceptions/SubmissionEvaluationFailedException.php index cd1cd9ec2..8b8484f9d 100644 --- a/app/exceptions/SubmissionEvaluationFailedException.php +++ b/app/exceptions/SubmissionEvaluationFailedException.php @@ -22,7 +22,7 @@ public function __construct( ) { parent::__construct( "Submission Evaluation Failed - $msg", - IResponse::S500_INTERNAL_SERVER_ERROR, + IResponse::S500_InternalServerError, $frontendErrorCode, $frontendErrorParams ); diff --git a/app/exceptions/SubmissionFailedException.php b/app/exceptions/SubmissionFailedException.php index 2740ea005..79a53d669 100644 --- a/app/exceptions/SubmissionFailedException.php +++ b/app/exceptions/SubmissionFailedException.php @@ -22,7 +22,7 @@ public function __construct( ) { parent::__construct( "Submission Failed - $msg", - IResponse::S500_INTERNAL_SERVER_ERROR, + IResponse::S500_InternalServerError, $frontendErrorCode, $frontendErrorParams ); diff --git a/app/exceptions/UnauthorizedException.php b/app/exceptions/UnauthorizedException.php index 35d3dca6c..84f2863a6 100644 --- a/app/exceptions/UnauthorizedException.php +++ b/app/exceptions/UnauthorizedException.php @@ -15,10 +15,10 @@ class UnauthorizedException extends ApiException * @param string $frontendErrorCode */ public function __construct( - string $msg = "You must provide a valid access token or other specified means of authentication to be allowed to perform this request.", + string $msg = "You must provide a valid access token to perform this request.", string $frontendErrorCode = FrontendErrorMappings::E401_000__UNAUTHORIZED ) { - parent::__construct($msg, IResponse::S401_UNAUTHORIZED, $frontendErrorCode); + parent::__construct($msg, IResponse::S401_Unauthorized, $frontendErrorCode); } public function getAdditionalHttpHeaders() diff --git a/app/exceptions/UploadedFileException.php b/app/exceptions/UploadedFileException.php index f089b6e9e..149733f46 100644 --- a/app/exceptions/UploadedFileException.php +++ b/app/exceptions/UploadedFileException.php @@ -25,7 +25,7 @@ public function __construct( ) { parent::__construct( "Uploaded files error - $msg", - IResponse::S500_INTERNAL_SERVER_ERROR, + IResponse::S500_InternalServerError, $frontendErrorCode, $frontendErrorParams, $previous diff --git a/app/exceptions/WrongCredentialsException.php b/app/exceptions/WrongCredentialsException.php index 67f91299b..c19322e0e 100644 --- a/app/exceptions/WrongCredentialsException.php +++ b/app/exceptions/WrongCredentialsException.php @@ -21,7 +21,7 @@ public function __construct( string $frontendErrorCode = FrontendErrorMappings::E400_100__WRONG_CREDENTIALS, $frontendErrorParams = null ) { - parent::__construct($msg, IResponse::S400_BAD_REQUEST, $frontendErrorCode, $frontendErrorParams); + parent::__construct($msg, IResponse::S400_BadRequest, $frontendErrorCode, $frontendErrorParams); } public function getAdditionalHttpHeaders() diff --git a/app/exceptions/WrongHttpMethodException.php b/app/exceptions/WrongHttpMethodException.php index 2deba24b2..88f00d373 100644 --- a/app/exceptions/WrongHttpMethodException.php +++ b/app/exceptions/WrongHttpMethodException.php @@ -18,8 +18,8 @@ public function __construct(string $method) { $method = strtoupper($method); parent::__construct( - "This endpoint does not respond to $method HTTP requests, check the API documentation for more information.", - IResponse::S405_METHOD_NOT_ALLOWED, + "This endpoint does not respond to $method HTTP requests, check the API documentation for details.", + IResponse::S405_MethodNotAllowed, FrontendErrorMappings::E405_000__METHOD_NOT_ALLOWED, ["method" => $method] ); diff --git a/app/helpers/AnnotationsParser.php b/app/helpers/AnnotationsParser.php index 78357e184..659316334 100644 --- a/app/helpers/AnnotationsParser.php +++ b/app/helpers/AnnotationsParser.php @@ -4,8 +4,10 @@ * This file is part of the Nette Framework (https://nette.org) * Copyright (c) 2004 David Grudl (https://davidgrudl.com) * - * We have copied this form abanndoned Nette/Reflection module, so we can use the parse and extend it in the future. + * We have copied this form abanndoned Nette/Reflection module, so we can use the parser and extend it in the future. * For the original code, visit https://github.com/nette/reflection/blob/master/src/Reflection/AnnotationsParser.php + * + * News: After the great endpoint parameter specification refactoring, this may no longer be required. */ namespace App\Helpers; diff --git a/app/helpers/AnonymizationHelper.php b/app/helpers/AnonymizationHelper.php index 916ccc69f..5df36fbb6 100644 --- a/app/helpers/AnonymizationHelper.php +++ b/app/helpers/AnonymizationHelper.php @@ -4,7 +4,6 @@ use Nette; use Nette\Utils\Arrays; -use App\Model\Entity\Login; use App\Model\Entity\User; use App\Model\Repository\Users; use App\Model\Repository\Logins; @@ -34,7 +33,7 @@ class AnonymizationHelper protected $anonymizedName; /** - * @var string Suffix appended to an email addres of deleted user. + * @var string Suffix appended to an email address of deleted user. */ protected $deletedEmailSuffix; diff --git a/app/helpers/BasicAuthHelper.php b/app/helpers/BasicAuthHelper.php index 9c6e7f396..98b78af76 100644 --- a/app/helpers/BasicAuthHelper.php +++ b/app/helpers/BasicAuthHelper.php @@ -21,7 +21,9 @@ public static function getCredentials(IRequest $req) { $auth = $req->getHeader("Authorization"); if ($auth === null || str_starts_with($auth, "Basic ") === false) { - throw new HttpBasicAuthException("The request from backend-service must contain HTTP Basic authentication."); + throw new HttpBasicAuthException( + "The request from backend-service must contain HTTP Basic authentication." + ); } $encodedCredentials = Strings::substring($auth, strlen("Basic ")); diff --git a/app/helpers/BrokerProxy.php b/app/helpers/BrokerProxy.php index 9d5d0e655..a06a386a9 100644 --- a/app/helpers/BrokerProxy.php +++ b/app/helpers/BrokerProxy.php @@ -6,7 +6,6 @@ use App\Exceptions\SubmissionFailedException; use ZMQ; use ZMQContext; -use ZMQException; use ZMQPoll; use ZMQPollException; use ZMQSocket; @@ -52,7 +51,7 @@ public function __construct(array $config) /** * Start evaluation of new job. This means sending proper message to broker that we want this new - * job to be evaluated, receive confirmation that the message was successfuly received and finally + * job to be evaluated, receive confirmation that the message was successfully received and finally * receive confirmation if the evaluation can be processed or not (for example if there is worker * for that hwgroup available). * @param string $jobId Unique identifier of the new job diff --git a/app/helpers/Emails/EmailLatteExtension.php b/app/helpers/Emails/EmailLatteExtension.php index 968cf5def..34a8b1285 100644 --- a/app/helpers/Emails/EmailLatteExtension.php +++ b/app/helpers/Emails/EmailLatteExtension.php @@ -22,7 +22,7 @@ class EmailLatteExtension extends Latte\Extension private static $subject = null; /** - * Used both by the extension and to re-set the subjec before rendering. + * Used both by the extension and to re-set the subject before rendering. * @param string|null $subject */ public static function setSubject(?string $subject): void diff --git a/app/helpers/Emails/EmailLatteFactory.php b/app/helpers/Emails/EmailLatteFactory.php index f5421da65..5fc71a59a 100644 --- a/app/helpers/Emails/EmailLatteFactory.php +++ b/app/helpers/Emails/EmailLatteFactory.php @@ -2,7 +2,6 @@ namespace App\Helpers\Emails; -use Latte; use Latte\Engine; use Latte\Essential\Filters; use League\CommonMark\CommonMarkConverter; @@ -13,7 +12,6 @@ */ class EmailLatteFactory { - /** * Create latte engine for email templates with helper filters. * @return EmailLatteWrapper diff --git a/app/helpers/Emails/EmailLatteWrapper.php b/app/helpers/Emails/EmailLatteWrapper.php index 32c52b8f0..fd640bdbd 100644 --- a/app/helpers/Emails/EmailLatteWrapper.php +++ b/app/helpers/Emails/EmailLatteWrapper.php @@ -9,7 +9,6 @@ */ class EmailLatteWrapper { - private $latte; public function __construct(Engine $latte) diff --git a/app/helpers/Emails/EmailLocalizationHelper.php b/app/helpers/Emails/EmailLocalizationHelper.php index 6a2750672..e5bf9accf 100644 --- a/app/helpers/Emails/EmailLocalizationHelper.php +++ b/app/helpers/Emails/EmailLocalizationHelper.php @@ -121,20 +121,20 @@ function (User $user) { private static $localizations = [ EmailLocalizationHelper::CZECH_LOCALE => [ // this is actually not perfect, but it will do for now - 'y' => [ 1 => "rok", 2 => "roky", 5 => "let" ], - 'm' => [ 1 => "měsíc", 2 => "měsíce", 5 => "měsíců" ], - 'd' => [ 1 => "den", 2 => "dny", 5 => 'dní' ], - 'h' => [ 1 => "hodina", 2 => "hodiny", 5 => "hodin" ], - 'i' => [ 1 => "minuta", 2 => "minuty", 5 => "minut" ], - 's' => [ 1 => "vteřina", 2 => "vteřiny", 5 => "vteřin" ], + 'y' => [1 => "rok", 2 => "roky", 5 => "let"], + 'm' => [1 => "měsíc", 2 => "měsíce", 5 => "měsíců"], + 'd' => [1 => "den", 2 => "dny", 5 => 'dní'], + 'h' => [1 => "hodina", 2 => "hodiny", 5 => "hodin"], + 'i' => [1 => "minuta", 2 => "minuty", 5 => "minut"], + 's' => [1 => "vteřina", 2 => "vteřiny", 5 => "vteřin"], ], EmailLocalizationHelper::DEFAULT_LOCALE => [ // default (English) - 'y' => [ 1 => "year", 2 => "years" ], - 'm' => [ 1 => "month", 2 => "months" ], - 'd' => [ 1 => "day", 2 => "days" ], - 'h' => [ 1 => "hour", 2 => "hours" ], - 'i' => [ 1 => "minute", 2 => "minutes" ], - 's' => [ 1 => "second", 2 => "seconds" ], + 'y' => [1 => "year", 2 => "years"], + 'm' => [1 => "month", 2 => "months"], + 'd' => [1 => "day", 2 => "days"], + 'h' => [1 => "hour", 2 => "hours"], + 'i' => [1 => "minute", 2 => "minutes"], + 's' => [1 => "second", 2 => "seconds"], ] ]; @@ -158,7 +158,7 @@ private static function getDateIntervalLocalizationSuffix(int $value, array $suf /** * Return localized string with an informal description of relative time (date interval). * It writes out up to two the most significant values, so it is brief yet it scales from seconds to years. - * The interval is treated as absoluted value (ignoring the sign). + * The interval is treated as absolute value (ignoring the sign). * @param DateInterval $dateDiff interval to be displayed * @param string $locale identification of the language * @return string formatted relative time diff --git a/app/helpers/EntityMetadata/HwGroupMeta.php b/app/helpers/EntityMetadata/HwGroupMeta.php index 9a851e9f4..27b39cbbc 100644 --- a/app/helpers/EntityMetadata/HwGroupMeta.php +++ b/app/helpers/EntityMetadata/HwGroupMeta.php @@ -10,7 +10,6 @@ */ class HwGroupMeta { - private static $MEMORY_KEY = "memory"; private static $CPU_TIME_PER_TEST_KEY = "cpuTimePerTest"; private static $CPU_TIME_PER_EXERCISE_KEY = "cpuTimePerExercise"; diff --git a/app/helpers/EntityMetadata/Solution/SolutionParams.php b/app/helpers/EntityMetadata/Solution/SolutionParams.php index 66eff2df5..2e97c8476 100644 --- a/app/helpers/EntityMetadata/Solution/SolutionParams.php +++ b/app/helpers/EntityMetadata/Solution/SolutionParams.php @@ -10,8 +10,7 @@ */ class SolutionParams { - - const VARIABLES_KEY = "variables"; + public const VARIABLES_KEY = "variables"; /** * @var SubmitVariable[] diff --git a/app/helpers/Evaluation/EvaluationLoadingHelper.php b/app/helpers/Evaluation/EvaluationLoadingHelper.php index cfbafec20..cf11d9e71 100644 --- a/app/helpers/Evaluation/EvaluationLoadingHelper.php +++ b/app/helpers/Evaluation/EvaluationLoadingHelper.php @@ -68,7 +68,10 @@ public function loadEvaluation(Submission $submission): bool // the result cannot be loaded even though the result MUST be ready at this point $message = "Loading evaluation results failed with exception '{$e->getMessage()}'"; - if ($submission instanceof AssignmentSolutionSubmission || $submission instanceof ReferenceSolutionSubmission) { + if ( + $submission instanceof AssignmentSolutionSubmission + || $submission instanceof ReferenceSolutionSubmission + ) { $failure = SubmissionFailure::create(SubmissionFailure::TYPE_LOADING_FAILURE, $message); $submission->setFailure($failure); } else { diff --git a/app/helpers/Evaluation/EvaluationResults/EvaluationResults.php b/app/helpers/Evaluation/EvaluationResults/EvaluationResults.php index cf6abef82..3a2831d40 100644 --- a/app/helpers/Evaluation/EvaluationResults/EvaluationResults.php +++ b/app/helpers/Evaluation/EvaluationResults/EvaluationResults.php @@ -13,10 +13,10 @@ */ class EvaluationResults { - const JOB_ID_KEY = "job-id"; - const HARDWARE_GROUP_KEY = "hw-group"; - const RESULTS_KEY = "results"; - const TASK_ID_KEY = "task-id"; + public const JOB_ID_KEY = "job-id"; + public const HARDWARE_GROUP_KEY = "hw-group"; + public const RESULTS_KEY = "results"; + public const TASK_ID_KEY = "task-id"; /** @var string Hardware group identifier of the worker that processed the job */ private $hardwareGroup; @@ -94,7 +94,7 @@ public function __construct(array $rawResults, JobConfig $config) } /** - * Initialisation was OK + * Initialization was OK * @return boolean The result */ public function initOK() diff --git a/app/helpers/Evaluation/EvaluationResults/Loader.php b/app/helpers/Evaluation/EvaluationResults/Loader.php index 175690126..99dac16f8 100644 --- a/app/helpers/Evaluation/EvaluationResults/Loader.php +++ b/app/helpers/Evaluation/EvaluationResults/Loader.php @@ -12,7 +12,6 @@ */ class Loader { - /** * Factory method for parsing evaluation results from YAML string. * @param string $results YAML encoded results received from backend diff --git a/app/helpers/Evaluation/EvaluationResults/SandboxResults/ISandboxResults.php b/app/helpers/Evaluation/EvaluationResults/SandboxResults/ISandboxResults.php index ca56cd121..783a26e80 100644 --- a/app/helpers/Evaluation/EvaluationResults/SandboxResults/ISandboxResults.php +++ b/app/helpers/Evaluation/EvaluationResults/SandboxResults/ISandboxResults.php @@ -30,7 +30,7 @@ public function getUsedCpuTime(): float; /** * Get total amount of consumed memory - * @return int The ammout of memory the process allocated + * @return int The amount of memory the process allocated */ public function getUsedMemory(): int; @@ -42,7 +42,7 @@ public function getExitCode(): int; /** * Get exit signal that terminated the program - * @return int|null The signal number or null if the program exitted normally + * @return int|null The signal number or null if the program exited normally */ public function getExitSignal(): ?int; diff --git a/app/helpers/Evaluation/EvaluationResults/SandboxResults/SkippedSandboxResults.php b/app/helpers/Evaluation/EvaluationResults/SandboxResults/SkippedSandboxResults.php index f54ed3788..a39f81319 100644 --- a/app/helpers/Evaluation/EvaluationResults/SandboxResults/SkippedSandboxResults.php +++ b/app/helpers/Evaluation/EvaluationResults/SandboxResults/SkippedSandboxResults.php @@ -45,7 +45,7 @@ public function getExitCode(): int /** * Get exit signal that examined program - * @return int|null The signal number or null if the program exitted normally + * @return int|null The signal number or null if the program exited normally */ public function getExitSignal(): ?int { diff --git a/app/helpers/Evaluation/EvaluationResults/TaskResults/SkippedTaskResult.php b/app/helpers/Evaluation/EvaluationResults/TaskResults/SkippedTaskResult.php index 501d8f404..3dbb94984 100644 --- a/app/helpers/Evaluation/EvaluationResults/TaskResults/SkippedTaskResult.php +++ b/app/helpers/Evaluation/EvaluationResults/TaskResults/SkippedTaskResult.php @@ -2,14 +2,11 @@ namespace App\Helpers\EvaluationResults; -use App\Exceptions\ResultsLoadingException; - /** * Task results for skipped tasks */ class SkippedTaskResult extends TaskResult { - /** * Constructor * @param string $id Task ID for which skipped results will be created diff --git a/app/helpers/Evaluation/EvaluationStatus/IEvaluable.php b/app/helpers/Evaluation/EvaluationStatus/IEvaluable.php index 894ecca65..781b32bab 100644 --- a/app/helpers/Evaluation/EvaluationStatus/IEvaluable.php +++ b/app/helpers/Evaluation/EvaluationStatus/IEvaluable.php @@ -9,7 +9,6 @@ */ interface IEvaluable { - /** * Query if the evaluation is ready * @return boolean The result diff --git a/app/helpers/Evaluation/IExercise.php b/app/helpers/Evaluation/IExercise.php index a7e9b7030..ade0d436d 100644 --- a/app/helpers/Evaluation/IExercise.php +++ b/app/helpers/Evaluation/IExercise.php @@ -53,7 +53,9 @@ public function getExerciseEnvironmentConfigs(): Collection; * @param RuntimeEnvironment $environment * @return ExerciseEnvironmentConfig|null */ - public function getExerciseEnvironmentConfigByEnvironment(RuntimeEnvironment $environment): ?ExerciseEnvironmentConfig; + public function getExerciseEnvironmentConfigByEnvironment( + RuntimeEnvironment $environment + ): ?ExerciseEnvironmentConfig; /** * Get collection of limits belonging to exercise. @@ -67,7 +69,10 @@ public function getExerciseLimits(): Collection; * @param HardwareGroup $hwGroup * @return ExerciseLimits|null */ - public function getLimitsByEnvironmentAndHwGroup(RuntimeEnvironment $environment, HardwareGroup $hwGroup): ?ExerciseLimits; + public function getLimitsByEnvironmentAndHwGroup( + RuntimeEnvironment $environment, + HardwareGroup $hwGroup + ): ?ExerciseLimits; /** * Get score configuration entity which holds the calculator type and its configuration. diff --git a/app/helpers/Evaluation/ScoreCalculators/ScoreCalculatorAccessor.php b/app/helpers/Evaluation/ScoreCalculators/ScoreCalculatorAccessor.php index f90cbe004..5c5fd4c4a 100644 --- a/app/helpers/Evaluation/ScoreCalculators/ScoreCalculatorAccessor.php +++ b/app/helpers/Evaluation/ScoreCalculators/ScoreCalculatorAccessor.php @@ -31,7 +31,7 @@ public function __construct(array $calculators) foreach ($calculators as $calculator) { $id = $calculator->getId(); if (!empty($this->calculators[$id])) { - throw new InvalidArgumentException("Provided calculators contain duplicit IDs ($id)"); + throw new InvalidArgumentException("Provided calculators contain duplicate IDs ($id)"); } $this->calculators[$id] = $calculator; } diff --git a/app/helpers/Evaluation/ScoreCalculators/UniformScoreCalculator.php b/app/helpers/Evaluation/ScoreCalculators/UniformScoreCalculator.php index f2ca19051..c9215809d 100644 --- a/app/helpers/Evaluation/ScoreCalculators/UniformScoreCalculator.php +++ b/app/helpers/Evaluation/ScoreCalculators/UniformScoreCalculator.php @@ -2,11 +2,8 @@ namespace App\Helpers\Evaluation; -use App\Exceptions\SubmissionEvaluationFailedException; use App\Exceptions\ExerciseConfigException; use App\Helpers\Evaluation\IScoreCalculator; -use App\Helpers\Yaml; -use App\Helpers\YamlException; /** * Simple uniform score calculator. It does not have a config, computes arithmetic average of all tests. diff --git a/app/helpers/Evaluation/ScoreCalculators/UniversalScoreCalculator.php b/app/helpers/Evaluation/ScoreCalculators/UniversalScoreCalculator.php index ea9843c1d..3f7616f57 100644 --- a/app/helpers/Evaluation/ScoreCalculators/UniversalScoreCalculator.php +++ b/app/helpers/Evaluation/ScoreCalculators/UniversalScoreCalculator.php @@ -5,8 +5,6 @@ use App\Exceptions\SubmissionEvaluationFailedException; use App\Exceptions\ExerciseConfigException; use App\Helpers\Evaluation\IScoreCalculator; -use App\Helpers\Yaml; -use App\Helpers\YamlException; /** * Universal score calculator. @@ -76,7 +74,7 @@ public function getDefaultConfig(array $testNames) $rootNode = new AstNodeValue(); $rootNode->setValue(1.0); } else { - // bulild an expression that does the same as uniform calculator + // build an expression that does the same as uniform calculator $avgNode = new AstNodeAverage(); foreach ($testNames as $name) { $testNode = new AstNodeTestResult(); diff --git a/app/helpers/Evaluation/ScoreCalculators/UniversalScoreCalculator/AstNode.php b/app/helpers/Evaluation/ScoreCalculators/UniversalScoreCalculator/AstNode.php index 4af876b62..f95b355b6 100644 --- a/app/helpers/Evaluation/ScoreCalculators/UniversalScoreCalculator/AstNode.php +++ b/app/helpers/Evaluation/ScoreCalculators/UniversalScoreCalculator/AstNode.php @@ -56,7 +56,7 @@ public static function createFromConfig(array $config): AstNode if (!array_key_exists(self::KEY_TYPE, $config)) { throw new AstNodeException("Node type is not specified in the score config."); } - + $type = $config[self::KEY_TYPE]; if (!array_key_exists($type, $types)) { throw new AstNodeException("Unknown AST node type '$type' found in the score config."); @@ -138,13 +138,13 @@ public function addChild(AstNode $child) /** * Perform internal validation of the node itself (not the subtree). * This method stands aside, so it can be reused and the main interface - * (validate() method) does not have to be overriden in derived classes. + * (validate() method) does not have to be overridden in derived classes. * @param array $testNames List of allowed test names (array of strings) * @throws AstNodeException if something is not valid */ protected function internalValidation(array $testNames = []) { - // expected to be overriden in derived classes + // expected to be overridden in derived classes } /** @@ -164,7 +164,7 @@ public function validate(array $testNames = []) $this->internalValidation($testNames); } - + /** * Compute the value of this node. * @param array $testResults Array with test results (keys are test names) which may be used in evaluation. diff --git a/app/helpers/Evaluation/ScoreCalculators/UniversalScoreCalculator/AstNodeBinary.php b/app/helpers/Evaluation/ScoreCalculators/UniversalScoreCalculator/AstNodeBinary.php index 1c3bbde0a..cfc780564 100644 --- a/app/helpers/Evaluation/ScoreCalculators/UniversalScoreCalculator/AstNodeBinary.php +++ b/app/helpers/Evaluation/ScoreCalculators/UniversalScoreCalculator/AstNodeBinary.php @@ -18,7 +18,7 @@ protected function internalValidation(array $testNames = []) ); } } - + public function addChild(AstNode $child) { if (count($this->children) >= 2) { diff --git a/app/helpers/Evaluation/ScoreCalculators/UniversalScoreCalculator/AstNodeException.php b/app/helpers/Evaluation/ScoreCalculators/UniversalScoreCalculator/AstNodeException.php index f979282cb..543989411 100644 --- a/app/helpers/Evaluation/ScoreCalculators/UniversalScoreCalculator/AstNodeException.php +++ b/app/helpers/Evaluation/ScoreCalculators/UniversalScoreCalculator/AstNodeException.php @@ -5,8 +5,6 @@ use Exception; /** - * Exception spcialization used for errors in AST representation of universal score config. + * Exception specialization used for errors in AST representation of universal score config. */ -class AstNodeException extends Exception -{ -} +class AstNodeException extends Exception {} diff --git a/app/helpers/Evaluation/ScoreCalculators/UniversalScoreCalculator/Nodes/AstNodeDivision.php b/app/helpers/Evaluation/ScoreCalculators/UniversalScoreCalculator/Nodes/AstNodeDivision.php index e6a486161..4e7ff4051 100644 --- a/app/helpers/Evaluation/ScoreCalculators/UniversalScoreCalculator/Nodes/AstNodeDivision.php +++ b/app/helpers/Evaluation/ScoreCalculators/UniversalScoreCalculator/Nodes/AstNodeDivision.php @@ -3,7 +3,7 @@ namespace App\Helpers\Evaluation; /** - * Class representing binary function that comuptes A / B. + * Class representing binary function that computes A / B. * If B == 0, the result is (unexpectedly) zero. */ class AstNodeDivision extends AstNodeBinary diff --git a/app/helpers/Evaluation/ScoreCalculators/WeightedScoreCalculator.php b/app/helpers/Evaluation/ScoreCalculators/WeightedScoreCalculator.php index cc8b56448..bfb557b43 100644 --- a/app/helpers/Evaluation/ScoreCalculators/WeightedScoreCalculator.php +++ b/app/helpers/Evaluation/ScoreCalculators/WeightedScoreCalculator.php @@ -5,8 +5,6 @@ use App\Exceptions\SubmissionEvaluationFailedException; use App\Exceptions\ExerciseConfigException; use App\Helpers\Evaluation\IScoreCalculator; -use App\Helpers\Yaml; -use App\Helpers\YamlException; /** * Weighted score calculator. It expect config in structured format such as: @@ -95,7 +93,7 @@ private function verifyTestNames(array $testWeights, array $testNames) return true; } - + /** * @param mixed $scoreConfig Structure containing configuration of the weights * @param array $testNames List of known test names (if empty, no check on names is performed) diff --git a/app/helpers/Extensions/ExtensionConfig.php b/app/helpers/Extensions/ExtensionConfig.php index e16dbc7af..a5977a019 100644 --- a/app/helpers/Extensions/ExtensionConfig.php +++ b/app/helpers/Extensions/ExtensionConfig.php @@ -73,7 +73,7 @@ class ExtensionConfig private array $userRoles = []; /** - * List of eligible user external login types. A user must hava at least one of these logins to see the extension. + * List of eligible user external login types. A user must have at least one of these logins to see the extension. * Empty list = no external logins are required. */ private array $userExternalLogins = []; @@ -97,7 +97,7 @@ public function __construct(array $config) $this->tokenScopes = Arrays::get( $config, ["token", "scopes"], - [ TokenScope::MASTER, TokenScope::REFRESH ] + [TokenScope::MASTER, TokenScope::REFRESH] ) ?? []; $this->tokenUserId = Arrays::get($config, ["token", "user"], null); $this->instances = Arrays::get($config, "instances", []) ?? []; diff --git a/app/helpers/ExternalLogin/ExternalServiceAuthenticator.php b/app/helpers/ExternalLogin/ExternalServiceAuthenticator.php index b9e4e6fc1..0af27f098 100644 --- a/app/helpers/ExternalLogin/ExternalServiceAuthenticator.php +++ b/app/helpers/ExternalLogin/ExternalServiceAuthenticator.php @@ -87,7 +87,7 @@ public function __construct( 'jwtSecret' => $auth['jwtSecret'], 'expiration' => Arrays::get($auth, 'expiration', 60), 'defaultRole' => Arrays::get($auth, 'defaultRole', null), - // if set, users may register even when extrnal authenticator does not provide role + // if set, users may register even when external authenticator does not provide role 'usedAlgorithm' => Arrays::get($auth, 'jwtAlgorithm', 'HS256'), 'extraIds' => Arrays::get($auth, 'extraIds', []), ]; @@ -125,12 +125,12 @@ public function hasAuthenticator(string $name): bool * @param string $authName name of the external authenticator * @param string $token form the external authentication service * @param string|null $instanceId identifier of an instance where the user should be registered - * (this may be overriden by a value in the token) + * (this may be overridden by a value in the token) * @return User * @throws BadRequestException * @throws WrongCredentialsException */ - public function authenticate(string $authName, string $token, string $instanceId = null): User + public function authenticate(string $authName, string $token, ?string $instanceId = null): User { $user = null; $decodedToken = $this->decodeToken($authName, $token); @@ -216,7 +216,7 @@ public function authenticate(string $authName, string $token, string $instanceId private function decodeToken(string $authName, string $token) { if (!$this->hasAuthenticator($authName)) { - throw new BadRequestException("Unkown external authenticator name '$authName'."); + throw new BadRequestException("Unknown external authenticator name '$authName'."); } $authenticator = $this->authenticators[$authName]; @@ -257,13 +257,13 @@ private function tryConnect(string $authName, UserData $userData): ?User * @param object $decodedToken which is searched for instanceId key * @param string $instanceId instance suggested externally */ - private function getInstance($decodedToken, string $instanceId = null): ?Instance + private function getInstance($decodedToken, ?string $instanceId = null): ?Instance { if (!empty($decodedToken->instanceId)) { $instanceId = $decodedToken->instanceId; } - // fetch the enetity from DB + // fetch the entity from DB if ($instanceId) { $instance = $this->instances->get($instanceId); if (!$instance) { @@ -311,7 +311,7 @@ private function handleExtraIds(User $user, $decodedToken, array $allowedService $extUser = $this->externalLogins->getUser($service, $eid); if ($extUser) { // a user with given ID exists if ($extUser->getId() !== $user->getId()) { - // Identity crysis! ID belongs to another user... + // Identity crisis! ID belongs to another user... $this->failureHelper->report( FailureHelper::TYPE_API_ERROR, sprintf( diff --git a/app/helpers/FileStorage/File/ArchivedImmutableFile.php b/app/helpers/FileStorage/File/ArchivedImmutableFile.php index 08b2a7f7d..3f2e46cd7 100644 --- a/app/helpers/FileStorage/File/ArchivedImmutableFile.php +++ b/app/helpers/FileStorage/File/ArchivedImmutableFile.php @@ -59,8 +59,8 @@ class ArchivedImmutableFile implements IImmutableFile public function __construct( string $archivePath, string $entry, - string $storagePath = null, - TmpFilesHelper $tmpFilesHelper = null + ?string $storagePath = null, + ?TmpFilesHelper $tmpFilesHelper = null ) { $this->archivePath = $archivePath; $this->entry = $entry; @@ -134,7 +134,7 @@ public function getContents(int $sizeLimit = 0): string if ($contents === false) { throw new FileStorageException( - "The ZIP archive is unable to retrive contents of entry '$this->entry'", + "The ZIP archive is unable to retrieve contents of entry '$this->entry'", $this->archivePath ); } diff --git a/app/helpers/FileStorage/FileStorageException.php b/app/helpers/FileStorage/FileStorageException.php index 1dd311d14..6bbc7cbd3 100644 --- a/app/helpers/FileStorage/FileStorageException.php +++ b/app/helpers/FileStorage/FileStorageException.php @@ -15,15 +15,15 @@ class FileStorageException extends Exception /** * Creates instance with further description. * @param string $msg description - * @param string $path name of the related file/direcroty that caused the exception + * @param string $path name of the related file/directory that caused the exception * @param Exception $previous Previous exception */ public function __construct( string $msg = 'Unexpected file storage error', - string $path = null, + ?string $path = null, $previous = null ) { - parent::__construct($msg, IResponse::S500_INTERNAL_SERVER_ERROR, $previous); + parent::__construct($msg, IResponse::S500_InternalServerError, $previous); $this->path = $path; } } diff --git a/app/helpers/FileStorage/IFileStorage.php b/app/helpers/FileStorage/IFileStorage.php index 79b58c0f0..ac136b003 100644 --- a/app/helpers/FileStorage/IFileStorage.php +++ b/app/helpers/FileStorage/IFileStorage.php @@ -103,7 +103,7 @@ public function delete(string $path): bool; /** * Garbage collector implemented over filesystem. Helps to manage tmp storages. * Note: it is valid if the implementation performs no deletions, if GC is handled by other means. - * @param string $glob wildcard pattern (relative storage paths) targetting files for deletion (not inside ZIPs!) + * @param string $glob wildcard pattern (relative storage paths) targeting files for deletion (not inside ZIPs!) * @param int $threshold unix timestamp with the threshold time (older files are removed) * @return int number of files removed */ diff --git a/app/helpers/FileStorage/IImmutableFile.php b/app/helpers/FileStorage/IImmutableFile.php index 839bb5af7..d997679fe 100644 --- a/app/helpers/FileStorage/IImmutableFile.php +++ b/app/helpers/FileStorage/IImmutableFile.php @@ -37,7 +37,7 @@ public function getSize(): int; public function getTime(): int; /** - * Retrive the entire file contents as a (binary) string. + * Retrieve the entire file contents as a (binary) string. * @param int $sizeLimit maximal length of the result, zero means no limit * @return string */ @@ -64,7 +64,7 @@ public function isZipArchive(): bool; public function getZipEntries(): array; /** - * Retrive the entire file and save it to local path. + * Retrieve the entire file and save it to local path. * @param string $path */ public function saveAs(string $path): void; diff --git a/app/helpers/FileStorage/LocalStorage/LocalFileStorage.php b/app/helpers/FileStorage/LocalStorage/LocalFileStorage.php index b2c6e29e2..e8503162e 100644 --- a/app/helpers/FileStorage/LocalStorage/LocalFileStorage.php +++ b/app/helpers/FileStorage/LocalStorage/LocalFileStorage.php @@ -73,12 +73,12 @@ private static function normalizePath(string $path): string /** * Decode a storage path. * @param string $path path is also normalized (that is why it is passed by reference) - * @param bool|null $exists If true/false, (non)existence checks are peformed, null = no checks. + * @param bool|null $exists If true/false, (non)existence checks are performed, null = no checks. * Checks are performed on real path only (not inside ZIP archives). * @param bool $mkdir whether to make sure all underlying sub-directories exist (mkdir if necessary) * @return array a tuple containing real path (first) and ZIP file entry or null (second) */ - private function decodePath(string &$path, bool $exists = null, $mkdir = false): array + private function decodePath(string &$path, ?bool $exists = null, $mkdir = false): array { $tokens = explode('#', $path, 2); array_push($tokens, null); // make sure second item always exists @@ -97,7 +97,7 @@ private function decodePath(string &$path, bool $exists = null, $mkdir = false): } if ($exists === false && !$zipEntry) { - // check the file does not exist (skipped for zip entries, since we are not openning the ZIP archive here) + // check the file does not exist (skipped for zip entries, since we are not opening the ZIP archive here) if (file_exists($realPath)) { throw new FileStorageException("File already exists.", $path); } @@ -295,7 +295,7 @@ public function copy(string $src, string $dst, bool $overwrite = false): void } if ($srcZip && $dstZip && $srcReal === $dstReal) { - // copy witin one archive -> use ZipFileStorage implementation + // copy within one archive -> use ZipFileStorage implementation $zip = new ZipFileStorage($this->tmpFilesHelper, $srcReal, null, false); $zip->copy($srcZip, $dstZip, $overwrite); $zip->close(); @@ -354,12 +354,12 @@ public function move(string $src, string $dst, bool $overwrite = false): void } if ($srcZip && $dstZip && $srcReal === $dstReal) { - // move witin one archive + // move within one archive $zip = new ZipFileStorage($this->tmpFilesHelper, $srcReal, null, false); $zip->move($srcZip, $dstZip, $overwrite); $zip->close(); } elseif ($srcZip || $dstZip) { - // move with some archive involvment, but not simply in one archive -> fallback to copy + // move with some archive involvement, but not simply in one archive -> fallback to copy $this->copy($src, $dst, $overwrite); if (!$this->delete($src)) { throw new FileStorageException("Unable to remove source file after copy-moving procedure.", $src); @@ -475,7 +475,7 @@ public function deleteByFilter(string $prefix, callable $filter): int } if (!is_dir($root) || !is_writeable($root)) { - return 0; // nothinth to do + return 0; // nothing to do } $rootDirLen = strlen($this->rootDirectory ?? '') + 1; // plus 1 for '/'; diff --git a/app/helpers/FileStorageManager.php b/app/helpers/FileStorageManager.php index a8065c33e..c1aac9168 100644 --- a/app/helpers/FileStorageManager.php +++ b/app/helpers/FileStorageManager.php @@ -204,7 +204,7 @@ public function storeUploadedFile(UploadedFile $fileRecord, FileUpload $fileData } /** - * Internal function used for concanenating partial file chunks. + * Internal function used for concatenating partial file chunks. * @param string $path file with next chunk to be appended * @param resource $targetStream where the file should be appended */ @@ -240,7 +240,7 @@ private function appendFileToStream(string $path, $targetStream) public function assembleUploadedPartialFile(UploadedPartialFile $partFile, UploadedFile $file): void { if (!$partFile->isUploadComplete()) { - throw new FileStorageException("Unable to assemble partal file when the upload was not completed yet."); + throw new FileStorageException("Unable to assemble partial file when the upload was not completed yet."); } $dstPath = $this->getUploadedFilePath($file); @@ -372,7 +372,7 @@ public function storeUploadedAttachmentFile(UploadedFile $uploadedFile, Attachme } /** - * Retrieve an atttachment file (file attached to specification of an exercise/assignment). + * Retrieve an attachment file (file attached to specification of an exercise/assignment). * @param AttachmentFile $file * @return IImmutableFile|null a file object or null if no such file exists */ @@ -383,7 +383,7 @@ public function getAttachmentFile(AttachmentFile $file): ?IImmutableFile } /** - * Remove an atttachment file (file attached to specification of an exercise/assignment). + * Remove an attachment file (file attached to specification of an exercise/assignment). * @param AttachmentFile $file * @return bool whether the file has been actually deleted (false = it does not exist) */ @@ -477,9 +477,9 @@ public function storeUploadedSolutionZipArchive(Solution $solution, UploadedFile /** * Retrieve a solution file or the entire archive. * @param Solution $solution - * @param string|null $file name of the file to be retrieved; entire archive is retrievd if null + * @param string|null $file name of the file to be retrieved; entire archive is retrieved if null */ - public function getSolutionFile(Solution $solution, string $file = null): ?IImmutableFile + public function getSolutionFile(Solution $solution, ?string $file = null): ?IImmutableFile { $path = $this->getSolutionArchivePath($solution); $path = $file ? "$path#$file" : $path; diff --git a/app/helpers/GeneralStatsHelper.php b/app/helpers/GeneralStatsHelper.php index 19aec84f6..7c497d9f7 100644 --- a/app/helpers/GeneralStatsHelper.php +++ b/app/helpers/GeneralStatsHelper.php @@ -109,7 +109,7 @@ class GeneralStats /** - * This helper gathers multiple statistics (typicaly numbers of new entites) + * This helper gathers multiple statistics (typically numbers of new entities) * over given period of time. */ class GeneralStatsHelper diff --git a/app/helpers/JobConfig/BoundDirectoryConfig.php b/app/helpers/JobConfig/BoundDirectoryConfig.php index aacfd0aee..f7db4ec91 100644 --- a/app/helpers/JobConfig/BoundDirectoryConfig.php +++ b/app/helpers/JobConfig/BoundDirectoryConfig.php @@ -10,11 +10,11 @@ class BoundDirectoryConfig { /** Source folder key */ - const SRC_KEY = "src"; + public const SRC_KEY = "src"; /** Destination folder key */ - const DST_KEY = "dst"; + public const DST_KEY = "dst"; /** Mode key */ - const MODE_KEY = "mode"; + public const MODE_KEY = "mode"; /** @var string Source folder for bound directory */ private $source = ""; diff --git a/app/helpers/JobConfig/JobConfig.php b/app/helpers/JobConfig/JobConfig.php index d782e078d..f6f2e0017 100644 --- a/app/helpers/JobConfig/JobConfig.php +++ b/app/helpers/JobConfig/JobConfig.php @@ -9,7 +9,7 @@ /** * Stores all possible information about some particular job. - * Job datas are parsed from structured configuration given at construction. + * Job data are parsed from structured configuration given at construction. */ class JobConfig { @@ -54,7 +54,7 @@ public function setSubmissionHeader(SubmissionHeader $header) } /** - * Get the identificator of this job including the type + * Get the identification of this job including the type * @return string */ public function getJobId(): string @@ -63,7 +63,7 @@ public function getJobId(): string } /** - * Get the identificator of this job without the type + * Get the identification of this job without the type * @return string */ public function getId(): string @@ -81,7 +81,7 @@ public function getJobType(): string } /** - * Set the identificator of this job + * Set the identification of this job * @param string $jobId * @return $this */ diff --git a/app/helpers/JobConfig/JobId.php b/app/helpers/JobConfig/JobId.php index 59e0ea5bd..97b33c38e 100644 --- a/app/helpers/JobConfig/JobId.php +++ b/app/helpers/JobConfig/JobId.php @@ -10,9 +10,9 @@ class JobId { /** Separator used in ID */ - const SEPARATOR = "_"; + public const SEPARATOR = "_"; /** Allowed types which can be used in ID */ - const ALLOWED_TYPES = array("student", "reference"); + public const ALLOWED_TYPES = array("student", "reference"); /** @var string Identification of the job */ private $id; diff --git a/app/helpers/JobConfig/Limits/Limits.php b/app/helpers/JobConfig/Limits/Limits.php index 6906b1a4b..5cec5c3a1 100644 --- a/app/helpers/JobConfig/Limits/Limits.php +++ b/app/helpers/JobConfig/Limits/Limits.php @@ -180,7 +180,7 @@ public function setMemoryLimit(int $memory) } /** - * Gets number of processes/threads which can be created in sandboxed program. + * Gets number of processes/threads which can be created in sand-boxed program. * @return int Number of processes/threads */ public function getParallel(): int @@ -220,7 +220,7 @@ public function setDiskSize(int $size) } /** - * Gets maximum number of opened files in sandboxed application. + * Gets maximum number of opened files in sand-boxed application. * @return int Number of files */ public function getDiskFiles(): int diff --git a/app/helpers/JobConfig/Loader.php b/app/helpers/JobConfig/Loader.php index 3ad59a15a..39c0329f9 100644 --- a/app/helpers/JobConfig/Loader.php +++ b/app/helpers/JobConfig/Loader.php @@ -72,7 +72,7 @@ public function loadBoundDirectoryConfig($data, $taskId = ""): BoundDirectoryCon if (!isset($data[BoundDirectoryConfig::SRC_KEY])) { throw new JobConfigLoadingException( "Task '" . $taskId . "': bound directory does not contain required field '" - . BoundDirectoryConfig::SRC_KEY . "'" + . BoundDirectoryConfig::SRC_KEY . "'" ); } $boundDir->setSource($data[BoundDirectoryConfig::SRC_KEY]); @@ -81,7 +81,7 @@ public function loadBoundDirectoryConfig($data, $taskId = ""): BoundDirectoryCon if (!isset($data[BoundDirectoryConfig::DST_KEY])) { throw new JobConfigLoadingException( "Task '" . $taskId . "': bound directory does not contain required field '" - . BoundDirectoryConfig::DST_KEY . "'" + . BoundDirectoryConfig::DST_KEY . "'" ); } $boundDir->setDestination($data[BoundDirectoryConfig::DST_KEY]); @@ -90,7 +90,7 @@ public function loadBoundDirectoryConfig($data, $taskId = ""): BoundDirectoryCon if (!isset($data[BoundDirectoryConfig::MODE_KEY])) { throw new JobConfigLoadingException( "Task '" . $taskId . "': bound directory does not contain required field '" - . BoundDirectoryConfig::MODE_KEY . "'" + . BoundDirectoryConfig::MODE_KEY . "'" ); } $boundDir->setMode($data[BoundDirectoryConfig::MODE_KEY]); @@ -119,13 +119,13 @@ public function loadLimits($data, $taskId = ""): Limits if (!isset($data[Limits::HW_GROUP_ID_KEY])) { throw new JobConfigLoadingException( "Task '" . $taskId . "': sandbox limits section does not contain required field '" - . Limits::HW_GROUP_ID_KEY . "'" + . Limits::HW_GROUP_ID_KEY . "'" ); } $limits->setId($data[Limits::HW_GROUP_ID_KEY]); unset($data[Limits::HW_GROUP_ID_KEY]); - // *** LOAD OPTIONAL DATAS + // *** LOAD OPTIONAL DATA if (isset($data[Limits::TIME_KEY])) { $limits->setTimeLimit(floatval($data[Limits::TIME_KEY])); @@ -199,7 +199,7 @@ public function loadSandboxConfig($data, $taskId = ""): SandboxConfig if (!isset($data[SandboxConfig::NAME_KEY])) { throw new JobConfigLoadingException( "Task '" . $taskId . "': sandbox section does not contain required field '" - . SandboxConfig::NAME_KEY . "'" + . SandboxConfig::NAME_KEY . "'" ); } $sandboxConfig->setName($data[SandboxConfig::NAME_KEY]); @@ -298,7 +298,7 @@ public function loadTask($data): Task if (!isset($data[Task::CMD_KEY][Task::CMD_BIN_KEY])) { throw new JobConfigLoadingException( "Task '" . $taskId . "' does not contain required field '" - . Task::CMD_KEY . "." . Task::CMD_BIN_KEY . "'" + . Task::CMD_KEY . "." . Task::CMD_BIN_KEY . "'" ); } $task->setCommandBinary($data[Task::CMD_KEY][Task::CMD_BIN_KEY]); diff --git a/app/helpers/JobConfig/SandboxConfig.php b/app/helpers/JobConfig/SandboxConfig.php index 890bd41d1..f9acc1f09 100644 --- a/app/helpers/JobConfig/SandboxConfig.php +++ b/app/helpers/JobConfig/SandboxConfig.php @@ -13,27 +13,27 @@ class SandboxConfig { /** Sandbox name key */ - const NAME_KEY = "name"; + public const NAME_KEY = "name"; /** Stdin config key */ - const STDIN_KEY = "stdin"; + public const STDIN_KEY = "stdin"; /** Stdout config key */ - const STDOUT_KEY = "stdout"; + public const STDOUT_KEY = "stdout"; /** Stderr config key */ - const STDERR_KEY = "stderr"; + public const STDERR_KEY = "stderr"; /** Stderr-to-stdout config key */ - const STDERR_TO_STDOUT_KEY = "stderr-to-stdout"; + public const STDERR_TO_STDOUT_KEY = "stderr-to-stdout"; /** Output config key */ - const OUTPUT_KEY = "output"; - /** Carboncopy stdout key */ - const CARBONCOPY_STDOUT_KEY = "carboncopy-stdout"; - /** Carboncopy stderr key */ - const CARBONCOPY_STDERR_KEY = "carboncopy-stderr"; + public const OUTPUT_KEY = "output"; + /** Carbon copy stdout key */ + public const CARBONCOPY_STDOUT_KEY = "carboncopy-stdout"; + /** Carbon copy stderr key */ + public const CARBONCOPY_STDERR_KEY = "carboncopy-stderr"; /** Change directory key */ - const CHDIR_KEY = "chdir"; + public const CHDIR_KEY = "chdir"; /** Working directory key */ - const WORKING_DIRECTORY_KEY = "working-directory"; + public const WORKING_DIRECTORY_KEY = "working-directory"; /** Limits collection key */ - const LIMITS_KEY = "limits"; + public const LIMITS_KEY = "limits"; /** @var string Sandbox name */ private $name = ""; @@ -47,9 +47,9 @@ class SandboxConfig private $stderrToStdout = false; /** @var bool Output from stdout and stderr will be written to result yaml */ private $output = false; - /** @var string|null Standard output carboncopy file */ + /** @var string|null Standard output carbon copy file */ private $carboncopyStdout = null; - /** @var string|null Standard error carboncopy file */ + /** @var string|null Standard error carbon copy file */ private $carboncopyStderr = null; /** @var string|null Change directory */ protected $chdir = null; @@ -181,7 +181,7 @@ public function setOutput(bool $output) } /** - * Return standard output carboncopy file. + * Return standard output carbon copy file. * @return string|null */ public function getCarboncopyStdout() @@ -190,7 +190,7 @@ public function getCarboncopyStdout() } /** - * Set output carboncopy file. + * Set output carbon copy file. * @param string $stdout * @return $this */ @@ -201,7 +201,7 @@ public function setCarboncopyStdout($stdout) } /** - * Get standard error carboncopy file. + * Get standard error carbon copy file. * @return string|null */ public function getCarboncopyStderr() @@ -210,7 +210,7 @@ public function getCarboncopyStderr() } /** - * Set error carboncopy file. + * Set error carbon copy file. * @param string $stderr * @return $this */ @@ -221,7 +221,7 @@ public function setCarboncopyStderr($stderr) } /** - * Get directory in which sandboxed program will be executed. + * Get directory in which sand-boxed program will be executed. * @return string|null */ public function getChdir() diff --git a/app/helpers/JobConfig/SubmissionHeader.php b/app/helpers/JobConfig/SubmissionHeader.php index d9b548f0d..7fca370fe 100644 --- a/app/helpers/JobConfig/SubmissionHeader.php +++ b/app/helpers/JobConfig/SubmissionHeader.php @@ -48,7 +48,7 @@ public function getJobId(): string } /** - * Set job identification alogside with its type. + * Set job identification alongside with its type. * @param string $jobId identification of job * @return $this */ diff --git a/app/helpers/JobConfig/Tasks/EvaluationTaskType.php b/app/helpers/JobConfig/Tasks/EvaluationTaskType.php index fd39f1e36..9d6360576 100644 --- a/app/helpers/JobConfig/Tasks/EvaluationTaskType.php +++ b/app/helpers/JobConfig/Tasks/EvaluationTaskType.php @@ -10,7 +10,7 @@ class EvaluationTaskType { /** Evaluation task type value */ - const TASK_TYPE = "evaluation"; + public const TASK_TYPE = "evaluation"; /** @var Task Evaluation task */ private $task; diff --git a/app/helpers/JobConfig/Tasks/ExecutionTaskType.php b/app/helpers/JobConfig/Tasks/ExecutionTaskType.php index da4f5dafd..47afe6a42 100644 --- a/app/helpers/JobConfig/Tasks/ExecutionTaskType.php +++ b/app/helpers/JobConfig/Tasks/ExecutionTaskType.php @@ -11,7 +11,7 @@ class ExecutionTaskType { /** Execution task type value */ - const TASK_TYPE = "execution"; + public const TASK_TYPE = "execution"; /** @var Task Execution task */ private $task; diff --git a/app/helpers/JobConfig/Tasks/InitiationTaskType.php b/app/helpers/JobConfig/Tasks/InitiationTaskType.php index 54137c8e6..6d1a71601 100644 --- a/app/helpers/JobConfig/Tasks/InitiationTaskType.php +++ b/app/helpers/JobConfig/Tasks/InitiationTaskType.php @@ -10,7 +10,7 @@ class InitiationTaskType { /** Initiation task type value */ - const TASK_TYPE = "initiation"; + public const TASK_TYPE = "initiation"; /** @var Task Initiation task */ private $task; diff --git a/app/helpers/JobConfig/TestConfig.php b/app/helpers/JobConfig/TestConfig.php index 2950e43df..0772136a9 100644 --- a/app/helpers/JobConfig/TestConfig.php +++ b/app/helpers/JobConfig/TestConfig.php @@ -9,7 +9,7 @@ use App\Helpers\JobConfig\Tasks\Task; /** - * Reprezentation of one test unit which belongs to job. + * Representation of one test unit which belongs to job. */ class TestConfig { @@ -53,7 +53,7 @@ public function __construct(string $id, array $tasks) if (empty($this->executionTaskType) || $this->evaluationTaskType === null) { throw new JobConfigLoadingException( "Each test must contain at least on task of type 'execution' and exactly one of type 'evaluation'." - . " Test '{$id}' does not meet these criteria." + . " Test '{$id}' does not meet these criteria." ); } } diff --git a/app/helpers/MetaFormats/MetaFormatHelper.php b/app/helpers/MetaFormats/MetaFormatHelper.php index 84b4d98ce..5c7ec8872 100644 --- a/app/helpers/MetaFormats/MetaFormatHelper.php +++ b/app/helpers/MetaFormats/MetaFormatHelper.php @@ -88,10 +88,10 @@ public static function extractFormatParameterData(ReflectionProperty $reflection { // find all property attributes $longAttributes = $reflectionObject->getAttributes(FormatParameterAttribute::class); - $pathAttribues = $reflectionObject->getAttributes(FPath::class); + $pathAttributes = $reflectionObject->getAttributes(FPath::class); $queryAttributes = $reflectionObject->getAttributes(FQuery::class); $postAttributes = $reflectionObject->getAttributes(FPost::class); - $requestAttributes = array_merge($longAttributes, $pathAttribues, $queryAttributes, $postAttributes); + $requestAttributes = array_merge($longAttributes, $pathAttributes, $queryAttributes, $postAttributes); // there should be only one attribute if (count($requestAttributes) == 0) { diff --git a/app/helpers/Plagiarism/SimilarityFragments.php b/app/helpers/Plagiarism/SimilarityFragments.php index e4865e87b..0336034e6 100644 --- a/app/helpers/Plagiarism/SimilarityFragments.php +++ b/app/helpers/Plagiarism/SimilarityFragments.php @@ -6,7 +6,7 @@ use JsonSerializable; /** - * Helper that handles validation and compression of similarity fragments structue. + * Helper that handles validation and compression of similarity fragments structure. * The structure holds an array of fragments, each fragment is a pair (array with 2 items) * of references (first one is tested file, second one is another file with detected similarities). * The reference is an object (encoded as associative array) with 'offset' and 'length' in human-friendly @@ -53,7 +53,7 @@ private static function loadFragmentRef(mixed $ref, int $index): array ); } - return [ 'o' => $offset, 'l' => $length ]; // compressed version + return ['o' => $offset, 'l' => $length]; // compressed version } /** diff --git a/app/helpers/SubmissionHelper/BackendSubmitHelper.php b/app/helpers/SubmissionHelper/BackendSubmitHelper.php index e4d90a1a0..890e605e4 100644 --- a/app/helpers/SubmissionHelper/BackendSubmitHelper.php +++ b/app/helpers/SubmissionHelper/BackendSubmitHelper.php @@ -13,7 +13,6 @@ */ class BackendSubmitHelper { - /** @var BrokerProxy */ private $broker; @@ -45,7 +44,7 @@ public function __construct(BrokerProxy $broker, FileStorageManager $fileStorage public function initiateEvaluation( JobConfig $jobConfig, array $headers = [], - string $hardwareGroup = null + ?string $hardwareGroup = null ): bool { // no files preparations are necessary, the submission archive can be constructed on demand $archiveUrl = $this->fileStorage->getWorkerSubmissionExternalUrl($jobConfig->getJobType(), $jobConfig->getId()); diff --git a/app/helpers/SubmissionHelper/SubmissionHelper.php b/app/helpers/SubmissionHelper/SubmissionHelper.php index 437be6ec6..80a5353f2 100644 --- a/app/helpers/SubmissionHelper/SubmissionHelper.php +++ b/app/helpers/SubmissionHelper/SubmissionHelper.php @@ -313,11 +313,11 @@ public function submit(AssignmentSolution $solution, User $user, bool $isDebug = // check for the license of instance of user $assignment = $solution->getAssignment(); - if ($assignment->getGroup() && $assignment->getGroup()->hasValidLicence() === false) { + if ($assignment->getGroup() && $assignment->getGroup()->hasValidLicense() === false) { throw new ForbiddenRequestException( - "Your institution does not have a valid licence and you cannot submit solutions for any assignment " . + "Your institution does not have a valid license and you cannot submit solutions for any assignment " . "in this group '{$assignment->getGroup()->getId()}'. Contact your supervisor for assistance.", - IResponse::S402_PAYMENT_REQUIRED + IResponse::S402_PaymentRequired ); } diff --git a/app/helpers/Swagger/AnnotationHelper.php b/app/helpers/Swagger/AnnotationHelper.php index 5d6d0ae59..77c3bce78 100644 --- a/app/helpers/Swagger/AnnotationHelper.php +++ b/app/helpers/Swagger/AnnotationHelper.php @@ -123,7 +123,7 @@ private static function getSwaggerType(string $annotationType): string } /** - * Extracts standart doc comments from endpoints, such as '@param string $id An identifier'. + * Extracts standard doc comments from endpoints, such as '@param string $id An identifier'. * Based on the HTTP route of the endpoint, the extracted param can be identified as either a path or * query parameter. * @param array $annotations An array of annotations. diff --git a/app/helpers/Swagger/AnnotationParameterData.php b/app/helpers/Swagger/AnnotationParameterData.php index 81dd24271..3426960c4 100644 --- a/app/helpers/Swagger/AnnotationParameterData.php +++ b/app/helpers/Swagger/AnnotationParameterData.php @@ -27,8 +27,8 @@ public function __construct( string $location, bool $required, bool $nullable, - string $example = null, - string $nestedArraySwaggerType = null, + ?string $example = null, + ?string $nestedArraySwaggerType = null, ?array $nestedObjectParameterData = null, ) { $this->swaggerType = $swaggerType; @@ -90,9 +90,9 @@ private function generateSchemaAnnotation(): string return $head . $body->toString(); } - /** - * Converts the object to a @OA\Parameter(...) annotation string - */ + /** + * Converts the object to a @OA\Parameter(...) annotation string + */ public function toParameterAnnotation(): string { $head = "@OA\\Parameter"; diff --git a/app/helpers/TmpFilesHelper.php b/app/helpers/TmpFilesHelper.php index 9e456d71d..45b634483 100644 --- a/app/helpers/TmpFilesHelper.php +++ b/app/helpers/TmpFilesHelper.php @@ -11,7 +11,7 @@ class TmpFilesHelper private $tempDirectory; private $files = []; - public function __construct(string $tempDirectory = null) + public function __construct(?string $tempDirectory = null) { $this->tempDirectory = $tempDirectory ? "$tempDirectory/tmpfiles" : sys_get_temp_dir(); } diff --git a/app/helpers/Validators.php b/app/helpers/Validators.php index 2735b80f1..9c62183f1 100644 --- a/app/helpers/Validators.php +++ b/app/helpers/Validators.php @@ -2,7 +2,6 @@ namespace App\Helpers; -use DateTime; use Nette\Utils; /** @@ -10,7 +9,6 @@ */ class Validators extends Utils\Validators { - /** * Registering new validating functions */ diff --git a/app/helpers/WebappLinks.php b/app/helpers/WebappLinks.php index 819c405c5..11b44de47 100644 --- a/app/helpers/WebappLinks.php +++ b/app/helpers/WebappLinks.php @@ -25,7 +25,7 @@ class WebappLinks private $solutionUrl; /** @var string */ - private $referenceSolutiontUrl; + private $referenceSolutionUrl; /** @var string */ private $forgottenPasswordUrl; @@ -67,9 +67,9 @@ public function __construct(string $webappUrl, array $linkTemplates) ["solutionUrl"], "$webappUrl/app/assignment/{assignmentId}/solution/{solutionId}" ); - $this->referenceSolutiontUrl = Arrays::get( + $this->referenceSolutionUrl = Arrays::get( $linkTemplates, - ["referenceSolutiontUrl"], + ["referenceSolutionUrl"], "$webappUrl/app/exercises/{exerciseId}/reference-solution/{solutionId}" ); $this->forgottenPasswordUrl = Arrays::get( @@ -100,7 +100,7 @@ public function __construct(string $webappUrl, array $linkTemplates) */ public function getAssignmentPageUrl(string $assignmentId): string { - return self::getLink($this->assignmentUrl, [ 'id' => $assignmentId ]); + return self::getLink($this->assignmentUrl, ['id' => $assignmentId]); } /** @@ -109,7 +109,7 @@ public function getAssignmentPageUrl(string $assignmentId): string */ public function getExercisePageUrl(string $exerciseId): string { - return self::getLink($this->exerciseUrl, [ 'id' => $exerciseId ]); + return self::getLink($this->exerciseUrl, ['id' => $exerciseId]); } /** @@ -118,7 +118,7 @@ public function getExercisePageUrl(string $exerciseId): string */ public function getShadowAssignmentPageUrl(string $assignmentId): string { - return self::getLink($this->shadowAssignmentUrl, [ 'id' => $assignmentId ]); + return self::getLink($this->shadowAssignmentUrl, ['id' => $assignmentId]); } /** @@ -128,7 +128,7 @@ public function getShadowAssignmentPageUrl(string $assignmentId): string */ public function getSolutionPageUrl(string $assignmentId, string $solutionId): string { - return self::getLink($this->solutionUrl, [ 'assignmentId' => $assignmentId, 'solutionId' => $solutionId ]); + return self::getLink($this->solutionUrl, ['assignmentId' => $assignmentId, 'solutionId' => $solutionId]); } /** @@ -139,8 +139,8 @@ public function getSolutionPageUrl(string $assignmentId, string $solutionId): st public function getReferenceSolutionPageUrl(string $exerciseId, string $solutionId): string { return self::getLink( - $this->referenceSolutiontUrl, - [ 'exerciseId' => $exerciseId, 'solutionId' => $solutionId ] + $this->referenceSolutionUrl, + ['exerciseId' => $exerciseId, 'solutionId' => $solutionId] ); } @@ -150,16 +150,16 @@ public function getReferenceSolutionPageUrl(string $exerciseId, string $solution */ public function getForgottenPasswordUrl(string $token): string { - return self::getLink($this->forgottenPasswordUrl, [ 'token' => $token ]); + return self::getLink($this->forgottenPasswordUrl, ['token' => $token]); } /** - * @param string $token JWT used to veify the email + * @param string $token JWT used to verify the email * @return string URL that can be used to verify an email */ public function getEmailVerificationUrl(string $token): string { - return self::getLink($this->emailVerificationUrl, [ 'token' => $token ]); + return self::getLink($this->emailVerificationUrl, ['token' => $token]); } /** @@ -168,7 +168,7 @@ public function getEmailVerificationUrl(string $token): string */ public function getInvitationUrl(string $token): string { - return self::getLink($this->invitationUrl, [ 'token' => $token ]); + return self::getLink($this->invitationUrl, ['token' => $token]); } /** @@ -180,7 +180,7 @@ public function getSolutionSourceFilesUrl(string $assignmentId, string $solution { return self::getLink( $this->solutionSourceFilesUrl, - [ 'assignmentId' => $assignmentId, 'solutionId' => $solutionId ] + ['assignmentId' => $assignmentId, 'solutionId' => $solutionId] ); } } diff --git a/app/helpers/Wildcards.php b/app/helpers/Wildcards.php index 9507e4813..0eb8bd8b3 100644 --- a/app/helpers/Wildcards.php +++ b/app/helpers/Wildcards.php @@ -81,7 +81,8 @@ public static function expandPattern($pattern) } /** - * Split a comma-separated pattern into top-level parts (i.e. split only on commas that are not inside curly brackets) + * Split a comma-separated pattern into top-level parts + * (i.e. split only on commas that are not inside curly brackets) * @param string $pattern the pattern to split (not enclosed in curly braces) * @return Generator */ diff --git a/app/http/RequestFactory.php b/app/http/RequestFactory.php index 350071079..5f1f5ff4f 100644 --- a/app/http/RequestFactory.php +++ b/app/http/RequestFactory.php @@ -32,7 +32,7 @@ public function fromGlobals(): Request ) { $body = file_get_contents('php://input'); try { - $json = $body ? Json::decode($body, Json::FORCE_ARRAY) : []; + $json = $body ? Json::decode($body, true) : []; } catch (JsonException $e) { throw new BadRequestException("Parsing of the JSON body failed: " . $e->getMessage()); } diff --git a/app/http/StorageFileResponse.php b/app/http/StorageFileResponse.php index 37e8eb8da..247b8acef 100644 --- a/app/http/StorageFileResponse.php +++ b/app/http/StorageFileResponse.php @@ -11,7 +11,6 @@ */ class StorageFileResponse implements Response { - /** @var IImmutableFile */ private $file; @@ -35,7 +34,7 @@ class StorageFileResponse implements Response public function __construct( IImmutableFile $file, string $name, - string $contentType = null, + ?string $contentType = null, bool $forceDownload = true ) { $this->file = $file; @@ -64,8 +63,8 @@ public function send(Nette\Http\IRequest $httpRequest, Nette\Http\IResponse $htt $httpResponse->setHeader( 'Content-Disposition', ($this->forceDownload ? 'attachment' : 'inline') - . '; filename="' . $this->name . '"' - . '; filename*=utf-8\'\'' . rawurlencode($this->name) + . '; filename="' . $this->name . '"' + . '; filename*=utf-8\'\'' . rawurlencode($this->name) ); $httpResponse->setHeader('Content-Length', $this->file->getSize()); diff --git a/app/http/ZipFilesResponse.php b/app/http/ZipFilesResponse.php index 5b92dd118..8f441aeec 100644 --- a/app/http/ZipFilesResponse.php +++ b/app/http/ZipFilesResponse.php @@ -41,7 +41,7 @@ class ZipFilesResponse implements Response * @param string|null $name * @param bool $forceDownload */ - public function __construct(array $files, string $name = null, bool $forceDownload = true) + public function __construct(array $files, ?string $name = null, bool $forceDownload = true) { $this->files = $files; $this->name = $name; diff --git a/app/model/entity/Assignment.php b/app/model/entity/Assignment.php index ae6dd1bd3..03cd6683d 100644 --- a/app/model/entity/Assignment.php +++ b/app/model/entity/Assignment.php @@ -31,7 +31,7 @@ private function __construct( bool $isPublic, int $submissionsCountLimit, bool $allowSecondDeadline, - DateTime $secondDeadline = null, + ?DateTime $secondDeadline = null, int $maxPointsBeforeSecondDeadline = 0, bool $canViewLimitRatios = false, bool $canViewMeasuredValues = false, @@ -84,7 +84,7 @@ public static function assignToGroup( Exercise $exercise, Group $group, $isPublic = false, - DateTime $firstDeadline = null + ?DateTime $firstDeadline = null ) { if ($exercise->getLocalizedTexts()->count() == 0) { throw new InvalidStateException("There are no localized descriptions of exercise"); @@ -182,7 +182,7 @@ public function isVisibleToStudents() */ protected $secondDeadline; - public function isAfterDeadline(DateTime $now = null): bool + public function isAfterDeadline(?DateTime $now = null): bool { if ($now === null) { $now = new DateTime(); @@ -195,7 +195,7 @@ public function isAfterDeadline(DateTime $now = null): bool } } - public function isAfterFirstDeadline(DateTime $now = null): bool + public function isAfterFirstDeadline(?DateTime $now = null): bool { if ($now === null) { $now = new DateTime(); @@ -218,7 +218,7 @@ public function isAfterFirstDeadline(DateTime $now = null): bool */ protected $maxPointsDeadlineInterpolation = false; - public function getMaxPoints(DateTime $time = null): int + public function getMaxPoints(?DateTime $time = null): int { if ($time === null || $time < $this->firstDeadline) { return $this->maxPointsBeforeFirstDeadline; @@ -454,8 +454,8 @@ public function areSupplementaryFilesInSync(): bool { $exercise = $this->getExercise(); return $exercise - && $this->getSupplementaryEvaluationFiles()->count() === $exercise->getSupplementaryEvaluationFiles( - )->count() + && $this->getSupplementaryEvaluationFiles()->count() + === $exercise->getSupplementaryEvaluationFiles()->count() && $this->getSupplementaryEvaluationFiles()->forAll( function ($key, SupplementaryExerciseFile $file) use ($exercise) { return $exercise->getSupplementaryEvaluationFiles()->contains($file); diff --git a/app/model/entity/AssignmentSolution.php b/app/model/entity/AssignmentSolution.php index b20baba02..4045b0967 100644 --- a/app/model/entity/AssignmentSolution.php +++ b/app/model/entity/AssignmentSolution.php @@ -192,7 +192,7 @@ function (AssignmentSolutionSubmission $submission) { /** * @var PlagiarismDetectionBatch|null * @ORM\ManyToOne(targetEntity="PlagiarismDetectionBatch") - * Refers to last plagarism detection batch, in which similarities were detected for this solution. + * Refers to last plagiarism detection batch, in which similarities were detected for this solution. * If null, no similarities were detected (yet). */ protected $plagiarismBatch = null; diff --git a/app/model/entity/AssignmentSolver.php b/app/model/entity/AssignmentSolver.php index 922e3a535..15ad99a7d 100644 --- a/app/model/entity/AssignmentSolver.php +++ b/app/model/entity/AssignmentSolver.php @@ -43,7 +43,7 @@ class AssignmentSolver implements JsonSerializable protected $lastAttemptIndex; /** - * Counts how many times one of the solutions have been evaluated (incuding re-evaluations). + * Counts how many times one of the solutions have been evaluated (including re-evaluations). * This counter is mainly for statistical purposes. * @ORM\Column(type="integer") */ diff --git a/app/model/entity/AsyncJob.php b/app/model/entity/AsyncJob.php index c86743773..2f0fa2718 100644 --- a/app/model/entity/AsyncJob.php +++ b/app/model/entity/AsyncJob.php @@ -4,11 +4,6 @@ use DateTime; use Doctrine\ORM\Mapping as ORM; -use Exception; -use Gedmo\Mapping\Annotation as Gedmo; -use App\Exceptions\ApiException; -use Symfony\Component\Yaml\Exception\ParseException; -use Symfony\Component\Yaml\Yaml; use InvalidArgumentException; use LogicException; use JsonSerializable; @@ -128,7 +123,7 @@ public function getRetries(): int /** * @ORM\Column(type="string", nullable=true) * @var string - * ID of a worker who took this task. Once a task is assigned to a worker, it may not be rellocated to another one. + * ID of a worker who took this task. Once a task is assigned to a worker, it may not be relocated to another one. */ protected $workerId = null; @@ -138,7 +133,7 @@ public function getWorkerId(): ?string } /** - * Allocate this job for patricular worker. If the job is allocated, the worker IDs must match. + * Allocate this job for particular worker. If the job is allocated, the worker IDs must match. * The retry counter is incremented. * @param string $workerId * @throws LogicException @@ -257,8 +252,12 @@ public function getAssociatedAssignment(): ?Assignment * @param array $arguments for the job execution * @param Assignment|null $assignment associated with the job */ - public function __construct(?User $createdBy, string $command, array $arguments = [], Assignment $assignment = null) - { + public function __construct( + ?User $createdBy, + string $command, + array $arguments = [], + ?Assignment $assignment = null + ) { $this->createdBy = $createdBy; $this->createdAt = new DateTime(); $this->command = $command; diff --git a/app/model/entity/Exercise.php b/app/model/entity/Exercise.php index c0fce91c9..045ae472c 100644 --- a/app/model/entity/Exercise.php +++ b/app/model/entity/Exercise.php @@ -8,7 +8,6 @@ use Doctrine\Common\Collections\ReadableCollection; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\ArrayCollection; -use Doctrine; use Exception; use Gedmo\Mapping\Annotation as Gedmo; use App\Helpers\ExercisesConfig; @@ -153,8 +152,8 @@ private function __construct( bool $isLocked = true, ?ExerciseScoreConfig $scoreConfig = null, string $configurationType = "simpleExerciseConfig", - int $solutionFilesLimit = null, - int $solutionSizeLimit = null + ?int $solutionFilesLimit = null, + ?int $solutionSizeLimit = null ) { $this->version = $version; $this->createdAt = new DateTime(); @@ -190,8 +189,8 @@ private function __construct( public static function create( User $user, Group $group, - ExerciseScoreConfig $scoreConfig = null, - ExercisesConfig $config = null + ?ExerciseScoreConfig $scoreConfig = null, + ?ExercisesConfig $config = null ): Exercise { return new self( 1, @@ -270,7 +269,7 @@ public function addExerciseTest(ExerciseTest $test): void public function removeExerciseTest(?ExerciseTest $test): void { - $this->exerciseTests->remove($test); + $this->exerciseTests->removeElement($test); } public function addHardwareGroup(HardwareGroup $hardwareGroup): void @@ -421,7 +420,7 @@ public function setScoreConfig(ExerciseScoreConfig $scoreConfig): void $this->scoreConfig = $scoreConfig; } - public function getReferenceSolutions(int $minimalVisibility = null): Collection + public function getReferenceSolutions(?int $minimalVisibility = null): Collection { if ($minimalVisibility !== null) { return $this->referenceSolutions->filter( diff --git a/app/model/entity/ExerciseConfig.php b/app/model/entity/ExerciseConfig.php index 2f44da6bd..f8db2a543 100644 --- a/app/model/entity/ExerciseConfig.php +++ b/app/model/entity/ExerciseConfig.php @@ -4,7 +4,6 @@ use App\Exceptions\ExerciseConfigException; use Doctrine\ORM\Mapping as ORM; -use Doctrine\Common\Collections\ArrayCollection; use App\Helpers\YamlException; use App\Helpers\Yaml; use DateTime; diff --git a/app/model/entity/ExerciseEnvironmentConfig.php b/app/model/entity/ExerciseEnvironmentConfig.php index e5cabc7f4..0b0bb2838 100644 --- a/app/model/entity/ExerciseEnvironmentConfig.php +++ b/app/model/entity/ExerciseEnvironmentConfig.php @@ -4,7 +4,6 @@ use App\Exceptions\ExerciseConfigException; use DateTime; -use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; use App\Helpers\YamlException; use App\Helpers\Yaml; @@ -68,7 +67,7 @@ public function __construct( RuntimeEnvironment $runtimeEnvironment, string $variablesTable, User $author, - ExerciseEnvironmentConfig $createdFrom = null + ?ExerciseEnvironmentConfig $createdFrom = null ) { $this->runtimeEnvironment = $runtimeEnvironment; $this->variablesTable = $variablesTable; diff --git a/app/model/entity/ExerciseLimits.php b/app/model/entity/ExerciseLimits.php index 426fb3ddc..3c3c253d6 100644 --- a/app/model/entity/ExerciseLimits.php +++ b/app/model/entity/ExerciseLimits.php @@ -72,7 +72,7 @@ public function __construct( HardwareGroup $hardwareGroup, string $limits, User $author, - ExerciseLimits $createdFrom = null + ?ExerciseLimits $createdFrom = null ) { $this->runtimeEnvironment = $runtimeEnvironment; $this->hardwareGroup = $hardwareGroup; diff --git a/app/model/entity/ExerciseScoreConfig.php b/app/model/entity/ExerciseScoreConfig.php index b75cb2bd1..d11a438e4 100644 --- a/app/model/entity/ExerciseScoreConfig.php +++ b/app/model/entity/ExerciseScoreConfig.php @@ -69,8 +69,8 @@ public function getConfigParsed() */ public function configEquals($config): bool { - $serializd = $config !== null ? Yaml::dump($config) : null; - return $serializd === $this->config; + $serialized = $config !== null ? Yaml::dump($config) : null; + return $serialized === $this->config; } /** @@ -88,7 +88,7 @@ public function configEquals($config): bool public function __construct( string $calculator = "", $config = null, - ExerciseScoreConfig $createdFrom = null + ?ExerciseScoreConfig $createdFrom = null ) { $this->createdAt = new DateTime(); diff --git a/app/model/entity/Group.php b/app/model/entity/Group.php index c49a3165e..af8ce3d90 100644 --- a/app/model/entity/Group.php +++ b/app/model/entity/Group.php @@ -29,8 +29,8 @@ class Group public function __construct( string $externalId, Instance $instance, - User $admin = null, - Group $parentGroup = null, + ?User $admin = null, + ?Group $parentGroup = null, bool $publicStats = false, bool $isPublic = false, bool $isOrganizational = false, @@ -159,7 +159,7 @@ private function setArchivingStatus(?DateTime $date) } } - public function archive(DateTime $date = null) + public function archive(?DateTime $date = null) { $date = $date ?? new DateTime(); $this->setArchivingStatus($date); @@ -260,7 +260,7 @@ public function isDirectlyArchived(): bool * Switch the group into an exam group by setting the begin and end dates of the exam. * @param DateTime $begin when the exam starts * @param DateTime $end when the exam ends - * @param bool $strict if true, locked users cannot acceess other groups (for reading) + * @param bool $strict if true, locked users cannot access other groups (for reading) */ public function setExamPeriod(DateTime $begin, DateTime $end, bool $strict = false): void { @@ -293,7 +293,7 @@ public function removeExamPeriod(): void * Whether this is an exam group. * @return bool true if an exam is set in this group */ - public function hasExamPeriodSet(DateTime $at = null): bool + public function hasExamPeriodSet(?DateTime $at = null): bool { $at = $at ?? new DateTime(); return $this->examBegin !== null && $this->examEnd !== null && $this->examEnd > $at; @@ -366,10 +366,10 @@ public function getInstance(): ?Instance return $this->instance->isDeleted() ? null : $this->instance; } - public function hasValidLicence() + public function hasValidLicense() { $instance = $this->getInstance(); - return $instance && $instance->hasValidLicence(); + return $instance && $instance->hasValidLicense(); } /** @@ -378,7 +378,7 @@ public function hasValidLicence() protected $memberships; /** - * Get the membership enetity for this group and given user (null is returned if no membership exists). + * Get the membership entity for this group and given user (null is returned if no membership exists). * @param User $user * @return GroupMembership|null */ diff --git a/app/model/entity/GroupInvitation.php b/app/model/entity/GroupInvitation.php index f4caa8787..3058ffa3f 100644 --- a/app/model/entity/GroupInvitation.php +++ b/app/model/entity/GroupInvitation.php @@ -53,7 +53,7 @@ class GroupInvitation implements JsonSerializable * @param DateTime|null $expireAt * @param string $note */ - public function __construct(Group $group, User $host, DateTime $expireAt = null, string $note) + public function __construct(Group $group, User $host, ?DateTime $expireAt = null, string $note = '') { $this->group = $group; $this->host = $host; diff --git a/app/model/entity/GroupMembership.php b/app/model/entity/GroupMembership.php index 95c7770ef..2f9d5a595 100644 --- a/app/model/entity/GroupMembership.php +++ b/app/model/entity/GroupMembership.php @@ -4,7 +4,6 @@ use App\Exceptions\InvalidMembershipException; use Doctrine\ORM\Mapping as ORM; -use Doctrine\Common\Collections\ArrayCollection; use JsonSerializable; use DateTime; @@ -28,14 +27,14 @@ class GroupMembership implements JsonSerializable ]; // membership types that are inherited from parent groups - // in the order of priorities (e.g., admin must be first as it supress other relations) + // in the order of priorities (e.g., admin must be first as it suppress other relations) public const INHERITABLE_TYPES = [ self::TYPE_ADMIN, ]; public const TYPE_ALL = "*"; - public function __construct(Group $group, User $user, string $type, Group $inheritedFrom = null) + public function __construct(Group $group, User $user, string $type, ?Group $inheritedFrom = null) { $this->group = $group; $this->user = $user; @@ -79,14 +78,14 @@ public function __construct(Group $group, User $user, string $type, Group $inher * Inheritance applies only for selected types of memberships (e.g., admin). * At present, explicit inherited memberships are used to capture inherited admin privileges * which are in place at the moment when a sub-groups are being placed to archive. - * In the futue, this technique may be used for performance optimizations as well. + * In the future, this technique may be used for performance optimizations as well. */ protected $inheritedFrom = null; public function setType(string $type) { if (!in_array($type, self::KNOWN_TYPES)) { - throw new InvalidMembershipException("Unsuported membership type '$type'"); + throw new InvalidMembershipException("Unsupported membership type '$type'"); } if ($this->type !== $type) { diff --git a/app/model/entity/Instance.php b/app/model/entity/Instance.php index 0da8d6977..6ac8834b6 100644 --- a/app/model/entity/Instance.php +++ b/app/model/entity/Instance.php @@ -86,7 +86,7 @@ function (Licence $licence) { ); } - public function hasValidLicence() + public function hasValidLicense() { return $this->needsLicence === false || $this->getValidLicences()->count() > 0; } @@ -134,7 +134,7 @@ public function getName() return $localizedRootGroup->getName(); } - public static function createInstance(array $localizedTexts, bool $isOpen, User $admin = null) + public static function createInstance(array $localizedTexts, bool $isOpen, ?User $admin = null) { $instance = new Instance(); $instance->isOpen = $isOpen; diff --git a/app/model/entity/Licence.php b/app/model/entity/Licence.php index 53d57a617..51f2a57b5 100644 --- a/app/model/entity/Licence.php +++ b/app/model/entity/Licence.php @@ -50,7 +50,7 @@ public function getInstance(): ?Instance * @param DateTime $when When the licence should have been valid. * @return bool */ - public function isValid(DateTime $when = null) + public function isValid(?DateTime $when = null) { if ($when === null) { $when = new DateTime(); @@ -59,7 +59,7 @@ public function isValid(DateTime $when = null) } /** - * Internal note for the licence. + * Internal note for the license. * @ORM\Column(type="string") */ protected $note; diff --git a/app/model/entity/LocalizedAssignment.php b/app/model/entity/LocalizedAssignment.php index a8d16a5b2..82ac6be82 100644 --- a/app/model/entity/LocalizedAssignment.php +++ b/app/model/entity/LocalizedAssignment.php @@ -20,7 +20,7 @@ class LocalizedAssignment extends LocalizedEntity implements JsonSerializable /** * Separate text visible to students which is kept separately from the exercise specification, - * so it will not be overriten every time an assigment is synced with exercise. + * so it will not be overwritten every time an assignment is synced with exercise. * @ORM\Column(type="text") */ protected $studentHint; diff --git a/app/model/entity/LocalizedExercise.php b/app/model/entity/LocalizedExercise.php index 3b4b99b7b..2b910d8e5 100644 --- a/app/model/entity/LocalizedExercise.php +++ b/app/model/entity/LocalizedExercise.php @@ -3,7 +3,6 @@ namespace App\Model\Entity; use Doctrine\ORM\Mapping as ORM; -use Doctrine\Common\Collections\ArrayCollection; use InvalidArgumentException; use JsonSerializable; diff --git a/app/model/entity/LocalizedNotification.php b/app/model/entity/LocalizedNotification.php index d4d827936..e40908814 100644 --- a/app/model/entity/LocalizedNotification.php +++ b/app/model/entity/LocalizedNotification.php @@ -10,7 +10,6 @@ */ class LocalizedNotification extends LocalizedEntity implements JsonSerializable { - /** * @ORM\Column(type="text") */ diff --git a/app/model/entity/Login.php b/app/model/entity/Login.php index effb4d6e8..189f97ad6 100644 --- a/app/model/entity/Login.php +++ b/app/model/entity/Login.php @@ -126,7 +126,7 @@ public function passwordsMatch($password, Passwords $passwordsService) * @param string $password * @return Login * @param Passwords|null $passwordsService injection of a service (we do not want to inject directly into entities) - * if null, the service is constructed inplace (special case to make fixtures work) + * if null, the service is constructed in place (special case to make fixtures work) * @throws InvalidApiArgumentException */ public static function createLogin(User $user, string $email, string $password, ?Passwords $passwordsService = null) diff --git a/app/model/entity/Pipeline.php b/app/model/entity/Pipeline.php index ba40908d5..72941c3fa 100644 --- a/app/model/entity/Pipeline.php +++ b/app/model/entity/Pipeline.php @@ -135,7 +135,7 @@ private function __construct( Collection $supplementaryEvaluationFiles, ?User $author = null, ?Pipeline $createdFrom = null, - Collection $runtimeEnvironments = null + ?Collection $runtimeEnvironments = null ) { $this->createdAt = new DateTime(); $this->updatedAt = new DateTime(); @@ -211,7 +211,7 @@ public function removeRuntimeEnvironment(RuntimeEnvironment $environment): void /** * Set completely new associations with runtime environments. - * @param RuntimeEnvironment[] $environments list of runtime environments to override current associatons + * @param RuntimeEnvironment[] $environments list of runtime environments to override current associations */ public function setRuntimeEnvironments(array $environments): void { diff --git a/app/model/entity/PipelineConfig.php b/app/model/entity/PipelineConfig.php index 6d069e877..91c8ba7e0 100644 --- a/app/model/entity/PipelineConfig.php +++ b/app/model/entity/PipelineConfig.php @@ -65,7 +65,7 @@ public function getAuthor(): ?User public function __construct( string $pipeline, ?User $author, - PipelineConfig $createdFrom = null + ?PipelineConfig $createdFrom = null ) { $this->createdAt = new DateTime(); $this->pipelines = new ArrayCollection(); diff --git a/app/model/entity/PlagiarismDetectedSimilarFile.php b/app/model/entity/PlagiarismDetectedSimilarFile.php index e0fa0ceb8..bd5540837 100644 --- a/app/model/entity/PlagiarismDetectedSimilarFile.php +++ b/app/model/entity/PlagiarismDetectedSimilarFile.php @@ -4,8 +4,6 @@ use Doctrine\ORM\Mapping as ORM; use App\Helpers\Plagiarism\SimilarityFragments; -use JsonSerializable; -use DateTime; /** * @ORM\Entity @@ -33,7 +31,7 @@ class PlagiarismDetectedSimilarFile /** * @var PlagiarismDetectedSimilarity * @ORM\ManyToOne(targetEntity="PlagiarismDetectedSimilarity") - * Reference to a detected simularity record to which this file reference contribute. + * Reference to a detected similarity record to which this file reference contribute. */ protected $detectedSimilarity; @@ -56,7 +54,7 @@ class PlagiarismDetectedSimilarFile /** * @ORM\Column(type="string") * Either a relative path within a ZIP file (if the solution file refers to the only ZIP archive), - * or a reference to external file soure that were used for comparison (preferably an URL). + * or a reference to external file source that were used for comparison (preferably an URL). */ protected $fileEntry; diff --git a/app/model/entity/PlagiarismDetectedSimilarity.php b/app/model/entity/PlagiarismDetectedSimilarity.php index 7ca13418d..7f72f6054 100644 --- a/app/model/entity/PlagiarismDetectedSimilarity.php +++ b/app/model/entity/PlagiarismDetectedSimilarity.php @@ -5,8 +5,6 @@ use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; -use JsonSerializable; -use DateTime; /** * @ORM\Entity @@ -15,7 +13,7 @@ * })}) * A record (node) representing a similarity detected between a file and a set of files of a particular user. * This entity holds the tested file and a reference to the author of similar files (possible sources of plagiarism). - * There should be at least one PlagiarismDetectedSimilarFile record associated with detected similarty + * There should be at least one PlagiarismDetectedSimilarFile record associated with detected similarity * (i.e., all possible sources of plagiarism of one author). */ class PlagiarismDetectedSimilarity diff --git a/app/model/entity/PlagiarismDetectionBatch.php b/app/model/entity/PlagiarismDetectionBatch.php index e1e6892de..ae97d6a42 100644 --- a/app/model/entity/PlagiarismDetectionBatch.php +++ b/app/model/entity/PlagiarismDetectionBatch.php @@ -46,7 +46,7 @@ class PlagiarismDetectionBatch implements JsonSerializable /** * @var DateTime * @ORM\Column(type="datetime", nullable=true) - * Time when all the plagiate records were uploaded. If null, the upload is still pending. + * Time when all the plagiarism records were uploaded. If null, the upload is still pending. */ protected $uploadCompletedAt = null; @@ -67,7 +67,7 @@ public function setUploadCompleted(bool $completed = true): void public function __construct( string $detectionTool, string $toolParameters, - User $supervisor = null + ?User $supervisor = null ) { $this->detectionTool = $detectionTool; $this->detectionToolParameters = $toolParameters; diff --git a/app/model/entity/ReferenceExerciseSolution.php b/app/model/entity/ReferenceExerciseSolution.php index 5f9c306c9..e119d8199 100644 --- a/app/model/entity/ReferenceExerciseSolution.php +++ b/app/model/entity/ReferenceExerciseSolution.php @@ -101,9 +101,9 @@ public function getDescription(): string return $this->description; } - public function setDescription(string $desccription): void + public function setDescription(string $description): void { - $this->description = $desccription; + $this->description = $description; } public function getSolution(): Solution diff --git a/app/model/entity/ReviewComment.php b/app/model/entity/ReviewComment.php index 1f3f87c29..622c90740 100644 --- a/app/model/entity/ReviewComment.php +++ b/app/model/entity/ReviewComment.php @@ -2,8 +2,6 @@ namespace App\Model\Entity; -use Doctrine\Common\Collections\ArrayCollection; -use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use JsonSerializable; use DateTime; diff --git a/app/model/entity/SecurityEvent.php b/app/model/entity/SecurityEvent.php index 594f5e6c1..a183ae0bf 100644 --- a/app/model/entity/SecurityEvent.php +++ b/app/model/entity/SecurityEvent.php @@ -9,7 +9,7 @@ /** * @ORM\Entity * @ORM\Table(indexes={@ORM\Index(name="event_created_at_idx", columns={"created_at"})}) - * A logged security event such as user loggin or token refresh. + * A logged security event such as user login or token refresh. */ class SecurityEvent implements JsonSerializable { @@ -128,7 +128,7 @@ public static function createInvalidateTokensEvent(string $remoteAddr, User $use * @param User $user involved in the action * @return SecurityEvent */ - public static function createChangePasswoedEvent(string $remoteAddr, User $user): SecurityEvent + public static function createChangePasswordEvent(string $remoteAddr, User $user): SecurityEvent { return new self(self::TYPE_CHANGE_PASSWORD, $remoteAddr, $user); } diff --git a/app/model/entity/Solution.php b/app/model/entity/Solution.php index 4ecdd2c43..f47af735d 100644 --- a/app/model/entity/Solution.php +++ b/app/model/entity/Solution.php @@ -6,7 +6,6 @@ use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\ArrayCollection; -use JsonSerializable; use DateTime; use App\Helpers\Yaml; diff --git a/app/model/entity/SolutionEvaluation.php b/app/model/entity/SolutionEvaluation.php index 483c04428..958777f0b 100644 --- a/app/model/entity/SolutionEvaluation.php +++ b/app/model/entity/SolutionEvaluation.php @@ -59,7 +59,7 @@ public function getScoreConfig(): ?ExerciseScoreConfig * @param float $score New value of the score * @param ExerciseScoreConfig|null $scoreConfig The config entity used to compute the score */ - public function setScore(float $score, ExerciseScoreConfig $scoreConfig = null): void + public function setScore(float $score, ?ExerciseScoreConfig $scoreConfig = null): void { $this->score = $score; $this->scoreConfig = $scoreConfig; diff --git a/app/model/entity/SolutionFile.php b/app/model/entity/SolutionFile.php index a2060263e..83ff69122 100644 --- a/app/model/entity/SolutionFile.php +++ b/app/model/entity/SolutionFile.php @@ -5,7 +5,6 @@ use App\Helpers\FileStorageManager; use App\Helpers\FileStorage\IImmutableFile; use Doctrine\ORM\Mapping as ORM; -use JsonSerializable; use DateTime; /** diff --git a/app/model/entity/SubmissionFailure.php b/app/model/entity/SubmissionFailure.php index 50b8a5a96..cf76b1e35 100644 --- a/app/model/entity/SubmissionFailure.php +++ b/app/model/entity/SubmissionFailure.php @@ -84,14 +84,14 @@ class SubmissionFailure implements JsonSerializable * @param string $description * @param DateTime|null $createdAt */ - private function __construct(string $type, string $description, DateTime $createdAt = null) + private function __construct(string $type, string $description, ?DateTime $createdAt = null) { $this->type = $type; $this->description = $description; $this->createdAt = $createdAt ?: new DateTime(); } - public static function create(string $type, string $description, DateTime $createdAt = null) + public static function create(string $type, string $description, ?DateTime $createdAt = null) { return new SubmissionFailure($type, $description, $createdAt); } @@ -100,7 +100,7 @@ public static function create(string $type, string $description, DateTime $creat * Accessors */ - public function resolve(string $note, DateTime $resolvedAt = null) + public function resolve(string $note, ?DateTime $resolvedAt = null) { $this->resolvedAt = $resolvedAt ?: new DateTime(); $this->resolutionNote = $note; diff --git a/app/model/entity/UploadedPartialFile.php b/app/model/entity/UploadedPartialFile.php index 8e46dcf3c..299e3f090 100644 --- a/app/model/entity/UploadedPartialFile.php +++ b/app/model/entity/UploadedPartialFile.php @@ -2,8 +2,6 @@ namespace App\Model\Entity; -use App\Helpers\FileStorageManager; -use App\Helpers\FileStorage\IImmutableFile; use Doctrine\ORM\Mapping as ORM; use JsonSerializable; use DateTime; diff --git a/app/model/entity/User.php b/app/model/entity/User.php index 8530dd63e..c9cc1b7bf 100644 --- a/app/model/entity/User.php +++ b/app/model/entity/User.php @@ -254,7 +254,7 @@ protected function makeMemberOf(Group $group, string $type) * @param string|null $type filter that selects only groups by defined type of membership * @param string|null $notType filter that excludes groups by defined type of membership */ - public function getGroups(string $type = null, string $notType = null) + public function getGroups(?string $type = null, ?string $notType = null) { $result = $this->getMemberships(); @@ -374,7 +374,7 @@ public function getConsolidatedExternalLogins(?array $filter = null) $externalIds = reset($externalIds); } } - unset($externalIds); // make sure this reference is not accidentaly reused + unset($externalIds); // make sure this reference is not accidentally reused // filter the list if necessary if ($filter !== null) { @@ -401,7 +401,7 @@ public function getConsolidatedExternalLogins(?array $filter = null) * Update the last authentication time to present. * @param DateTime|null $time the authentication time (if null, current time is set) */ - public function updateLastAuthenticationAt(DateTime $time = null) + public function updateLastAuthenticationAt(?DateTime $time = null) { $this->lastAuthenticationAt = $time ?? new DateTime(); } @@ -452,10 +452,10 @@ public function isIpLocked(): bool /** * Set a new IP lock. - * @param string $ip addres in IPv4 or IPv6 human-readable format (e.g., '192.168.1.2') + * @param string $ip address in IPv4 or IPv6 human-readable format (e.g., '192.168.1.2') * @param DateTime|null $expiration of the IP lock, if null, the lock will never expire */ - public function setIpLock(string $ip, DateTime $expiration = null): void + public function setIpLock(string $ip, ?DateTime $expiration = null): void { $ipNum = inet_pton($ip); if ($ipNum === false) { @@ -548,9 +548,9 @@ public function getGroupLockExpiration(): ?DateTimeInterface * Lock the user within a group. * @param Group $group * @param DateTime|null $expiration of the lock, if null, the lock will never expire - * @param bool $strict if true, the user may not even accress other groups for reading + * @param bool $strict if true, the user may not even access other groups for reading */ - public function setGroupLock(Group $group, DateTime $expiration = null, bool $strict = false): void + public function setGroupLock(Group $group, ?DateTime $expiration = null, bool $strict = false): void { // basic asserts to be on the safe side if (!$group->hasExamPeriodSet()) { diff --git a/app/model/entity/base/VersionableEntity.php b/app/model/entity/base/VersionableEntity.php index 6496040a3..e51d1f1b2 100644 --- a/app/model/entity/base/VersionableEntity.php +++ b/app/model/entity/base/VersionableEntity.php @@ -6,7 +6,6 @@ trait VersionableEntity { - /** * @ORM\Column(type="integer") */ diff --git a/app/model/helpers/CustomCoalesceFunction.php b/app/model/helpers/CustomCoalesceFunction.php index ff30835c0..cfdc4e4aa 100644 --- a/app/model/helpers/CustomCoalesceFunction.php +++ b/app/model/helpers/CustomCoalesceFunction.php @@ -3,6 +3,7 @@ namespace DoctrineExtensions\Query\Functions; use Doctrine\ORM\Query\Lexer; +use Doctrine\ORM\Query\TokenType; use Doctrine\ORM\Query\AST\Functions\FunctionNode; /** @@ -38,21 +39,21 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) */ public function parse(\Doctrine\ORM\Query\Parser $parser) { - $parser->match(Lexer::T_IDENTIFIER); - $parser->match(Lexer::T_OPEN_PARENTHESIS); + $parser->match(TokenType::T_IDENTIFIER); + $parser->match(TokenType::T_OPEN_PARENTHESIS); - $parser->match(Lexer::T_OPEN_PARENTHESIS); + $parser->match(TokenType::T_OPEN_PARENTHESIS); $this->subselectExpressions[] = $parser->Subselect(); - $parser->match(Lexer::T_CLOSE_PARENTHESIS); + $parser->match(TokenType::T_CLOSE_PARENTHESIS); - while ($parser->getLexer()->isNextToken(Lexer::T_COMMA)) { - $parser->match(Lexer::T_COMMA); + while ($parser->getLexer()->isNextToken(TokenType::T_COMMA)) { + $parser->match(TokenType::T_COMMA); - $parser->match(Lexer::T_OPEN_PARENTHESIS); + $parser->match(TokenType::T_OPEN_PARENTHESIS); $this->subselectExpressions[] = $parser->Subselect(); - $parser->match(Lexer::T_CLOSE_PARENTHESIS); + $parser->match(TokenType::T_CLOSE_PARENTHESIS); } - $parser->match(Lexer::T_CLOSE_PARENTHESIS); + $parser->match(TokenType::T_CLOSE_PARENTHESIS); } } diff --git a/app/model/helpers/DqlTypeFunction.php b/app/model/helpers/DqlTypeFunction.php index 64b3bca19..93acb8280 100644 --- a/app/model/helpers/DqlTypeFunction.php +++ b/app/model/helpers/DqlTypeFunction.php @@ -7,13 +7,14 @@ use Doctrine\ORM\Query\Parser; use Doctrine\ORM\Query\QueryException; use Doctrine\ORM\Query\SqlWalker; +use Doctrine\ORM\Query\TokenType; /** * Provides a way to access an entity's discriminator field in DQL * queries. * * Assuming the same "Person" entity from Doctrine's documentation on - * Inheritence Mapping, which has a discriminator field named "discr": + * Inheritance Mapping, which has a discriminator field named "discr": * * Using the TYPE() function, DQL will interpret this: * @@ -66,11 +67,11 @@ public function getSql(SqlWalker $sqlWalker) */ public function parse(Parser $parser) { - $parser->match(Lexer::T_IDENTIFIER); - $parser->match(Lexer::T_OPEN_PARENTHESIS); + $parser->match(TokenType::T_IDENTIFIER); + $parser->match(TokenType::T_OPEN_PARENTHESIS); $this->dqlAlias = $parser->IdentificationVariable(); - $parser->match(Lexer::T_CLOSE_PARENTHESIS); + $parser->match(TokenType::T_CLOSE_PARENTHESIS); } } diff --git a/app/model/helpers/OrderByCollationInjectionMysqlWalker.php b/app/model/helpers/OrderByCollationInjectionMysqlWalker.php index 1565c789b..f36cd97ce 100644 --- a/app/model/helpers/OrderByCollationInjectionMysqlWalker.php +++ b/app/model/helpers/OrderByCollationInjectionMysqlWalker.php @@ -13,8 +13,8 @@ class OrderByCollationInjectionMysqlWalker extends SqlWalker /** * Name of the hint, which holds the actual collation. */ - const HINT_COLLATION = 'orderByCollationInjectionMysqlWalker.collation'; - const HINT_COLLATION_FORBIDDEN_COLUMNS = 'orderByCollationInjectionMysqlWalker.forbiddenCols'; + public const HINT_COLLATION = 'orderByCollationInjectionMysqlWalker.collation'; + public const HINT_COLLATION_FORBIDDEN_COLUMNS = 'orderByCollationInjectionMysqlWalker.forbiddenCols'; private function isForbidden($orderByItemTokens) { diff --git a/app/model/helpers/PaginationDBHelper.php b/app/model/helpers/PaginationDBHelper.php index e97839609..b760c11c1 100644 --- a/app/model/helpers/PaginationDBHelper.php +++ b/app/model/helpers/PaginationDBHelper.php @@ -47,7 +47,7 @@ class PaginationDbHelper /** * Internal function that appends andWhere clause to query builder handling - * fultext search of one search token. + * full text search of one search token. */ private function addSearchCondition(QueryBuilder $qb, string $searchToken, string $alias) { @@ -81,10 +81,10 @@ private function addSearchCondition(QueryBuilder $qb, string $searchToken, strin } /** - * Createa and initialize the helper. + * Create and initialize the helper. * @param array $orderByColumns Known order by names (sent from UI), each holding a list * of corresponding order by DB columns. - * @param array $searchCols List of columns which are tested by fultext search filter. + * @param array $searchCols List of columns which are tested by full text search filter. * @param string|null $localizedTextsClass Name of an entity class which is used for localization texts. * If null, no localization is expected. */ @@ -116,7 +116,7 @@ public function applySearchFilter(QueryBuilder $qb, string $search, ?string $ali } /** - * Apply the helper on a query bulider (add common clauses) using pagination metadata. + * Apply the helper on a query builder (add common clauses) using pagination metadata. * @param QueryBuilder $qb Query builder being augmented. * @param Pagination $pagination Pagination object which holds the filter and order by parameters. * @param string|null $alias Alias of the main table use in the query builder. If null, alias is auto-detected. @@ -152,7 +152,7 @@ public function apply(QueryBuilder $qb, Pagination $pagination, ?string $alias = } /** - * Apply collation patches on the query yileded from the builder and fetch the results. + * Apply collation patches on the query yielded from the builder and fetch the results. * @param QueryBuilder $qb Query builder holding the final query. * @param Pagination $pagination Pagination object which holds the filter and order by parameters. * @return array diff --git a/app/model/repository/AssignmentSolutionSubmissions.php b/app/model/repository/AssignmentSolutionSubmissions.php index 16f1c3880..a3312c872 100644 --- a/app/model/repository/AssignmentSolutionSubmissions.php +++ b/app/model/repository/AssignmentSolutionSubmissions.php @@ -12,7 +12,6 @@ */ class AssignmentSolutionSubmissions extends BaseRepository { - public function __construct(EntityManagerInterface $em) { parent::__construct($em, AssignmentSolutionSubmission::class); @@ -42,7 +41,7 @@ public function getLastSubmission( ?AssignmentSolutionSubmission $omitThisSubmission = null ): ?AssignmentSolutionSubmission { $submissions = $this->findBy( - [ "assignmentSolution" => $solution ], + ["assignmentSolution" => $solution], [ "submittedAt" => "DESC", // make sure the last one submitted is first one in the result "id" => "ASC", diff --git a/app/model/repository/AssignmentSolutions.php b/app/model/repository/AssignmentSolutions.php index 8b2960aaf..4e1d502e7 100644 --- a/app/model/repository/AssignmentSolutions.php +++ b/app/model/repository/AssignmentSolutions.php @@ -292,7 +292,7 @@ public function findPendingReviewsOfTeacher(User $user): array $qb = $this->createQueryBuilder('s'); $qb->innerJoin("s.assignment", "a")->innerJoin("a.group", "g")->innerJoin("g.memberships", "gm"); $qb->where($qb->expr()->eq("gm.user", ":user")) - ->andWhere($qb->expr()->in("gm.type", [ GroupMembership::TYPE_ADMIN, GroupMembership::TYPE_SUPERVISOR ])) + ->andWhere($qb->expr()->in("gm.type", [GroupMembership::TYPE_ADMIN, GroupMembership::TYPE_SUPERVISOR])) ->andWhere($qb->expr()->isNotNull("s.reviewStartedAt")) ->andWhere($qb->expr()->isNull("s.reviewedAt")) ->andWhere($qb->expr()->isNull("g.archivedAt")) @@ -321,7 +321,7 @@ public function getSolutionStats(Assignment $assignment, User $user): array $conn = $this->em->getConnection(); $stmt = $conn->prepare($query); - return $stmt->execute([ + return $stmt->executeQuery([ 'assignmentId' => $assignment->getId(), 'authorId' => $user->getId(), ])->fetchAssociative(); @@ -330,7 +330,7 @@ public function getSolutionStats(Assignment $assignment, User $user): array /** * Get all solutions with review request flag set from one group (optionally filtered for one student). * @param Group $group from which the solutions are loaded - * @param User|null $user if not null, only soliutions of this user will be returned + * @param User|null $user if not null, only solutions of this user will be returned * @return AssignmentSolution[] */ public function findReviewRequestSolutions(Group $group, ?User $user = null): array @@ -353,7 +353,7 @@ public function findReviewRequestSolutions(Group $group, ?User $user = null): ar /** * As findReviewRequestSolutions(), but returns the result in associative array structure. * @param Group $group from which the solutions are loaded - * @param User|null $user if not null, only soliutions of this user will be returned + * @param User|null $user if not null, only solutions of this user will be returned * @return array[] solutions in array hierarchy [userId][assignmentId] -> Solution */ public function findReviewRequestSolutionsIndexed(Group $group, ?User $user = null): array @@ -380,7 +380,7 @@ public function findReviewRequestSolutionsOfTeacher(User $user): array $qb = $this->createQueryBuilder('s'); $qb->innerJoin("s.assignment", "a")->innerJoin("a.group", "g")->innerJoin("g.memberships", "gm"); $qb->where($qb->expr()->eq("gm.user", ":user")) - ->andWhere($qb->expr()->in("gm.type", [ GroupMembership::TYPE_ADMIN, GroupMembership::TYPE_SUPERVISOR ])) + ->andWhere($qb->expr()->in("gm.type", [GroupMembership::TYPE_ADMIN, GroupMembership::TYPE_SUPERVISOR])) ->andWhere($qb->expr()->isNull("s.reviewStartedAt")) ->andWhere($qb->expr()->eq("s.reviewRequest", 1)) ->andWhere($qb->expr()->isNull("g.archivedAt")) diff --git a/app/model/repository/AssignmentSolvers.php b/app/model/repository/AssignmentSolvers.php index b191410fc..099fd67a0 100644 --- a/app/model/repository/AssignmentSolvers.php +++ b/app/model/repository/AssignmentSolvers.php @@ -27,7 +27,7 @@ public function __construct(EntityManagerInterface $em) */ public function findInAssignment(Assignment $assignment, ?User $solver = null): array { - $constraints = [ "assignment" => $assignment ]; + $constraints = ["assignment" => $assignment]; if ($solver) { $constraints["solver"] = $solver; } @@ -49,7 +49,7 @@ public function findInGroup(Group $group, ?User $solver = null): array if ($solver) { $qb->andWhere($qb->expr()->eq("s.solver", ':solver')) - ->setParameter("solver", $solver->getId()); + ->setParameter("solver", $solver->getId()); } return $qb->getQuery()->getResult(); @@ -65,7 +65,7 @@ public function findInGroup(Group $group, ?User $solver = null): array */ public function getNextAttemptIndex(Assignment $assignment, User $solver): int { - $candidates = $this->findBy([ "assignment" => $assignment, "solver" => $solver ]); + $candidates = $this->findBy(["assignment" => $assignment, "solver" => $solver]); if (count($candidates) > 1) { // ooops, something is very wrong since unique index should prevent that throw new InternalServerException("Database integrity constraints have failed."); @@ -77,7 +77,7 @@ public function getNextAttemptIndex(Assignment $assignment, User $solver): int $assignmentSolver = new AssignmentSolver($assignment, $solver); } - // increment the index and retur new value + // increment the index and return new value $index = $assignmentSolver->incrementLastAttemptIndex(); $this->persist($assignmentSolver); return $index; @@ -96,7 +96,7 @@ public function incrementEvaluationsCount(Assignment $assignment, User $solver): SET s.evaluationsCount = s.evaluationsCount + 1 WHERE IDENTITY(s.assignment) = :assignmentId AND IDENTITY(s.solver) = :solverId "); - $query->setParameters([ "assignmentId" => $assignment->getId(), "solverId" => $solver->getId() ]); + $query->setParameters(["assignmentId" => $assignment->getId(), "solverId" => $solver->getId()]); $query->execute(); } diff --git a/app/model/repository/Assignments.php b/app/model/repository/Assignments.php index b11c9b0b0..1c7b2b9c7 100644 --- a/app/model/repository/Assignments.php +++ b/app/model/repository/Assignments.php @@ -14,7 +14,6 @@ */ class Assignments extends BaseSoftDeleteRepository { - public function __construct(EntityManagerInterface $em) { parent::__construct($em, Assignment::class); diff --git a/app/model/repository/AsyncJobs.php b/app/model/repository/AsyncJobs.php index edb6827d5..097844518 100644 --- a/app/model/repository/AsyncJobs.php +++ b/app/model/repository/AsyncJobs.php @@ -6,8 +6,6 @@ use App\Model\Entity\Assignment; use App\Model\Entity\User; use Doctrine\ORM\EntityManagerInterface; -use Doctrine\Common\Collections\Criteria; -use Exception; use DateTime; /** @@ -25,14 +23,14 @@ public function __construct(EntityManagerInterface $em) * @param string|null $command only jobs of particular command are retrieved * @param bool $includeScheduled if true, scheduled jobs are also considered pending jobs * @param User|null $createdBy if set, only jobs created by a particular user are retrieved - * @param Assignment|null $assignment if set, only jobs associated with particular assignment are retireved + * @param Assignment|null $assignment if set, only jobs associated with particular assignment are retrieved * @return AsyncJob[] */ public function findPendingJobs( - string $command = null, + ?string $command = null, bool $includeScheduled = true, - User $createdBy = null, - Assignment $assignment = null + ?User $createdBy = null, + ?Assignment $assignment = null ): array { $qb = $this->repository->createQueryBuilder("j"); $qb->andWhere($qb->expr()->isNull("j.finishedAt")); @@ -63,13 +61,13 @@ public function findPendingJobs( * Get recently failed jobs that fits given criteria. * @param string|null $command only jobs of particular command are retrieved * @param User|null $createdBy if set, only jobs created by a particular user are retrieved - * @param Assignment|null $assignment if set, only jobs associated with particular assignment are retireved + * @param Assignment|null $assignment if set, only jobs associated with particular assignment are retrieved * @return AsyncJob[] */ public function findFailedJobs( - string $command = null, - User $createdBy = null, - Assignment $assignment = null + ?string $command = null, + ?User $createdBy = null, + ?Assignment $assignment = null ): array { $qb = $this->repository->createQueryBuilder("j"); $qb->andWhere($qb->expr()->isNotNull("j.finishedAt"))->andWhere($qb->expr()->isNotNull("j.error")); @@ -100,7 +98,7 @@ public function findFailedJobs( * (so not only fresh jobs, but also retries can be fetched) * @return AsyncJob[] */ - public function findAllReadyForExecution(int $schedulingWindow, string $workerId = null): array + public function findAllReadyForExecution(int $schedulingWindow, ?string $workerId = null): array { $qb = $this->repository->createQueryBuilder("j"); diff --git a/app/model/repository/BaseRepository.php b/app/model/repository/BaseRepository.php index 97501fd01..f630ec4b9 100644 --- a/app/model/repository/BaseRepository.php +++ b/app/model/repository/BaseRepository.php @@ -66,7 +66,7 @@ public function findAll(): array /** * @return T[] */ - public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null): array + public function findBy(array $criteria, ?array $orderBy = null, $limit = null, $offset = null): array { return $this->repository->findBy($criteria, $orderBy, $limit, $offset); } @@ -114,7 +114,7 @@ public function findOrThrow($id) */ protected function findByDateTimeColumn(?DateTime $since, ?DateTime $until, $column = 'createdAt'): array { - $qb = $this->createQueryBuilder('e'); // takes care of softdelete cases + $qb = $this->createQueryBuilder('e'); // takes care of soft delete cases if ($since) { $qb->andWhere("e.$column >= :since")->setParameter('since', $since); } @@ -176,7 +176,7 @@ public function matching(Criteria $params): AbstractLazyCollection * @param string|null $indexBy * @return QueryBuilder */ - protected function createQueryBuilder(string $alias, string $indexBy = null): QueryBuilder + protected function createQueryBuilder(string $alias, ?string $indexBy = null): QueryBuilder { return $this->repository->createQueryBuilder($alias, $indexBy); } @@ -187,7 +187,7 @@ protected function createQueryBuilder(string $alias, string $indexBy = null): Qu * @param string|null $search * @return T[] */ - protected function search(array $columns, string $search = null): array + protected function search(array $columns, ?string $search = null): array { $filter = Criteria::create(); @@ -206,7 +206,7 @@ protected function search(array $columns, string $search = null): array * @param null|string $search * @return T[] */ - protected function searchBy(array $columns, string $search = null): array + protected function searchBy(array $columns, ?string $search = null): array { return $this->searchHelper( $search, diff --git a/app/model/repository/BaseSoftDeleteRepository.php b/app/model/repository/BaseSoftDeleteRepository.php index 82d899093..d2bf58672 100644 --- a/app/model/repository/BaseSoftDeleteRepository.php +++ b/app/model/repository/BaseSoftDeleteRepository.php @@ -67,7 +67,7 @@ public function findAllAndIReallyMeanAllOkay(): array * @param null $offset * @return T[] */ - public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null): array + public function findBy(array $criteria, ?array $orderBy = null, $limit = null, $offset = null): array { return $this->repository->findBy( array_merge( @@ -136,7 +136,7 @@ public function matching(Criteria $params): AbstractLazyCollection * @param string|null $indexBy * @return QueryBuilder */ - public function createQueryBuilder(string $alias, string $indexBy = null): QueryBuilder + public function createQueryBuilder(string $alias, ?string $indexBy = null): QueryBuilder { $qb = $this->repository->createQueryBuilder($alias, $indexBy); $softDeleteColumn = $alias ? "$alias.$this->softDeleteColumn" : $this->softDeleteColumn; diff --git a/app/model/repository/Comments.php b/app/model/repository/Comments.php index 08845ce02..2b1f2b5bc 100644 --- a/app/model/repository/Comments.php +++ b/app/model/repository/Comments.php @@ -3,9 +3,8 @@ namespace App\Model\Repository; use Doctrine\ORM\EntityManagerInterface; -use Nette; -use DateTime; use Doctrine\Common\Collections\Criteria; +use Doctrine\Common\Collections\Order; use App\Model\Entity\Comment; use App\Model\Entity\CommentThread; use App\Model\Entity\User; @@ -36,7 +35,7 @@ public function getThread(string $id): ?CommentThread * the authorship of comments directly as a performance optimization (we need only the count, not all entities). * @param CommentThread $thread * @param User $user - * @param bool $allVisible True = all coments visible for the user, false = comments made by the user. + * @param bool $allVisible True = all comments visible for the user, false = comments made by the user. * @return int * @throws \Doctrine\ORM\NoResultException * @throws \Doctrine\ORM\NonUniqueResultException @@ -106,7 +105,7 @@ public function getThreadLastComment(CommentThread $thread, User $user): ?Commen ) ) ) - ->orderBy(["postedAt" => Criteria::DESC]) + ->orderBy(["postedAt" => Order::Descending]) ->setMaxResults(1) )->first(); } diff --git a/app/model/repository/ExerciseTests.php b/app/model/repository/ExerciseTests.php index 1779aef45..03c1e92bc 100644 --- a/app/model/repository/ExerciseTests.php +++ b/app/model/repository/ExerciseTests.php @@ -10,7 +10,6 @@ */ class ExerciseTests extends BaseRepository { - public function __construct(EntityManagerInterface $em) { parent::__construct($em, ExerciseTest::class); diff --git a/app/model/repository/Exercises.php b/app/model/repository/Exercises.php index a228008ce..3425f6158 100644 --- a/app/model/repository/Exercises.php +++ b/app/model/repository/Exercises.php @@ -121,11 +121,11 @@ private function getPreparedForPaginationEnvsFilter(QueryBuilder $qb, $envs): vo * @param User $user currently logged in (so we can restrict the selection based on user privileges) * @return Exercise[] */ - public function getPreparedForPagination(Pagination $pagination, Groups $groups, User $user = null): array + public function getPreparedForPagination(Pagination $pagination, Groups $groups, ?User $user = null): array { - // Welcome to Doctrine HELL! Put your sickbags on standby! + // Welcome to Doctrine HELL! Put your sick bags on standby! - $qb = $this->createQueryBuilder('e'); // takes care of softdelete cases + $qb = $this->createQueryBuilder('e'); // takes care of soft delete cases if ($pagination->hasFilter("archived")) { $archived = $pagination->getFilter("archived"); @@ -183,7 +183,7 @@ public function getPreparedForPagination(Pagination $pagination, Groups $groups, $adminOf = $user->getGroups(GroupMembership::TYPE_ADMIN); // primary admin $adminOfIndex = BaseRepository::createIdIndex($adminOf, true); // all values are "true" - // filter the groups of residence using membeship filters + // filter the groups of residence using membership filters $filteredGroupsOfResidence = array_filter( $groupsOfResidence, function ($group) use ($memberOfIndex, $adminOfIndex) { @@ -275,7 +275,7 @@ function ($group) use ($memberOfIndex, $adminOfIndex) { /** * Get distinct authors of all exercises. * @param string|null $instanceId ID of an instance from which the authors are selected. - * @param string|null $groupId A group which restricts the exercies. + * @param string|null $groupId A group which restricts the exercises. * Only exercises attached to that group (or any ancestral group) are considered. * @param Groups $groups groups repository * @return User[] List of exercises authors. @@ -287,7 +287,7 @@ public function getAuthors(?string $instanceId, ?string $groupId, Groups $groups $qb->andWhere(":instance MEMBER OF a.instances")->setParameter("instance", $instanceId); } - $sub = $this->createQueryBuilder("e"); // takes care of softdelete cases + $sub = $this->createQueryBuilder("e"); // takes care of soft delete cases $sub->andWhere("a = e.author"); if ($groupId) { @@ -319,7 +319,7 @@ public function getPipelineExercises(string $pipelineId): array $sub->andWhere("ec.config LIKE :like"); // select the exercises corresponding to those configs - $qb = $this->createQueryBuilder('e'); // takes care of softdelete cases + $qb = $this->createQueryBuilder('e'); // takes care of soft delete cases $qb->andWhere($qb->expr()->exists($sub->getDQL())); $qb->andWhere($qb->expr()->isNull('e.archivedAt')); $qb->setParameter("like", "%$pipelineId%"); diff --git a/app/model/repository/GroupExams.php b/app/model/repository/GroupExams.php index 3d138d696..60d46c7d4 100644 --- a/app/model/repository/GroupExams.php +++ b/app/model/repository/GroupExams.php @@ -4,7 +4,6 @@ use App\Model\Entity\Group; use App\Model\Entity\GroupExam; -use App\Model\Entity\User; use Doctrine\ORM\EntityManagerInterface; use DateTime; use Exception; @@ -49,9 +48,9 @@ public function findPendingForGroup(Group $group): ?GroupExam */ public function findOrCreate( Group $group, - DateTime $begin = null, - DateTime $end = null, - bool $strict = null + ?DateTime $begin = null, + ?DateTime $end = null, + ?bool $strict = null ): GroupExam { $begin = $begin ?? $group->getExamBegin(); $end = $end ?? $group->getExamEnd(); diff --git a/app/model/repository/GroupExternalAttributes.php b/app/model/repository/GroupExternalAttributes.php index 1c65deff8..663c4f4bb 100644 --- a/app/model/repository/GroupExternalAttributes.php +++ b/app/model/repository/GroupExternalAttributes.php @@ -2,9 +2,7 @@ namespace App\Model\Repository; -use App\Model\Entity\Group; use App\Model\Entity\GroupExternalAttribute; -use App\Model\Entity\User; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\QueryBuilder; use InvalidArgumentException; @@ -20,7 +18,7 @@ public function __construct(EntityManagerInterface $em) } /** - * Helper function that constructs AND expression representing a filter clause for fiven query builder. + * Helper function that constructs AND expression representing a filter clause for find query builder. * @param QueryBuilder $qb * @param int $counter used for generating unique parameter identifiers * @param array $clause represented as associative array @@ -59,7 +57,7 @@ private static function createFilterClause(QueryBuilder $qb, int &$counter, arra public function findByFilter(array $filter): array { if (!$filter) { - throw new InvalidArgumentException("Arument filter is empty."); + throw new InvalidArgumentException("Argument filter is empty."); } $qb = $this->createQueryBuilder('ea')->join('ea.group', 'g'); diff --git a/app/model/repository/GroupInvitations.php b/app/model/repository/GroupInvitations.php index 280e26719..b95af1aeb 100644 --- a/app/model/repository/GroupInvitations.php +++ b/app/model/repository/GroupInvitations.php @@ -2,10 +2,7 @@ namespace App\Model\Repository; -use DateTime; -use App\Model\Entity\Group; use App\Model\Entity\GroupInvitation; -use App\Model\Entity\User; use Doctrine\ORM\EntityManagerInterface; /** diff --git a/app/model/repository/GroupMemberships.php b/app/model/repository/GroupMemberships.php index 287fa034c..ee34959e4 100644 --- a/app/model/repository/GroupMemberships.php +++ b/app/model/repository/GroupMemberships.php @@ -10,7 +10,6 @@ */ class GroupMemberships extends BaseRepository { - public function __construct(EntityManagerInterface $em) { parent::__construct($em, GroupMembership::class); diff --git a/app/model/repository/Groups.php b/app/model/repository/Groups.php index 70bd03926..ea160acc1 100644 --- a/app/model/repository/Groups.php +++ b/app/model/repository/Groups.php @@ -120,14 +120,14 @@ public function findByName(string $locale, string $name, Instance $instance, ?Gr /** * Fetch all groups in which the given user has membership (all relations except admin). - * @param User $user The user whos memberships are considered. + * @param User $user The user whose memberships are considered. * @param array $allowed List of allowed membership types (empty list = no restrictions) * @param array $denied List of denied membership types (empty list = no restrictions) * @return Group[] Array indexed by group IDs. */ public function findGroupsByMembership(User $user, array $allowed = [], array $denied = []): array { - $qb = $this->createQueryBuilder('g'); // takes care of softdelete cases + $qb = $this->createQueryBuilder('g'); // takes care of soft delete cases $sub = $qb->getEntityManager()->createQueryBuilder()->select("gm")->from(GroupMembership::class, "gm"); $sub->andWhere($sub->expr()->eq('gm.group', 'g')); $sub->andWhere($sub->expr()->eq('gm.user', $sub->expr()->literal($user->getId()))); @@ -160,7 +160,7 @@ private function findAllChildrenOf(array $parentsIds): array if (!$parentsIds) { return []; } - $qb = $this->createQueryBuilder('g'); // takes care of softdelete cases + $qb = $this->createQueryBuilder('g'); // takes care of soft delete cases $qb->andWhere($qb->expr()->in("g.parentGroup", $parentsIds)); return $qb->getQuery()->getResult(); } @@ -175,7 +175,7 @@ public function findSupervisedGroupsIds(User $user): array $res = []; // Add groups where user is admin or inherits admin privileges. - $admined = $this->findGroupsByMembership($user, [ GroupMembership::TYPE_ADMIN ]); + $admined = $this->findGroupsByMembership($user, [GroupMembership::TYPE_ADMIN]); while ($admined) { $parents = []; // groups that become parents of next iteration foreach ($admined as $group) { @@ -188,7 +188,7 @@ public function findSupervisedGroupsIds(User $user): array } // Add groups where user is direct supervisor. - $supervised = $this->findGroupsByMembership($user, [ GroupMembership::TYPE_SUPERVISOR ]); + $supervised = $this->findGroupsByMembership($user, [GroupMembership::TYPE_SUPERVISOR]); foreach ($supervised as $group) { $res[$group->getId()] = $group; } @@ -200,14 +200,14 @@ public function findSupervisedGroupsIds(User $user): array /** * Filter list of groups so that only groups affiliated to given user * (by direct membership or by admin rights) and public groups remain in the result. - * @param User $user User whos affiliation is considered. + * @param User $user User whose affiliation is considered. * @param Group[] $groups List of groups to be filtered. * @return Group[] */ private function filterGroupsByUser(User $user, array $groups): array { - $memberOf = $this->findGroupsByMembership($user, [], [ GroupMembership::TYPE_ADMIN ]); // not admins - $adminOf = $this->findGroupsByMembership($user, [ GroupMembership::TYPE_ADMIN ]); // only admins + $memberOf = $this->findGroupsByMembership($user, [], [GroupMembership::TYPE_ADMIN]); // not admins + $adminOf = $this->findGroupsByMembership($user, [GroupMembership::TYPE_ADMIN]); // only admins return array_filter( $groups, @@ -246,13 +246,13 @@ function (Group $group) use ($memberOf, &$adminOf) { * @return Group[] */ public function findFiltered( - User $user = null, - string $instanceId = null, - string $search = null, + ?User $user = null, + ?string $instanceId = null, + ?string $search = null, bool $archived = false, bool $onlyArchived = false ): array { - $qb = $this->createQueryBuilder('g'); // takes care of softdelete cases + $qb = $this->createQueryBuilder('g'); // takes care of soft delete cases // Filter by instance ID... $instanceId = trim($instanceId ?? ""); @@ -354,7 +354,7 @@ public function getArchivedCount(): int /** * Retrieve all groups that where at least one exercise resides. - * @param Exercises $exercises repository (used for subselect) + * @param Exercises $exercises repository (used for sub-select) * @param bool $onlyIds whether to retrieve only groupIDs or all entities * @param bool $archived if true, archived groups are also returned * @return array (either string[] if onlyIds is set, or Group[] otherwise) diff --git a/app/model/repository/HardwareGroups.php b/app/model/repository/HardwareGroups.php index 342d1cdf5..1f1e45229 100644 --- a/app/model/repository/HardwareGroups.php +++ b/app/model/repository/HardwareGroups.php @@ -10,7 +10,6 @@ */ class HardwareGroups extends BaseRepository { - public function __construct(EntityManagerInterface $em) { parent::__construct($em, HardwareGroup::class); diff --git a/app/model/repository/Licences.php b/app/model/repository/Licences.php index 4019777ae..e78dccca9 100644 --- a/app/model/repository/Licences.php +++ b/app/model/repository/Licences.php @@ -10,7 +10,6 @@ */ class Licences extends BaseRepository { - public function __construct(EntityManagerInterface $em) { parent::__construct($em, Licence::class); diff --git a/app/model/repository/Logins.php b/app/model/repository/Logins.php index edd7f3fe1..d13f5c305 100644 --- a/app/model/repository/Logins.php +++ b/app/model/repository/Logins.php @@ -13,7 +13,6 @@ */ class Logins extends BaseRepository { - public function __construct(EntityManagerInterface $em) { parent::__construct($em, Login::class); diff --git a/app/model/repository/Pipelines.php b/app/model/repository/Pipelines.php index b6f4feae8..9c4d2c610 100644 --- a/app/model/repository/Pipelines.php +++ b/app/model/repository/Pipelines.php @@ -19,7 +19,7 @@ public function __construct(EntityManagerInterface $em) public function findByName(string $name): array { - return $this->findBy([ 'name' => $name ]); + return $this->findBy(['name' => $name]); } /** @@ -30,7 +30,7 @@ public function findByName(string $name): array */ public function getPreparedForPagination(Pagination $pagination): array { - $qb = $this->createQueryBuilder('p'); // takes care of softdelete cases + $qb = $this->createQueryBuilder('p'); // takes care of soft delete cases // Only pipelines of given author ... if ($pagination->hasFilter("authorId")) { @@ -61,7 +61,7 @@ public function getPreparedForPagination(Pagination $pagination): array */ public function getRuntimeEnvironmentPipelines(string $runtimeId): array { - $qb = $this->createQueryBuilder('p'); // takes care of softdelete cases + $qb = $this->createQueryBuilder('p'); // takes care of soft delete cases $qb->andWhere(":rteId MEMBER OF p.runtimeEnvironments")->setParameter('rteId', $runtimeId); return $qb->getQuery()->getResult(); } diff --git a/app/model/repository/PlagiarismDetectedSimilarFiles.php b/app/model/repository/PlagiarismDetectedSimilarFiles.php index 0570fbe8b..a8df1b781 100644 --- a/app/model/repository/PlagiarismDetectedSimilarFiles.php +++ b/app/model/repository/PlagiarismDetectedSimilarFiles.php @@ -13,7 +13,6 @@ */ class PlagiarismDetectedSimilarFiles extends BaseRepository { - public function __construct(EntityManagerInterface $em) { parent::__construct($em, PlagiarismDetectedSimilarFile::class); @@ -25,7 +24,7 @@ public function __construct(EntityManagerInterface $em) * @param AssignmentSolution $testedSolution a related similarity detection record must exist * @param AssignmentSolution $solution similar solution to be found * @param SolutionFile|null $file reference to the similar file to be found - * @param string|null $fileEntry a file entry or referene to an external source to be found + * @param string|null $fileEntry a file entry or reference to an external source to be found * @return PlagiarismDetectedSimilarFile[] */ public function findByTestedAndSimilarSolution( diff --git a/app/model/repository/PlagiarismDetectedSimilarities.php b/app/model/repository/PlagiarismDetectedSimilarities.php index 7b46383a8..028f03c51 100644 --- a/app/model/repository/PlagiarismDetectedSimilarities.php +++ b/app/model/repository/PlagiarismDetectedSimilarities.php @@ -12,7 +12,6 @@ */ class PlagiarismDetectedSimilarities extends BaseRepository { - public function __construct(EntityManagerInterface $em) { parent::__construct($em, PlagiarismDetectedSimilarity::class); diff --git a/app/model/repository/PlagiarismDetectionBatches.php b/app/model/repository/PlagiarismDetectionBatches.php index a8821b3e1..06e21bec4 100644 --- a/app/model/repository/PlagiarismDetectionBatches.php +++ b/app/model/repository/PlagiarismDetectionBatches.php @@ -12,7 +12,6 @@ */ class PlagiarismDetectionBatches extends BaseRepository { - public function __construct(EntityManagerInterface $em) { parent::__construct($em, PlagiarismDetectionBatch::class); diff --git a/app/model/repository/ReferenceExerciseSolutions.php b/app/model/repository/ReferenceExerciseSolutions.php index b641355ff..d4599b2bd 100644 --- a/app/model/repository/ReferenceExerciseSolutions.php +++ b/app/model/repository/ReferenceExerciseSolutions.php @@ -10,7 +10,6 @@ */ class ReferenceExerciseSolutions extends BaseRepository { - public function __construct(EntityManagerInterface $em) { parent::__construct($em, ReferenceExerciseSolution::class); diff --git a/app/model/repository/ReferenceSolutionSubmissions.php b/app/model/repository/ReferenceSolutionSubmissions.php index adf720a3f..ab4c21cb4 100644 --- a/app/model/repository/ReferenceSolutionSubmissions.php +++ b/app/model/repository/ReferenceSolutionSubmissions.php @@ -12,7 +12,6 @@ */ class ReferenceSolutionSubmissions extends BaseRepository { - public function __construct(EntityManagerInterface $em) { parent::__construct($em, ReferenceSolutionSubmission::class); @@ -42,7 +41,7 @@ public function getLastSubmission( ?ReferenceSolutionSubmission $omitThisSubmission = null ): ?ReferenceSolutionSubmission { $submissions = $this->findBy( - [ "referenceSolution" => $solution ], + ["referenceSolution" => $solution], [ "submittedAt" => "DESC", // make sure the last one submitted is first one in the result "id" => "ASC", diff --git a/app/model/repository/RuntimeEnvironments.php b/app/model/repository/RuntimeEnvironments.php index fc9b5be66..dc28ff015 100644 --- a/app/model/repository/RuntimeEnvironments.php +++ b/app/model/repository/RuntimeEnvironments.php @@ -10,7 +10,6 @@ */ class RuntimeEnvironments extends BaseRepository { - public function __construct(EntityManagerInterface $em) { parent::__construct($em, RuntimeEnvironment::class); diff --git a/app/model/repository/SecurityEvents.php b/app/model/repository/SecurityEvents.php index 33d540084..3bed909b5 100644 --- a/app/model/repository/SecurityEvents.php +++ b/app/model/repository/SecurityEvents.php @@ -3,11 +3,7 @@ namespace App\Model\Repository; use App\Model\Entity\SecurityEvent; -use App\Model\Entity\GroupExam; -use App\Model\Entity\User; use Doctrine\ORM\EntityManagerInterface; -use DateTime; -use Exception; /** * @extends BaseRepository diff --git a/app/model/repository/ShadowAssignmentPointsRepository.php b/app/model/repository/ShadowAssignmentPointsRepository.php index 4e4ae30cb..1f4403c22 100644 --- a/app/model/repository/ShadowAssignmentPointsRepository.php +++ b/app/model/repository/ShadowAssignmentPointsRepository.php @@ -12,7 +12,6 @@ */ class ShadowAssignmentPointsRepository extends BaseRepository { - public function __construct(EntityManagerInterface $em) { parent::__construct($em, ShadowAssignmentPoints::class); diff --git a/app/model/repository/SolutionEvaluations.php b/app/model/repository/SolutionEvaluations.php index 68b280aa7..748ec009d 100644 --- a/app/model/repository/SolutionEvaluations.php +++ b/app/model/repository/SolutionEvaluations.php @@ -10,7 +10,6 @@ */ class SolutionEvaluations extends BaseRepository { - public function __construct(EntityManagerInterface $em) { parent::__construct($em, SolutionEvaluation::class); diff --git a/app/model/repository/SupplementaryExerciseFiles.php b/app/model/repository/SupplementaryExerciseFiles.php index ee71b63f7..bbdffe846 100644 --- a/app/model/repository/SupplementaryExerciseFiles.php +++ b/app/model/repository/SupplementaryExerciseFiles.php @@ -10,7 +10,6 @@ */ class SupplementaryExerciseFiles extends BaseRepository { - public function __construct(EntityManagerInterface $em) { parent::__construct($em, SupplementaryExerciseFile::class); diff --git a/app/model/repository/UploadedFiles.php b/app/model/repository/UploadedFiles.php index 1560b3332..7b472d889 100644 --- a/app/model/repository/UploadedFiles.php +++ b/app/model/repository/UploadedFiles.php @@ -13,7 +13,6 @@ */ class UploadedFiles extends BaseRepository { - public function __construct(EntityManagerInterface $em) { parent::__construct($em, UploadedFile::class); @@ -44,7 +43,7 @@ public function findGroupForSolutionFile(UploadedFile $file): ?Group FROM App\Model\Entity\AssignmentSolution sub WHERE IDENTITY(sub.solution) = :solutionId "); - $query->setParameters([ 'solutionId' => $file->getSolution()->getId() ]); + $query->setParameters(['solutionId' => $file->getSolution()->getId()]); $result = $query->getResult(); if (count($result) === 0) { @@ -71,7 +70,7 @@ public function findGroupsForReferenceSolutionFile(UploadedFile $file): array FROM App\Model\Entity\ReferenceExerciseSolution ref WHERE IDENTITY(ref.solution) = :solutionId "); - $query->setParameters([ 'solutionId' => $file->getSolution()->getId() ]); + $query->setParameters(['solutionId' => $file->getSolution()->getId()]); $result = $query->getResult(); if (count($result) === 0) { @@ -101,7 +100,7 @@ public function findUnused(DateTime $now, string $threshold): array WHERE TYPE(f) = 'uploadedfile' AND f.uploadedAt < :threshold "); - $query->setParameters([ "threshold" => $thresholdDate ]); + $query->setParameters(["threshold" => $thresholdDate]); return $query->getResult(); } diff --git a/app/model/repository/UserCalendars.php b/app/model/repository/UserCalendars.php index 70e3c4569..ae86f3d6b 100644 --- a/app/model/repository/UserCalendars.php +++ b/app/model/repository/UserCalendars.php @@ -4,7 +4,6 @@ use App\Model\Entity\UserCalendar; use Doctrine\ORM\EntityManagerInterface; -use DateTime; /** * @extends BaseRepository diff --git a/app/model/repository/Users.php b/app/model/repository/Users.php index 33c9a2e49..5ddb27e36 100644 --- a/app/model/repository/Users.php +++ b/app/model/repository/Users.php @@ -31,7 +31,7 @@ public function getByEmail(string $email): ?User */ public function getPaginated(Pagination $pagination, &$totalCount): array { - $qb = $this->createQueryBuilder('u'); // takes care of softdelete cases + $qb = $this->createQueryBuilder('u'); // takes care of soft delete cases // Filter by instance ID ... if ($pagination->hasFilter("instanceId")) { @@ -75,7 +75,7 @@ public function getPaginated(Pagination $pagination, &$totalCount): array /** - * Search users firstnames and surnames based on given string. + * Search users first names and surnames based on given string. * @param string|null $search * @return User[] */ @@ -103,7 +103,7 @@ public function findByRoles(string ...$roles): array */ public function findByLastAuthentication(?DateTime $before, ?bool $allowed = null, array $roles = []): array { - $qb = $this->createQueryBuilder('u'); // takes care of softdelete cases + $qb = $this->createQueryBuilder('u'); // takes care of soft delete cases if ($before) { $qb->andWhere( 'u.createdAt <= :before AND (u.lastAuthenticationAt <= :before OR u.lastAuthenticationAt IS NULL)' diff --git a/app/model/view/AssignmentSolutionViewFactory.php b/app/model/view/AssignmentSolutionViewFactory.php index b7c0eb3e8..8014f8e78 100644 --- a/app/model/view/AssignmentSolutionViewFactory.php +++ b/app/model/view/AssignmentSolutionViewFactory.php @@ -6,8 +6,6 @@ use App\Model\Repository\Comments; use App\Model\Repository\AssignmentSolutions; use App\Model\Entity\AssignmentSolution; -use App\Model\Entity\Group; -use App\Model\Entity\User; use App\Security\ACL\IAssignmentSolutionPermissions; use App\Security\UserStorage; use App\Exceptions\InternalServerException; @@ -158,7 +156,7 @@ public function getSolutionData(AssignmentSolution $solution, $bestSolutionsHint * @param AssignmentSolution[] $solutions * @param bool|array|null $bestSolutionsHints * If bool value is provided, it holds the `isBestSolution` value already for all solutions. - * If iterrable value is provided, it holds a list of best solutions + * If iterable value is provided, it holds a list of best solutions * Otherwise the view factory determines the `isBestSolution` value on its own. * @return array */ diff --git a/app/model/view/GroupViewFactory.php b/app/model/view/GroupViewFactory.php index 6acd99ed3..5f01a99df 100644 --- a/app/model/view/GroupViewFactory.php +++ b/app/model/view/GroupViewFactory.php @@ -4,14 +4,11 @@ use App\Helpers\EvaluationStatus\EvaluationStatus; use App\Helpers\GroupBindings\GroupBindingAccessor; -use App\Helpers\Localizations; -use App\Helpers\Pair; use App\Helpers\PermissionHints; use App\Model\Entity\Assignment; use App\Model\Entity\AssignmentSolution; use App\Model\Entity\Group; use App\Model\Entity\GroupExamLock; -use App\Model\Entity\LocalizedGroup; use App\Model\Entity\ShadowAssignment; use App\Model\Entity\ShadowAssignmentPoints; use App\Model\Entity\User; @@ -20,7 +17,6 @@ use App\Security\ACL\IAssignmentPermissions; use App\Security\ACL\IShadowAssignmentPermissions; use App\Security\ACL\IGroupPermissions; -use Doctrine\Common\Collections\Collection; use Nette\Utils\Arrays; /** @@ -101,7 +97,7 @@ function ($carry, ShadowAssignmentPoints $points) { * @param Group $group * @param User $student Student of this group * @param array $assignmentSolutions Loaded assignment solutions of the student for all assignments in the group. - * This varialble allows us bulk-load optimizations for the solutions. + * This variable allows us bulk-load optimizations for the solutions. * @return array Students statistics */ private function getStudentStatsInternal( @@ -238,7 +234,7 @@ public function getGroup(Group $group, bool $ignoreArchived = true): array "observers" => $group->getObserversIds(), "students" => $this->groupAcl->canViewStudents($group) ? $group->getStudentsIds() : [], "instanceId" => $group->getInstance() ? $group->getInstance()->getId() : null, - "hasValidLicence" => $group->hasValidLicence(), + "hasValidLicence" => $group->hasValidLicense(), "assignments" => $group->getAssignments()->filter( function (Assignment $assignment) { return $this->assignmentAcl->canViewDetail($assignment); diff --git a/app/model/view/InstanceViewFactory.php b/app/model/view/InstanceViewFactory.php index d7ba807f1..e17a5859a 100644 --- a/app/model/view/InstanceViewFactory.php +++ b/app/model/view/InstanceViewFactory.php @@ -46,7 +46,7 @@ public function getInstance(Instance $instance, ?User $loggedUser = null): array "id" => $instance->getId(), "name" => $localizedRootGroup ? $localizedRootGroup->getName() : "", // BC "description" => $localizedRootGroup ? $localizedRootGroup->getDescription() : "", // BC - "hasValidLicence" => $instance->hasValidLicence(), + "hasValidLicence" => $instance->hasValidLicense(), "isOpen" => $instance->isOpen(), "isAllowed" => $instance->isAllowed(), "createdAt" => $instance->getCreatedAt()->getTimestamp(), diff --git a/app/model/view/PipelineViewFactory.php b/app/model/view/PipelineViewFactory.php index 76af3e607..913898c66 100644 --- a/app/model/view/PipelineViewFactory.php +++ b/app/model/view/PipelineViewFactory.php @@ -9,7 +9,6 @@ class PipelineViewFactory { - /** @var IPipelinePermissions */ private $pipelineAcl; diff --git a/app/model/view/ShadowAssignmentViewFactory.php b/app/model/view/ShadowAssignmentViewFactory.php index 994f5e263..ec64d7b04 100644 --- a/app/model/view/ShadowAssignmentViewFactory.php +++ b/app/model/view/ShadowAssignmentViewFactory.php @@ -12,7 +12,6 @@ class ShadowAssignmentViewFactory { - /** @var IShadowAssignmentPermissions */ public $shadowAssignmentAcl; diff --git a/app/model/view/UserViewFactory.php b/app/model/view/UserViewFactory.php index ebe1fd483..c3ac97744 100644 --- a/app/model/view/UserViewFactory.php +++ b/app/model/view/UserViewFactory.php @@ -51,7 +51,7 @@ private function getExternalIds(User $user, bool $canViewAllExternalIds = false) } $filter = array_keys($this->loggedInUser->getConsolidatedExternalLogins()); } else { - $filter = null; // no filterings + $filter = null; // no filtering } return $user->getConsolidatedExternalLogins($filter); } diff --git a/app/model/view/helpers/SubmissionViewOptions.php b/app/model/view/helpers/SubmissionViewOptions.php index 1594f55f8..8cf34b8a2 100644 --- a/app/model/view/helpers/SubmissionViewOptions.php +++ b/app/model/view/helpers/SubmissionViewOptions.php @@ -8,7 +8,7 @@ use Nette\SmartObject; /** - * Structure that holds all options controling submission view construction. + * Structure that holds all options controlling submission view construction. */ class SubmissionViewOptions {