Compare commits

..

15 Commits

29 changed files with 893 additions and 14 deletions

1
.gitignore vendored
View File

@@ -1,3 +1,4 @@
/public/uploads
###> symfony/framework-bundle ###
/.env.local

9
Makefile Normal file
View File

@@ -0,0 +1,9 @@
SHELL := /bin/bash
tests:
symfony console doctrine:database:drop --force --env=test || true
symfony console doctrine:database:create --env=test
symfony console doctrine:migrations:migrate -n --env=test
symfony console doctrine:fixtures:load -n --env=test
symfony php bin/phpunit $(MAKECMDGOALS)
.PHONY: tests

View File

@@ -100,6 +100,7 @@
}
},
"require-dev": {
"doctrine/doctrine-fixtures-bundle": "^3.6",
"phpunit/phpunit": "^9.5",
"symfony/browser-kit": "6.4.*",
"symfony/css-selector": "6.4.*",

173
composer.lock generated
View File

@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "8c1a998d0fd531901efdf4231f51010e",
"content-hash": "7a088b51b25fa5dd11238a61747b340d",
"packages": [
{
"name": "blackfire/php-sdk",
@@ -8015,6 +8015,177 @@
}
],
"packages-dev": [
{
"name": "doctrine/data-fixtures",
"version": "1.7.0",
"source": {
"type": "git",
"url": "https://github.com/doctrine/data-fixtures.git",
"reference": "bbcb74f2ac6dbe81a14b3c3687d7623490a0448f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/doctrine/data-fixtures/zipball/bbcb74f2ac6dbe81a14b3c3687d7623490a0448f",
"reference": "bbcb74f2ac6dbe81a14b3c3687d7623490a0448f",
"shasum": ""
},
"require": {
"doctrine/deprecations": "^0.5.3 || ^1.0",
"doctrine/persistence": "^2.0|^3.0",
"php": "^7.4 || ^8.0"
},
"conflict": {
"doctrine/dbal": "<3.5 || >=5",
"doctrine/orm": "<2.14 || >=4",
"doctrine/phpcr-odm": "<1.3.0"
},
"require-dev": {
"doctrine/annotations": "^1.12 || ^2",
"doctrine/coding-standard": "^12",
"doctrine/dbal": "^3.5 || ^4",
"doctrine/mongodb-odm": "^1.3.0 || ^2.0.0",
"doctrine/orm": "^2.14 || ^3",
"ext-sqlite3": "*",
"phpstan/phpstan": "^1.10",
"phpunit/phpunit": "^9.6.13 || ^10.4.2",
"symfony/cache": "^5.4 || ^6.3 || ^7",
"symfony/var-exporter": "^5.4 || ^6.3 || ^7",
"vimeo/psalm": "^5.9"
},
"suggest": {
"alcaeus/mongo-php-adapter": "For using MongoDB ODM 1.3 with PHP 7 (deprecated)",
"doctrine/mongodb-odm": "For loading MongoDB ODM fixtures",
"doctrine/orm": "For loading ORM fixtures",
"doctrine/phpcr-odm": "For loading PHPCR ODM fixtures"
},
"type": "library",
"autoload": {
"psr-4": {
"Doctrine\\Common\\DataFixtures\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Jonathan Wage",
"email": "jonwage@gmail.com"
}
],
"description": "Data Fixtures for all Doctrine Object Managers",
"homepage": "https://www.doctrine-project.org",
"keywords": [
"database"
],
"support": {
"issues": "https://github.com/doctrine/data-fixtures/issues",
"source": "https://github.com/doctrine/data-fixtures/tree/1.7.0"
},
"funding": [
{
"url": "https://www.doctrine-project.org/sponsorship.html",
"type": "custom"
},
{
"url": "https://www.patreon.com/phpdoctrine",
"type": "patreon"
},
{
"url": "https://tidelift.com/funding/github/packagist/doctrine%2Fdata-fixtures",
"type": "tidelift"
}
],
"time": "2023-11-24T11:18:31+00:00"
},
{
"name": "doctrine/doctrine-fixtures-bundle",
"version": "3.6.1",
"source": {
"type": "git",
"url": "https://github.com/doctrine/DoctrineFixturesBundle.git",
"reference": "d13a08ebf244f74c8adb8ff15aa55d01c404e534"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/doctrine/DoctrineFixturesBundle/zipball/d13a08ebf244f74c8adb8ff15aa55d01c404e534",
"reference": "d13a08ebf244f74c8adb8ff15aa55d01c404e534",
"shasum": ""
},
"require": {
"doctrine/data-fixtures": "^1.3",
"doctrine/doctrine-bundle": "^2.2",
"doctrine/orm": "^2.14.0 || ^3.0",
"doctrine/persistence": "^2.4|^3.0",
"php": "^7.4 || ^8.0",
"symfony/config": "^5.4|^6.0|^7.0",
"symfony/console": "^5.4|^6.0|^7.0",
"symfony/dependency-injection": "^5.4|^6.0|^7.0",
"symfony/deprecation-contracts": "^2.1|^3",
"symfony/doctrine-bridge": "^5.4|^6.0|^7.0",
"symfony/http-kernel": "^5.4|^6.0|^7.0"
},
"conflict": {
"doctrine/dbal": "< 3"
},
"require-dev": {
"doctrine/coding-standard": "^12",
"phpstan/phpstan": "^1.10.39",
"phpunit/phpunit": "^9.6.13",
"symfony/phpunit-bridge": "^6.3.6",
"vimeo/psalm": "^5.15"
},
"type": "symfony-bundle",
"autoload": {
"psr-4": {
"Doctrine\\Bundle\\FixturesBundle\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
},
{
"name": "Doctrine Project",
"homepage": "https://www.doctrine-project.org"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony DoctrineFixturesBundle",
"homepage": "https://www.doctrine-project.org",
"keywords": [
"Fixture",
"persistence"
],
"support": {
"issues": "https://github.com/doctrine/DoctrineFixturesBundle/issues",
"source": "https://github.com/doctrine/DoctrineFixturesBundle/tree/3.6.1"
},
"funding": [
{
"url": "https://www.doctrine-project.org/sponsorship.html",
"type": "custom"
},
{
"url": "https://www.patreon.com/phpdoctrine",
"type": "patreon"
},
{
"url": "https://tidelift.com/funding/github/packagist/doctrine%2Fdoctrine-fixtures-bundle",
"type": "tidelift"
}
],
"time": "2024-05-07T07:16:35+00:00"
},
{
"name": "masterminds/html5",
"version": "2.9.0",

View File

@@ -14,4 +14,5 @@ return [
Symfony\Bundle\MonologBundle\MonologBundle::class => ['all' => true],
Symfony\Bundle\MakerBundle\MakerBundle::class => ['dev' => true],
EasyCorp\Bundle\EasyAdminBundle\EasyAdminBundle::class => ['all' => true],
Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle::class => ['dev' => true, 'test' => true],
];

View File

@@ -4,14 +4,26 @@ security:
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
# https://symfony.com/doc/current/security.html#loading-the-user-the-user-provider
providers:
users_in_memory: { memory: null }
# used to reload user from session & other features (e.g. switch_user)
app_user_provider:
entity:
class: App\Entity\Admin
property: username
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
lazy: true
provider: users_in_memory
provider: app_user_provider
form_login:
login_path: app_login
check_path: app_login
enable_csrf: true
logout:
path: app_logout
# where to redirect after logout
# target: app_any_route
# activate different ways to authenticate
# https://symfony.com/doc/current/security.html#the-firewall
@@ -24,6 +36,7 @@ security:
access_control:
# - { path: ^/admin, roles: ROLE_ADMIN }
# - { path: ^/profile, roles: ROLE_USER }
- { path: ^/admin, roles: ROLE_ADMIN }
when@test:
security:

View File

@@ -4,6 +4,7 @@
# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices.html#use-parameters-for-application-configuration
parameters:
photo_dir: "%kernel.project_dir%/public/uploads/photos"
services:
# default configuration for services in *this* file

View File

@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20240728050727 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE conference ADD slug VARCHAR(255)');
$this->addSql("UPDATE conference SET slug=CONCAT(LOWER(city), '-', year)");
$this->addSql('ALTER TABLE conference ALTER COLUMN slug SET NOT NULL');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE SCHEMA public');
$this->addSql('ALTER TABLE conference DROP slug');
}
}

View File

@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20240728051153 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE UNIQUE INDEX UNIQ_911533C8989D9B62 ON conference (slug)');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE SCHEMA public');
$this->addSql('DROP INDEX UNIQ_911533C8989D9B62');
}
}

