1
0
mirror of https://framagit.org/tykayn/date-poll-api synced 2023-08-25 08:23:11 +02:00

Compare commits

..

No commits in common. "747ebb9d2fdcf005ea47f66ce43b1eaac7c93b2c" and "1d72bfe68410438119f41be9bf4a38f3e8bf6cd7" have entirely different histories.

30 changed files with 1354 additions and 1441 deletions

View File

@ -2,9 +2,14 @@
namespace App\Controller;
use App\Entity\Owner;
use App\Entity\Poll;
use App\Repository\PollRepository;
use App\Service\MailService;
use FOS\RestBundle\Controller\Annotations\Get;
use FOS\RestBundle\Controller\Annotations\Route;
use JMS\Serializer\Type\Exception\Exception;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
/**

View File

@ -5,10 +5,8 @@ namespace App\Controller;
use App\Entity\Owner;
use App\Entity\Poll;
use JMS\Serializer\Type\Exception\Exception;
use Swift_Mailer;
use Swift_Message;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
/**
* sending emails controller
@ -20,37 +18,16 @@ class EmailsController extends AbstractController {
private $mail_service;
public function __construct( Swift_Mailer $mailer ) {
public function __construct( \Swift_Mailer $mailer ) {
$this->mail_service = $mailer;
}
/**
* send created polls to an owner
*
* @param Owner $owner
*
* @return int|void
* @throws Exception
* @throws TransportExceptionInterface
*/
public function sendOwnerPollsAction( Owner $owner ) {
$config = [
'owner' => $owner,
'title' => $this->getParameter( 'WEBSITE_NAME' ) . ' | Mes sondages',
'email_template' => 'emails/owner-list.html.twig',
];
$this->sendMailWithVars( $config );
return 1;
}
/**
* generic way to send email with html template
*
* @param $config
*
* @throws TransportExceptionInterface
* @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
*/
public function sendMailWithVars( $config ) {
@ -95,11 +72,33 @@ class EmailsController extends AbstractController {
}
/**
* send created polls to an owner
*
* @param Owner $owner
*
* @return int|void
* @throws Exception
* @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
*/
public function sendOwnerPollsAction( Owner $owner ) {
$config = [
'owner' => $owner,
'title' => $this->getParameter( 'WEBSITE_NAME' ) . ' | Mes sondages',
'email_template' => 'emails/owner-list.html.twig',
];
$this->sendMailWithVars( $config );
return 1;
}
/**
* @param Owner $foundOwner
* @param Poll|null $poll
*
* @throws TransportExceptionInterface
* @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
*/
public function sendCreationMailAction( Owner $foundOwner, Poll $poll = null ) {
@ -121,7 +120,7 @@ class EmailsController extends AbstractController {
* @param $comment
*
* @return int
* @throws TransportExceptionInterface
* @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
*/
public function sendCommentNotificationAction( Owner $owner, $comment ) {
@ -142,7 +141,7 @@ class EmailsController extends AbstractController {
* @param $stackOfVotes
*
* @return int
* @throws TransportExceptionInterface
* @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
*/
public function sendVoteNotificationAction( Owner $owner, $stackOfVotes ) {

View File

@ -1,19 +1,20 @@
<?php
namespace App\Controller;
//use FOS\RestBundle\Controller\Annotations\Get;
//use FOS\RestBundle\Controller\Annotations\Route;
use App\Entity\Choice;
use App\Entity\Comment;
use App\Entity\Owner;
use App\Entity\Poll;
use App\Entity\StackOfVotes;
use App\Entity\Vote;
use App\Repository\PollRepository;
use App\Service\MailService;
use FOS\RestBundle\Controller\Annotations\Get;
use FOS\RestBundle\Controller\Annotations\Route;
use PDO;
use JMS\Serializer\Type\Exception\Exception;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Entity\Owner;
use App\Entity\Poll;
/**
* Class DefaultController
@ -33,7 +34,7 @@ class MigrationController extends EmailsController {
return new JsonResponse( [
'error' => 'NOPE! veuillez vérifier votre fichier .env',
] );
}
};
// fetch old Database
@ -44,13 +45,13 @@ class MigrationController extends EmailsController {
$pollsBySlug = [];
$pdo_options[ PDO::ATTR_ERRMODE ] = PDO::ERRMODE_EXCEPTION;
$bdd = new PDO( 'mysql:host=localhost;dbname=' . $this->getParameter( 'OLD_DATABASE_NAME' ),
$pdo_options[ \PDO::ATTR_ERRMODE ] = \PDO::ERRMODE_EXCEPTION;
$bdd = new \PDO( 'mysql:host=localhost;dbname=' . $this->getParameter( 'OLD_DATABASE_NAME' ),
$this->getParameter( 'OLD_DATABASE_USER' ),
$this->getParameter( 'OLD_DATABASE_PASS' ),
$pdo_options );
$res_polls = $bdd->query( 'SELECT * FROM fd_poll' );
while ( $d = $res_polls->fetch( PDO::FETCH_OBJ ) ) {
while ( $d = $res_polls->fetch( \PDO::FETCH_OBJ ) ) {
$debug .= " <br> ajout de sondage : ".$d->title .' - '. $d->id ;
@ -74,7 +75,7 @@ class MigrationController extends EmailsController {
->setChoicesMax( $d->ValueMax )
->setPassword( $d->password_hash )
->setDescription( $d->description )
->setCreatedAt( date_create( $d->creation_date ) );
->setCreationDate( date_create( $d->creation_date ) );
$pollsBySlug[ $d->id ] = $newPoll;
@ -87,7 +88,7 @@ class MigrationController extends EmailsController {
$pollChoicesOrderedBySlug = [];
$choicesCreated = [];
while ( $d = $res_slots->fetch( PDO::FETCH_OBJ ) ) {
while ( $d = $res_slots->fetch( \PDO::FETCH_OBJ ) ) {
$debug .= " <br> ajout de slot, converti en choix de réponse : ".$d->poll_id. ' : '. $d->moments;
@ -114,7 +115,7 @@ class MigrationController extends EmailsController {
// get votes
$stacksOfVote = [];
$res_votes = $bdd->query( 'SELECT * FROM fd_vote' );
while ( $d = $res_votes->fetch( PDO::FETCH_OBJ ) ) {
while ( $d = $res_votes->fetch( \PDO::FETCH_OBJ ) ) {
$debug .= " <br> ajout de stack de vote : ".$d->name;
$pollSlug = $d->poll_id;
@ -125,11 +126,13 @@ class MigrationController extends EmailsController {
$newOwner
->setPseudo($d->name)
->setEmail('the_anonymous_email_from_@_migration_offramadate.org')
->setModifierToken( $d->uniqId );
->setModifierToken($d->uniqId)
;
$newStack->setPoll($poll)
->setOwner($newOwner)
->setPseudo( $d->name );
->setPseudo($d->name)
;
// each choice answer is encoded in a value :
@ -147,7 +150,8 @@ class MigrationController extends EmailsController {
->setChoice($choice)
->setStacksOfVotes($newStack)
->setPoll($poll)
->setValue( $this->mapAnswerNumberToWord( $vote_code ) );
->setValue( $this->mapAnswerNumberToWord($vote_code))
;
$newStack->addVote($newVote);
$em->persist( $newVote );
@ -165,7 +169,7 @@ class MigrationController extends EmailsController {
$comments = [];
$res_comments = $bdd->query( 'SELECT * FROM fd_comment' );
while ( $d = $res_comments->fetch( PDO::FETCH_OBJ ) ) {
while ( $d = $res_comments->fetch( \PDO::FETCH_OBJ ) ) {
$debug .= " <br> ajout de commentaire : ".$d->name. ' '. $d->comment;
@ -190,8 +194,7 @@ class MigrationController extends EmailsController {
// failure notice
$debug .= " <br> <br> ça c'est fait. ";
return $this->render( 'pages/migration.html.twig',
[
return $this->render('pages/migration.html.twig' , [
"message" => "welcome to the framadate migration endpoint, it has yet to be done",
"debug" => $debug,
"OLD_DATABASE_NAME" => $this->getParameter( 'OLD_DATABASE_NAME' ),
@ -202,15 +205,13 @@ class MigrationController extends EmailsController {
'choices' => count($choicesCreated),
'stacks_of_votes' => count($stacksOfVote),
'votes' => count($votes),
],
]
]);
}
/**
* @param $numberToConvert
* conversion of answer:
* space character : no answer, 0 : no , 1 : maybe , 2 : yes
*
* @return string
*/
public function mapAnswerNumberToWord($numberToConvert){
@ -228,7 +229,6 @@ class MigrationController extends EmailsController {
default:
$word = 'no';
}
return $word;
}

View File

@ -9,24 +9,25 @@ use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
/**
* @Route("/poll")
*/
class PollController extends AbstractController {
class PollController extends AbstractController
{
/**
* @Route("/", name="poll_index", methods={"GET"})
*/
public function index( PollRepository $pollRepository ): Response {
public function index(PollRepository $pollRepository): Response
{
$polls = $pollRepository->findAll();
$titles=[];
foreach ( $polls as $poll ) {
$titles[] = $poll->getTitle();
}
return $this->render( 'poll/index.html.twig',
[
return $this->render('poll/index.html.twig', [
'count' => count($polls),
'titles' => $titles,
'polls' => $polls,
@ -36,7 +37,8 @@ class PollController extends AbstractController {
/**
* @Route("/new", name="poll_new", methods={"GET","POST"})
*/
public function new( Request $request ): Response {
public function new(Request $request): Response
{
$poll = new Poll();
$form = $this->createForm(PollType::class, $poll);
$form->handleRequest($request);
@ -49,8 +51,7 @@ class PollController extends AbstractController {
return $this->redirectToRoute('poll_index');
}
return $this->render( 'poll/new.html.twig',
[
return $this->render('poll/new.html.twig', [
'poll' => $poll,
'form' => $form->createView(),
]);
@ -60,18 +61,17 @@ class PollController extends AbstractController {
* on cherche un sondage par son url personnalisée
* @Route("/{id}", name="poll_show", methods={"GET"})
*/
public function show( $id ): Response {
public function show($id): Response
{
$repository = $this->getDoctrine()->getRepository(Poll::class);
$foundPoll = $repository->findOneByCustomUrl($id);
if(!$foundPoll){
return $this->json([
'message' => $id . ' : not found',
],
404 );
'message' => $id.' : not found'
], 404);
}
return $this->render( 'poll/show.html.twig',
[
return $this->render('poll/show.html.twig', [
'poll' => $foundPoll,
]);
}
@ -79,7 +79,8 @@ class PollController extends AbstractController {
/**
* @Route("/{id}/edit", name="poll_edit", methods={"GET","POST"})
*/
public function edit( Request $request, Poll $poll ): Response {
public function edit(Request $request, Poll $poll): Response
{
$form = $this->createForm(PollType::class, $poll);
$form->handleRequest($request);
@ -89,8 +90,7 @@ class PollController extends AbstractController {
return $this->redirectToRoute('poll_index');
}
return $this->render( 'poll/edit.html.twig',
[
return $this->render('poll/edit.html.twig', [
'poll' => $poll,
'form' => $form->createView(),
]);
@ -99,7 +99,8 @@ class PollController extends AbstractController {
/**
* @Route("/{id}", name="poll_delete", methods={"DELETE"})
*/
public function delete( Request $request, Poll $poll ): Response {
public function delete(Request $request, Poll $poll): Response
{
if ($this->isCsrfTokenValid('delete'.$poll->getId(), $request->request->get('_token'))) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($poll);

View File

@ -38,9 +38,7 @@ class CommentController extends EmailsController {
) {
$jsonResponse = $serializer->serialize([
'message' => 'here are your comments of the poll',
'data' => $poll->getComments(),
],
'json' );
'data' => $poll->getComments()], 'json');
$response = new Response($jsonResponse);
$response->headers->set('Content-Type', 'application/json');

View File

@ -7,11 +7,6 @@ use App\Entity\Choice;
use App\Entity\Owner;
use App\Entity\Poll;
use App\Repository\PollRepository;
use FOS\RestBundle\Controller\Annotations\Delete;
use FOS\RestBundle\Controller\Annotations\Get;
use FOS\RestBundle\Controller\Annotations\Post;
use FOS\RestBundle\Controller\Annotations\Put;
use FOS\RestBundle\Controller\Annotations\Route;
use JMS\Serializer\Exception\RuntimeException;
use JMS\Serializer\SerializerBuilder;
use JMS\Serializer\SerializerInterface;
@ -19,6 +14,13 @@ use Swift_Mailer;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use FOS\RestBundle\Controller\Annotations\Get;
use FOS\RestBundle\Controller\Annotations\Put;
use FOS\RestBundle\Controller\Annotations\Delete;
use FOS\RestBundle\Controller\Annotations\Post;
use FOS\RestBundle\Controller\Annotations\Route;
/**
* Class DefaultController
@ -61,6 +63,19 @@ class PollController extends EmailsController {
}
/**
* @param $id
* message when the poll is not found
*
* @return JsonResponse
*/
public function notFoundPoll( $id ): Response {
return $this->json( [
'message' => $id . ' : poll not found',
],
404 );
}
/**
* get a poll config by its custom URL, we do not want polls to be reachable by their numeric id
* @Get(
@ -88,9 +103,30 @@ class PollController extends EmailsController {
$comments = $poll->getComments();
$stacks = $poll->getStacksOfVotes();
$displayedComments = [];
foreach ( $comments as $comment ) {
$displayedComments[] = $comment->display();
}
$displayedStackOfVotes = [];
foreach ( $stacks as $stack ) {
$displayedStackOfVotes[] = $stack->display();
}
$displayedChoices = [];
foreach ( $poll->getChoices() as $choice
) {
$displayedChoices[] = $choice->display();
}
$pass = $poll->getPassword();
$returnedPoll = [
'message' => 'your poll config for ' . $poll->getTitle(),
'poll' => $poll->display(),
// TODO do not render sub objects of owner, it returns too many thing
'stacks' => $displayedStackOfVotes,
'choices' => $displayedChoices,
'comments' => $displayedComments,
];
/**
* password protected content
@ -104,24 +140,13 @@ class PollController extends EmailsController {
} else {
// free access to poll
return $this->json( $poll->display() );
// return $this->returnPollData( $poll, $serializer );
return $this->json( $returnedPoll );
// return $this->json($poll);
}
}
/**
* @param $id
* message when the poll is not found
*
* @return JsonResponse
*/
public function notFoundPoll( $id ): Response {
return $this->json( [
'message' => $id . ' : poll not found',
],
404 );
}
/**
* get a poll config by its custom URL, we do not want polls to be reachable by their numeric id
* @Get(
@ -142,9 +167,9 @@ class PollController extends EmailsController {
return $this->notFoundPoll( $customUrl );
}
if ( md5( $poll->getPassword() ) === $md5 ) {
if ( $poll->getPassword() === $md5 ) {
// good matching pass
return $this->json( $poll->display() );
return $this->returnPollData( $poll, $serializer );
} else {
// wrong pass
return $this->json( [
@ -193,8 +218,10 @@ class PollController extends EmailsController {
$em->persist( $poll );
$em->flush();
return $this->json( $poll->displayForAdmin()
,
return $this->json( [
'message' => 'you updated the poll ' . $poll->getTitle(),
"poll" => $poll,
],
200 );
}
@ -276,6 +303,7 @@ class PollController extends EmailsController {
$newChoice = new Choice();
$newChoice
->setPoll( $newpoll )
// ->setUrl( $c[ 'url' ] )
->setName( $c[ 'literal' ] );
$em->persist( $newChoice );
// TODO add also choices for each time range in a day
@ -303,8 +331,10 @@ class PollController extends EmailsController {
return $this->json( [
'message' => 'you created a poll ' . $precision,
'poll' => $newpoll->displayForAdmin,
'poll' => $newpoll,
'password_protected' => is_string( $newpoll->getPassword() ),
'admin_key' => $newpoll->getAdminKey(),
'owner_modifier_token' => $foundOwner->getModifierToken(),
],
201 );

View File

@ -31,7 +31,6 @@ class VoteController extends EmailsController {
* name = "new_vote_stack",
* requirements = {"content"="\w+", "poll_id"="\d+"}
* )
*
* @param SerializerInterface $serializer
* @param Poll $poll
* @param Request $request
@ -67,11 +66,10 @@ class VoteController extends EmailsController {
}
// TODO anti flood
$foundOwner
->setModifierToken( $poll->generateRandomKey() );
->setModifierToken( $poll->generateAdminKey() );
$stack = new StackOfVotes();
$stack
->setOwner( $foundOwner )
->setIp( $_SERVER[ 'REMOTE_ADDR' ] )
->setPseudo( $data[ 'pseudo' ] )
->setPoll( $poll );
foreach ( $data[ 'votes' ] as $voteInfo ) {
@ -141,7 +139,6 @@ class VoteController extends EmailsController {
* name = "update_vote_stack",
* requirements = { "id"="\d+"}
* )
*
* @param SerializerInterface $serializer
* @param StackOfVotes $id
* @param $modifierToken
@ -178,8 +175,7 @@ class VoteController extends EmailsController {
'message' => 'ok',
'modifier_token' => $voteStack->getOwner()->getModifierToken(),
'vote_stack' => $voteStack,
],
'json' );
], 'json');
$response = new Response($jsonResponse);
$response->headers->set('Content-Type', 'application/json');
@ -211,13 +207,11 @@ class VoteController extends EmailsController {
return $this->json( [
'message' => 'boom! les ' . $length . ' votes du sondage ont été supprimés',
],
200 );
],200 );
} else {
return $this->json( [
'message' => 'le token d\'autorisation est invalide, vous ne pouvez pas modifier ce sondage',
],
403 );
'message' => 'le token d\'autorisation est invalide, vous ne pouvez pas modifier ce sondage'
],403 );
}
}
}

View File

@ -6,8 +6,10 @@ use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
class AppFixtures extends Fixture {
public function load( ObjectManager $manager ) {
class AppFixtures extends Fixture
{
public function load(ObjectManager $manager)
{
// $product = new Product();
// $manager->persist($product);

View File

@ -3,6 +3,7 @@
namespace App\DataFixtures;
use App\Entity\Owner;
use App\Entity\Poll;
use App\Entity\StackOfVotes;
use App\Entity\Vote;
use Doctrine\Bundle\FixturesBundle\Fixture;
@ -10,7 +11,8 @@ use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Doctrine\Persistence\ObjectManager;
class VotesStacksFixtures extends Fixture implements DependentFixtureInterface {
public function getDependencies() {
public function getDependencies()
{
return [
AppPollFixtures::class,
];

View File

@ -2,7 +2,6 @@
namespace App\Entity;
use App\Traits\TimeStampableTrait;
use DateTime;
use DateTimeInterface;
use Doctrine\Common\Collections\ArrayCollection;
@ -16,9 +15,6 @@ use JMS\Serializer\Annotation as Serializer;
* @Serializer\ExclusionPolicy("all")
*/
class Choice {
use TimeStampableTrait;
/**
* @ORM\Id()
* @ORM\GeneratedValue()
@ -40,7 +36,11 @@ class Choice {
*/
public $url;
/**
* @ORM\Column(type="datetime", nullable=true)
* @Serializer\Type("datetime")
*/
public $dateTime;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Vote", mappedBy="choice", cascade={"persist"})
* @Serializer\Type("App\Entity\Vote")
@ -53,7 +53,6 @@ class Choice {
private $poll;
public function __construct( $optionalName = null ) {
$this->setCreatedAt( new DateTime() );
$this->poll = new ArrayCollection();
$this->votes = new ArrayCollection();
$this->setDateTime( new DateTime() );
@ -62,31 +61,30 @@ class Choice {
}
}
public function setDateTime( ?DateTimeInterface $dateTime ): self {
$this->dateTime = $dateTime;
return $this;
}
public function display( $kind = 'text' ) {
$fields = [
public function display() {
return [
'id' => $this->getId(),
'created_at' => $this->getCreatedAtAsString(),
'date' => $this->getDateTime(),
'name' => $this->getName(),
'url' => $this->getUrl(),
];
if ( $kind === 'date' ) {
$date = new DateTime( $this->getName() );
$fields[ 'name' ] = $date->format( 'c' );
}
return $fields;
}
public function getId(): ?int {
return $this->id;
}
public function getDateTime(): ?DateTimeInterface {
return $this->dateTime;
}
public function setDateTime( ?DateTimeInterface $dateTime ): self {
$this->dateTime = $dateTime;
return $this;
}
public function getName(): ?string {
return $this->name;
}
@ -97,20 +95,6 @@ class Choice {
return $this;
}
public function getUrl(): ?string {
return $this->url;
}
public function setUrl( ?string $url ): self {
$this->url = $url;
return $this;
}
public function getDateTime(): ?DateTimeInterface {
return $this->dateTime;
}
public function getPoll(): ?Poll {
return $this->poll;
}
@ -148,4 +132,14 @@ class Choice {
return $this;
}
public function getUrl(): ?string {
return $this->url;
}
public function setUrl( ?string $url ): self {
$this->url = $url;
return $this;
}
}

View File

@ -2,8 +2,6 @@
namespace App\Entity;
use App\Traits\TimeStampableTrait;
use DateTime;
use DateTimeInterface;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as Serializer;
@ -13,9 +11,6 @@ use JMS\Serializer\Annotation as Serializer;
* @Serializer\ExclusionPolicy("all")
*/
class Comment {
use TimeStampableTrait;
/**
* @ORM\Id()
* @ORM\GeneratedValue()
@ -44,38 +39,45 @@ class Comment {
*/
private $text;
/**
* @ORM\Column(type="datetime")
* @Serializer\Type("datetime")
* @Serializer\Expose()
*/
private $createdAt;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Poll", inversedBy="comments")
*/
private $poll;
function __construct() {
$this->setCreatedAt( new DateTime() );
}
public function setCreatedAt( DateTimeInterface $createdAt ): self {
$this->createdAt = $createdAt;
return $this;
}
public function getCreatedAt(): ?DateTimeInterface {
return $this->createdAt;
}
function display() {
return [
'id' => $this->getId(),
'text' => $this->getText(),
'pseudo' => $this->getOwner()->getPseudo(),
'created_at' => $this->getCreatedAtAsString(),
'date' => $this->getCreatedAt(),
];
}
function __construct() {
$this->setCreatedAt( new \DateTime() );
}
public function getId(): ?int {
return $this->id;
}
public function getOwner(): ?Owner {
return $this->owner;
}
public function setOwner( ?Owner $owner ): self {
$this->owner = $owner;
return $this;
}
public function getText(): ?string {
return $this->text;
}
@ -86,12 +88,12 @@ class Comment {
return $this;
}
public function getOwner(): ?Owner {
return $this->owner;
public function getCreatedAt(): ?DateTimeInterface {
return $this->createdAt;
}
public function setOwner( ?Owner $owner ): self {
$this->owner = $owner;
public function setCreatedAt( DateTimeInterface $createdAt ): self {
$this->createdAt = $createdAt;
return $this;
}
@ -106,11 +108,13 @@ class Comment {
return $this;
}
public function getPseudo(): ?string {
public function getPseudo(): ?string
{
return $this->pseudo;
}
public function setPseudo( string $pseudo ): self {
public function setPseudo(string $pseudo): self
{
$this->pseudo = $pseudo;
return $this;

View File

@ -2,9 +2,6 @@
namespace App\Entity;
use App\Traits\TimeStampableTrait;
use DateTime;
use DateTimeInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
@ -14,26 +11,24 @@ use JMS\Serializer\Annotation as Serializer;
* @ORM\Entity(repositoryClass="App\Repository\OwnerRepository")
*/
class Owner {
use TimeStampableTrait;
/**
* @ORM\Column(type="string", length=255)
* @Serializer\Type("string")
* @Serializer\Expose()
*/
public $pseudo;
/**
* @ORM\Column(type="string", length=255)
* @Serializer\Type("string")
* @Serializer\Expose()
*/
public $email;
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
* @Serializer\Type("string")
* @Serializer\Expose()
*/
public $email;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Poll", mappedBy="owner",cascade={"persist","remove"},orphanRemoval=true)
* @Serializer\Type("App\Entity\Poll")
@ -54,7 +49,10 @@ class Owner {
* @ORM\Column(type="string", length=255)
*/
private $modifierToken;
/**
* @ORM\Column(type="datetime" , options={"default"="CURRENT_TIMESTAMP"})
*/
private $createdAt;
/**
* @ORM\Column(type="datetime" , options={"default"="CURRENT_TIMESTAMP"},nullable=true)
*/
@ -64,54 +62,10 @@ class Owner {
$this->polls = new ArrayCollection();
$this->comments = new ArrayCollection();
$this->stackOfVotes = new ArrayCollection();
$this->setCreatedAt( new DateTime() );
$this->setCreatedAt( new \DateTime() );
$this->setModifierToken( uniqid() );
$this->setCreatedAt( new DateTime() );
}
public function setCreatedAt( DateTimeInterface $createdAt ): self {
$this->createdAt = $createdAt;
return $this;
}
public function getCreatedAt(): ?DateTimeInterface {
return $this->createdAt;
}
public function display() {
return [
'pseudo' => $this->getPseudo(),
];
}
public function getPseudo(): ?string {
return $this->pseudo;
}
public function setPseudo( string $pseudo ): self {
$this->pseudo = $pseudo;
return $this;
}
public function displayForAdmin() {
return [
'pseudo' => $this->getPseudo(),
'modifier_token' => $this->getModifierToken(),
'created_at' => $this->getCreatedAtAsString(),
];
}
public function getModifierToken(): ?string {
return $this->modifierToken;
}
public function setModifierToken( string $modifierToken ): self {
$this->modifierToken = $modifierToken;
return $this;
}
public function getId(): ?int {
return $this->id;
@ -127,6 +81,16 @@ class Owner {
return $this;
}
public function getPseudo(): ?string {
return $this->pseudo;
}
public function setPseudo( string $pseudo ): self {
$this->pseudo = $pseudo;
return $this;
}
/**
* @return Collection|Poll[]
*/
@ -211,6 +175,16 @@ class Owner {
return $this;
}
public function getModifierToken(): ?string {
return $this->modifierToken;
}
public function setModifierToken( string $modifierToken ): self {
$this->modifierToken = $modifierToken;
return $this;
}
public function addComment( Comment $comment ): self {
if ( ! $this->comments->contains( $comment ) ) {
$this->comments[] = $comment;
@ -232,6 +206,16 @@ class Owner {
return $this;
}
public function getCreatedAt(): ?\DateTimeInterface {
return $this->createdAt;
}
public function setCreatedAt( \DateTimeInterface $createdAt ): self {
$this->createdAt = $createdAt;
return $this;
}
public function getRequestedPollsDate() {
return $this->requestedPollsDate;
}

View File

@ -2,14 +2,10 @@
namespace App\Entity;
use App\Traits\RandomTrait;
use App\Traits\TimeStampableTrait;
use DateTime;
use DateTimeInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use ErrorException;
use JMS\Serializer\Annotation as Serializer;
/**
@ -17,11 +13,6 @@ use JMS\Serializer\Annotation as Serializer;
* @Serializer\ExclusionPolicy("all")
*/
class Poll {
use RandomTrait;
use TimeStampableTrait;
/**
* @ORM\Id()
* @ORM\GeneratedValue()
@ -49,7 +40,11 @@ class Poll {
* @Serializer\Type("string")
*/
public $description;
/**
* @ORM\Column(type="datetime" , options={"default"="CURRENT_TIMESTAMP"})
* @Serializer\Expose()
*/
public $creationDate;
/**
* @ORM\Column(type="datetime")
* @Serializer\Expose()
@ -173,12 +168,6 @@ class Poll {
* @Serializer\Type("ArrayCollection<App\Entity\Comment>")
*/
public $comments;
/**
* number of days from now for default expiracy date
* @var int
* @Serializer\Expose()
*/
public $defaultExpiracyDaysFromNow = 60;
/**
* vote restricted by a password in md5 format
* @ORM\Column(type="string", length=255, nullable=true)
@ -190,97 +179,30 @@ class Poll {
* @Serializer\Type("string")
*/
private $adminKey;
/**
* number of days from now for default expiracy date
* @var int
* @Serializer\Expose()
*/
public $defaultExpiracyDaysFromNow = 60;
private $maxChoicesLimit = 25;
public function __construct() {
$this->initiate();
$this->setCreatedAt( new DateTime() );
$this->votes = new ArrayCollection();
$this->stacksOfVotes = new ArrayCollection();
$this->choices = new ArrayCollection();
$this->comments = new ArrayCollection();
}
private function initiate() {
$this->votes = new ArrayCollection();
$this->stacksOfVotes = new ArrayCollection();
$this->choices = new ArrayCollection();
$this->comments = new ArrayCollection();
$this->setAdminKey( $this->generateRandomKey() );
$this->setCreatedAt( new DateTime() );
$this->setExpiracyDate( $this->addDaysToDate(
new DateTime(),
$this->defaultExpiracyDaysFromNow
) );
$this->setAllowedAnswers( [ 'yes', 'maybe', 'no' ] );
}
public function setCreatedAt( DateTimeInterface $createdAt ): self {
$this->createdAt = $createdAt;
return $this;
}
public function displayForAdmin() {
$content = $this->display();
$content[ 'owner' ] = $this->getOwner()->displayForAdmin();
$content[ 'admin_key' ] = $this->getAdminKey();
$content[ 'password_hash' ] = $this->getPassword();
$content[ 'id' ] = $this->getId();
return $content;
}
// counts each number of answer for this choice
public function display() {
$computedAnswers = $this->computeAnswers();
$displayedStackOfVotes = [];
foreach ( $this->getStacksOfVotes() as $stack ) {
$displayedStackOfVotes[] = $stack->display();
}
$displayedChoices = [];
foreach ( $this->getChoices() as $choice ) {
$displayedChoices[] = $choice->display();
}
$displayedComments = [];
foreach ( $this->getComments() as $comment ) {
$displayedComments[] = $comment->display();
}
return [
'title' => $this->getTitle(),
'description' => $this->getDescription(),
'created_at' => $this->getCreatedAt()->format( 'c' ),
'expiracy_date' => $this->getExpiracyDate()->format( 'c' ),
'votes_max' => $this->getVotesMax(),
'choices_max' => $this->getChoicesMax(),
'kind' => $this->getKind(),
'allowed_answers' => $this->getAllowedAnswers(),
'votes_allowed' => $this->getVotesAllowed(),
'modification_policy' => $this->getModificationPolicy(),
'hide_results' => $this->getHideResults(),
'show_results_even_if_password' => $this->getShowResultEvenIfPasswords(),
'owner' => [
'pseudo' => $this->getOwner()->getPseudo(),
]
,
'password_protected' => $this->getPassword() ? 'yes' : 'no',
'max_score' => $computedAnswers[ 'max_score' ],
'choices' => $computedAnswers[ 'answers' ],
'stacks' => $displayedStackOfVotes,
'comments' => $displayedComments,
];
}
public function computeAnswers() {
// counts each number of answer for this choice
$computedArray = [];
$maxScore = 0;
$scoreInfos = [
foreach ( $this->getStacksOfVotes() as $stack_of_vote ) {
foreach ( $stack_of_vote->getVotes() as $vote ) {
$answer = $vote->getValue();
$choice_id = $vote->getChoice()->getId();
if ( ! isset( $computedArray[ $choice_id ] ) ) {
$computedArray[ $choice_id ] = [
'choice_id' => $choice_id,
'choice_text' => $vote->getChoice()->getName(),
'id' => $vote->getId(),
'score' => 0,
'yes' => [
'count' => 0,
@ -295,25 +217,6 @@ class Poll {
'people' => [],
],
];
// first, prefill all choices
foreach ( $this->getChoices() as $choice ) {
$computedArray[ $choice->getId() ] = array_merge( $scoreInfos, $choice->display( $this->getKind() ) );
}
// then, compute stack of votes scores on each choice
foreach ( $this->getStacksOfVotes() as $stack_of_vote ) {
foreach ( $stack_of_vote->getVotes() as $vote ) {
$answer = $vote->getValue();
$choice_id = $vote->getChoice()->getId();
$choice_url = $vote->getChoice()->getUrl();
if ( ! isset( $computedArray[ $choice_id ] ) ) {
$computedArray[ $choice_id ] = [
'id' => $choice_id,
'url' => $choice_url,
'name' => $vote->getChoice()->getName(),
];
}
$computedArray[ $choice_id ][ $answer ][ 'count' ] ++;
$computedArray[ $choice_id ][ $answer ][ 'people' ][] = $stack_of_vote->getOwner()->getPseudo();
@ -329,49 +232,106 @@ class Poll {
}
}
}
$answersWithStats = [];
foreach ( $computedArray as $choice_stat ) {
$answersWithStats[] = $choice_stat;
}
return [
'answers' => $answersWithStats,
'max_score' => $maxScore,
'counts' => $computedArray,
'maxScore' => $maxScore,
];
}
/**
* @return Collection|Choice[]
*/
public function getChoices(): Collection {
return $this->choices;
public function display() {
return [
'config' => $this,
'password_protected' => $this->getPassword() ? 'yes' : 'no',
'answers' => $this->computeAnswers(),
];
}
public function getKind(): ?string {
return $this->kind;
public function __construct() {
$this->initiate();
}
public function setKind( string $kind ): self {
$this->kind = $kind;
return $this;
private function initiate() {
$this->votes = new ArrayCollection();
$this->stacksOfVotes = new ArrayCollection();
$this->choices = new ArrayCollection();
$this->comments = new ArrayCollection();
$this->setAdminKey( $this->generateAdminKey() );
$this->setCreationDate( new \DateTime() );
$this->setExpiracyDate( $this->addDaysToDate(
new \DateTime(),
$this->defaultExpiracyDaysFromNow
) );
$this->setAllowedAnswers( [ 'yes', 'maybe', 'no' ] );
}
public function getStacksOfVotes() {
return $this->stacksOfVotes;
}
public function setStacksOfVotes( ?StackOfVotes $stacksOfVotes ): self {
$this->stacksOfVotes = $stacksOfVotes;
public function generateAdminKey() {
$rand = random_int( PHP_INT_MIN, PHP_INT_MAX );
return $this;
return str_shuffle( md5( $rand ) . $rand . $this->random_str() );
}
/**
* @return Collection|Comment[]
* Generate a random string, using a cryptographically secure
* pseudorandom number generator (random_int)
*
* This function uses type hints now (PHP 7+ only), but it was originally
* written for PHP 5 as well.
*
* For PHP 7, random_int is a PHP core function
* For PHP 5.x, depends on https://github.com/paragonie/random_compat
*
* @param int $length How many characters do we want?
* @param string $keyspace A string of all possible characters
* to select from
*
* @return string
*/
public function getComments(): Collection {
return $this->comments;
public function random_str(
int $length = 64,
string $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
): string {
if ( $length < 1 ) {
throw new \RangeException( "Length must be a positive integer" );
}
$pieces = [];
$max = mb_strlen( $keyspace, '8bit' ) - 1;
for ( $i = 0 ; $i < $length ; ++ $i ) {
$pieces [] = $keyspace[ random_int( 0, $max ) ];
}
return implode( '', $pieces );
}
public function findChoiceById( int $id ) {
$choices = $this->getChoices();
$counter = 0;
// there must be something cleaner than this in Doctrine ArrayCollection
foreach ( $choices as $choice ) {
$counter ++;
if ( $counter > $this->maxChoicesLimit ) {
throw new \ErrorException( "max number of choices reached for this poll" );
}
if ( $choice && $choice->getId() == $id ) {
return $choice;
}
}
return null;
}
public function addDaysToDate( \DateTime $date, int $days ) {
$st = strtotime( $date->getTimestamp() );
return new \DateTime( $st );
}
public function getId(): ?int {
return $this->id;
}
public function getTitle(): ?string {
@ -384,100 +344,22 @@ class Poll {
return $this;
}
public function getDescription(): ?string {
return $this->description;
public function getCreationDate(): ?DateTimeInterface {
return $this->creationDate;
}
public function setDescription( string $description ): self {
$this->description = $description;
public function setCreationDate( DateTimeInterface $creationDate ): self {
$this->creationDate = $creationDate;
return $this;
}
public function getCreatedAt(): ?DateTimeInterface {
return $this->createdAt;
}
public function getExpiracyDate(): ?DateTimeInterface {
return $this->expiracyDate;
}
public function setExpiracyDate( DateTimeInterface $expiracyDate ): self {
$this->expiracyDate = $expiracyDate;
return $this;
}
public function getVotesMax() {
return $this->votesMax;
}
public function setVotesMax( $votesMax ): self {
$this->votesMax = $votesMax;
return $this;
}
public function getChoicesMax() {
return $this->choicesMax;
}
public function setChoicesMax( $choicesMax ): self {
$this->choicesMax = $choicesMax;
return $this;
}
public function getAllowedAnswers(): ?array {
return $this->allowedAnswers;
}
public function setAllowedAnswers( array $allowedAnswers ): self {
$this->allowedAnswers = $allowedAnswers;
return $this;
}
public function getVotesAllowed(): ?bool {
return $this->votesAllowed;
}
public function setVotesAllowed( ?bool $votesAllowed ): self {
$this->votesAllowed = $votesAllowed;
return $this;
}
public function getModificationPolicy(): ?string {
return $this->modificationPolicy;
}
public function setModificationPolicy( string $modificationPolicy ): self {
$this->modificationPolicy = $modificationPolicy;
return $this;
}
public function getHideResults(): ?bool {
return $this->hideResults;
}
public function setHideResults( bool $hideResults ): self {
$this->hideResults = $hideResults;
return $this;
}
public function getShowResultEvenIfPasswords(): ?bool {
return $this->showResultEvenIfPasswords;
}
public function setShowResultEvenIfPasswords( bool $showResultEvenIfPasswords ): self {
$this->showResultEvenIfPasswords = $showResultEvenIfPasswords;
return $this;
}
public function getOwner(): ?Owner {
return $this->owner;
}
@ -488,15 +370,13 @@ class Poll {
return $this;
}
public function getPassword(): ?string {
return $this->password;
/**
* @return Collection|Vote[]
*/
public function getVotes(): Collection {
return $this->votes;
}
public function setPassword( string $password ): self {
$this->password = md5( $password );
return $this;
}
public function getAdminKey(): ?string {
return $this->adminKey;
@ -508,34 +388,24 @@ class Poll {
return $this;
}
public function getId(): ?int {
return $this->id;
public function getDescription(): ?string {
return $this->description;
}
public function findChoiceById( int $id ) {
public function setDescription( string $description ): self {
$this->description = $description;
$choices = $this->getChoices();
$counter = 0;
// there must be something cleaner than this in Doctrine ArrayCollection
foreach ( $choices as $choice ) {
$counter ++;
if ( $counter > $this->maxChoicesLimit ) {
throw new ErrorException( "max number of choices reached for this poll" );
}
if ( $choice && $choice->getId() == $id ) {
return $choice;
return $this;
}
public function getKind(): ?string {
return $this->kind;
}
return null;
}
public function setKind( string $kind ): self {
$this->kind = $kind;
/**
* @return Collection|Vote[]
*/
public function getVotes(): Collection {
return $this->votes;
return $this;
}
public function getCustomUrl(): ?string {
@ -548,6 +418,26 @@ class Poll {
return $this;
}
public function getPassword(): ?string {
return $this->password;
}
public function setPassword( string $password ): self {
$this->password = md5( $password );
return $this;
}
public function getModificationPolicy(): ?string {
return $this->modificationPolicy;
}
public function setModificationPolicy( string $modificationPolicy ): self {
$this->modificationPolicy = $modificationPolicy;
return $this;
}
public function getMailOnComment(): ?bool {
return $this->mailOnComment;
}
@ -568,6 +458,34 @@ class Poll {
return $this;
}
public function getHideResults(): ?bool {
return $this->hideResults;
}
public function setHideResults( bool $hideResults ): self {
$this->hideResults = $hideResults;
return $this;
}
public function getShowResultEvenIfPasswords(): ?bool {
return $this->showResultEvenIfPasswords;
}
public function setShowResultEvenIfPasswords( bool $showResultEvenIfPasswords ): self {
$this->showResultEvenIfPasswords = $showResultEvenIfPasswords;
return $this;
}
/**
* @return Collection|Comment[]
*/
public function getComments(): Collection {
return $this->comments;
}
public function addComment( Comment $comment ): self {
if ( ! $this->comments->contains( $comment ) ) {
$this->comments[] = $comment;
@ -589,6 +507,17 @@ class Poll {
return $this;
}
public function getStacksOfVotes() {
return $this->stacksOfVotes;
}
public function setStacksOfVotes( ?StackOfVotes $stacksOfVotes ): self {
$this->stacksOfVotes = $stacksOfVotes;
return $this;
}
public function addStackOfVote( StackOfVotes $stackOfVote ): self {
if ( ! $this->stacksOfVotes->contains( $stackOfVote ) ) {
$this->stacksOfVotes[] = $stackOfVote;
@ -610,6 +539,10 @@ class Poll {
return $this;
}
public function getExpiracyDate(): ?\DateTimeInterface {
return $this->expiracyDate;
}
public function addVote( Vote $vote ): self {
if ( ! $this->votes->contains( $vote ) ) {
$this->votes[] = $vote;
@ -631,6 +564,13 @@ class Poll {
return $this;
}
/**
* @return Collection|Choice[]
*/
public function getChoices(): Collection {
return $this->choices;
}
public function addTextChoiceArray( array $choiceTextArray ): self {
foreach ( $choiceTextArray as $text ) {
$newChoice = new Choice();
@ -641,17 +581,13 @@ class Poll {
return $this;
}
public function addChoice( Choice $choice ): self {
if ( ! is_null( $this->choices ) ) {
if ( ! $this->choices->contains( $choice ) ) {
$this->choices[] = $choice;
$choice->setPoll( $this );
}
} else {
$this->choices[] = $choice;
$choice->setPoll( $this );
public function getAllowedAnswers(): ?array {
return $this->allowedAnswers;
}
public function setAllowedAnswers( array $allowedAnswers ): self {
$this->allowedAnswers = $allowedAnswers;
return $this;
}
@ -677,6 +613,21 @@ class Poll {
return $this;
}
public function addChoice( Choice $choice ): self {
if ( ! is_null( $this->choices ) ) {
if ( ! $this->choices->contains( $choice ) ) {
$this->choices[] = $choice;
$choice->setPoll( $this );
}
} else {
$this->choices[] = $choice;
$choice->setPoll( $this );
}
return $this;
}
public function removeChoice( Choice $choice ): self {
if ( $this->choices->contains( $choice ) ) {
$this->choices->removeElement( $choice );
@ -689,6 +640,36 @@ class Poll {
return $this;
}
public function getVotesAllowed(): ?bool {
return $this->votesAllowed;
}
public function setVotesAllowed( ?bool $votesAllowed ): self {
$this->votesAllowed = $votesAllowed;
return $this;
}
public function getVotesMax() {
return $this->votesMax;
}
public function setVotesMax( $votesMax ): self {
$this->votesMax = $votesMax;
return $this;
}
public function getChoicesMax() {
return $this->choicesMax;
}
public function setChoicesMax( $choicesMax ): self {
$this->choicesMax = $choicesMax;
return $this;
}
public function getCommentsAllowed(): ?bool {
return $this->commentsAllowed;
}

View File

@ -2,8 +2,6 @@
namespace App\Entity;
use App\Traits\TimeStampableTrait;
use DateTime;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
@ -16,9 +14,12 @@ use JMS\Serializer\Annotation as Serializer;
* @Serializer\ExclusionPolicy("all")
*/
class StackOfVotes {
use TimeStampableTrait;
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
* @Serializer\Type("string")
@ -30,12 +31,6 @@ class StackOfVotes {
* @Serializer\Expose()
*/
public $votes;
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Poll", inversedBy="stacksOfVotes", cascade={"persist"})
*/
@ -47,58 +42,33 @@ class StackOfVotes {
*/
private $owner;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
private $ip;
public function __construct() {
$this->setCreatedAt( new DateTime() );
$this->votes = new ArrayCollection();
}
public function display() {
$votes = $this->getVotes();
$tab = [
// 'id' => $this->getId(),
'id' => $this->getId(),
// 'modifier_token' => $this->getOwner()->getModifierToken(),
'pseudo' => $this->getPseudo(),
'created_at' => $this->getCreatedAtAsString(),
'pseudo' => '',
'creation_date' => '',
'votes' => [],
];
// prefill votes with all choices ids
// foreach ( $this->getPoll()->getChoices() as $choice ) {
// $tab[ 'votes' ][ $choice->getId() ] = [
// 'choice_id' => $choice->getId(),
// 'value' => null,
// ];
// }
foreach ( $this->getPoll()->getChoices() as $choice ) {
$tab[ 'votes' ][ $choice->getId() ] = [
'choice_id' => $choice->getId(),
'name' => $choice->getName(),
];
}
foreach ( $votes as $vote ) {
$tab[ 'votes' ][ $vote->getChoice()->getId() ] = $vote->display();
foreach ( $this->getVotes() as $vote ) {
// $tab[ 'votes' ][ $vote->getChoice()->getId() ] = $vote->display();
$tab[ 'votes' ][ $vote->getChoice()->getId() ][ 'stack_id' ] = $this->getId();
$tab[ 'pseudo' ] = $this->getPseudo();
$tab[ 'creation_date' ] = $vote->getCreationDate();
}
return $tab;
}
/**
* @return Collection|poll[]
*/
public function getVotes(): Collection {
return $this->votes;
}
public function getPseudo(): ?string {
return $this->pseudo;
}
public function setPseudo( ?string $pseudo ): self {
$this->pseudo = $pseudo;
return $this;
}
/**
* @ORM\PrePersist
*/
@ -106,20 +76,21 @@ class StackOfVotes {
$this->setPseudo( $this->getOwner()->getPseudo() );
}
public function getOwner(): ?Owner {
return $this->owner;
}
public function setOwner( ?Owner $owner ): self {
$this->owner = $owner;
return $this;
public function __construct() {
$this->votes = new ArrayCollection();
}
public function getId(): ?int {
return $this->id;
}
/**
* @return Collection|poll[]
*/
public function getVotes(): Collection {
return $this->votes;
}
public function addVote( Vote $vote ): self {
if ( ! $this->votes->contains( $vote ) ) {
$vote->setPoll( $this->getPoll() );
@ -131,16 +102,6 @@ class StackOfVotes {
return $this;
}
public function getPoll(): ?Poll {
return $this->poll;
}
public function setPoll( ?Poll $poll ): self {
$this->poll = $poll;
return $this;
}
public function removeVote( Vote $vote ): self {
if ( $this->votes->contains( $vote ) ) {
$this->votes->removeElement( $vote );
@ -153,12 +114,32 @@ class StackOfVotes {
return $this;
}
public function getIp(): ?string {
return $this->ip;
public function getPseudo(): ?string {
return $this->pseudo;
}
public function setIp( string $ip ): self {
$this->ip = $ip;
public function setPseudo( ?string $pseudo ): self {
$this->pseudo = $pseudo;
return $this;
}
public function getOwner(): ?Owner {
return $this->owner;
}
public function setOwner( ?Owner $owner ): self {
$this->owner = $owner;
return $this;
}
public function getPoll(): ?Poll {
return $this->poll;
}
public function setPoll( ?Poll $poll ): self {
$this->poll = $poll;
return $this;
}

View File

@ -2,8 +2,6 @@
namespace App\Entity;
use App\Traits\TimeStampableTrait;
use DateTime;
use DateTimeInterface;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as Serializer;
@ -13,9 +11,6 @@ use JMS\Serializer\Annotation as Serializer;
* @Serializer\ExclusionPolicy("all")
*/
class Vote {
use TimeStampableTrait;
/**
* for a text kind of choice: could be "yes" "no" "maybe" and empty.
* for a date kind, the choice linked is equivalent to the value selected
@ -24,7 +19,12 @@ class Vote {
* @Serializer\Expose()
*/
public $value;
/**
* @ORM\Column(type="datetime" , options={"default"="CURRENT_TIMESTAMP"})
* @Serializer\Type("datetime")
* @Serializer\Expose()
*/
public $creationDate;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Choice", inversedBy="votes", cascade={"persist"})
* @ORM\JoinColumn(nullable=false)
@ -52,16 +52,7 @@ class Vote {
*/
private $stacksOfVotes;
public function __construct() {
$this->setCreatedAt( new DateTime() );
}
public function display() {
$value = $this->getValue();
if ( ! $value ) {
return null;
} else {
return [
'id' => $this->getId(),
'value' => $this->getValue(),
@ -69,22 +60,28 @@ class Vote {
'text' => $this->getChoice()->getName(),
];
}
}
public function getValue(): ?string {
return $this->value;
}
public function setValue( ?string $value ): self {
$this->value = $value;
return $this;
public function __construct() {
$this->setCreationDate( new \DateTime() );
}
public function getId(): ?int {
return $this->id;
}
public function getPoll(): ?Poll {
return $this->poll;
}
public function setPoll( ?Poll $poll ): self {
$this->poll = $poll;
if ( $poll ) {
$poll->addVote( $this );
}
return $this;
}
public function getChoice(): ?Choice {
return $this->choice;
}
@ -95,15 +92,12 @@ class Vote {
return $this;
}
public function getPoll(): ?Poll {
return $this->poll;
public function getValue(): ?string {
return $this->value;
}
public function setPoll( ?Poll $poll ): self {
$this->poll = $poll;
if ( $poll ) {
$poll->addVote( $this );
}
public function setValue( ?string $value ): self {
$this->value = $value;
return $this;
}

12
src/Entity/timedTrait.php Executable file
View File

@ -0,0 +1,12 @@
<?php
namespace App\Traits;
use Doctrine\ORM\Mapping as ORM;
trait Timed {
/**
* @ORM\Column(type="datetime" , options={"default"="CURRENT_TIMESTAMP"})
*/
private $createdAt;
}

View File

@ -7,13 +7,15 @@ use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class PollType extends AbstractType {
public function buildForm( FormBuilderInterface $builder, array $options ) {
class PollType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('customUrl')
->add('description')
->add( 'createdAt' )
->add('creationDate')
->add('expiracyDate')
->add('kind')
->add('allowedAnswers')
@ -24,10 +26,12 @@ class PollType extends AbstractType {
->add('showResultEvenIfPasswords')
->add('password')
->add('adminKey')
->add( 'owner' );
->add('owner')
;
}
public function configureOptions( OptionsResolver $resolver ) {
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Poll::class,
]);

View File

@ -6,30 +6,32 @@ use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
use function dirname;
class Kernel extends BaseKernel {
class Kernel extends BaseKernel
{
use MicroKernelTrait;
protected function configureContainer( ContainerConfigurator $container ): void {
protected function configureContainer(ContainerConfigurator $container): void
{
$container->import('../config/{packages}/*.yaml');
$container->import('../config/{packages}/'.$this->environment.'/*.yaml');
if ( is_file( dirname( __DIR__ ) . '/config/services.yaml' ) ) {
if (is_file(\dirname(__DIR__).'/config/services.yaml')) {
$container->import('../config/services.yaml');
$container->import('../config/{services}_'.$this->environment.'.yaml');
} elseif ( is_file( $path = dirname( __DIR__ ) . '/config/services.php' ) ) {
} elseif (is_file($path = \dirname(__DIR__).'/config/services.php')) {
(require $path)($container->withPath($path), $this);
}
}
protected function configureRoutes( RoutingConfigurator $routes ): void {
protected function configureRoutes(RoutingConfigurator $routes): void
{
$routes->import('../config/{routes}/'.$this->environment.'/*.yaml');
$routes->import('../config/{routes}/*.yaml');
if ( is_file( dirname( __DIR__ ) . '/config/routes.yaml' ) ) {
if (is_file(\dirname(__DIR__).'/config/routes.yaml')) {
$routes->import('../config/routes.yaml');
} elseif ( is_file( $path = dirname( __DIR__ ) . '/config/routes.php' ) ) {
} elseif (is_file($path = \dirname(__DIR__).'/config/routes.php')) {
(require $path)($routes->withPath($path), $this);
}
}

View File

@ -12,8 +12,10 @@ use Doctrine\Common\Persistence\ManagerRegistry;
* @method Choice[] findAll()
* @method Choice[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class ChoiceRepository extends ServiceEntityRepository {
public function __construct( ManagerRegistry $registry ) {
class ChoiceRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Choice::class);
}

View File

@ -12,8 +12,10 @@ use Doctrine\Common\Persistence\ManagerRegistry;
* @method Comment[] findAll()
* @method Comment[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class CommentRepository extends ServiceEntityRepository {
public function __construct( ManagerRegistry $registry ) {
class CommentRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Comment::class);
}

View File

@ -12,8 +12,10 @@ use Doctrine\Common\Persistence\ManagerRegistry;
* @method Owner[] findAll()
* @method Owner[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class OwnerRepository extends ServiceEntityRepository {
public function __construct( ManagerRegistry $registry ) {
class OwnerRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Owner::class);
}

View File

@ -5,6 +5,7 @@ namespace App\Repository;
use App\Entity\Poll;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use MongoDB\Driver\Manager;
/**
* @method Poll|null find($id, $lockMode = null, $lockVersion = null)
@ -12,10 +13,11 @@ use Doctrine\Persistence\ManagerRegistry;
* @method Poll[] findAll()
* @method Poll[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class PollRepository extends ServiceEntityRepository {
public function __construct(
ManagerRegistry $registry
) {
class PollRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry
$registry)
{
parent::__construct($registry, Poll::class);
}

View File

@ -12,8 +12,10 @@ use Doctrine\Common\Persistence\ManagerRegistry;
* @method StackOfVotes[] findAll()
* @method StackOfVotes[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class StackOfVotesRepository extends ServiceEntityRepository {
public function __construct( ManagerRegistry $registry ) {
class StackOfVotesRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, StackOfVotes::class);
}

View File

@ -12,8 +12,10 @@ use Doctrine\Common\Persistence\ManagerRegistry;
* @method Vote[] findAll()
* @method Vote[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class VoteRepository extends ServiceEntityRepository {
public function __construct( ManagerRegistry $registry ) {
class VoteRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Vote::class);
}

View File

@ -12,7 +12,6 @@ use Exception;
use Swift_Mailer;
use Swift_Message;
use Swift_SmtpTransport;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
class MailService {
@ -50,7 +49,7 @@ class MailService {
* @param Owner $foundOwner
* @param Poll|null $poll
*
* @throws TransportExceptionInterface
* @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
*/
public function sendCreationMailAction( Owner $foundOwner, Poll $poll = null ) {
@ -67,12 +66,74 @@ class MailService {
return $this->sendMailWithVars( $config );
}
/**
* anti spam , limit to every minute TODO
*
* @param Owner $owner
*
* @return bool
*/
public function antispamCheck( Owner $owner ) {
// $lastSend = $admin_user->getRequestedPollsDate();
// $now = new \DateTime();
// if ( date_diff( $lastSend, $now ) < 60 ) {
// // too soon!
// die( 'too soon!' );
// }
// $admin_user->setRequestedPollsDate( $now );
// $em->persist( $admin_user );
// $em->flush();
return true;
}
/**
* send created polls to an owner
*
* @param Owner $owner
*
* @return int|void
* @throws Exception
* @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
*/
public function sendOwnerPollsAction( Owner $owner ) {
$config = [
'owner' => $owner,
'title' => 'Framadate | Mes sondages',
'email_template' => 'emails/owner-list.html.twig',
];
$this->sendMailWithVars( $config );
return 1;
}
/**
* @param Comment $comment
*
* @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
*/
public function sendCommentNotification( Comment $comment ) {
$config = [
'comment' => $comment,
'owner' => $comment->getOwner(),
'title' => 'Framadate | commentaire de ' . $comment->getOwner()->getPseudo() . ' _ sondage ' . $comment->getPoll()->getTitle(),
'email_template' => 'emails/comment-notification.html.twig',
];
$this->sendMailWithVars( $config );
}
/**
* generic way to send email with html template
*
* @param $config
*
* @throws TransportExceptionInterface
* @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
*/
public function sendMailWithVars( $config ) {
@ -148,64 +209,4 @@ class MailService {
}
/**
* anti spam , limit to every minute TODO
*
* @param Owner $owner
*
* @return bool
*/
public function antispamCheck( Owner $owner ) {
// $lastSend = $admin_user->getRequestedPollsDate();
// $now = new \DateTime();
// if ( date_diff( $lastSend, $now ) < 60 ) {
// // too soon!
// die( 'too soon!' );
// }
// $admin_user->setRequestedPollsDate( $now );
// $em->persist( $admin_user );
// $em->flush();
return true;
}
/**
* send created polls to an owner
*
* @param Owner $owner
*
* @return int|void
* @throws Exception
* @throws TransportExceptionInterface
*/
public function sendOwnerPollsAction( Owner $owner ) {
$config = [
'owner' => $owner,
'title' => 'Framadate | Mes sondages',
'email_template' => 'emails/owner-list.html.twig',
];
$this->sendMailWithVars( $config );
return 1;
}
/**
* @param Comment $comment
*
* @throws TransportExceptionInterface
*/
public function sendCommentNotification( Comment $comment ) {
$config = [
'comment' => $comment,
'owner' => $comment->getOwner(),
'title' => 'Framadate | commentaire de ' . $comment->getOwner()->getPseudo() . ' _ sondage ' . $comment->getPoll()->getTitle(),
'email_template' => 'emails/comment-notification.html.twig',
];
$this->sendMailWithVars( $config );
}
}

View File

@ -1,45 +0,0 @@
<?php
namespace App\Traits;
trait RandomTrait {
public function generateRandomKey() {
$rand = random_int( PHP_INT_MIN, PHP_INT_MAX );
return str_shuffle( md5( $rand ) . $rand . $this->random_str() );
}
/**
* Generate a random string, using a cryptographically secure
* pseudorandom number generator (random_int)
*
* This function uses type hints now (PHP 7+ only), but it was originally
* written for PHP 5 as well.
*
* For PHP 7, random_int is a PHP core function
* For PHP 5.x, depends on https://github.com/paragonie/random_compat
*
* @param int $length How many characters do we want?
* @param string $keyspace A string of all possible characters
* to select from
*
* @return string
*/
public function random_str(
int $length = 64,
string $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
): string {
if ( $length < 1 ) {
throw new RangeException( "Length must be a positive integer" );
}
$pieces = [];
$max = mb_strlen( $keyspace, '8bit' ) - 1;
for ( $i = 0 ; $i < $length ; ++ $i ) {
$pieces [] = $keyspace[ random_int( 0, $max ) ];
}
return implode( '', $pieces );
}
}

View File

@ -1,37 +0,0 @@
<?php
namespace App\Traits;
use DateInterval;
use DateTime;
use DateTimeInterface;
use Doctrine\ORM\Mapping as ORM;
trait TimeStampableTrait {
/**
* @ORM\Column(type="datetime" , options={"default"="CURRENT_TIMESTAMP"})
*/
private $createdAt;
public function getCreatedAt(): ?DateTimeInterface {
return $this->createdAt;
}
public function setCreatedAt( DateTimeInterface $createdAt ): self {
$this->createdAt = $createdAt;
return $this;
}
public function getCreatedAtAsString(): string {
return $this->createdAt->format( 'c' );
}
public function addDaysToDate( DateTime $date, int $days ) {
return $date->add( new DateInterval( 'P' . $days . 'D' ) );
}
}

View File

@ -85,8 +85,6 @@ fi
git config --global diff.submodule log
git submodule update
git submodule foreach git reset --hard && git checkout master && git pull
cecho g "######################"
cecho g " check dependencies of the frontend with yarn "
cecho g "######################"
@ -139,9 +137,6 @@ mv polyfills-es5* es5-polyfills.js
mv polyfills* other-polyfills.js
mv scripts* scripts.js
mv styles* styles.css
chown www-data:www-data . -R
cecho b " finished at ------- $(date) ------- "
cecho g "##################################################################"
cecho g " "