From 5e93c07a127efbdcdf625234f11e4b3c6eb769a0 Mon Sep 17 00:00:00 2001 From: Yonel Ceruto Date: Wed, 6 Sep 2017 11:38:19 -0400 Subject: [PATCH] Add scalar typehints/return types --- src/Controller/Admin/BlogController.php | 11 ++-- src/Controller/BlogController.php | 17 ++---- src/Controller/SecurityController.php | 5 +- src/DataFixtures/FixturesTrait.php | 12 ++-- src/DataFixtures/ORM/PostFixtures.php | 11 ++-- src/DataFixtures/ORM/TagFixtures.php | 2 +- src/DataFixtures/ORM/UserFixtures.php | 2 +- src/Entity/Comment.php | 29 ++++------ src/Entity/Post.php | 57 +++++++------------ src/Entity/Tag.php | 13 ++--- src/Entity/User.php | 52 ++++++++--------- .../CheckRequirementsSubscriber.php | 10 ++-- .../CommentNotificationSubscriber.php | 4 +- src/EventSubscriber/ControllerSubscriber.php | 4 +- .../RedirectToPreferredLocaleSubscriber.php | 26 +-------- .../TagArrayToStringTransformer.php | 8 +-- src/Repository/PostRepository.php | 26 ++------- src/Security/PostVoter.php | 4 +- src/Twig/AppExtension.php | 14 ++--- src/Twig/SourceCodeExtension.php | 24 +++----- src/Utils/Markdown.php | 7 +-- src/Utils/MomentFormatConverter.php | 6 +- src/Utils/Slugger.php | 7 +-- src/Utils/Validator.php | 8 +-- 24 files changed, 126 insertions(+), 233 deletions(-) diff --git a/src/Controller/Admin/BlogController.php b/src/Controller/Admin/BlogController.php index 388b1c54a..a81c0537b 100644 --- a/src/Controller/Admin/BlogController.php +++ b/src/Controller/Admin/BlogController.php @@ -20,6 +20,7 @@ use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; /** * Controller used to manage blog contents in the backend. @@ -53,7 +54,7 @@ class BlogController extends Controller * @Route("/", name="admin_post_index") * @Method("GET") */ - public function indexAction() + public function indexAction(): Response { $em = $this->getDoctrine()->getManager(); $posts = $em->getRepository(Post::class)->findBy(['author' => $this->getUser()], ['publishedAt' => 'DESC']); @@ -71,7 +72,7 @@ public function indexAction() * to constraint the HTTP methods each controller responds to (by default * it responds to all methods). */ - public function newAction(Request $request) + public function newAction(Request $request): Response { $post = new Post(); $post->setAuthor($this->getUser()); @@ -118,7 +119,7 @@ public function newAction(Request $request) * @Route("/{id}", requirements={"id": "\d+"}, name="admin_post_show") * @Method("GET") */ - public function showAction(Post $post) + public function showAction(Post $post): Response { // This security check can also be performed // using an annotation: @Security("is_granted('show', post)") @@ -135,7 +136,7 @@ public function showAction(Post $post) * @Route("/{id}/edit", requirements={"id": "\d+"}, name="admin_post_edit") * @Method({"GET", "POST"}) */ - public function editAction(Request $request, Post $post) + public function editAction(Request $request, Post $post): Response { $this->denyAccessUnlessGranted('edit', $post, 'Posts can only be edited by their authors.'); @@ -167,7 +168,7 @@ public function editAction(Request $request, Post $post) * The Security annotation value is an expression (if it evaluates to false, * the authorization mechanism will prevent the user accessing this resource). */ - public function deleteAction(Request $request, Post $post) + public function deleteAction(Request $request, Post $post): Response { if (!$this->isCsrfTokenValid('delete', $request->request->get('token'))) { return $this->redirectToRoute('admin_post_index'); diff --git a/src/Controller/BlogController.php b/src/Controller/BlogController.php index 5b266aa6a..4f90d2368 100644 --- a/src/Controller/BlogController.php +++ b/src/Controller/BlogController.php @@ -23,7 +23,6 @@ use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\GenericEvent; -use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; @@ -48,7 +47,7 @@ class BlogController extends Controller * Content-Type header for the response. * See https://symfony.com/doc/current/quick_tour/the_controller.html#using-formats */ - public function indexAction($page, $_format) + public function indexAction(int $page, string $_format): Response { $em = $this->getDoctrine()->getManager(); $posts = $em->getRepository(Post::class)->findLatest($page); @@ -68,7 +67,7 @@ public function indexAction($page, $_format) * value given in the route. * See https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html */ - public function postShowAction(Post $post) + public function postShowAction(Post $post): Response { // Symfony provides a function called 'dump()' which is an improved version // of the 'var_dump()' function. It's useful to quickly debug the contents @@ -93,7 +92,7 @@ public function postShowAction(Post $post) * (postSlug) doesn't match any of the Doctrine entity properties (slug). * See https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html#doctrine-converter */ - public function commentNewAction(Request $request, Post $post, EventDispatcherInterface $eventDispatcher) + public function commentNewAction(Request $request, Post $post, EventDispatcherInterface $eventDispatcher): Response { $comment = new Comment(); $comment->setAuthor($this->getUser()); @@ -137,12 +136,8 @@ public function commentNewAction(Request $request, Post $post, EventDispatcherIn * * The "id" of the Post is passed in and then turned into a Post object * automatically by the ParamConverter. - * - * @param Post $post - * - * @return Response */ - public function commentFormAction(Post $post) + public function commentFormAction(Post $post): Response { $form = $this->createForm(CommentType::class); @@ -155,10 +150,8 @@ public function commentFormAction(Post $post) /** * @Route("/search", name="blog_search") * @Method("GET") - * - * @return Response|JsonResponse */ - public function searchAction(Request $request) + public function searchAction(Request $request): Response { if (!$request->isXmlHttpRequest()) { return $this->render('blog/search.html.twig'); diff --git a/src/Controller/SecurityController.php b/src/Controller/SecurityController.php index fd338f5a7..cddedc9b4 100644 --- a/src/Controller/SecurityController.php +++ b/src/Controller/SecurityController.php @@ -13,6 +13,7 @@ use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; +use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Http\Authentication\AuthenticationUtils; /** @@ -27,7 +28,7 @@ class SecurityController extends Controller /** * @Route("/login", name="security_login") */ - public function loginAction(AuthenticationUtils $helper) + public function loginAction(AuthenticationUtils $helper): Response { return $this->render('security/login.html.twig', [ // last username entered by the user (if any) @@ -45,7 +46,7 @@ public function loginAction(AuthenticationUtils $helper) * * @Route("/logout", name="security_logout") */ - public function logoutAction() + public function logoutAction(): void { throw new \Exception('This should never be reached!'); } diff --git a/src/DataFixtures/FixturesTrait.php b/src/DataFixtures/FixturesTrait.php index 504d61137..16ecdf0f2 100644 --- a/src/DataFixtures/FixturesTrait.php +++ b/src/DataFixtures/FixturesTrait.php @@ -16,7 +16,7 @@ */ trait FixturesTrait { - private function getPostContent() + private function getPostContent(): string { return <<<'MARKDOWN' Lorem ipsum dolor sit amet consectetur adipisicing elit, sed do eiusmod tempor @@ -56,7 +56,7 @@ private function getPostContent() MARKDOWN; } - private function getPhrases() + private function getPhrases(): array { return [ 'Lorem ipsum dolor sit amet consectetur adipiscing elit', @@ -92,7 +92,7 @@ private function getPhrases() ]; } - private function getTagNames() + private function getTagNames(): array { return [ 'lorem', @@ -107,7 +107,7 @@ private function getTagNames() ]; } - private function getRandomPostTitles() + private function getRandomPostTitles(): array { $phrases = $this->getPhrases(); @@ -119,7 +119,7 @@ private function getRandomPostTitles() return $phrases; } - private function getRandomPostSummary($maxLength = 255) + private function getRandomPostSummary(int $maxLength = 255): string { $phrases = $this->getPhrases(); @@ -134,7 +134,7 @@ private function getRandomPostSummary($maxLength = 255) return $summary; } - private function getRandomCommentContent() + private function getRandomCommentContent(): string { $phrases = $this->getPhrases(); diff --git a/src/DataFixtures/ORM/PostFixtures.php b/src/DataFixtures/ORM/PostFixtures.php index 465546ef6..d0d16cc5f 100644 --- a/src/DataFixtures/ORM/PostFixtures.php +++ b/src/DataFixtures/ORM/PostFixtures.php @@ -14,6 +14,7 @@ use App\DataFixtures\FixturesTrait; use App\Entity\Comment; use App\Entity\Post; +use App\Entity\User; use App\Utils\Slugger; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\DependentFixtureInterface; @@ -38,7 +39,7 @@ class PostFixtures extends AbstractFixture implements DependentFixtureInterface /** * {@inheritdoc} */ - public function load(ObjectManager $manager) + public function load(ObjectManager $manager): void { foreach ($this->getRandomPostTitles() as $i => $title) { $post = new Post(); @@ -82,10 +83,8 @@ public function load(ObjectManager $manager) * Instead of defining the exact order in which the fixtures files must be loaded, * this method defines which other fixtures this file depends on. Then, Doctrine * will figure out the best order to fit all the dependencies. - * - * @return array */ - public function getDependencies() + public function getDependencies(): array { return [ TagFixtures::class, @@ -93,7 +92,7 @@ public function getDependencies() ]; } - private function getRandomUser() + private function getRandomUser(): User { $admins = ['jane-admin', 'tom-admin']; $index = array_rand($admins); @@ -101,7 +100,7 @@ private function getRandomUser() return $this->getReference($admins[$index]); } - private function getRandomTags($numTags = 0) + private function getRandomTags(int $numTags = 0): array { $tags = []; diff --git a/src/DataFixtures/ORM/TagFixtures.php b/src/DataFixtures/ORM/TagFixtures.php index 4b600d56e..bd07ccf1b 100644 --- a/src/DataFixtures/ORM/TagFixtures.php +++ b/src/DataFixtures/ORM/TagFixtures.php @@ -33,7 +33,7 @@ class TagFixtures extends AbstractFixture /** * {@inheritdoc} */ - public function load(ObjectManager $manager) + public function load(ObjectManager $manager): void { foreach ($this->getTagNames() as $index => $name) { $tag = new Tag(); diff --git a/src/DataFixtures/ORM/UserFixtures.php b/src/DataFixtures/ORM/UserFixtures.php index c4cedeca5..cf55942f5 100644 --- a/src/DataFixtures/ORM/UserFixtures.php +++ b/src/DataFixtures/ORM/UserFixtures.php @@ -36,7 +36,7 @@ class UserFixtures extends AbstractFixture implements ContainerAwareInterface /** * {@inheritdoc} */ - public function load(ObjectManager $manager) + public function load(ObjectManager $manager): void { $passwordEncoder = $this->container->get('security.password_encoder'); diff --git a/src/Entity/Comment.php b/src/Entity/Comment.php index 8bcdc5964..20cf16cd2 100644 --- a/src/Entity/Comment.php +++ b/src/Entity/Comment.php @@ -84,63 +84,54 @@ public function __construct() /** * @Assert\IsTrue(message="comment.is_spam") */ - public function isLegitComment() + public function isLegitComment(): bool { $containsInvalidCharacters = false !== mb_strpos($this->content, '@'); return !$containsInvalidCharacters; } - public function getId() + public function getId(): int { return $this->id; } - public function getContent() + public function getContent(): ?string { return $this->content; } - /** - * @param string $content - */ - public function setContent($content) + public function setContent(string $content): void { $this->content = $content; } - public function getPublishedAt() + public function getPublishedAt(): \DateTime { return $this->publishedAt; } - public function setPublishedAt(\DateTime $publishedAt) + public function setPublishedAt(\DateTime $publishedAt): void { $this->publishedAt = $publishedAt; } - /** - * @return User - */ - public function getAuthor() + public function getAuthor(): User { return $this->author; } - /** - * @param User $author - */ - public function setAuthor(User $author) + public function setAuthor(User $author): void { $this->author = $author; } - public function getPost() + public function getPost(): Post { return $this->post; } - public function setPost(Post $post) + public function setPost(Post $post): void { $this->post = $post; } diff --git a/src/Entity/Post.php b/src/Entity/Post.php index 7d86913fd..4689691be 100644 --- a/src/Entity/Post.php +++ b/src/Entity/Post.php @@ -12,6 +12,7 @@ namespace App\Entity; use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; @@ -126,82 +127,67 @@ public function __construct() $this->tags = new ArrayCollection(); } - public function getId() + public function getId(): int { return $this->id; } - public function getTitle() + public function getTitle(): ?string { return $this->title; } - /** - * @param string $title - */ - public function setTitle($title) + public function setTitle(string $title): void { $this->title = $title; } - public function getSlug() + public function getSlug(): ?string { return $this->slug; } - /** - * @param string $slug - */ - public function setSlug($slug) + public function setSlug(string $slug): void { $this->slug = $slug; } - public function getContent() + public function getContent(): ?string { return $this->content; } - /** - * @param string $content - */ - public function setContent($content) + public function setContent(string $content): void { $this->content = $content; } - public function getPublishedAt() + public function getPublishedAt(): \DateTime { return $this->publishedAt; } - public function setPublishedAt(\DateTime $publishedAt) + public function setPublishedAt(\DateTime $publishedAt): void { $this->publishedAt = $publishedAt; } - /** - * @return User - */ - public function getAuthor() + public function getAuthor(): User { return $this->author; } - /** - * @param User $author - */ - public function setAuthor(User $author) + public function setAuthor(User $author): void { $this->author = $author; } - public function getComments() + public function getComments(): Collection { return $this->comments; } - public function addComment(Comment $comment) + public function addComment(Comment $comment): void { $comment->setPost($this); if (!$this->comments->contains($comment)) { @@ -209,38 +195,35 @@ public function addComment(Comment $comment) } } - public function removeComment(Comment $comment) + public function removeComment(Comment $comment): void { $comment->setPost(null); $this->comments->removeElement($comment); } - public function getSummary() + public function getSummary(): ?string { return $this->summary; } - /** - * @param string $summary - */ - public function setSummary($summary) + public function setSummary(string $summary): void { $this->summary = $summary; } - public function addTag(Tag $tag) + public function addTag(Tag $tag): void { if (!$this->tags->contains($tag)) { $this->tags->add($tag); } } - public function removeTag(Tag $tag) + public function removeTag(Tag $tag): void { $this->tags->removeElement($tag); } - public function getTags() + public function getTags(): Collection { return $this->tags; } diff --git a/src/Entity/Tag.php b/src/Entity/Tag.php index 7c7d09b66..046d681b9 100644 --- a/src/Entity/Tag.php +++ b/src/Entity/Tag.php @@ -41,20 +41,17 @@ class Tag implements \JsonSerializable */ private $name; - public function getId() + public function getId(): int { return $this->id; } - /** - * @param string $name - */ - public function setName($name) + public function setName(string $name): void { $this->name = $name; } - public function getName() + public function getName(): string { return $this->name; } @@ -62,7 +59,7 @@ public function getName() /** * {@inheritdoc} */ - public function jsonSerialize() + public function jsonSerialize(): string { // This entity implements JsonSerializable (http://php.net/manual/en/class.jsonserializable.php) // so this method is used to customize its JSON representation when json_encode() @@ -71,7 +68,7 @@ public function jsonSerialize() return $this->name; } - public function __toString() + public function __toString(): string { return $this->name; } diff --git a/src/Entity/User.php b/src/Entity/User.php index 6a8906245..febc66201 100644 --- a/src/Entity/User.php +++ b/src/Entity/User.php @@ -73,59 +73,47 @@ class User implements UserInterface, \Serializable */ private $roles = []; - public function getId() + public function getId(): int { return $this->id; } - /** - * @param string $fullName - */ - public function setFullName($fullName) + public function setFullName(string $fullName): void { $this->fullName = $fullName; } - public function getFullName() + public function getFullName(): string { return $this->fullName; } - public function getUsername() + public function getUsername(): string { return $this->username; } - /** - * @param string $username - */ - public function setUsername($username) + public function setUsername(string $username): void { $this->username = $username; } - public function getEmail() + public function getEmail(): string { return $this->email; } - /** - * @param string $email - */ - public function setEmail($email) + public function setEmail(string $email): void { $this->email = $email; } - public function getPassword() + public function getPassword(): string { return $this->password; } - /** - * @param string $password - */ - public function setPassword($password) + public function setPassword(string $password): void { $this->password = $password; } @@ -133,7 +121,7 @@ public function setPassword($password) /** * Returns the roles or permissions granted to the user for security. */ - public function getRoles() + public function getRoles(): array { $roles = $this->roles; @@ -145,7 +133,7 @@ public function getRoles() return array_unique($roles); } - public function setRoles(array $roles) + public function setRoles(array $roles): void { $this->roles = $roles; } @@ -155,11 +143,13 @@ public function setRoles(array $roles) * * {@inheritdoc} */ - public function getSalt() + public function getSalt(): ?string { // See "Do you need to use a Salt?" at https://symfony.com/doc/current/cookbook/security/entity_provider.html // we're using bcrypt in security.yml to encode the password, so // the salt value is built-in and you don't have to generate one + + return null; } /** @@ -167,14 +157,16 @@ public function getSalt() * * {@inheritdoc} */ - public function eraseCredentials() + public function eraseCredentials(): void { // if you had a plainPassword property, you'd nullify it here // $this->plainPassword = null; } - /** @see \Serializable::serialize() */ - public function serialize() + /** + * {@inheritdoc} + */ + public function serialize(): string { return serialize([ $this->id, @@ -185,8 +177,10 @@ public function serialize() ]); } - /** @see \Serializable::unserialize() */ - public function unserialize($serialized) + /** + * {@inheritdoc} + */ + public function unserialize($serialized): void { list( $this->id, diff --git a/src/EventSubscriber/CheckRequirementsSubscriber.php b/src/EventSubscriber/CheckRequirementsSubscriber.php index fe9def3b0..31b33b8dc 100644 --- a/src/EventSubscriber/CheckRequirementsSubscriber.php +++ b/src/EventSubscriber/CheckRequirementsSubscriber.php @@ -41,7 +41,7 @@ public function __construct(EntityManagerInterface $entityManager) // listen to. You can listen to several events, execute more than one method // for each event and set the priority of each event too. // See https://symfony.com/doc/current/event_dispatcher.html#creating-an-event-subscriber - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { return [ // Errors are one of the events defined by the Console. See the @@ -57,7 +57,7 @@ public static function getSubscribedEvents() * the database and then, it checks if the 'sqlite3' PHP extension is enabled * or not to display a better error message. */ - public function handleConsoleError(ConsoleErrorEvent $event) + public function handleConsoleError(ConsoleErrorEvent $event): void { $commandNames = ['doctrine:fixtures:load', 'doctrine:database:create', 'doctrine:schema:create', 'doctrine:database:drop']; @@ -73,7 +73,7 @@ public function handleConsoleError(ConsoleErrorEvent $event) * This method checks if the triggered exception is related to the database * and then, it checks if the required 'sqlite3' PHP extension is enabled. */ - public function handleKernelException(GetResponseForExceptionEvent $event) + public function handleKernelException(GetResponseForExceptionEvent $event): void { $exception = $event->getException(); // Since any exception thrown during a Twig template rendering is wrapped @@ -91,10 +91,8 @@ public function handleKernelException(GetResponseForExceptionEvent $event) /** * Checks if the application is using SQLite as its database. - * - * @return bool */ - private function isSQLitePlatform() + private function isSQLitePlatform(): bool { $databasePlatform = $this->entityManager->getConnection()->getDatabasePlatform(); diff --git a/src/EventSubscriber/CommentNotificationSubscriber.php b/src/EventSubscriber/CommentNotificationSubscriber.php index 578b926a3..42a3c4ca6 100644 --- a/src/EventSubscriber/CommentNotificationSubscriber.php +++ b/src/EventSubscriber/CommentNotificationSubscriber.php @@ -38,14 +38,14 @@ public function __construct(\Swift_Mailer $mailer, UrlGeneratorInterface $urlGen $this->sender = $sender; } - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { return [ Events::COMMENT_CREATED => 'onCommentCreated', ]; } - public function onCommentCreated(GenericEvent $event) + public function onCommentCreated(GenericEvent $event): void { /** @var Comment $comment */ $comment = $event->getSubject(); diff --git a/src/EventSubscriber/ControllerSubscriber.php b/src/EventSubscriber/ControllerSubscriber.php index 9a5bf7eb5..7848efe46 100644 --- a/src/EventSubscriber/ControllerSubscriber.php +++ b/src/EventSubscriber/ControllerSubscriber.php @@ -32,14 +32,14 @@ public function __construct(SourceCodeExtension $twigExtension) $this->twigExtension = $twigExtension; } - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { return [ KernelEvents::CONTROLLER => 'registerCurrentController', ]; } - public function registerCurrentController(FilterControllerEvent $event) + public function registerCurrentController(FilterControllerEvent $event): void { // this check is needed because in Symfony a request can perform any // number of sub-requests. See diff --git a/src/EventSubscriber/RedirectToPreferredLocaleSubscriber.php b/src/EventSubscriber/RedirectToPreferredLocaleSubscriber.php index 495ab9011..7684bc588 100644 --- a/src/EventSubscriber/RedirectToPreferredLocaleSubscriber.php +++ b/src/EventSubscriber/RedirectToPreferredLocaleSubscriber.php @@ -27,31 +27,11 @@ */ class RedirectToPreferredLocaleSubscriber implements EventSubscriberInterface { - /** - * @var UrlGeneratorInterface - */ private $urlGenerator; - - /** - * List of supported locales. - * - * @var string[] - */ private $locales = []; - - /** - * @var string - */ private $defaultLocale = ''; - /** - * Constructor. - * - * @param UrlGeneratorInterface $urlGenerator - * @param string $locales Supported locales separated by '|' - * @param string|null $defaultLocale - */ - public function __construct(UrlGeneratorInterface $urlGenerator, $locales, $defaultLocale = null) + public function __construct(UrlGeneratorInterface $urlGenerator, string $locales, string $defaultLocale = null) { $this->urlGenerator = $urlGenerator; @@ -73,14 +53,14 @@ public function __construct(UrlGeneratorInterface $urlGenerator, $locales, $defa $this->locales = array_unique($this->locales); } - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { return [ KernelEvents::REQUEST => 'onKernelRequest', ]; } - public function onKernelRequest(GetResponseEvent $event) + public function onKernelRequest(GetResponseEvent $event): void { $request = $event->getRequest(); diff --git a/src/Form/DataTransformer/TagArrayToStringTransformer.php b/src/Form/DataTransformer/TagArrayToStringTransformer.php index 26d4cdad7..eb8a4278b 100644 --- a/src/Form/DataTransformer/TagArrayToStringTransformer.php +++ b/src/Form/DataTransformer/TagArrayToStringTransformer.php @@ -36,20 +36,20 @@ public function __construct(ObjectManager $manager) /** * {@inheritdoc} */ - public function transform($array) + public function transform($tags): string { // The value received is an array of Tag objects generated with // Symfony\Bridge\Doctrine\Form\DataTransformer\CollectionToArrayTransformer::transform() // The value returned is a string that concatenates the string representation of those objects - /* @var Tag[] $array */ - return implode(',', $array); + /* @var Tag[] $tags */ + return implode(',', $tags); } /** * {@inheritdoc} */ - public function reverseTransform($string) + public function reverseTransform($string): array { if ('' === $string || null === $string) { return []; diff --git a/src/Repository/PostRepository.php b/src/Repository/PostRepository.php index 577c29318..9addff135 100644 --- a/src/Repository/PostRepository.php +++ b/src/Repository/PostRepository.php @@ -29,12 +29,7 @@ */ class PostRepository extends EntityRepository { - /** - * @param int $page - * - * @return Pagerfanta - */ - public function findLatest($page = 1) + public function findLatest(int $page = 1): Pagerfanta { $query = $this->getEntityManager() ->createQuery(' @@ -51,7 +46,7 @@ public function findLatest($page = 1) return $this->createPaginator($query, $page); } - private function createPaginator(Query $query, $page) + private function createPaginator(Query $query, int $page): Pagerfanta { $paginator = new Pagerfanta(new DoctrineORMAdapter($query)); $paginator->setMaxPerPage(Post::NUM_ITEMS); @@ -61,12 +56,9 @@ private function createPaginator(Query $query, $page) } /** - * @param string $rawQuery The search query as input by the user - * @param int $limit The maximum number of results returned - * * @return Post[] */ - public function findBySearchQuery($rawQuery, $limit = Post::NUM_ITEMS) + public function findBySearchQuery(string $rawQuery, int $limit = Post::NUM_ITEMS): array { $query = $this->sanitizeSearchQuery($rawQuery); $searchTerms = $this->extractSearchTerms($query); @@ -93,24 +85,16 @@ public function findBySearchQuery($rawQuery, $limit = Post::NUM_ITEMS) /** * Removes all non-alphanumeric characters except whitespaces. - * - * @param string $query - * - * @return string */ - private function sanitizeSearchQuery($query) + private function sanitizeSearchQuery(string $query): string { return preg_replace('/[^[:alnum:] ]/', '', trim(preg_replace('/[[:space:]]+/', ' ', $query))); } /** * Splits the search query into terms and removes the ones which are irrelevant. - * - * @param string $searchQuery - * - * @return array */ - private function extractSearchTerms($searchQuery) + private function extractSearchTerms(string $searchQuery): array { $terms = array_unique(explode(' ', mb_strtolower($searchQuery))); diff --git a/src/Security/PostVoter.php b/src/Security/PostVoter.php index efda06a0f..a43f376cd 100644 --- a/src/Security/PostVoter.php +++ b/src/Security/PostVoter.php @@ -35,7 +35,7 @@ class PostVoter extends Voter /** * {@inheritdoc} */ - protected function supports($attribute, $subject) + protected function supports($attribute, $subject): bool { // this voter is only executed for three specific permissions on Post objects return $subject instanceof Post && in_array($attribute, [self::SHOW, self::EDIT, self::DELETE], true); @@ -44,7 +44,7 @@ protected function supports($attribute, $subject) /** * {@inheritdoc} */ - protected function voteOnAttribute($attribute, $post, TokenInterface $token) + protected function voteOnAttribute($attribute, $post, TokenInterface $token): bool { $user = $token->getUser(); diff --git a/src/Twig/AppExtension.php b/src/Twig/AppExtension.php index 5a8c6b23a..30b037637 100644 --- a/src/Twig/AppExtension.php +++ b/src/Twig/AppExtension.php @@ -45,7 +45,7 @@ public function __construct(Markdown $parser, $locales) /** * {@inheritdoc} */ - public function getFilters() + public function getFilters(): array { return [ new TwigFilter('md2html', [$this, 'markdownToHtml'], ['is_safe' => ['html']]), @@ -55,7 +55,7 @@ public function getFilters() /** * {@inheritdoc} */ - public function getFunctions() + public function getFunctions(): array { return [ new TwigFunction('locales', [$this, 'getLocales']), @@ -64,12 +64,8 @@ public function getFunctions() /** * Transforms the given Markdown content into HTML content. - * - * @param string $content - * - * @return string */ - public function markdownToHtml($content) + public function markdownToHtml(string $content): string { return $this->parser->toHtml($content); } @@ -78,10 +74,8 @@ public function markdownToHtml($content) * Takes the list of codes of the locales (languages) enabled in the * application and returns an array with the name of each locale written * in its own language (e.g. English, Français, Español, etc.). - * - * @return array */ - public function getLocales() + public function getLocales(): array { if (null !== $this->locales) { return $this->locales; diff --git a/src/Twig/SourceCodeExtension.php b/src/Twig/SourceCodeExtension.php index 27c780944..96c943875 100644 --- a/src/Twig/SourceCodeExtension.php +++ b/src/Twig/SourceCodeExtension.php @@ -29,7 +29,7 @@ class SourceCodeExtension extends AbstractExtension { private $controller; - public function setController($controller) + public function setController(?callable $controller) { $this->controller = $controller; } @@ -37,14 +37,14 @@ public function setController($controller) /** * {@inheritdoc} */ - public function getFunctions() + public function getFunctions(): array { return [ new TwigFunction('show_source_code', [$this, 'showSourceCode'], ['is_safe' => ['html'], 'needs_environment' => true]), ]; } - public function showSourceCode(Environment $twig, $template) + public function showSourceCode(Environment $twig, $template): string { return $twig->render('debug/source_code.html.twig', [ 'controller' => $this->getController(), @@ -52,11 +52,11 @@ public function showSourceCode(Environment $twig, $template) ]); } - private function getController() + private function getController(): ?array { // this happens for example for exceptions (404 errors, etc.) if (null === $this->controller) { - return; + return null; } $method = $this->getCallableReflector($this->controller); @@ -76,12 +76,8 @@ private function getController() * Gets a reflector for a callable. * * This logic is copied from Symfony\Component\HttpKernel\Controller\ControllerResolver::getArguments - * - * @param callable $callable - * - * @return \ReflectionFunctionAbstract */ - private function getCallableReflector($callable) + private function getCallableReflector(callable $callable): \ReflectionFunctionAbstract { if (is_array($callable)) { return new \ReflectionMethod($callable[0], $callable[1]); @@ -96,7 +92,7 @@ private function getCallableReflector($callable) return new \ReflectionFunction($callable); } - private function getTemplateSource(Template $template) + private function getTemplateSource(Template $template): array { $templateSource = $template->getSourceContext(); @@ -114,12 +110,8 @@ private function getTemplateSource(Template $template) /** * Utility method that "unindents" the given $code when all its lines start * with a tabulation of four white spaces. - * - * @param string $code - * - * @return string */ - private function unindentCode($code) + private function unindentCode(string $code): string { $formattedCode = $code; $codeLines = explode("\n", $code); diff --git a/src/Utils/Markdown.php b/src/Utils/Markdown.php index a2c45996b..433b5b91d 100644 --- a/src/Utils/Markdown.php +++ b/src/Utils/Markdown.php @@ -34,12 +34,7 @@ public function __construct() $this->purifier = new \HTMLPurifier($purifierConfig); } - /** - * @param string $text - * - * @return string - */ - public function toHtml($text) + public function toHtml(string $text): string { $html = $this->parser->text($text); $safeHtml = $this->purifier->purify($html); diff --git a/src/Utils/MomentFormatConverter.php b/src/Utils/MomentFormatConverter.php index 221c0a98d..be5af13c5 100644 --- a/src/Utils/MomentFormatConverter.php +++ b/src/Utils/MomentFormatConverter.php @@ -40,12 +40,8 @@ class MomentFormatConverter /** * Returns associated moment.js format. - * - * @param string $format PHP Date format - * - * @return string */ - public function convert($format) + public function convert(string $format): string { return strtr($format, self::$formatConvertRules); } diff --git a/src/Utils/Slugger.php b/src/Utils/Slugger.php index a9a73a53f..af6499d19 100644 --- a/src/Utils/Slugger.php +++ b/src/Utils/Slugger.php @@ -17,12 +17,7 @@ */ class Slugger { - /** - * @param string $string - * - * @return string - */ - public static function slugify($string) + public static function slugify(string $string): string { return preg_replace('/\s+/', '-', mb_strtolower(trim(strip_tags($string)), 'UTF-8')); } diff --git a/src/Utils/Validator.php b/src/Utils/Validator.php index 36a09001b..bcdee26f8 100644 --- a/src/Utils/Validator.php +++ b/src/Utils/Validator.php @@ -19,7 +19,7 @@ */ class Validator { - public function validateUsername($username) + public function validateUsername(?string $username): string { if (empty($username)) { throw new \Exception('The username can not be empty.'); @@ -32,7 +32,7 @@ public function validateUsername($username) return $username; } - public function validatePassword($plainPassword) + public function validatePassword(?string $plainPassword): string { if (empty($plainPassword)) { throw new \Exception('The password can not be empty.'); @@ -45,7 +45,7 @@ public function validatePassword($plainPassword) return $plainPassword; } - public function validateEmail($email) + public function validateEmail(?string $email): string { if (empty($email)) { throw new \Exception('The email can not be empty.'); @@ -58,7 +58,7 @@ public function validateEmail($email) return $email; } - public function validateFullName($fullName) + public function validateFullName(?string $fullName): string { if (empty($fullName)) { throw new \Exception('The full name can not be empty.');