View File

@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20240728210115 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE SEQUENCE admin_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
$this->addSql('CREATE TABLE admin (id INT NOT NULL, username VARCHAR(180) NOT NULL, roles JSON NOT NULL, password VARCHAR(255) NOT NULL, PRIMARY KEY(id))');
$this->addSql('CREATE UNIQUE INDEX UNIQ_IDENTIFIER_USERNAME ON admin (username)');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE SCHEMA public');
$this->addSql('DROP SEQUENCE admin_id_seq CASCADE');
$this->addSql('DROP TABLE admin');
}
}

View File

@@ -10,6 +10,7 @@ use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateTimeField;
use EasyCorp\Bundle\EasyAdminBundle\Field\EmailField;
use EasyCorp\Bundle\EasyAdminBundle\Field\IdField;
use EasyCorp\Bundle\EasyAdminBundle\Field\ImageField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextareaField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextEditorField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
@@ -46,7 +47,9 @@ class CommentCrudController extends AbstractCrudController
yield TextareaField::new('text')
->hideOnIndex()
;
yield TextField::new('photoFilename')
yield ImageField::new('photoFilename')
->setBasePath('/uploads/photos')
->setLabel('Photo')
->onlyOnIndex()
;
@@ -56,8 +59,6 @@ class CommentCrudController extends AbstractCrudController
]);
if(Crud::PAGE_EDIT === $pageName) {
yield $createdAt->setFormTypeOption('disabled', true);
} else {
yield $createdAt;
}
}
}

View File

@@ -2,10 +2,14 @@
namespace App\Controller;
use App\Entity\Comment;
use App\Entity\Conference;
use App\Form\CommentType;
use App\Repository\CommentRepository;
use App\Repository\ConferenceRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
@@ -13,6 +17,11 @@ use Twig\Environment;
class ConferenceController extends AbstractController
{
public function __construct(
private EntityManagerInterface $entityManager,
){
}
#[Route('/', name: 'homepage')]
public function index(ConferenceRepository $conferenceRepository): Response
{
@@ -21,9 +30,30 @@ class ConferenceController extends AbstractController
]);
}
#[Route('/conference/{id}', name: 'conference')]
public function show(Request $request, Conference $conference, CommentRepository $commentRepository): Response
{
#[Route('/conference/{slug}', name: 'conference')]
public function show(
Request $request,
Conference $conference,
CommentRepository $commentRepository,
#[Autowire('%photo_dir%')] string $photoDir,
): Response {
$comment = new Comment();
$form = $this->createForm(CommentType::class, $comment);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$comment->setConference($conference);
if($photo = $form['photo']->getData()) {
$filename = bin2hex(random_bytes(6)) . '.' . $photo->guessExtension();
$photo->move($photoDir, $filename);
$comment->setPhotoFilename($filename);
}
$this->entityManager->persist($comment);
$this->entityManager->flush();
return $this->redirectToRoute('conference', ['slug' => $conference->getSlug()]);
}
$offset = max(0, $request->query->getInt('offset', 0));
$paginator = $commentRepository->getCommentPaginator($conference, $offset);
@@ -31,7 +61,8 @@ class ConferenceController extends AbstractController
'conference' => $conference,
'comments' => $paginator,
'previous' => $offset - CommentRepository::COMMENTS_PER_PAGE,
'next' => min(count($paginator), $offset + CommentRepository::COMMENTS_PER_PAGE)
'next' => min(count($paginator), $offset + CommentRepository::COMMENTS_PER_PAGE),
'comment_form' => $form,
]);
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class SecurityController extends AbstractController
{
#[Route(path: '/login', name: 'app_login')]
public function login(AuthenticationUtils $authenticationUtils): Response
{
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
]);
}
#[Route(path: '/logout', name: 'app_logout')]
public function logout(): void
{
throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
}

View File

@@ -0,0 +1,48 @@
<?php
namespace App\DataFixtures;
use App\Entity\Admin;
use App\Entity\Comment;
use App\Entity\Conference;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactoryInterface;
class AppFixtures extends Fixture
{
public function __construct(
private PasswordHasherFactoryInterface $passwordHasherFactory,
) {
}
public function load(ObjectManager $manager): void
{
$amsterdam = new Conference();
$amsterdam->setCity('Amsterdam');
$amsterdam->setYear('2019');
$amsterdam->setIsInternational(true);
$manager->persist($amsterdam);
$slc = new Conference();
$slc->setCity('Salt Lake City');
$slc->setYear('2021');
$slc->setIsInternational(false);
$manager->persist($slc);
$comment1 = new Comment();
$comment1->setConference($amsterdam);
$comment1->setAuthor('Jake');
$comment1->setEmail('jake@example.com');
$comment1->setText('This was a great conference.');
$manager->persist($comment1);
$admin = new Admin();
$admin->setRoles(['ROLE_ADMIN']);
$admin->setUsername('admin');
$admin->setPassword($this->passwordHasherFactory->getPasswordHasher(Admin::class)->hash('admin'));
$manager->persist($admin);
$manager->flush();
}
}

108
src/Entity/Admin.php Normal file
View File

@@ -0,0 +1,108 @@
<?php
namespace App\Entity;
use App\Repository\AdminRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
#[ORM\Entity(repositoryClass: AdminRepository::class)]
#[ORM\UniqueConstraint(name: 'UNIQ_IDENTIFIER_USERNAME', fields: ['username'])]
class Admin implements UserInterface, PasswordAuthenticatedUserInterface
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 180)]
private ?string $username = null;
/**
* @var list<string> The user roles
*/
#[ORM\Column]
private array $roles = [];
/**
* @var string The hashed password
*/
#[ORM\Column]
private ?string $password = null;
public function getId(): ?int
{
return $this->id;
}
public function getUsername(): ?string
{
return $this->username;
}
public function setUsername(string $username): static
{
$this->username = $username;
return $this;
}
/**
* A visual identifier that represents this user.
*
* @see UserInterface
*/
public function getUserIdentifier(): string
{
return (string) $this->username;
}
/**
* @see UserInterface
*
* @return list<string>
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
/**
* @param list<string> $roles
*/
public function setRoles(array $roles): static
{
$this->roles = $roles;
return $this;
}
/**
* @see PasswordAuthenticatedUserInterface
*/
public function getPassword(): string
{
return $this->password;
}
public function setPassword(string $password): static
{
$this->password = $password;
return $this;
}
/**
* @see UserInterface
*/
public function eraseCredentials(): void
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
}

View File

@@ -5,8 +5,10 @@ namespace App\Entity;
use App\Repository\CommentRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Symphony\Component\Validator\Constraints as Assert;
#[ORM\Entity(repositoryClass: CommentRepository::class)]
#[ORM\HasLifecycleCallbacks]
class Comment
{
#[ORM\Id]
@@ -15,12 +17,16 @@ class Comment
private ?int $id = null;
#[ORM\Column(length: 255)]
#[Assert\NotBlank]
private ?string $author = null;
#[ORM\Column(type: Types::TEXT)]
#[Assert\NotBlank]
private ?string $text = null;
#[ORM\Column(length: 255)]
#[Assert\NotBlank]
#[Assert\Email]
private ?string $email = null;
#[ORM\Column]
@@ -86,6 +92,12 @@ class Comment
return $this;
}
#[ORM\PrePersist]
public function setCreatedAtValue()
{
$this->createdAt = new \DateTimeImmutable();
}
public function getConference(): ?Conference
{
return $this->conference;

View File

@@ -6,8 +6,11 @@ use App\Repository\ConferenceRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\String\Slugger\SluggerInterface;
#[ORM\Entity(repositoryClass: ConferenceRepository::class)]
#[UniqueEntity('slug')]
class Conference
{
#[ORM\Id]
@@ -30,6 +33,9 @@ class Conference
#[ORM\OneToMany(targetEntity: Comment::class, mappedBy: 'conference', orphanRemoval: true)]
private Collection $comments;
#[ORM\Column(length: 255, unique: true)]
private ?string $slug = null;
public function __construct()
{
$this->comments = new ArrayCollection();
@@ -44,6 +50,13 @@ class Conference
return $this->id;
}
public function computeSlug(SluggerInterface $slugger)
{
if(!$this->slug || '-' === $this->slug) {
$this->slug = (string)$slugger->slug((string)$this)->lower();
}
}
public function getCity(): ?string
{
return $this->city;
@@ -109,4 +122,16 @@ class Conference
return $this;
}
public function getSlug(): ?string
{
return $this->slug;
}
public function setSlug(string $slug): static
{
$this->slug = $slug;
return $this;
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace App\EntityListener;
use App\Entity\Conference;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsEntityListener;
use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use Symfony\Component\String\Slugger\SluggerInterface;
#[AsEntityListener(event: Events::prePersist, entity: Conference::class)]
#[AsEntityListener(event: Events::preUpdate, entity: Conference::class)]
class ConferenceEntityListener
{
public function __construct(
private SluggerInterface $slugger,
) {
}
public function prePersist(Conference $conference, LifecycleEventArgs $event)
{
$conference->computeSlug($this->slugger);
}
public function preUpdate(Conference $conference, LifecycleEventArgs $event)
{
$conference->computeSlug($this->slugger);
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace App\EventSubscriber;
use App\Repository\ConferenceRepository;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Twig\Environment;
class TwigEventSubscriber implements EventSubscriberInterface
{
private $twig;
private $conferenceRepository;
public function __construct(Environment $twig, ConferenceRepository $conferenceRepository)
{
$this->twig = $twig;
$this->conferenceRepository = $conferenceRepository;
}
public function onControllerEvent(ControllerEvent $event): void
{
$this->twig->addGlobal('conferences', $this->conferenceRepository->findAll());
}
public static function getSubscribedEvents(): array
{
return [
ControllerEvent::class => 'onControllerEvent',
];
}
}

43
src/Form/CommentType.php Normal file
View File

@@ -0,0 +1,43 @@
<?php
namespace App\Form;
use App\Entity\Comment;
use App\Entity\Conference;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Image;
class CommentType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('author', null, [
'label' => 'Your name'
])
->add('text')
->add('email', EmailType::class)
->add('photo', FileType::class, [
'required' => false,
'mapped' => false,
'constraints' => [
new Image(['maxSize' => '1024k'])
],
])
->add('submit', SubmitType::class)
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Comment::class,
]);
}
}

View File

@@ -0,0 +1,60 @@
<?php
namespace App\Repository;
use App\Entity\Admin;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
/**
* @extends ServiceEntityRepository<Admin>
*/
class AdminRepository extends ServiceEntityRepository implements PasswordUpgraderInterface
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Admin::class);
}
/**
* Used to upgrade (rehash) the user's password automatically over time.
*/
public function upgradePassword(PasswordAuthenticatedUserInterface $user, string $newHashedPassword): void
{
if (!$user instanceof Admin) {
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', $user::class));
}
$user->setPassword($newHashedPassword);
$this->getEntityManager()->persist($user);
$this->getEntityManager()->flush();
}
// /**
// * @return Admin[] Returns an array of Admin objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('a')
// ->andWhere('a.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('a.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?Admin
// {
// return $this->createQueryBuilder('a')
// ->andWhere('a.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}

View File

@@ -16,6 +16,12 @@ class ConferenceRepository extends ServiceEntityRepository
parent::__construct($registry, Conference::class);
}
public function findAll(): array
{
// Override findAll() to use custom sorting
return $this->findBy([], ['year' => 'ASC', 'city' => 'ASC']);
}
// /**
// * @return Conference[] Returns an array of Conference objects
// */

View File

@@ -25,6 +25,18 @@
"src/Repository/.gitignore"
]
},
"doctrine/doctrine-fixtures-bundle": {
"version": "3.6",
"recipe": {
"repo": "github.com/symfony/recipes",
"branch": "main",
"version": "3.0",
"ref": "1f5514cfa15b947298df4d771e694e578d4c204d"
},
"files": [
"src/DataFixtures/AppFixtures.php"
]
},
"doctrine/doctrine-migrations-bundle": {
"version": "3.3",
"recipe": {

View File

@@ -12,6 +12,15 @@
{% endblock %}
</head>
<body>
<header>
<h1><a href="{{ path('homepage') }}">Guestbook</a></h1>
<ul>
{%for conference in conferences %}
<li><a href="{{ path('conference', { slug: conference.slug }) }}">{{ conference }}</a></li>
{% endfor %}
</ul>
<hr/>
</header>
{% block body %}{% endblock %}
</body>
</html>

View File

@@ -8,7 +8,7 @@
{% for conference in conferences %}
<h4>{{ conference }}</h4>
<p>
<a href="{{ path('conference', { id: conference.id }) }}">View</a>
<a href="{{ path('conference', { slug: conference.slug }) }}">View</a>
</p>
{% endfor %}
{% endblock %}

View File

@@ -3,7 +3,7 @@
{% block title %}Conference Guestbook - {{ conference }}{% endblock %}
{% block body %}
<h2>{{ conference }} Conference<h2>
<h2>{{ conference }} Conference</h2>
{% if comments|length > 0 %}
<div>There are {{ comments|length }} comments.</div>
@@ -22,12 +22,16 @@
{% endfor %}
{% if previous >= 0 %}
<a href="{{ path('conference', { id: conference.id, offset: previous }) }}">Previous</a>
<a href="{{ path('conference', { slug: conference.slug, offset: previous }) }}">Previous</a>
{% endif %}
{% if next < comments|length %}
<a href="{{ path('conference', { id: conference.id, offset: next }) }}">Next</a>
<a href="{{ path('conference', { slug: conference.slug, offset: next }) }}">Next</a>
{% endif %}
{% else %}
<div>No comments have been posted yet for this conference.</div>
{% endif %}
<h2>Add your own feedback</h2>
{{ form(comment_form) }}
{% endblock %}

View File

@@ -0,0 +1,41 @@
{% extends 'base.html.twig' %}
{% block title %}Log in!{% endblock %}
{% block body %}
<form method="post">
{% if error %}
<div class="alert alert-danger">{{ error.messageKey|trans(error.messageData, 'security') }}</div>
{% endif %}
{% if app.user %}
<div class="mb-3">
You are logged in as {{ app.user.userIdentifier }}, <a href="{{ path('app_logout') }}">Logout</a>
</div>
{% endif %}
<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
<label for="username">Username</label>
<input type="text" value="{{ last_username }}" name="_username" id="username" class="form-control" autocomplete="username" required autofocus>
<label for="password">Password</label>
<input type="password" name="_password" id="password" class="form-control" autocomplete="current-password" required>
<input type="hidden" name="_csrf_token"
value="{{ csrf_token('authenticate') }}"
>
{#
Uncomment this section and add a remember_me option below your firewall to activate remember me functionality.
See https://symfony.com/doc/current/security/remember_me.html
<div class="checkbox mb-3">
<input type="checkbox" name="_remember_me" id="_remember_me">
<label for="_remember_me">Remember me</label>
</div>
#}
<button class="btn btn-lg btn-primary" type="submit">
Sign in
</button>
</form>
{% endblock %}

View File

@@ -0,0 +1,41 @@
<?php
namespace App\Tests;
use App\Entity\Conference;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\String\Slugger\SluggerInterface;
class ConferenceSluggerTest extends KernelTestCase
{
/**
* @dataProvider provideConferences
*/
public function testConferenceComputeSlug(string $expectedResult, Conference $conference): void
{
self::bootKernel();
$slugger = static::getContainer()->get(SluggerInterface::class);
$conference->computeSlug($slugger);
$this->assertSame($expectedResult, $conference->getSlug());
}
public static function provideConferences(): iterable
{
$conference = new Conference();
$conference->setCity("Barcelona");
$conference->setyear("2002");
yield ["barcelona-2002", $conference];
$conference = new Conference();
$conference->setCity("Tokyo");
$conference->setyear("2020");
yield ["tokyo-2020", $conference];
$conference = new Conference();
$conference->setCity("Mexico City");
$conference->setyear("1999");
yield ["mexico-city-1999", $conference];
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace App\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class ConferenceControllerTest extends WebTestCase
{
public function testIndex()
{
$client = static::createClient();
$client->request('GET', '/');
$this->assertResponseIsSuccessful();
$this->assertSelectorTextContains('h2', 'Give your feedback');
}
public function testConferencePage()
{
$client = static::createClient();
$crawler = $client->request('GET', '/');
$this->assertCount(2, $crawler->filter('h4'));
$client->clickLink('View');
$this->assertPageTitleContains('Amsterdam');
$this->assertResponseIsSuccessful();
$this->assertSelectorTextContains('h2', 'Amsterdam 2019');
$this->assertSelectorExists('div:contains("There are 1 comments")');
}
public function testCommentSubmission()
{
$client = static::createClient();
$client->request('GET', 'conference/amsterdam-2019');
$client->submitForm('Submit', [
'comment[author]' => 'Bob',
'comment[text]' => 'Some feedback from an automated functional test',
'comment[email]' => 'test@example.com',
'comment[photo]' => dirname(__DIR__, 2) . '/public/images/under-construction.gif',
]);
$this->assertResponseRedirects();
$client->followRedirect();
$this->assertSelectorExists('div:contains("There are 2 comments")');
}
}