Commit 0751700b authored by Clouard Regis's avatar Clouard Regis
Browse files

Refactored Model

parent 8738505c
......@@ -40,7 +40,8 @@
"symfony/validator": "5.3.*",
"symfony/web-link": "5.3.*",
"symfony/yaml": "5.3.*",
"ext-zlib": "*"
"ext-zlib": "*",
"ext-zip": "*"
},
"require-dev": {
"dama/doctrine-test-bundle": "^6.6",
......
......@@ -82,7 +82,7 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface
{
$this->error = UserValidator::checkValid($this->username, $this->email);
return $this->error == UserValidator::$NO_ERR;
return $this->error == UserValidator::$NO_ERROR;
}
public function remove(ObjectManager $entityManager)
......
......@@ -6,7 +6,6 @@ use DOMDocument;
use function libxml_use_internal_errors;
use function simplexml_load_string;
// TODO
class CourseValidator
{
//outside of class compare to those variable
......@@ -33,7 +32,7 @@ class CourseValidator
}
$extension = strtolower(pathinfo($image, PATHINFO_EXTENSION));
if (!($extension == "png" || $extension == "jpg" || $extension == "jpeg")) {
self::$ERROR_IMAGE_TYPE_INVALID;
return self::$ERROR_IMAGE_TYPE_INVALID;
}
return self::$NO_ERROR;
......@@ -113,7 +112,7 @@ class CourseValidator
public static function checkPrintable(bool $printable): int
{
if ($printable !== true && $printable !== false) { // TODO Simplify
if ($printable !== true && $printable !== false) {
return self::$ERROR_COURSE_PRINTABLE_INVALID;
}
......
......@@ -16,7 +16,6 @@ use App\Entity\User;
use function in_array;
use function simplexml_load_string;
// TODO
class CreateCourse
{
private Course $course;
......@@ -138,7 +137,7 @@ class CreateCourse
}
}
private function generatePreviewKml(string $kml)
private function generatePreviewKml(string $kml): string
{
$error = CourseValidator::checkKml($kml);
if ($error == CourseValidator::$NO_ERROR) {
......@@ -148,7 +147,7 @@ class CreateCourse
}
}
private function generatePreviewImage(string $image)
private function generatePreviewImage(string $image): string
{
$error = CourseValidator::checkImage($image);
if ($error == CourseValidator::$NO_ERROR) {
......@@ -380,7 +379,7 @@ class CreateCourse
return null;
}
public function translateError(int $error_code)
public function translateError(int $error_code): string
{
switch ($error_code) {
case CourseValidator::$NO_ERROR:
......
......@@ -8,7 +8,6 @@ use Exception;
use App\Entity\MissingControlPoint;
use function json_decode;
// TODO
class CreateMissingControlPoint
{
private MissingControlPoint $controlPoint;
......@@ -48,11 +47,8 @@ class CreateMissingControlPoint
$entityManager->persist($this->controlPoint);
$entityManager->flush();
} catch (Exception $e) {
if (strpos($e->getMessage(), "Integrity constraint violation")) {
return false;
} else {
return false;
}
return false;
}
return true;
......
......@@ -8,7 +8,6 @@ use Exception;
use App\Entity\Track;
use function json_decode;
// TODO
class CreateTrack
{
private Track $track;
......
......@@ -3,18 +3,16 @@
namespace App\Model;
use Doctrine\DBAL\DBALException;
use Doctrine\ORM\ORMException;
use Doctrine\Persistence\ObjectManager;
use Exception;
use Swift_Mailer;
use Swift_Message;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use PDOException;
use App\Entity\User;
use Symfony\Contracts\Translation\TranslatorInterface;
// TODO
class CreateUser
{
private User $user;
......@@ -27,7 +25,7 @@ class CreateUser
$this->translator = $translator;
}
public function addUser(UserPasswordEncoderInterface $passwordEncoder, ObjectManager $entityManager)
public function addUser(UserPasswordHasherInterface $passwordEncoder, ObjectManager $entityManager)
{
if ($this->user->getPassword() != "") {
$info = password_get_info($this->user->getPassword());
......@@ -35,13 +33,13 @@ class CreateUser
if (strlen($this->user->getPassword()) < 4 || strlen($this->user->getPassword()) > 4095) {
return $this->translator->trans("password.invalid_length", ['length' => 4]);
} else {
$encodedPassword = $passwordEncoder->encodePassword($this->user, $this->user->getPassword());
$encodedPassword = $passwordEncoder->hashPassword($this->user, $this->user->getPassword());
$this->user->setPassword($encodedPassword);
}
}
} else {
$this->plainPassword = self::generatePassword();
$encodedPassword = $passwordEncoder->encodePassword($this->user, $this->plainPassword);
$encodedPassword = $passwordEncoder->hashPassword($this->user, $this->plainPassword);
$this->user->setPassword($encodedPassword);
}
if (!$this->user->isValid()) {
......@@ -50,7 +48,7 @@ class CreateUser
try {
$entityManager->persist($this->user);
$entityManager->flush();
} catch (DBALException $e) { // TODO Never throw
} catch (DBALException $e) {
if (strpos($e->getMessage(), "Duplicate entry")) {
return $this->translator->trans("name.already.exist");
} elseif (strpos($e->getMessage(), "Integrity constraint violation")) {
......@@ -58,9 +56,7 @@ class CreateUser
} else {
return $e->getMessage();
}
} catch (PDOException $e) {
return $e->getMessage();
} catch (ORMException $e) { // TODO Never throw
} catch (Exception $e) {
return $e->getMessage();
}
......@@ -68,10 +64,10 @@ class CreateUser
}
}
public function changeUser(UserPasswordEncoderInterface $passwordEncoder, ObjectManager $entityManager)
public function changeUser(UserPasswordHasherInterface $passwordEncoder, ObjectManager $entityManager)
{
if ($this->user->getPlainPassword() != '') {
$encodedPassword = $passwordEncoder->encodePassword($this->user, $this->user->getPlainPassword());
$encodedPassword = $passwordEncoder->hashPassword($this->user, $this->user->getPlainPassword());
$this->user->setPassword($encodedPassword);
}
if (!$this->user->isValid()) {
......@@ -91,18 +87,18 @@ class CreateUser
}
}
public function forgotPassword(UserPasswordEncoderInterface $encoder, ObjectManager $entityManager)
public function forgotPassword(UserPasswordHasherInterface $encoder, ObjectManager $entityManager)
{
$this->plainPassword = self::generatePassword();
$encoded = $encoder->encodePassword($this->user, $this->plainPassword);
$encoded = $encoder->hashPassword($this->user, $this->plainPassword);
$this->user->setPassword($encoded);
$entityManager->persist($this->user);
$entityManager->flush();
}
public function changePassword(String $newPassword, UserPasswordEncoderInterface $encoder, ObjectManager $entityManager)
public function changePassword(String $newPassword, UserPasswordHasherInterface $encoder, ObjectManager $entityManager)
{
$encoded = $encoder->encodePassword($this->user, $newPassword);
$encoded = $encoder->hashPassword($this->user, $newPassword);
$this->user->setPassword($encoded);
$entityManager->persist($this->user);
$entityManager->flush();
......@@ -126,7 +122,7 @@ class CreateUser
$mailer->send($message);
}
public static function generatePassword()
public static function generatePassword(): string
{
// Random_int is supposed to be "cryptographically secure" number
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
......@@ -144,14 +140,14 @@ class CreateUser
return $str;
}
public function translateError(int $error_code)
public function translateError(int $error_code): string
{
switch ($error_code) {
case UserValidator::$NO_ERR:
case UserValidator::$NO_ERROR:
return $this->translator->trans("error.no");
case UserValidator::$USERNAME_INV:
case UserValidator::$USERNAME_ERROR:
return $this->translator->trans("error.user.name.invalid");
case UserValidator::$EMAIL_INV;
case UserValidator::$EMAIL_ERROR;
return $this->translator->trans("error.email.invalid");
default: // unknown error
return $this->translator->trans("error.unknown");
......
......@@ -3,12 +3,9 @@
namespace App\Model;
use DOMDocument;
use phpDocumentor\Reflection\Types\Array_;
use Symfony\Component\HttpFoundation\File\File;
use ZipArchive;
use function date_default_timezone_set;
// TODO
class FileUploader
{
public static function uploadFile($file, int $userId)
......@@ -29,9 +26,9 @@ class FileUploader
}
self::cleanDir($userId, $extension);
date_default_timezone_set("UTC");
$newFileName = time() . "." . $userId . ".";
$newFileName = time().".".$userId.".";
$tmpDir = "tmp_files";
$file->move($tmpDir, $newFileName . $extension);
$file->move($tmpDir, $newFileName.$extension);
// KMZ archive must be unzipped to retrieve .kml and .jpeg, then deleted
if ($extension == "zip") {
......@@ -39,10 +36,10 @@ class FileUploader
self::cleanDir($userId, "jpg");
$zip = new ZipArchive;
$res = $zip->open($tmpDir.'/'.$newFileName.$extension);
if ($res === TRUE) {
if ($res === true) {
$zip->renameName("doc.kml", $newFileName."kml");
$zip->renameName("files/tile_0_0.jpg", $newFileName."jpg");
$zip->extractTo($tmpDir, array($newFileName."kml",$newFileName."jpg"));
$zip->extractTo($tmpDir, array($newFileName."kml", $newFileName."jpg"));
$zip->close();
}
if (file_exists($tmpDir."/".$newFileName.$extension)) {
......@@ -51,21 +48,23 @@ class FileUploader
}
$content = "";
if ($extension == "xml"){
if ($extension == "xml") {
$xml = simplexml_load_file($tmpDir."/".$newFileName.$extension);
$array = array();
foreach ($xml->RaceCourseData->Course as $course){
array_push($array,$course->Name->__toString());
foreach ($xml->RaceCourseData->Course as $course) {
array_push($array, $course->Name->__toString());
}
$content = $array;
}
return json_encode([ "extension"=> $extension, "content" => $content]);
return json_encode(["extension" => $extension, "content" => $content]);
}
/* Directory will get clean only when one user adds a course
if you want to clean at regular interval you might want to use
a deamond calling this script (or another cleaning script). */
/**
* Directory will get clean only when one user adds a course
* if you want to clean at regular interval you might want to use
* a deamond calling this script (or another cleaning script).
*/
public static function cleanDir(int $userid, string $extension)
{
date_default_timezone_set("UTC");
......@@ -75,27 +74,27 @@ class FileUploader
mkdir($dir);
}
foreach (scandir($dir) as $file) {
if (!is_dir($dir . "/" . $file)) {
if (!is_dir($dir."/".$file)) {
$files_parts = preg_split("/[.]/", $file);
//delete files older than one day
if (intval($files_parts[0]) + $day_value < time()) {
//probably useless check but we never no
if (file_exists($dir . "/" . $file)) {
unlink($dir . "/" . $file);
if (file_exists($dir."/".$file)) {
unlink($dir."/".$file);
}
}
//delete old file of user according to extension
if ($userid == $files_parts[1]) {
if ($extension == $files_parts[2] || $extension == "all") {
//check in case the file was a day or more old
if (file_exists($dir . "/" . $file)) {
unlink($dir . "/" . $file);
if (file_exists($dir."/".$file)) {
unlink($dir."/".$file);
}
}
if ($extension == "jpeg" || $extension == "jpg" || $extension == "png"){
if ($files_parts[2] == "jpeg" || $files_parts[2] == "jpg" || $files_parts[2] == "png"){
if (file_exists($dir . "/" . $file)) {
unlink($dir . "/" . $file);
if ($extension == "jpeg" || $extension == "jpg" || $extension == "png") {
if ($files_parts[2] == "jpeg" || $files_parts[2] == "jpg" || $files_parts[2] == "png") {
if (file_exists($dir."/".$file)) {
unlink($dir."/".$file);
}
}
}
......@@ -108,12 +107,12 @@ class FileUploader
{
$dir = "tmp_files";
foreach (scandir($dir) as $file) {
if (!is_dir($dir . "/" . $file)) {
if (!is_dir($dir."/".$file)) {
$files_parts = preg_split("/[.]/", $file);
if ($userid == $files_parts[1]) {
if ($extension == $files_parts[2] || ($extension == "image" && ($files_parts[2] == "png" || $files_parts[2] == "jpg" || $files_parts[2] == "jpeg"))) {
return $dir . "/" . $file;
return $dir."/".$file;
}
}
}
......
......@@ -7,7 +7,6 @@ use App\Entity\Track;
use Exception;
use Symfony\Component\HttpFoundation\File\UploadedFile;
// TODO
class GpxImport
{
private string $nickname;
......
......@@ -7,7 +7,6 @@ use App\Entity\Participant;
use App\Repository\ParticipantMakeEventCourseRepository;
use Doctrine\Persistence\ObjectManager;
// TODO
class ManuallySetPenaltyOfParticipantMakeEventCourse
{
private ?Participant $participant = null;
......@@ -82,15 +81,15 @@ class ManuallySetPenaltyOfParticipantMakeEventCourse
public function modify(ObjectManager $entityManager, ParticipantMakeEventCourseRepository $participantMakeEventCourseRepository)
{
$participantMakeEventCourse = $participantMakeEventCourseRepository->find(array("eventCourse" => $this->eventCourse, "participant" => $this->participant));
if($this->nbOT===null){
if ($this->nbOT === null) {
$participantMakeEventCourse->setOtPenaltyManuallySet(false);
}else{
} else {
$participantMakeEventCourse->setOtPenaltyManuallySet(true);
$participantMakeEventCourse->setNbOverTimePenalty($this->nbOT);
}
if($this->nbPM===null){
if ($this->nbPM === null) {
$participantMakeEventCourse->setPmPenaltyManuallySet(false);
}else{
} else {
$participantMakeEventCourse->setPmPenaltyManuallySet(true);
$participantMakeEventCourse->setNbMissingPunchPenalty($this->nbPM);
}
......@@ -98,4 +97,4 @@ class ManuallySetPenaltyOfParticipantMakeEventCourse
$entityManager->flush();
$participantMakeEventCourse->getEventCourse()->getEvent()->update($entityManager, $participantMakeEventCourseRepository);
}
}
\ No newline at end of file
}
......@@ -4,17 +4,12 @@ namespace App\Model;
use App\Entity\EventCourse;
// TODO
class ModifyEventCourse
{
private int $id;
private int $format;
private int $missingPunchPenalty;
private int $overTimePenalty;
private ?int $id;
private ?int $format;
private ?int $missingPunchPenalty;
private ?int $overTimePenalty;
private string $time;
function __construct(EventCourse $eventCourse)
......@@ -26,7 +21,8 @@ class ModifyEventCourse
$this->time = (string)$eventCourse->getMaxTime() / 1000;
}
function modify($eventCourseRepository, $entityManager){
function modify($eventCourseRepository, $entityManager)
{
$eventCourse = $eventCourseRepository->find($this->id);
$eventCourse->setFormat($this->format);
$eventCourse->setMissingPunchPenalty($this->missingPunchPenalty);
......
......@@ -2,14 +2,11 @@
namespace App\Model;
use App\Entity\EventCourse;
use App\Entity\Participant;
use App\Entity\ParticipantMakeEventCourse;
use App\Entity\Track;
use App\Repository\ParticipantMakeEventCourseRepository;
use Doctrine\Persistence\ObjectManager;
// TODO
class ModifyParticipantMakeEventCourse
{
private ?Track $track = null;
......
......@@ -2,12 +2,9 @@
namespace App\Model;
use App\Controller\CourseController;
// TODO
class TrackStatistics
{
public function distanceInMeters($lat1, $lng1, $lat2, $lng2)
public function distanceInMeters($lat1, $lng1, $lat2, $lng2): float
{
$rad = M_PI / 180;
$lat1r = $lat1 * $rad;
......@@ -17,10 +14,10 @@ class TrackStatistics
$a = $sinDLat * $sinDLat + cos($lat1r) * cos($lat2r) * $sinDLon * $sinDLon;
$c = 2 * atan2(sqrt($a), sqrt(1 - $a));
return 6371000 * $c;
return 6371000.0 * $c;
}
public function computeSplitTime(array $controlPoints)
public function computeSplitTime(array $controlPoints): array
{
$splitTimes = array();
$splitTimes[] = "";
......@@ -39,7 +36,7 @@ class TrackStatistics
return $splitTimes;
}
public function computeActualSplitDistance(array $controlPoints, string $trace)
public function computeActualSplitDistance(array $controlPoints, string $trace): array
{
$distances = array();
$distances[] = "";
......@@ -53,7 +50,7 @@ class TrackStatistics
$currentWayPointTimeInMillis = $wayPoint[2];
$distance += $this->distanceInMeters($previousWayPoint[0], $previousWayPoint[1], $wayPoint[0], $wayPoint[1]);
$previousWayPoint = $wayPoint;
if ($currentWayPointTimeInMillis >= $nextLegTimeInMillis and $currentLeg<count($controlPoints)-1) {
if ($currentWayPointTimeInMillis >= $nextLegTimeInMillis and $currentLeg < count($controlPoints) - 1) {
$currentLeg++;
$distances[] = (int)$distance;
$distance = 0;
......@@ -64,7 +61,7 @@ class TrackStatistics
return $distances;
}
public function computeSplitPaces(array $splitTimes, array $lengths)
public function computeSplitPaces(array $splitTimes, array $lengths): array
{
$paces = array();
$paces[] = 0;
......@@ -88,9 +85,7 @@ class TrackStatistics
$wayPoints = array();
$xmlData = simplexml_load_string($trace);
foreach ($xmlData->trk->trkseg->children() as $trkpt) {
$timeInMs = $this->convertDateToMilliseconds($trkpt->time);
$lat = $trkpt["lat"];
$lon = $trkpt["lon"];
array_push($wayPoints, [$lat, $lon, $timeInMs]);
......
......@@ -2,34 +2,33 @@
namespace App\Model;
// TODO
class UserValidator
{
static int $NO_ERR = 0;
static int $USERNAME_INV = 1;
static int $EMAIL_INV = 2;
static int $NO_ERROR = 0;
static int $USERNAME_ERROR = 1;
static int $EMAIL_ERROR = 2;
public static function checkUsername(string $name): int
{
if (preg_match("/[a-zA-Z][a-zA-Z0-9]*/", $name)) {
return self::$NO_ERR;
return self::$NO_ERROR;
} else {
return self::$USERNAME_INV;
return self::$USERNAME_ERROR;
}
}
public static function checkEmail(string $email): int
{
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
return self::$NO_ERR;
return self::$NO_ERROR;
} else {
return self::$EMAIL_INV;
return self::$EMAIL_ERROR;
}
}
public static function checkValid(string $name, string $email)
{
//smallest error code is always NO_ERROR
// Caveat: smallest error code is always NO_ERR
return max(self::checkUsername($name), self::checkEmail($email));
}
}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment