diff --git a/app/config/routing_dev.yml b/app/config/routing_dev.yml index 95c1b0263..a57028de1 100644 --- a/app/config/routing_dev.yml +++ b/app/config/routing_dev.yml @@ -7,7 +7,7 @@ _profiler: prefix: /_profiler _errors: - resource: "@TwigBundle/Resources/config/routing/errors.xml" + resource: '@TwigBundle/Resources/config/routing/errors.xml' prefix: /_error _main: diff --git a/app/config/services.yml b/app/config/services.yml index 333ad3e69..d63413d48 100644 --- a/app/config/services.yml +++ b/app/config/services.yml @@ -43,6 +43,79 @@ services: resource: '../../src/Wallabag/CoreBundle/*' exclude: ['../../src/Wallabag/CoreBundle/{Controller,Entity}', '../../src/Wallabag/CoreBundle/Event/*Event.php'] + # controllers are imported separately to make sure services can be injected + # as action arguments even if you don't extend any base controller class + Wallabag\AnnotationBundle\Controller\: + resource: '../../src/Wallabag/AnnotationBundle/Controller/' + tags: ['controller.service_arguments'] + + Wallabag\ApiBundle\Controller\: + resource: '../../src/Wallabag/ApiBundle/Controller/' + tags: ['controller.service_arguments'] + + Wallabag\CoreBundle\Controller\: + resource: '../../src/Wallabag/CoreBundle/Controller/' + tags: ['controller.service_arguments'] + + Wallabag\ImportBundle\Controller\: + resource: '../../src/Wallabag/ImportBundle/Controller/' + tags: ['controller.service_arguments'] + + Wallabag\UserBundle\Controller\: + resource: '../../src/Wallabag/UserBundle/Controller/' + tags: ['controller.service_arguments'] + + # inject alias service into controllers + Wallabag\ImportBundle\Controller\ChromeController: + arguments: + $rabbitMqProducer: '@old_sound_rabbit_mq.import_chrome_producer' + $redisProducer: '@wallabag_import.producer.redis.chrome' + + Wallabag\ImportBundle\Controller\DeliciousController: + arguments: + $rabbitMqProducer: '@old_sound_rabbit_mq.import_delicious_producer' + $redisProducer: '@wallabag_import.producer.redis.delicious' + + Wallabag\ImportBundle\Controller\ElcuratorController: + arguments: + $rabbitMqProducer: '@old_sound_rabbit_mq.import_elcurator_producer' + $redisProducer: '@wallabag_import.producer.redis.elcurator' + + Wallabag\ImportBundle\Controller\FirefoxController: + arguments: + $rabbitMqProducer: '@old_sound_rabbit_mq.import_firefox_producer' + $redisProducer: '@wallabag_import.producer.redis.firefox' + + Wallabag\ImportBundle\Controller\InstapaperController: + arguments: + $rabbitMqProducer: '@old_sound_rabbit_mq.import_instapaper_producer' + $redisProducer: '@wallabag_import.producer.redis.instapaper' + + Wallabag\ImportBundle\Controller\PinboardController: + arguments: + $rabbitMqProducer: '@old_sound_rabbit_mq.import_pinboard_producer' + $redisProducer: '@wallabag_import.producer.redis.pinboard' + + Wallabag\ImportBundle\Controller\PocketController: + arguments: + $rabbitMqProducer: '@old_sound_rabbit_mq.import_pocket_producer' + $redisProducer: '@wallabag_import.producer.redis.pocket' + + Wallabag\ImportBundle\Controller\ReadabilityController: + arguments: + $rabbitMqProducer: '@old_sound_rabbit_mq.import_readability_producer' + $redisProducer: '@wallabag_import.producer.redis.readability' + + Wallabag\ImportBundle\Controller\WallabagV1Controller: + arguments: + $rabbitMqProducer: '@old_sound_rabbit_mq.import_wallabag_v1_producer' + $redisProducer: '@wallabag_import.producer.redis.wallabag_v1' + + Wallabag\ImportBundle\Controller\WallabagV2Controller: + arguments: + $rabbitMqProducer: '@old_sound_rabbit_mq.import_wallabag_v2_producer' + $redisProducer: '@wallabag_import.producer.redis.wallabag_v2' + Wallabag\ImportBundle\: resource: '../../src/Wallabag/ImportBundle/*' exclude: '../../src/Wallabag/ImportBundle/{Consumer,Controller,Redis}' @@ -183,8 +256,6 @@ services: path: '%redis_path%' password: '%redis_password%' - Wallabag\CoreBundle\Controller\ExceptionController: ~ - Wallabag\CoreBundle\Event\Subscriber\SQLiteCascadeDeleteSubscriber: tags: - { name: doctrine.event_subscriber } diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 69768400c..a65463051 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -1,30 +1,10 @@ parameters: ignoreErrors: - - - message: "#^Call to an undefined method Psr\\\\Container\\\\ContainerInterface\\:\\:getParameter\\(\\)\\.$#" - count: 2 - path: src/Wallabag/ApiBundle/Controller/EntryRestController.php - - - - message: "#^Call to an undefined method Psr\\\\Container\\\\ContainerInterface\\:\\:getParameter\\(\\)\\.$#" - count: 1 - path: src/Wallabag/ApiBundle/Controller/UserRestController.php - - - - message: "#^Call to an undefined method Psr\\\\Container\\\\ContainerInterface\\:\\:getParameter\\(\\)\\.$#" - count: 3 - path: src/Wallabag/ApiBundle/Controller/WallabagRestController.php - - message: "#^Call to an undefined method Wallabag\\\\CoreBundle\\\\Entity\\\\RuleInterface\\:\\:getConfig\\(\\)\\.$#" count: 1 path: src/Wallabag/CoreBundle/Controller/ConfigController.php - - - message: "#^Call to an undefined method Psr\\\\Container\\\\ContainerInterface\\:\\:getParameter\\(\\)\\.$#" - count: 1 - path: src/Wallabag/CoreBundle/Controller/StaticController.php - - message: "#^Call to an undefined method Lexik\\\\Bundle\\\\FormFilterBundle\\\\Filter\\\\Query\\\\QueryInterface\\:\\:getExpressionBuilder\\(\\)\\.$#" count: 1 @@ -77,10 +57,10 @@ parameters: - message: "#^Method Symfony\\\\Contracts\\\\EventDispatcher\\\\EventDispatcherInterface\\:\\:dispatch()#" - count: 1 - path: src/Wallabag/CoreBundle/Command/InstallCommand.php + count: 15 + path: src/* - - message: "#^Method Symfony\\\\Contracts\\\\EventDispatcher\\\\EventDispatcherInterface\\:\\:dispatch()#" - count: 1 - path: src/Wallabag/CoreBundle/Command/ReloadEntryCommand.php + message: "#^Method FOS\\\\UserBundle\\\\Model\\\\UserManagerInterface\\:\\:updateUser()#" + count: 7 + path: src/Wallabag/CoreBundle/Controller/ConfigController.php diff --git a/src/Wallabag/AnnotationBundle/Controller/WallabagAnnotationController.php b/src/Wallabag/AnnotationBundle/Controller/WallabagAnnotationController.php index 20c34f55d..56abd18aa 100644 --- a/src/Wallabag/AnnotationBundle/Controller/WallabagAnnotationController.php +++ b/src/Wallabag/AnnotationBundle/Controller/WallabagAnnotationController.php @@ -2,6 +2,7 @@ namespace Wallabag\AnnotationBundle\Controller; +use Doctrine\ORM\EntityManagerInterface; use FOS\RestBundle\Controller\AbstractFOSRestController; use JMS\Serializer\SerializerInterface; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; @@ -12,10 +13,22 @@ use Symfony\Component\Routing\Annotation\Route; use Wallabag\AnnotationBundle\Entity\Annotation; use Wallabag\AnnotationBundle\Form\EditAnnotationType; use Wallabag\AnnotationBundle\Form\NewAnnotationType; +use Wallabag\AnnotationBundle\Repository\AnnotationRepository; use Wallabag\CoreBundle\Entity\Entry; class WallabagAnnotationController extends AbstractFOSRestController { + protected EntityManagerInterface $entityManager; + protected SerializerInterface $serializer; + protected FormFactoryInterface $formFactory; + + public function __construct(EntityManagerInterface $entityManager, SerializerInterface $serializer, FormFactoryInterface $formFactory) + { + $this->entityManager = $entityManager; + $this->serializer = $serializer; + $this->formFactory = $formFactory; + } + /** * Retrieve annotations for an entry. * @@ -25,16 +38,14 @@ class WallabagAnnotationController extends AbstractFOSRestController * * @return JsonResponse */ - public function getAnnotationsAction(Entry $entry) + public function getAnnotationsAction(Entry $entry, AnnotationRepository $annotationRepository) { - $annotationRows = $this - ->getDoctrine() - ->getRepository(Annotation::class) - ->findAnnotationsByPageId($entry->getId(), $this->getUser()->getId()); + $annotationRows = $annotationRepository->findAnnotationsByPageId($entry->getId(), $this->getUser()->getId()); + $total = \count($annotationRows); $annotations = ['total' => $total, 'rows' => $annotationRows]; - $json = $this->get(SerializerInterface::class)->serialize($annotations, 'json'); + $json = $this->serializer->serialize($annotations, 'json'); return (new JsonResponse())->setJson($json); } @@ -52,21 +63,20 @@ class WallabagAnnotationController extends AbstractFOSRestController { $data = json_decode($request->getContent(), true); - $em = $this->get('doctrine')->getManager(); $annotation = new Annotation($this->getUser()); $annotation->setEntry($entry); - $form = $this->get(FormFactoryInterface::class)->createNamed('', NewAnnotationType::class, $annotation, [ + $form = $this->formFactory->createNamed('', NewAnnotationType::class, $annotation, [ 'csrf_protection' => false, 'allow_extra_fields' => true, ]); $form->submit($data); if ($form->isValid()) { - $em->persist($annotation); - $em->flush(); + $this->entityManager->persist($annotation); + $this->entityManager->flush(); - $json = $this->get(SerializerInterface::class)->serialize($annotation, 'json'); + $json = $this->serializer->serialize($annotation, 'json'); return JsonResponse::fromJsonString($json); } @@ -88,18 +98,17 @@ class WallabagAnnotationController extends AbstractFOSRestController { $data = json_decode($request->getContent(), true); - $form = $this->get(FormFactoryInterface::class)->createNamed('', EditAnnotationType::class, $annotation, [ + $form = $this->formFactory->createNamed('', EditAnnotationType::class, $annotation, [ 'csrf_protection' => false, 'allow_extra_fields' => true, ]); $form->submit($data); if ($form->isValid()) { - $em = $this->get('doctrine')->getManager(); - $em->persist($annotation); - $em->flush(); + $this->entityManager->persist($annotation); + $this->entityManager->flush(); - $json = $this->get(SerializerInterface::class)->serialize($annotation, 'json'); + $json = $this->serializer->serialize($annotation, 'json'); return JsonResponse::fromJsonString($json); } @@ -119,11 +128,10 @@ class WallabagAnnotationController extends AbstractFOSRestController */ public function deleteAnnotationAction(Annotation $annotation) { - $em = $this->get('doctrine')->getManager(); - $em->remove($annotation); - $em->flush(); + $this->entityManager->remove($annotation); + $this->entityManager->flush(); - $json = $this->get(SerializerInterface::class)->serialize($annotation, 'json'); + $json = $this->serializer->serialize($annotation, 'json'); return (new JsonResponse())->setJson($json); } diff --git a/src/Wallabag/ApiBundle/Controller/ConfigRestController.php b/src/Wallabag/ApiBundle/Controller/ConfigRestController.php index 0bcc20e01..a73d6b93e 100644 --- a/src/Wallabag/ApiBundle/Controller/ConfigRestController.php +++ b/src/Wallabag/ApiBundle/Controller/ConfigRestController.php @@ -27,11 +27,11 @@ class ConfigRestController extends WallabagRestController * * @return JsonResponse */ - public function getConfigAction() + public function getConfigAction(SerializerInterface $serializer) { $this->validateAuthentication(); - $json = $this->get(SerializerInterface::class)->serialize( + $json = $serializer->serialize( $this->getUser()->getConfig(), 'json', SerializationContext::create()->setGroups(['config_api']) diff --git a/src/Wallabag/ApiBundle/Controller/DeveloperController.php b/src/Wallabag/ApiBundle/Controller/DeveloperController.php index c15c57678..052bda99d 100644 --- a/src/Wallabag/ApiBundle/Controller/DeveloperController.php +++ b/src/Wallabag/ApiBundle/Controller/DeveloperController.php @@ -2,17 +2,18 @@ namespace Wallabag\ApiBundle\Controller; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; +use Doctrine\ORM\EntityManagerInterface; +use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; -use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\Routing\Annotation\Route; -use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorInterface; use Wallabag\ApiBundle\Entity\Client; use Wallabag\ApiBundle\Form\Type\ClientType; +use Wallabag\ApiBundle\Repository\ClientRepository; -class DeveloperController extends Controller +class DeveloperController extends AbstractController { /** * List all clients and link to create a new one. @@ -21,9 +22,9 @@ class DeveloperController extends Controller * * @return Response */ - public function indexAction() + public function indexAction(ClientRepository $repo) { - $clients = $this->get('doctrine')->getRepository(Client::class)->findByUser($this->getUser()->getId()); + $clients = $repo->findByUser($this->getUser()->getId()); return $this->render('@WallabagCore/Developer/index.html.twig', [ 'clients' => $clients, @@ -37,21 +38,20 @@ class DeveloperController extends Controller * * @return Response */ - public function createClientAction(Request $request) + public function createClientAction(Request $request, EntityManagerInterface $entityManager, TranslatorInterface $translator) { - $em = $this->get('doctrine')->getManager(); $client = new Client($this->getUser()); $clientForm = $this->createForm(ClientType::class, $client); $clientForm->handleRequest($request); if ($clientForm->isSubmitted() && $clientForm->isValid()) { $client->setAllowedGrantTypes(['token', 'authorization_code', 'password', 'refresh_token']); - $em->persist($client); - $em->flush(); + $entityManager->persist($client); + $entityManager->flush(); - $this->get(SessionInterface::class)->getFlashBag()->add( + $this->addFlash( 'notice', - $this->get(TranslatorInterface::class)->trans('flashes.developer.notice.client_created', ['%name%' => $client->getName()]) + $translator->trans('flashes.developer.notice.client_created', ['%name%' => $client->getName()]) ); return $this->render('@WallabagCore/Developer/client_parameters.html.twig', [ @@ -73,19 +73,18 @@ class DeveloperController extends Controller * * @return RedirectResponse */ - public function deleteClientAction(Client $client) + public function deleteClientAction(Client $client, EntityManagerInterface $entityManager, TranslatorInterface $translator) { if (null === $this->getUser() || $client->getUser()->getId() !== $this->getUser()->getId()) { throw $this->createAccessDeniedException('You can not access this client.'); } - $em = $this->get('doctrine')->getManager(); - $em->remove($client); - $em->flush(); + $entityManager->remove($client); + $entityManager->flush(); - $this->get(SessionInterface::class)->getFlashBag()->add( + $this->addFlash( 'notice', - $this->get(TranslatorInterface::class)->trans('flashes.developer.notice.client_deleted', ['%name%' => $client->getName()]) + $translator->trans('flashes.developer.notice.client_deleted', ['%name%' => $client->getName()]) ); return $this->redirect($this->generateUrl('developer')); diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index c2b6158d3..ef91d7fb8 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -6,6 +6,7 @@ use Hateoas\Configuration\Route as HateoasRoute; use Hateoas\Representation\Factory\PagerfantaFactory; use Nelmio\ApiDocBundle\Annotation\Operation; use Pagerfanta\Pagerfanta; +use Psr\Log\LoggerInterface; use Swagger\Annotations as SWG; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpFoundation\JsonResponse; @@ -23,6 +24,7 @@ use Wallabag\CoreBundle\Helper\EntriesExport; use Wallabag\CoreBundle\Helper\TagsAssigner; use Wallabag\CoreBundle\Helper\UrlHasher; use Wallabag\CoreBundle\Repository\EntryRepository; +use Wallabag\CoreBundle\Repository\TagRepository; class EntryRestController extends WallabagRestController { @@ -85,10 +87,9 @@ class EntryRestController extends WallabagRestController * * @return JsonResponse */ - public function getEntriesExistsAction(Request $request) + public function getEntriesExistsAction(Request $request, EntryRepository $entryRepository) { $this->validateAuthentication(); - $repo = $this->get('doctrine')->getRepository(Entry::class); $returnId = (null === $request->query->get('return_id')) ? false : (bool) $request->query->get('return_id'); @@ -116,7 +117,7 @@ class EntryRestController extends WallabagRestController } $results = array_fill_keys($hashedUrls, null); - $res = $repo->findByUserIdAndBatchHashedUrls($this->getUser()->getId(), $hashedUrls); + $res = $entryRepository->findByUserIdAndBatchHashedUrls($this->getUser()->getId(), $hashedUrls); foreach ($res as $e) { $_hashedUrl = array_keys($hashedUrls, 'blah', true); if ([] !== array_keys($hashedUrls, $e['hashedUrl'], true)) { @@ -279,7 +280,7 @@ class EntryRestController extends WallabagRestController * * @return JsonResponse */ - public function getEntriesAction(Request $request) + public function getEntriesAction(Request $request, EntryRepository $entryRepository) { $this->validateAuthentication(); @@ -297,7 +298,7 @@ class EntryRestController extends WallabagRestController try { /** @var Pagerfanta $pager */ - $pager = $this->get(EntryRepository::class)->findEntries( + $pager = $entryRepository->findEntries( $this->getUser()->getId(), $isArchived, $isStarred, @@ -404,12 +405,12 @@ class EntryRestController extends WallabagRestController * * @return Response */ - public function getEntryExportAction(Entry $entry, Request $request) + public function getEntryExportAction(Entry $entry, Request $request, EntriesExport $entriesExport) { $this->validateAuthentication(); $this->validateUserAccess($entry->getUser()->getId()); - return $this->get(EntriesExport::class) + return $entriesExport ->setEntries($entry) ->updateTitle('entry') ->updateAuthor('entry') @@ -439,7 +440,7 @@ class EntryRestController extends WallabagRestController * * @return JsonResponse */ - public function deleteEntriesListAction(Request $request) + public function deleteEntriesListAction(Request $request, EntryRepository $entryRepository, EventDispatcherInterface $eventDispatcher) { $this->validateAuthentication(); @@ -453,7 +454,7 @@ class EntryRestController extends WallabagRestController // handle multiple urls foreach ($urls as $key => $url) { - $entry = $this->get(EntryRepository::class)->findByUrlAndUserId( + $entry = $entryRepository->findByUrlAndUserId( $url, $this->getUser()->getId() ); @@ -462,11 +463,10 @@ class EntryRestController extends WallabagRestController if (false !== $entry) { // entry deleted, dispatch event about it! - $this->get(EventDispatcherInterface::class)->dispatch(new EntryDeletedEvent($entry), EntryDeletedEvent::NAME); + $eventDispatcher->dispatch(new EntryDeletedEvent($entry), EntryDeletedEvent::NAME); - $em = $this->get('doctrine')->getManager(); - $em->remove($entry); - $em->flush(); + $this->entityManager->remove($entry); + $this->entityManager->flush(); } $results[$key]['entry'] = $entry instanceof Entry ? true : false; @@ -500,13 +500,13 @@ class EntryRestController extends WallabagRestController * * @return JsonResponse */ - public function postEntriesListAction(Request $request) + public function postEntriesListAction(Request $request, EntryRepository $entryRepository, EventDispatcherInterface $eventDispatcher, ContentProxy $contentProxy) { $this->validateAuthentication(); $urls = json_decode($request->query->get('urls', [])); - $limit = $this->container->getParameter('wallabag_core.api_limit_mass_actions'); + $limit = $this->getParameter('wallabag_core.api_limit_mass_actions'); if (\count($urls) > $limit) { throw new HttpException(400, 'API limit reached'); @@ -519,7 +519,7 @@ class EntryRestController extends WallabagRestController // handle multiple urls foreach ($urls as $key => $url) { - $entry = $this->get(EntryRepository::class)->findByUrlAndUserId( + $entry = $entryRepository->findByUrlAndUserId( $url, $this->getUser()->getId() ); @@ -529,17 +529,16 @@ class EntryRestController extends WallabagRestController if (false === $entry) { $entry = new Entry($this->getUser()); - $this->get(ContentProxy::class)->updateEntry($entry, $url); + $contentProxy->updateEntry($entry, $url); } - $em = $this->get('doctrine')->getManager(); - $em->persist($entry); - $em->flush(); + $this->entityManager->persist($entry); + $this->entityManager->flush(); $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false; // entry saved, dispatch event about it! - $this->get(EventDispatcherInterface::class)->dispatch(new EntrySavedEvent($entry), EntrySavedEvent::NAME); + $eventDispatcher->dispatch(new EntrySavedEvent($entry), EntrySavedEvent::NAME); } return $this->sendResponse($results); @@ -683,13 +682,13 @@ class EntryRestController extends WallabagRestController * * @return JsonResponse */ - public function postEntriesAction(Request $request) + public function postEntriesAction(Request $request, EntryRepository $entryRepository, ContentProxy $contentProxy, LoggerInterface $logger, TagsAssigner $tagsAssigner, EventDispatcherInterface $eventDispatcher) { $this->validateAuthentication(); $url = $request->request->get('url'); - $entry = $this->get(EntryRepository::class)->findByUrlAndUserId( + $entry = $entryRepository->findByUrlAndUserId( $url, $this->getUser()->getId() ); @@ -702,7 +701,7 @@ class EntryRestController extends WallabagRestController $data = $this->retrieveValueFromRequest($request); try { - $this->get(ContentProxy::class)->updateEntry( + $contentProxy->updateEntry( $entry, $entry->getUrl(), [ @@ -717,10 +716,10 @@ class EntryRestController extends WallabagRestController ] ); } catch (\Exception $e) { - // $this->get('logger')->error('Error while saving an entry', [ - // 'exception' => $e, - // 'entry' => $entry, - // ]); + $logger->error('Error while saving an entry', [ + 'exception' => $e, + 'entry' => $entry, + ]); } if (null !== $data['isArchived']) { @@ -732,7 +731,7 @@ class EntryRestController extends WallabagRestController } if (!empty($data['tags'])) { - $this->get(TagsAssigner::class)->assignTagsToEntry($entry, $data['tags']); + $tagsAssigner->assignTagsToEntry($entry, $data['tags']); } if (!empty($data['origin_url'])) { @@ -748,19 +747,18 @@ class EntryRestController extends WallabagRestController } if (empty($entry->getDomainName())) { - $this->get(ContentProxy::class)->setEntryDomainName($entry); + $contentProxy->setEntryDomainName($entry); } if (empty($entry->getTitle())) { - $this->get(ContentProxy::class)->setDefaultEntryTitle($entry); + $contentProxy->setDefaultEntryTitle($entry); } - $em = $this->get('doctrine')->getManager(); - $em->persist($entry); - $em->flush(); + $this->entityManager->persist($entry); + $this->entityManager->flush(); // entry saved, dispatch event about it! - $this->get(EventDispatcherInterface::class)->dispatch(new EntrySavedEvent($entry), EntrySavedEvent::NAME); + $eventDispatcher->dispatch(new EntrySavedEvent($entry), EntrySavedEvent::NAME); return $this->sendResponse($entry); } @@ -888,13 +886,11 @@ class EntryRestController extends WallabagRestController * * @return JsonResponse */ - public function patchEntriesAction(Entry $entry, Request $request) + public function patchEntriesAction(Entry $entry, Request $request, ContentProxy $contentProxy, LoggerInterface $logger, TagsAssigner $tagsAssigner, EventDispatcherInterface $eventDispatcher) { $this->validateAuthentication(); $this->validateUserAccess($entry->getUser()->getId()); - $contentProxy = $this->get(ContentProxy::class); - $data = $this->retrieveValueFromRequest($request); // this is a special case where user want to manually update the entry content @@ -911,10 +907,10 @@ class EntryRestController extends WallabagRestController true ); } catch (\Exception $e) { - // $this->get('logger')->error('Error while saving an entry', [ - // 'exception' => $e, - // 'entry' => $entry, - // ]); + $logger->error('Error while saving an entry', [ + 'exception' => $e, + 'entry' => $entry, + ]); } } @@ -948,7 +944,7 @@ class EntryRestController extends WallabagRestController if (!empty($data['tags'])) { $entry->removeAllTags(); - $this->get(TagsAssigner::class)->assignTagsToEntry($entry, $data['tags']); + $tagsAssigner->assignTagsToEntry($entry, $data['tags']); } if (null !== $data['isPublic']) { @@ -964,19 +960,18 @@ class EntryRestController extends WallabagRestController } if (empty($entry->getDomainName())) { - $this->get(ContentProxy::class)->setEntryDomainName($entry); + $contentProxy->setEntryDomainName($entry); } if (empty($entry->getTitle())) { - $this->get(ContentProxy::class)->setDefaultEntryTitle($entry); + $contentProxy->setDefaultEntryTitle($entry); } - $em = $this->get('doctrine')->getManager(); - $em->persist($entry); - $em->flush(); + $this->entityManager->persist($entry); + $this->entityManager->flush(); // entry saved, dispatch event about it! - $this->get(EventDispatcherInterface::class)->dispatch(new EntrySavedEvent($entry), EntrySavedEvent::NAME); + $eventDispatcher->dispatch(new EntrySavedEvent($entry), EntrySavedEvent::NAME); return $this->sendResponse($entry); } @@ -1006,33 +1001,32 @@ class EntryRestController extends WallabagRestController * * @return JsonResponse */ - public function patchEntriesReloadAction(Entry $entry) + public function patchEntriesReloadAction(Entry $entry, ContentProxy $contentProxy, LoggerInterface $logger, EventDispatcherInterface $eventDispatcher) { $this->validateAuthentication(); $this->validateUserAccess($entry->getUser()->getId()); try { - $this->get(ContentProxy::class)->updateEntry($entry, $entry->getUrl()); + $contentProxy->updateEntry($entry, $entry->getUrl()); } catch (\Exception $e) { - // $this->get('logger')->error('Error while saving an entry', [ - // 'exception' => $e, - // 'entry' => $entry, - // ]); + $logger->error('Error while saving an entry', [ + 'exception' => $e, + 'entry' => $entry, + ]); return new JsonResponse([], 304); } // if refreshing entry failed, don't save it - if ($this->container->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) { + if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) { return new JsonResponse([], 304); } - $em = $this->get('doctrine')->getManager(); - $em->persist($entry); - $em->flush(); + $this->entityManager->persist($entry); + $this->entityManager->flush(); // entry saved, dispatch event about it! - $this->get(EventDispatcherInterface::class)->dispatch(new EntrySavedEvent($entry), EntrySavedEvent::NAME); + $eventDispatcher->dispatch(new EntrySavedEvent($entry), EntrySavedEvent::NAME); return $this->sendResponse($entry); } @@ -1064,7 +1058,7 @@ class EntryRestController extends WallabagRestController * * @return JsonResponse */ - public function deleteEntriesAction(Entry $entry, Request $request) + public function deleteEntriesAction(Entry $entry, Request $request, EventDispatcherInterface $eventDispatcher) { $expect = $request->query->get('expect', 'entry'); if (!\in_array($expect, ['id', 'entry'], true)) { @@ -1083,11 +1077,10 @@ class EntryRestController extends WallabagRestController } // entry deleted, dispatch event about it! - $this->get(EventDispatcherInterface::class)->dispatch(new EntryDeletedEvent($entry), EntryDeletedEvent::NAME); + $eventDispatcher->dispatch(new EntryDeletedEvent($entry), EntryDeletedEvent::NAME); - $em = $this->get('doctrine')->getManager(); - $em->remove($entry); - $em->flush(); + $this->entityManager->remove($entry); + $this->entityManager->flush(); return $response; } @@ -1158,19 +1151,18 @@ class EntryRestController extends WallabagRestController * * @return JsonResponse */ - public function postEntriesTagsAction(Request $request, Entry $entry) + public function postEntriesTagsAction(Request $request, Entry $entry, TagsAssigner $tagsAssigner) { $this->validateAuthentication(); $this->validateUserAccess($entry->getUser()->getId()); $tags = $request->request->get('tags', ''); if (!empty($tags)) { - $this->get(TagsAssigner::class)->assignTagsToEntry($entry, $tags); + $tagsAssigner->assignTagsToEntry($entry, $tags); } - $em = $this->get('doctrine')->getManager(); - $em->persist($entry); - $em->flush(); + $this->entityManager->persist($entry); + $this->entityManager->flush(); return $this->sendResponse($entry); } @@ -1213,9 +1205,9 @@ class EntryRestController extends WallabagRestController $this->validateUserAccess($entry->getUser()->getId()); $entry->removeTag($tag); - $em = $this->get('doctrine')->getManager(); - $em->persist($entry); - $em->flush(); + + $this->entityManager->persist($entry); + $this->entityManager->flush(); return $this->sendResponse($entry); } @@ -1243,7 +1235,7 @@ class EntryRestController extends WallabagRestController * * @return JsonResponse */ - public function deleteEntriesTagsListAction(Request $request) + public function deleteEntriesTagsListAction(Request $request, TagRepository $tagRepository, EntryRepository $entryRepository) { $this->validateAuthentication(); @@ -1257,7 +1249,7 @@ class EntryRestController extends WallabagRestController $results = []; foreach ($list as $key => $element) { - $entry = $this->get(EntryRepository::class)->findByUrlAndUserId( + $entry = $entryRepository->findByUrlAndUserId( $element->url, $this->getUser()->getId() ); @@ -1272,18 +1264,15 @@ class EntryRestController extends WallabagRestController foreach ($tags as $label) { $label = trim($label); - $tag = $this->get('doctrine') - ->getRepository(Tag::class) - ->findOneByLabel($label); + $tag = $tagRepository->findOneByLabel($label); if (false !== $tag) { $entry->removeTag($tag); } } - $em = $this->get('doctrine')->getManager(); - $em->persist($entry); - $em->flush(); + $this->entityManager->persist($entry); + $this->entityManager->flush(); } } @@ -1313,7 +1302,7 @@ class EntryRestController extends WallabagRestController * * @return JsonResponse */ - public function postEntriesTagsListAction(Request $request) + public function postEntriesTagsListAction(Request $request, EntryRepository $entryRepository, TagsAssigner $tagsAssigner) { $this->validateAuthentication(); @@ -1327,7 +1316,7 @@ class EntryRestController extends WallabagRestController // handle multiple urls foreach ($list as $key => $element) { - $entry = $this->get(EntryRepository::class)->findByUrlAndUserId( + $entry = $entryRepository->findByUrlAndUserId( $element->url, $this->getUser()->getId() ); @@ -1338,11 +1327,10 @@ class EntryRestController extends WallabagRestController $tags = $element->tags; if (false !== $entry && !(empty($tags))) { - $this->get(TagsAssigner::class)->assignTagsToEntry($entry, $tags); + $tagsAssigner->assignTagsToEntry($entry, $tags); - $em = $this->get('doctrine')->getManager(); - $em->persist($entry); - $em->flush(); + $this->entityManager->persist($entry); + $this->entityManager->flush(); } } diff --git a/src/Wallabag/ApiBundle/Controller/SearchRestController.php b/src/Wallabag/ApiBundle/Controller/SearchRestController.php index caaf4772a..ad914c6d0 100644 --- a/src/Wallabag/ApiBundle/Controller/SearchRestController.php +++ b/src/Wallabag/ApiBundle/Controller/SearchRestController.php @@ -58,7 +58,7 @@ class SearchRestController extends WallabagRestController * * @return JsonResponse */ - public function getSearchAction(Request $request) + public function getSearchAction(Request $request, EntryRepository $entryRepository) { $this->validateAuthentication(); @@ -66,12 +66,11 @@ class SearchRestController extends WallabagRestController $page = (int) $request->query->get('page', 1); $perPage = (int) $request->query->get('perPage', 30); - $qb = $this->get(EntryRepository::class) - ->getBuilderForSearchByUser( - $this->getUser()->getId(), - $term, - null - ); + $qb = $entryRepository->getBuilderForSearchByUser( + $this->getUser()->getId(), + $term, + null + ); $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false); $pager = new Pagerfanta($pagerAdapter); diff --git a/src/Wallabag/ApiBundle/Controller/TagRestController.php b/src/Wallabag/ApiBundle/Controller/TagRestController.php index 7e943be55..e50928b7d 100644 --- a/src/Wallabag/ApiBundle/Controller/TagRestController.php +++ b/src/Wallabag/ApiBundle/Controller/TagRestController.php @@ -2,7 +2,6 @@ namespace Wallabag\ApiBundle\Controller; -use JMS\Serializer\SerializerInterface; use Nelmio\ApiDocBundle\Annotation\Operation; use Swagger\Annotations as SWG; use Symfony\Component\HttpFoundation\JsonResponse; @@ -10,6 +9,8 @@ use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Tag; +use Wallabag\CoreBundle\Repository\EntryRepository; +use Wallabag\CoreBundle\Repository\TagRepository; class TagRestController extends WallabagRestController { @@ -29,15 +30,13 @@ class TagRestController extends WallabagRestController * * @return JsonResponse */ - public function getTagsAction() + public function getTagsAction(TagRepository $tagRepository) { $this->validateAuthentication(); - $tags = $this->get('doctrine') - ->getRepository(Tag::class) - ->findAllFlatTagsWithNbEntries($this->getUser()->getId()); + $tags = $tagRepository->findAllFlatTagsWithNbEntries($this->getUser()->getId()); - $json = $this->get(SerializerInterface::class)->serialize($tags, 'json'); + $json = $this->serializer->serialize($tags, 'json'); return (new JsonResponse())->setJson($json); } @@ -66,12 +65,12 @@ class TagRestController extends WallabagRestController * * @return JsonResponse */ - public function deleteTagLabelAction(Request $request) + public function deleteTagLabelAction(Request $request, TagRepository $tagRepository, EntryRepository $entryRepository) { $this->validateAuthentication(); $label = $request->get('tag', ''); - $tags = $this->get('doctrine')->getRepository(Tag::class)->findByLabelsAndUser([$label], $this->getUser()->getId()); + $tags = $tagRepository->findByLabelsAndUser([$label], $this->getUser()->getId()); if (empty($tags)) { throw $this->createNotFoundException('Tag not found'); @@ -79,13 +78,11 @@ class TagRestController extends WallabagRestController $tag = $tags[0]; - $this->get('doctrine') - ->getRepository(Entry::class) - ->removeTag($this->getUser()->getId(), $tag); + $entryRepository->removeTag($this->getUser()->getId(), $tag); $this->cleanOrphanTag($tag); - $json = $this->get(SerializerInterface::class)->serialize($tag, 'json'); + $json = $this->serializer->serialize($tag, 'json'); return (new JsonResponse())->setJson($json); } @@ -116,25 +113,23 @@ class TagRestController extends WallabagRestController * * @return JsonResponse */ - public function deleteTagsLabelAction(Request $request) + public function deleteTagsLabelAction(Request $request, TagRepository $tagRepository, EntryRepository $entryRepository) { $this->validateAuthentication(); $tagsLabels = $request->get('tags', ''); - $tags = $this->get('doctrine')->getRepository(Tag::class)->findByLabelsAndUser(explode(',', $tagsLabels), $this->getUser()->getId()); + $tags = $tagRepository->findByLabelsAndUser(explode(',', $tagsLabels), $this->getUser()->getId()); if (empty($tags)) { throw $this->createNotFoundException('Tags not found'); } - $this->get('doctrine') - ->getRepository(Entry::class) - ->removeTags($this->getUser()->getId(), $tags); + $entryRepository->removeTags($this->getUser()->getId(), $tags); $this->cleanOrphanTag($tags); - $json = $this->get(SerializerInterface::class)->serialize($tags, 'json'); + $json = $this->serializer->serialize($tags, 'json'); return (new JsonResponse())->setJson($json); } @@ -163,23 +158,21 @@ class TagRestController extends WallabagRestController * * @return JsonResponse */ - public function deleteTagAction(Tag $tag) + public function deleteTagAction(Tag $tag, TagRepository $tagRepository, EntryRepository $entryRepository) { $this->validateAuthentication(); - $tagFromDb = $this->get('doctrine')->getRepository(Tag::class)->findByLabelsAndUser([$tag->getLabel()], $this->getUser()->getId()); + $tagFromDb = $tagRepository->findByLabelsAndUser([$tag->getLabel()], $this->getUser()->getId()); if (empty($tagFromDb)) { throw $this->createNotFoundException('Tag not found'); } - $this->get('doctrine') - ->getRepository(Entry::class) - ->removeTag($this->getUser()->getId(), $tag); + $entryRepository->removeTag($this->getUser()->getId(), $tag); $this->cleanOrphanTag($tag); - $json = $this->get(SerializerInterface::class)->serialize($tag, 'json'); + $json = $this->serializer->serialize($tag, 'json'); return (new JsonResponse())->setJson($json); } @@ -195,14 +188,12 @@ class TagRestController extends WallabagRestController $tags = [$tags]; } - $em = $this->get('doctrine')->getManager(); - foreach ($tags as $tag) { if (0 === \count($tag->getEntries())) { - $em->remove($tag); + $this->entityManager->remove($tag); } } - $em->flush(); + $this->entityManager->flush(); } } diff --git a/src/Wallabag/ApiBundle/Controller/UserRestController.php b/src/Wallabag/ApiBundle/Controller/UserRestController.php index 42b22f203..8f9bf7e3f 100644 --- a/src/Wallabag/ApiBundle/Controller/UserRestController.php +++ b/src/Wallabag/ApiBundle/Controller/UserRestController.php @@ -3,18 +3,17 @@ namespace Wallabag\ApiBundle\Controller; use Craue\ConfigBundle\Util\Config; +use Doctrine\ORM\EntityManagerInterface; use FOS\UserBundle\Event\UserEvent; use FOS\UserBundle\FOSUserEvents; use FOS\UserBundle\Model\UserManagerInterface; use JMS\Serializer\SerializationContext; -use JMS\Serializer\SerializerInterface; use Nelmio\ApiDocBundle\Annotation\Operation; use Swagger\Annotations as SWG; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; -use Symfony\Component\Translation\TranslatorInterface; use Wallabag\ApiBundle\Entity\Client; use Wallabag\UserBundle\Entity\User; use Wallabag\UserBundle\Form\NewUserType; @@ -90,17 +89,16 @@ class UserRestController extends WallabagRestController * * @return JsonResponse */ - public function putUserAction(Request $request) + public function putUserAction(Request $request, Config $craueConfig, UserManagerInterface $userManager, EntityManagerInterface $entityManager, EventDispatcherInterface $eventDispatcher) { - if (!$this->container->getParameter('fosuser_registration') || !$this->get(Config::class)->get('api_user_registration')) { - $json = $this->get(SerializerInterface::class)->serialize(['error' => "Server doesn't allow registrations"], 'json'); + if (!$this->getParameter('fosuser_registration') || !$craueConfig->get('api_user_registration')) { + $json = $this->serializer->serialize(['error' => "Server doesn't allow registrations"], 'json'); return (new JsonResponse()) ->setJson($json) ->setStatusCode(JsonResponse::HTTP_FORBIDDEN); } - $userManager = $this->get(UserManagerInterface::class); $user = $userManager->createUser(); \assert($user instanceof User); // user will be disabled BY DEFAULT to avoid spamming account to be enabled @@ -140,7 +138,7 @@ class UserRestController extends WallabagRestController $errors['password'] = $this->translateErrors($data['plainPassword']['children']['first']['errors']); } - $json = $this->get(SerializerInterface::class)->serialize(['error' => $errors], 'json'); + $json = $this->serializer->serialize(['error' => $errors], 'json'); return (new JsonResponse()) ->setJson($json) @@ -151,15 +149,14 @@ class UserRestController extends WallabagRestController $client = new Client($user); $client->setName($request->request->get('client_name', 'Default client')); - $this->get('doctrine')->getManager()->persist($client); + $entityManager->persist($client); $user->addClient($client); $userManager->updateUser($user); // dispatch a created event so the associated config will be created - $event = new UserEvent($user, $request); - $this->get(EventDispatcherInterface::class)->dispatch($event, FOSUserEvents::USER_CREATED); + $eventDispatcher->dispatch(new UserEvent($user, $request), FOSUserEvents::USER_CREATED); return $this->sendUser($user, 'user_api_with_client', JsonResponse::HTTP_CREATED); } @@ -174,7 +171,7 @@ class UserRestController extends WallabagRestController */ private function sendUser(User $user, $group = 'user_api', $status = JsonResponse::HTTP_OK) { - $json = $this->get(SerializerInterface::class)->serialize( + $json = $this->serializer->serialize( $user, 'json', SerializationContext::create()->setGroups([$group]) @@ -196,7 +193,7 @@ class UserRestController extends WallabagRestController { $translatedErrors = []; foreach ($errors as $error) { - $translatedErrors[] = $this->get(TranslatorInterface::class)->trans($error); + $translatedErrors[] = $this->translator->trans($error); } return $translatedErrors; diff --git a/src/Wallabag/ApiBundle/Controller/WallabagRestController.php b/src/Wallabag/ApiBundle/Controller/WallabagRestController.php index 4716addd6..43394bd3c 100644 --- a/src/Wallabag/ApiBundle/Controller/WallabagRestController.php +++ b/src/Wallabag/ApiBundle/Controller/WallabagRestController.php @@ -2,6 +2,7 @@ namespace Wallabag\ApiBundle\Controller; +use Doctrine\ORM\EntityManagerInterface; use FOS\RestBundle\Controller\AbstractFOSRestController; use JMS\Serializer\SerializationContext; use JMS\Serializer\SerializerInterface; @@ -12,10 +13,26 @@ use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; use Symfony\Component\Security\Core\Exception\AccessDeniedException; +use Symfony\Contracts\Translation\TranslatorInterface; use Wallabag\UserBundle\Entity\User; class WallabagRestController extends AbstractFOSRestController { + protected EntityManagerInterface $entityManager; + protected SerializerInterface $serializer; + protected AuthorizationCheckerInterface $authorizationChecker; + protected TokenStorageInterface $tokenStorage; + protected TranslatorInterface $translator; + + public function __construct(EntityManagerInterface $entityManager, SerializerInterface $serializer, AuthorizationCheckerInterface $authorizationChecker, TokenStorageInterface $tokenStorage, TranslatorInterface $translator) + { + $this->entityManager = $entityManager; + $this->serializer = $serializer; + $this->authorizationChecker = $authorizationChecker; + $this->tokenStorage = $tokenStorage; + $this->translator = $translator; + } + /** * Retrieve version number. * @@ -36,8 +53,8 @@ class WallabagRestController extends AbstractFOSRestController */ public function getVersionAction() { - $version = $this->container->getParameter('wallabag_core.version'); - $json = $this->get(SerializerInterface::class)->serialize($version, 'json'); + $version = $this->getParameter('wallabag_core.version'); + $json = $this->serializer->serialize($version, 'json'); return (new JsonResponse())->setJson($json); } @@ -62,16 +79,16 @@ class WallabagRestController extends AbstractFOSRestController { $info = [ 'appname' => 'wallabag', - 'version' => $this->container->getParameter('wallabag_core.version'), - 'allowed_registration' => $this->container->getParameter('fosuser_registration'), + 'version' => $this->getParameter('wallabag_core.version'), + 'allowed_registration' => $this->getParameter('fosuser_registration'), ]; - return (new JsonResponse())->setJson($this->get(SerializerInterface::class)->serialize($info, 'json')); + return (new JsonResponse())->setJson($this->serializer->serialize($info, 'json')); } protected function validateAuthentication() { - if (false === $this->get(AuthorizationCheckerInterface::class)->isGranted('IS_AUTHENTICATED_FULLY')) { + if (false === $this->authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')) { throw new AccessDeniedException(); } } @@ -84,8 +101,9 @@ class WallabagRestController extends AbstractFOSRestController */ protected function validateUserAccess($requestUserId) { - $user = $this->get(TokenStorageInterface::class)->getToken()->getUser(); + $user = $this->tokenStorage->getToken()->getUser(); \assert($user instanceof User); + if ($requestUserId !== $user->getId()) { throw $this->createAccessDeniedException('Access forbidden. Entry user id: ' . $requestUserId . ', logged user id: ' . $user->getId()); } @@ -104,7 +122,7 @@ class WallabagRestController extends AbstractFOSRestController $context = new SerializationContext(); $context->setSerializeNull(true); - $json = $this->get(SerializerInterface::class)->serialize($data, 'json', $context); + $json = $this->serializer->serialize($data, 'json', $context); return (new JsonResponse())->setJson($json); } diff --git a/src/Wallabag/CoreBundle/Controller/ConfigController.php b/src/Wallabag/CoreBundle/Controller/ConfigController.php index bc650c57b..ea1be664e 100644 --- a/src/Wallabag/CoreBundle/Controller/ConfigController.php +++ b/src/Wallabag/CoreBundle/Controller/ConfigController.php @@ -4,13 +4,13 @@ namespace Wallabag\CoreBundle\Controller; use Craue\ConfigBundle\Util\Config; use Doctrine\DBAL\Platforms\SqlitePlatform; -use Doctrine\Persistence\ManagerRegistry; +use Doctrine\ORM\EntityManagerInterface; use FOS\UserBundle\Model\UserManagerInterface; use JMS\Serializer\SerializationContext; use JMS\Serializer\SerializerBuilder; use PragmaRX\Recovery\Recovery as BackupCodes; use Scheb\TwoFactorBundle\Security\TwoFactor\Provider\Google\GoogleAuthenticatorInterface; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; +use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; @@ -20,7 +20,7 @@ use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Validator\Constraints\Locale as LocaleConstraint; use Symfony\Component\Validator\Validator\ValidatorInterface; -use Wallabag\AnnotationBundle\Entity\Annotation; +use Wallabag\AnnotationBundle\Repository\AnnotationRepository; use Wallabag\CoreBundle\Entity\Config as ConfigEntity; use Wallabag\CoreBundle\Entity\IgnoreOriginUserRule; use Wallabag\CoreBundle\Entity\RuleInterface; @@ -32,21 +32,39 @@ use Wallabag\CoreBundle\Form\Type\IgnoreOriginUserRuleType; use Wallabag\CoreBundle\Form\Type\TaggingRuleImportType; use Wallabag\CoreBundle\Form\Type\TaggingRuleType; use Wallabag\CoreBundle\Form\Type\UserInformationType; +use Wallabag\CoreBundle\Repository\ConfigRepository; use Wallabag\CoreBundle\Repository\EntryRepository; +use Wallabag\CoreBundle\Repository\IgnoreOriginUserRuleRepository; +use Wallabag\CoreBundle\Repository\TaggingRuleRepository; use Wallabag\CoreBundle\Repository\TagRepository; use Wallabag\CoreBundle\Tools\Utils; use Wallabag\UserBundle\Repository\UserRepository; -class ConfigController extends Controller +class ConfigController extends AbstractController { + private EntityManagerInterface $entityManager; + private UserManagerInterface $userManager; + private EntryRepository $entryRepository; + private TagRepository $tagRepository; + private AnnotationRepository $annotationRepository; + private ConfigRepository $configRepository; + + public function __construct(EntityManagerInterface $entityManager, UserManagerInterface $userManager, EntryRepository $entryRepository, TagRepository $tagRepository, AnnotationRepository $annotationRepository, ConfigRepository $configRepository) + { + $this->entityManager = $entityManager; + $this->userManager = $userManager; + $this->entryRepository = $entryRepository; + $this->tagRepository = $tagRepository; + $this->annotationRepository = $annotationRepository; + $this->configRepository = $configRepository; + } + /** * @Route("/config", name="config") */ - public function indexAction(Request $request) + public function indexAction(Request $request, Config $craueConfig, TaggingRuleRepository $taggingRuleRepository, IgnoreOriginUserRuleRepository $ignoreOriginUserRuleRepository, UserRepository $userRepository) { - $em = $this->get('doctrine')->getManager(); $config = $this->getConfig(); - $userManager = $this->container->get(UserManagerInterface::class); $user = $this->getUser(); // handle basic config detail (this form is defined as a service) @@ -54,8 +72,8 @@ class ConfigController extends Controller $configForm->handleRequest($request); if ($configForm->isSubmitted() && $configForm->isValid()) { - $em->persist($config); - $em->flush(); + $this->entityManager->persist($config); + $this->entityManager->flush(); $request->getSession()->set('_locale', $config->getLanguage()); @@ -72,13 +90,13 @@ class ConfigController extends Controller $pwdForm->handleRequest($request); if ($pwdForm->isSubmitted() && $pwdForm->isValid()) { - if ($this->get(Config::class)->get('demo_mode_enabled') && $this->get(Config::class)->get('demo_mode_username') === $user->getUsername()) { + if ($craueConfig->get('demo_mode_enabled') && $craueConfig->get('demo_mode_username') === $user->getUsername()) { $message = 'flashes.config.notice.password_not_updated_demo'; } else { $message = 'flashes.config.notice.password_updated'; $user->setPlainPassword($pwdForm->get('new_password')->getData()); - $userManager->updateUser($user, true); + $this->userManager->updateUser($user, true); } $this->addFlash('notice', $message); @@ -94,7 +112,7 @@ class ConfigController extends Controller $userForm->handleRequest($request); if ($userForm->isSubmitted() && $userForm->isValid()) { - $userManager->updateUser($user, true); + $this->userManager->updateUser($user, true); $this->addFlash( 'notice', @@ -109,8 +127,8 @@ class ConfigController extends Controller $feedForm->handleRequest($request); if ($feedForm->isSubmitted() && $feedForm->isValid()) { - $em->persist($config); - $em->flush(); + $this->entityManager->persist($config); + $this->entityManager->flush(); $this->addFlash( 'notice', @@ -125,9 +143,7 @@ class ConfigController extends Controller $action = $this->generateUrl('config') . '#set5'; if ($request->query->has('tagging-rule')) { - $taggingRule = $this->get('doctrine') - ->getRepository(TaggingRule::class) - ->find($request->query->get('tagging-rule')); + $taggingRule = $taggingRuleRepository->find($request->query->get('tagging-rule')); if ($this->getUser()->getId() !== $taggingRule->getConfig()->getUser()->getId()) { return $this->redirect($action); @@ -141,8 +157,8 @@ class ConfigController extends Controller if ($newTaggingRule->isSubmitted() && $newTaggingRule->isValid()) { $taggingRule->setConfig($config); - $em->persist($taggingRule); - $em->flush(); + $this->entityManager->persist($taggingRule); + $this->entityManager->flush(); $this->addFlash( 'notice', @@ -169,10 +185,10 @@ class ConfigController extends Controller $taggingRule->setRule($rule['rule']); $taggingRule->setTags($rule['tags']); $taggingRule->setConfig($config); - $em->persist($taggingRule); + $this->entityManager->persist($taggingRule); } - $em->flush(); + $this->entityManager->flush(); $message = 'flashes.config.notice.tagging_rules_imported'; } @@ -188,8 +204,7 @@ class ConfigController extends Controller $action = $this->generateUrl('config') . '#set6'; if ($request->query->has('ignore-origin-user-rule')) { - $ignoreOriginUserRule = $this->get('doctrine') - ->getRepository(IgnoreOriginUserRule::class) + $ignoreOriginUserRule = $ignoreOriginUserRuleRepository ->find($request->query->get('ignore-origin-user-rule')); if ($this->getUser()->getId() !== $ignoreOriginUserRule->getConfig()->getUser()->getId()) { @@ -206,8 +221,8 @@ class ConfigController extends Controller if ($newIgnoreOriginUserRule->isSubmitted() && $newIgnoreOriginUserRule->isValid()) { $ignoreOriginUserRule->setConfig($config); - $em->persist($ignoreOriginUserRule); - $em->flush(); + $this->entityManager->persist($ignoreOriginUserRule); + $this->entityManager->flush(); $this->addFlash( 'notice', @@ -233,7 +248,7 @@ class ConfigController extends Controller ], 'twofactor_auth' => $this->getParameter('twofactor_auth'), 'wallabag_url' => $this->getParameter('domain_name'), - 'enabled_users' => $this->get(UserRepository::class)->getSumEnabledUsers(), + 'enabled_users' => $userRepository->getSumEnabledUsers(), ]); } @@ -251,7 +266,7 @@ class ConfigController extends Controller $user = $this->getUser(); $user->setEmailTwoFactor(false); - $this->container->get(UserManagerInterface::class)->updateUser($user, true); + $this->userManager->updateUser($user, true); $this->addFlash( 'notice', @@ -278,7 +293,7 @@ class ConfigController extends Controller $user->setBackupCodes(null); $user->setEmailTwoFactor(true); - $this->container->get(UserManagerInterface::class)->updateUser($user, true); + $this->userManager->updateUser($user, true); $this->addFlash( 'notice', @@ -304,7 +319,7 @@ class ConfigController extends Controller $user->setGoogleAuthenticatorSecret(''); $user->setBackupCodes(null); - $this->container->get(UserManagerInterface::class)->updateUser($user, true); + $this->userManager->updateUser($user, true); $this->addFlash( 'notice', @@ -319,14 +334,14 @@ class ConfigController extends Controller * * @Route("/config/otp/app", name="config_otp_app") */ - public function otpAppAction() + public function otpAppAction(GoogleAuthenticatorInterface $googleAuthenticator) { if (!$this->getParameter('twofactor_auth')) { return $this->createNotFoundException('two_factor not enabled'); } $user = $this->getUser(); - $secret = $this->get(GoogleAuthenticatorInterface::class)->generateSecret(); + $secret = $googleAuthenticator->generateSecret(); $user->setGoogleAuthenticatorSecret($secret); $user->setEmailTwoFactor(false); @@ -341,7 +356,7 @@ class ConfigController extends Controller $user->setBackupCodes($backupCodesHashed); - $this->container->get(UserManagerInterface::class)->updateUser($user, true); + $this->userManager->updateUser($user, true); $this->addFlash( 'notice', @@ -350,7 +365,7 @@ class ConfigController extends Controller return $this->render('@WallabagCore/Config/otp_app.html.twig', [ 'backupCodes' => $backupCodes, - 'qr_code' => $this->get(GoogleAuthenticatorInterface::class)->getQRContent($user), + 'qr_code' => $googleAuthenticator->getQRContent($user), 'secret' => $secret, ]); } @@ -370,7 +385,7 @@ class ConfigController extends Controller $user->setGoogleAuthenticatorSecret(null); $user->setBackupCodes(null); - $this->container->get(UserManagerInterface::class)->updateUser($user, true); + $this->userManager->updateUser($user, true); return $this->redirect($this->generateUrl('config') . '#set3'); } @@ -380,9 +395,9 @@ class ConfigController extends Controller * * @Route("/config/otp/app/check", name="config_otp_app_check") */ - public function otpAppCheckAction(Request $request) + public function otpAppCheckAction(Request $request, GoogleAuthenticatorInterface $googleAuthenticator) { - $isValid = $this->get(GoogleAuthenticatorInterface::class)->checkCode( + $isValid = $googleAuthenticator->checkCode( $this->getUser(), $request->get('_auth_code') ); @@ -414,9 +429,8 @@ class ConfigController extends Controller $config = $this->getConfig(); $config->setFeedToken(Utils::generateToken()); - $em = $this->get('doctrine')->getManager(); - $em->persist($config); - $em->flush(); + $this->entityManager->persist($config); + $this->entityManager->flush(); if ($request->isXmlHttpRequest()) { return new JsonResponse(['token' => $config->getFeedToken()]); @@ -440,9 +454,8 @@ class ConfigController extends Controller $config = $this->getConfig(); $config->setFeedToken(null); - $em = $this->get('doctrine')->getManager(); - $em->persist($config); - $em->flush(); + $this->entityManager->persist($config); + $this->entityManager->flush(); if ($request->isXmlHttpRequest()) { return new JsonResponse(); @@ -467,9 +480,8 @@ class ConfigController extends Controller { $this->validateRuleAction($rule); - $em = $this->get('doctrine')->getManager(); - $em->remove($rule); - $em->flush(); + $this->entityManager->remove($rule); + $this->entityManager->flush(); $this->addFlash( 'notice', @@ -504,9 +516,8 @@ class ConfigController extends Controller { $this->validateRuleAction($rule); - $em = $this->get('doctrine')->getManager(); - $em->remove($rule); - $em->flush(); + $this->entityManager->remove($rule); + $this->entityManager->flush(); $this->addFlash( 'notice', @@ -537,13 +548,11 @@ class ConfigController extends Controller * * @return RedirectResponse */ - public function resetAction($type) + public function resetAction(string $type, AnnotationRepository $annotationRepository, EntryRepository $entryRepository) { switch ($type) { case 'annotations': - $this->get('doctrine') - ->getRepository(Annotation::class) - ->removeAllByUserId($this->getUser()->getId()); + $annotationRepository->removeAllByUserId($this->getUser()->getId()); break; case 'tags': $this->removeAllTagsByUserId($this->getUser()->getId()); @@ -551,24 +560,24 @@ class ConfigController extends Controller case 'entries': // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff // otherwise they won't be removed ... - if ($this->get(ManagerRegistry::class)->getConnection()->getDatabasePlatform() instanceof SqlitePlatform) { - $this->get('doctrine')->getRepository(Annotation::class)->removeAllByUserId($this->getUser()->getId()); + if ($this->entityManager->getConnection()->getDatabasePlatform() instanceof SqlitePlatform) { + $annotationRepository->removeAllByUserId($this->getUser()->getId()); } // manually remove tags to avoid orphan tag $this->removeAllTagsByUserId($this->getUser()->getId()); - $this->get(EntryRepository::class)->removeAllByUserId($this->getUser()->getId()); + $entryRepository->removeAllByUserId($this->getUser()->getId()); break; case 'archived': - if ($this->get(ManagerRegistry::class)->getConnection()->getDatabasePlatform() instanceof SqlitePlatform) { + if ($this->entityManager->getConnection()->getDatabasePlatform() instanceof SqlitePlatform) { $this->removeAnnotationsForArchivedByUserId($this->getUser()->getId()); } // manually remove tags to avoid orphan tag $this->removeTagsForArchivedByUserId($this->getUser()->getId()); - $this->get(EntryRepository::class)->removeArchivedByUserId($this->getUser()->getId()); + $entryRepository->removeArchivedByUserId($this->getUser()->getId()); break; } @@ -589,10 +598,9 @@ class ConfigController extends Controller * * @return RedirectResponse */ - public function deleteAccountAction(Request $request) + public function deleteAccountAction(Request $request, UserRepository $userRepository, TokenStorageInterface $tokenStorage) { - $enabledUsers = $this->get(UserRepository::class) - ->getSumEnabledUsers(); + $enabledUsers = $userRepository->getSumEnabledUsers(); if ($enabledUsers <= 1) { throw new AccessDeniedHttpException(); @@ -601,11 +609,10 @@ class ConfigController extends Controller $user = $this->getUser(); // logout current user - $this->get(TokenStorageInterface::class)->setToken(null); + $tokenStorage->setToken(null); $request->getSession()->invalidate(); - $em = $this->get(UserManagerInterface::class); - $em->deleteUser($user); + $this->userManager->deleteUser($user); return $this->redirect($this->generateUrl('fos_user_security_login')); } @@ -622,9 +629,8 @@ class ConfigController extends Controller $user = $this->getUser(); $user->getConfig()->setListMode(!$user->getConfig()->getListMode()); - $em = $this->get('doctrine')->getManager(); - $em->persist($user); - $em->flush(); + $this->entityManager->persist($user); + $this->entityManager->flush(); return $this->redirect($request->headers->get('referer')); } @@ -638,9 +644,9 @@ class ConfigController extends Controller * * @return RedirectResponse */ - public function setLocaleAction(Request $request, $language = null) + public function setLocaleAction(Request $request, ValidatorInterface $validator, $language = null) { - $errors = $this->get(ValidatorInterface::class)->validate($language, (new LocaleConstraint())); + $errors = $validator->validate($language, (new LocaleConstraint())); if (0 === \count($errors)) { $request->getSession()->set('_locale', $language); @@ -687,19 +693,16 @@ class ConfigController extends Controller return; } - $this->get(EntryRepository::class) - ->removeTags($userId, $tags); + $this->entryRepository->removeTags($userId, $tags); // cleanup orphan tags - $em = $this->get('doctrine')->getManager(); - foreach ($tags as $tag) { if (0 === \count($tag->getEntries())) { - $em->remove($tag); + $this->entityManager->remove($tag); } } - $em->flush(); + $this->entityManager->flush(); } /** @@ -709,7 +712,7 @@ class ConfigController extends Controller */ private function removeAllTagsByUserId($userId) { - $tags = $this->get(TagRepository::class)->findAllTags($userId); + $tags = $this->tagRepository->findAllTags($userId); $this->removeAllTagsByStatusAndUserId($tags, $userId); } @@ -720,23 +723,20 @@ class ConfigController extends Controller */ private function removeTagsForArchivedByUserId($userId) { - $tags = $this->get(TagRepository::class)->findForArchivedArticlesByUser($userId); + $tags = $this->tagRepository->findForArchivedArticlesByUser($userId); $this->removeAllTagsByStatusAndUserId($tags, $userId); } private function removeAnnotationsForArchivedByUserId($userId) { - $em = $this->get('doctrine')->getManager(); - - $archivedEntriesAnnotations = $this->get('doctrine') - ->getRepository(Annotation::class) + $archivedEntriesAnnotations = $this->annotationRepository ->findAllArchivedEntriesByUser($userId); foreach ($archivedEntriesAnnotations as $archivedEntriesAnnotation) { - $em->remove($archivedEntriesAnnotation); + $this->entityManager->remove($archivedEntriesAnnotation); } - $em->flush(); + $this->entityManager->flush(); } /** @@ -757,9 +757,7 @@ class ConfigController extends Controller */ private function getConfig() { - $config = $this->get('doctrine') - ->getRepository(ConfigEntity::class) - ->findOneByUser($this->getUser()); + $config = $this->configRepository->findOneByUser($this->getUser()); // should NEVER HAPPEN ... if (!$config) { diff --git a/src/Wallabag/CoreBundle/Controller/EntryController.php b/src/Wallabag/CoreBundle/Controller/EntryController.php index d11021993..e1e29bb60 100644 --- a/src/Wallabag/CoreBundle/Controller/EntryController.php +++ b/src/Wallabag/CoreBundle/Controller/EntryController.php @@ -3,6 +3,7 @@ namespace Wallabag\CoreBundle\Controller; use Craue\ConfigBundle\Util\Config; +use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\NoResultException; use Lexik\Bundle\FormFilterBundle\Filter\FilterBuilderUpdaterInterface; use Pagerfanta\Doctrine\ORM\QueryAdapter as DoctrineORMAdapter; @@ -13,10 +14,9 @@ use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; -use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; -use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorInterface; use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Tag; use Wallabag\CoreBundle\Event\EntryDeletedEvent; @@ -33,14 +33,32 @@ use Wallabag\CoreBundle\Repository\TagRepository; class EntryController extends Controller { + private EntityManagerInterface $entityManager; + private EventDispatcherInterface $eventDispatcher; + private EntryRepository $entryRepository; + private Redirect $redirectHelper; + private PreparePagerForEntries $preparePagerForEntriesHelper; + private FilterBuilderUpdaterInterface $filterBuilderUpdater; + private ContentProxy $contentProxy; + + public function __construct(EntityManagerInterface $entityManager, EventDispatcherInterface $eventDispatcher, EntryRepository $entryRepository, Redirect $redirectHelper, PreparePagerForEntries $preparePagerForEntriesHelper, FilterBuilderUpdaterInterface $filterBuilderUpdater, ContentProxy $contentProxy) + { + $this->entityManager = $entityManager; + $this->eventDispatcher = $eventDispatcher; + $this->entryRepository = $entryRepository; + $this->redirectHelper = $redirectHelper; + $this->preparePagerForEntriesHelper = $preparePagerForEntriesHelper; + $this->filterBuilderUpdater = $filterBuilderUpdater; + $this->contentProxy = $contentProxy; + } + /** * @Route("/mass", name="mass_action") * * @return Response */ - public function massAction(Request $request) + public function massAction(Request $request, TagRepository $tagRepository) { - $em = $this->get('doctrine')->getManager(); $values = $request->request->all(); $tagsToAdd = []; @@ -67,7 +85,7 @@ class EntryController extends Controller $label = substr($label, 1); $remove = true; } - $tag = $this->get(TagRepository::class)->findOneByLabel($label); + $tag = $tagRepository->findOneByLabel($label); if ($remove) { if (null !== $tag) { $tagsToRemove[] = $tag; @@ -86,7 +104,7 @@ class EntryController extends Controller if (isset($values['entry-checkbox'])) { foreach ($values['entry-checkbox'] as $id) { /** @var Entry * */ - $entry = $this->get(EntryRepository::class)->findById((int) $id)[0]; + $entry = $this->entryRepository->findById((int) $id)[0]; $this->checkUserAction($entry); @@ -102,15 +120,15 @@ class EntryController extends Controller $entry->removeTag($tag); } } elseif ('delete' === $action) { - $this->get(EventDispatcherInterface::class)->dispatch(new EntryDeletedEvent($entry), EntryDeletedEvent::NAME); - $em->remove($entry); + $this->eventDispatcher->dispatch(new EntryDeletedEvent($entry), EntryDeletedEvent::NAME); + $this->entityManager->remove($entry); } } - $em->flush(); + $this->entityManager->flush(); } - $redirectUrl = $this->get(Redirect::class)->to($request->headers->get('referer')); + $redirectUrl = $this->redirectHelper->to($request->headers->get('referer')); return $this->redirect($redirectUrl); } @@ -151,7 +169,7 @@ class EntryController extends Controller * * @return Response */ - public function addEntryFormAction(Request $request) + public function addEntryFormAction(Request $request, TranslatorInterface $translator) { $entry = new Entry($this->getUser()); @@ -163,9 +181,9 @@ class EntryController extends Controller $existingEntry = $this->checkIfEntryAlreadyExists($entry); if (false !== $existingEntry) { - $this->get(SessionInterface::class)->getFlashBag()->add( + $this->addFlash( 'notice', - $this->get(TranslatorInterface::class)->trans('flashes.entry.notice.entry_already_saved', ['%date%' => $existingEntry->getCreatedAt()->format('d-m-Y')]) + $translator->trans('flashes.entry.notice.entry_already_saved', ['%date%' => $existingEntry->getCreatedAt()->format('d-m-Y')]) ); return $this->redirect($this->generateUrl('view', ['id' => $existingEntry->getId()])); @@ -173,12 +191,11 @@ class EntryController extends Controller $this->updateEntry($entry); - $em = $this->get('doctrine')->getManager(); - $em->persist($entry); - $em->flush(); + $this->entityManager->persist($entry); + $this->entityManager->flush(); // entry saved, dispatch event about it! - $this->get(EventDispatcherInterface::class)->dispatch(new EntrySavedEvent($entry), EntrySavedEvent::NAME); + $this->eventDispatcher->dispatch(new EntrySavedEvent($entry), EntrySavedEvent::NAME); return $this->redirect($this->generateUrl('homepage')); } @@ -201,12 +218,11 @@ class EntryController extends Controller if (false === $this->checkIfEntryAlreadyExists($entry)) { $this->updateEntry($entry); - $em = $this->get('doctrine')->getManager(); - $em->persist($entry); - $em->flush(); + $this->entityManager->persist($entry); + $this->entityManager->flush(); // entry saved, dispatch event about it! - $this->get(EventDispatcherInterface::class)->dispatch(new EntrySavedEvent($entry), EntrySavedEvent::NAME); + $this->eventDispatcher->dispatch(new EntrySavedEvent($entry), EntrySavedEvent::NAME); } return $this->redirect($this->generateUrl('homepage')); @@ -238,11 +254,10 @@ class EntryController extends Controller $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { - $em = $this->get('doctrine')->getManager(); - $em->persist($entry); - $em->flush(); + $this->entityManager->persist($entry); + $this->entityManager->flush(); - $this->get(SessionInterface::class)->getFlashBag()->add( + $this->addFlash( 'notice', 'flashes.entry.notice.entry_updated' ); @@ -281,7 +296,7 @@ class EntryController extends Controller public function showUnreadAction(Request $request, $page) { // load the quickstart if no entry in database - if (1 === (int) $page && 0 === $this->get(EntryRepository::class)->countAllEntriesByUser($this->getUser()->getId())) { + if (1 === (int) $page && 0 === $this->entryRepository->countAllEntriesByUser($this->getUser()->getId())) { return $this->redirect($this->generateUrl('quickstart')); } @@ -347,21 +362,17 @@ class EntryController extends Controller /** * Shows random entry depending on the given type. * - * @param string $type - * * @Route("/{type}/random", name="random_entry", requirements={"type": "unread|starred|archive|untagged|annotated|all"}) * * @return RedirectResponse */ - public function redirectRandomEntryAction($type = 'all') + public function redirectRandomEntryAction(string $type = 'all') { try { - $entry = $this->get(EntryRepository::class) + $entry = $this->entryRepository ->getRandomEntry($this->getUser()->getId(), $type); } catch (NoResultException $e) { - $bag = $this->get(SessionInterface::class)->getFlashBag(); - $bag->clear(); - $bag->add('notice', 'flashes.entry.notice.no_random_entry'); + $this->addFlash('notice', 'flashes.entry.notice.no_random_entry'); return $this->redirect($this->generateUrl($type)); } @@ -402,19 +413,16 @@ class EntryController extends Controller // if refreshing entry failed, don't save it if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) { - $bag = $this->get(SessionInterface::class)->getFlashBag(); - $bag->clear(); - $bag->add('notice', 'flashes.entry.notice.entry_reloaded_failed'); + $this->addFlash('notice', 'flashes.entry.notice.entry_reloaded_failed'); return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()])); } - $em = $this->get('doctrine')->getManager(); - $em->persist($entry); - $em->flush(); + $this->entityManager->persist($entry); + $this->entityManager->flush(); // entry saved, dispatch event about it! - $this->get(EventDispatcherInterface::class)->dispatch(new EntrySavedEvent($entry), EntrySavedEvent::NAME); + $this->eventDispatcher->dispatch(new EntrySavedEvent($entry), EntrySavedEvent::NAME); return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()])); } @@ -431,19 +439,19 @@ class EntryController extends Controller $this->checkUserAction($entry); $entry->toggleArchive(); - $this->get('doctrine')->getManager()->flush(); + $this->entityManager->flush(); $message = 'flashes.entry.notice.entry_unarchived'; if ($entry->isArchived()) { $message = 'flashes.entry.notice.entry_archived'; } - $this->get(SessionInterface::class)->getFlashBag()->add( + $this->addFlash( 'notice', $message ); - $redirectUrl = $this->get(Redirect::class)->to($request->headers->get('referer')); + $redirectUrl = $this->redirectHelper->to($request->headers->get('referer')); return $this->redirect($redirectUrl); } @@ -461,19 +469,19 @@ class EntryController extends Controller $entry->toggleStar(); $entry->updateStar($entry->isStarred()); - $this->get('doctrine')->getManager()->flush(); + $this->entityManager->flush(); $message = 'flashes.entry.notice.entry_unstarred'; if ($entry->isStarred()) { $message = 'flashes.entry.notice.entry_starred'; } - $this->get(SessionInterface::class)->getFlashBag()->add( + $this->addFlash( 'notice', $message ); - $redirectUrl = $this->get(Redirect::class)->to($request->headers->get('referer')); + $redirectUrl = $this->redirectHelper->to($request->headers->get('referer')); return $this->redirect($redirectUrl); } @@ -498,13 +506,12 @@ class EntryController extends Controller ); // entry deleted, dispatch event about it! - $this->get(EventDispatcherInterface::class)->dispatch(new EntryDeletedEvent($entry), EntryDeletedEvent::NAME); + $this->eventDispatcher->dispatch(new EntryDeletedEvent($entry), EntryDeletedEvent::NAME); - $em = $this->get('doctrine')->getManager(); - $em->remove($entry); - $em->flush(); + $this->entityManager->remove($entry); + $this->entityManager->flush(); - $this->get(SessionInterface::class)->getFlashBag()->add( + $this->addFlash( 'notice', 'flashes.entry.notice.entry_deleted' ); @@ -513,7 +520,7 @@ class EntryController extends Controller $referer = $request->headers->get('referer'); $to = (1 !== preg_match('#' . $url . '$#i', $referer) ? $referer : null); - $redirectUrl = $this->get(Redirect::class)->to($to); + $redirectUrl = $this->redirectHelper->to($to); return $this->redirect($redirectUrl); } @@ -532,9 +539,8 @@ class EntryController extends Controller if (null === $entry->getUid()) { $entry->generateUid(); - $em = $this->get('doctrine')->getManager(); - $em->persist($entry); - $em->flush(); + $this->entityManager->persist($entry); + $this->entityManager->flush(); } return $this->redirect($this->generateUrl('share_entry', [ @@ -555,9 +561,8 @@ class EntryController extends Controller $entry->cleanUid(); - $em = $this->get('doctrine')->getManager(); - $em->persist($entry); - $em->flush(); + $this->entityManager->persist($entry); + $this->entityManager->flush(); return $this->redirect($this->generateUrl('view', [ 'id' => $entry->getId(), @@ -572,9 +577,9 @@ class EntryController extends Controller * * @return Response */ - public function shareEntryAction(Entry $entry) + public function shareEntryAction(Entry $entry, Config $craueConfig) { - if (!$this->get(Config::class)->get('share_public')) { + if (!$craueConfig->get('share_public')) { throw $this->createAccessDeniedException('Sharing an entry is disabled for this user.'); } @@ -609,7 +614,6 @@ class EntryController extends Controller */ private function showEntries($type, Request $request, $page) { - $repository = $this->get(EntryRepository::class); $searchTerm = (isset($request->get('search_entry')['term']) ? $request->get('search_entry')['term'] : ''); $currentRoute = (null !== $request->query->get('currentRoute') ? $request->query->get('currentRoute') : ''); @@ -617,31 +621,31 @@ class EntryController extends Controller switch ($type) { case 'search': - $qb = $repository->getBuilderForSearchByUser($this->getUser()->getId(), $searchTerm, $currentRoute); + $qb = $this->entryRepository->getBuilderForSearchByUser($this->getUser()->getId(), $searchTerm, $currentRoute); break; case 'untagged': - $qb = $repository->getBuilderForUntaggedByUser($this->getUser()->getId()); + $qb = $this->entryRepository->getBuilderForUntaggedByUser($this->getUser()->getId()); break; case 'starred': - $qb = $repository->getBuilderForStarredByUser($this->getUser()->getId()); + $qb = $this->entryRepository->getBuilderForStarredByUser($this->getUser()->getId()); $formOptions['filter_starred'] = true; break; case 'archive': - $qb = $repository->getBuilderForArchiveByUser($this->getUser()->getId()); + $qb = $this->entryRepository->getBuilderForArchiveByUser($this->getUser()->getId()); $formOptions['filter_archived'] = true; break; case 'annotated': - $qb = $repository->getBuilderForAnnotationsByUser($this->getUser()->getId()); + $qb = $this->entryRepository->getBuilderForAnnotationsByUser($this->getUser()->getId()); break; case 'unread': - $qb = $repository->getBuilderForUnreadByUser($this->getUser()->getId()); + $qb = $this->entryRepository->getBuilderForUnreadByUser($this->getUser()->getId()); $formOptions['filter_unread'] = true; break; case 'same-domain': - $qb = $repository->getBuilderForSameDomainByUser($this->getUser()->getId(), $request->get('id')); + $qb = $this->entryRepository->getBuilderForSameDomainByUser($this->getUser()->getId(), $request->get('id')); break; case 'all': - $qb = $repository->getBuilderForAllByUser($this->getUser()->getId()); + $qb = $this->entryRepository->getBuilderForAllByUser($this->getUser()->getId()); break; default: throw new \InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type)); @@ -654,12 +658,12 @@ class EntryController extends Controller $form->submit($request->query->get($form->getName())); // build the query from the given form object - $this->get(FilterBuilderUpdaterInterface::class)->addFilterConditions($form, $qb); + $this->filterBuilderUpdater->addFilterConditions($form, $qb); } $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false); - $entries = $this->get(PreparePagerForEntries::class)->prepare($pagerAdapter); + $entries = $this->preparePagerForEntriesHelper->prepare($pagerAdapter); try { $entries->setCurrentPage($page); @@ -669,7 +673,7 @@ class EntryController extends Controller } } - $nbEntriesUntagged = $this->get(EntryRepository::class) + $nbEntriesUntagged = $this->entryRepository ->countUntaggedEntriesByUser($this->getUser()->getId()); return $this->render( @@ -695,7 +699,7 @@ class EntryController extends Controller $message = 'flashes.entry.notice.' . $prefixMessage; try { - $this->get(ContentProxy::class)->updateEntry($entry, $entry->getUrl()); + $this->contentProxy->updateEntry($entry, $entry->getUrl()); } catch (\Exception $e) { // $this->logger->error('Error while saving an entry', [ // 'exception' => $e, @@ -706,14 +710,14 @@ class EntryController extends Controller } if (empty($entry->getDomainName())) { - $this->get(ContentProxy::class)->setEntryDomainName($entry); + $this->contentProxy->setEntryDomainName($entry); } if (empty($entry->getTitle())) { - $this->get(ContentProxy::class)->setDefaultEntryTitle($entry); + $this->contentProxy->setDefaultEntryTitle($entry); } - $this->get(SessionInterface::class)->getFlashBag()->add('notice', $message); + $this->addFlash('notice', $message); } /** @@ -733,6 +737,6 @@ class EntryController extends Controller */ private function checkIfEntryAlreadyExists(Entry $entry) { - return $this->get(EntryRepository::class)->findByUrlAndUserId($entry->getUrl(), $this->getUser()->getId()); + return $this->entryRepository->findByUrlAndUserId($entry->getUrl(), $this->getUser()->getId()); } } diff --git a/src/Wallabag/CoreBundle/Controller/ExportController.php b/src/Wallabag/CoreBundle/Controller/ExportController.php index 5b2325507..832ca070f 100644 --- a/src/Wallabag/CoreBundle/Controller/ExportController.php +++ b/src/Wallabag/CoreBundle/Controller/ExportController.php @@ -21,8 +21,6 @@ class ExportController extends Controller /** * Gets one entry content. * - * @param string $format - * * @Route("/export/{id}.{format}", name="export_entry", requirements={ * "format": "epub|mobi|pdf|json|xml|txt|csv", * "id": "\d+" @@ -30,10 +28,10 @@ class ExportController extends Controller * * @return Response */ - public function downloadEntryAction(Entry $entry, $format) + public function downloadEntryAction(Entry $entry, EntriesExport $entriesExport, string $format) { try { - return $this->get(EntriesExport::class) + return $entriesExport ->setEntries($entry) ->updateTitle('entry') ->updateAuthor('entry') @@ -46,9 +44,6 @@ class ExportController extends Controller /** * Export all entries for current user. * - * @param string $format - * @param string $category - * * @Route("/export/{category}.{format}", name="export_entries", requirements={ * "format": "epub|mobi|pdf|json|xml|txt|csv", * "category": "all|unread|starred|archive|tag_entries|untagged|search|annotated|same_domain" @@ -56,17 +51,16 @@ class ExportController extends Controller * * @return Response */ - public function downloadEntriesAction(Request $request, $format, $category) + public function downloadEntriesAction(Request $request, EntryRepository $entryRepository, TagRepository $tagRepository, EntriesExport $entriesExport, string $format, string $category) { $method = ucfirst($category); $methodBuilder = 'getBuilderFor' . $method . 'ByUser'; - $repository = $this->get(EntryRepository::class); $title = $method; if ('tag_entries' === $category) { - $tag = $this->get(TagRepository::class)->findOneBySlug($request->query->get('tag')); + $tag = $tagRepository->findOneBySlug($request->query->get('tag')); - $entries = $repository->findAllByTagId( + $entries = $entryRepository->findAllByTagId( $this->getUser()->getId(), $tag->getId() ); @@ -76,7 +70,7 @@ class ExportController extends Controller $searchTerm = (isset($request->get('search_entry')['term']) ? $request->get('search_entry')['term'] : ''); $currentRoute = (null !== $request->query->get('currentRoute') ? $request->query->get('currentRoute') : ''); - $entries = $repository->getBuilderForSearchByUser( + $entries = $entryRepository->getBuilderForSearchByUser( $this->getUser()->getId(), $searchTerm, $currentRoute @@ -85,21 +79,21 @@ class ExportController extends Controller $title = 'Search ' . $searchTerm; } elseif ('annotated' === $category) { - $entries = $repository->getBuilderForAnnotationsByUser( + $entries = $entryRepository->getBuilderForAnnotationsByUser( $this->getUser()->getId() )->getQuery() ->getResult(); $title = 'With annotations'; } else { - $entries = $repository + $entries = $entryRepository ->$methodBuilder($this->getUser()->getId()) ->getQuery() ->getResult(); } try { - return $this->get(EntriesExport::class) + return $entriesExport ->setEntries($entries) ->updateTitle($title) ->updateAuthor($method) diff --git a/src/Wallabag/CoreBundle/Controller/FeedController.php b/src/Wallabag/CoreBundle/Controller/FeedController.php index ee0490623..7a1527650 100644 --- a/src/Wallabag/CoreBundle/Controller/FeedController.php +++ b/src/Wallabag/CoreBundle/Controller/FeedController.php @@ -20,6 +20,13 @@ use Wallabag\UserBundle\Entity\User; class FeedController extends Controller { + private EntryRepository $entryRepository; + + public function __construct(EntryRepository $entryRepository) + { + $this->entryRepository = $entryRepository; + } + /** * Shows unread entries for current user. * @@ -92,7 +99,7 @@ class FeedController extends Controller * * @return Response */ - public function showTagsFeedAction(Request $request, User $user, Tag $tag, $page) + public function showTagsFeedAction(Request $request, User $user, Tag $tag, PreparePagerForEntries $preparePagerForEntries, $page) { $sort = $request->query->get('sort', 'created'); @@ -115,7 +122,7 @@ class FeedController extends Controller UrlGeneratorInterface::ABSOLUTE_URL ); - $entriesByTag = $this->get(EntryRepository::class)->findAllByTagId( + $entriesByTag = $this->entryRepository->findAllByTagId( $user->getId(), $tag->getId(), $sorts[$sort] @@ -123,7 +130,7 @@ class FeedController extends Controller $pagerAdapter = new ArrayAdapter($entriesByTag); - $entries = $this->get(PreparePagerForEntries::class)->prepare( + $entries = $preparePagerForEntries->prepare( $pagerAdapter, $user ); @@ -184,22 +191,20 @@ class FeedController extends Controller * * @return Response */ - private function showEntries($type, User $user, $page = 1) + private function showEntries(string $type, User $user, $page = 1) { - $repository = $this->get(EntryRepository::class); - switch ($type) { case 'starred': - $qb = $repository->getBuilderForStarredByUser($user->getId()); + $qb = $this->entryRepository->getBuilderForStarredByUser($user->getId()); break; case 'archive': - $qb = $repository->getBuilderForArchiveByUser($user->getId()); + $qb = $this->entryRepository->getBuilderForArchiveByUser($user->getId()); break; case 'unread': - $qb = $repository->getBuilderForUnreadByUser($user->getId()); + $qb = $this->entryRepository->getBuilderForUnreadByUser($user->getId()); break; case 'all': - $qb = $repository->getBuilderForAllByUser($user->getId()); + $qb = $this->entryRepository->getBuilderForAllByUser($user->getId()); break; default: throw new \InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type)); diff --git a/src/Wallabag/CoreBundle/Controller/IgnoreOriginInstanceRuleController.php b/src/Wallabag/CoreBundle/Controller/IgnoreOriginInstanceRuleController.php index 1414de8c1..cd1e11da2 100644 --- a/src/Wallabag/CoreBundle/Controller/IgnoreOriginInstanceRuleController.php +++ b/src/Wallabag/CoreBundle/Controller/IgnoreOriginInstanceRuleController.php @@ -2,14 +2,14 @@ namespace Wallabag\CoreBundle\Controller; +use Doctrine\ORM\EntityManagerInterface; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\Form\Form; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; -use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\Routing\Annotation\Route; -use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorInterface; use Wallabag\CoreBundle\Entity\IgnoreOriginInstanceRule; use Wallabag\CoreBundle\Form\Type\IgnoreOriginInstanceRuleType; use Wallabag\CoreBundle\Repository\IgnoreOriginInstanceRuleRepository; @@ -21,14 +21,23 @@ use Wallabag\CoreBundle\Repository\IgnoreOriginInstanceRuleRepository; */ class IgnoreOriginInstanceRuleController extends Controller { + private EntityManagerInterface $entityManager; + private TranslatorInterface $translator; + + public function __construct(EntityManagerInterface $entityManager, TranslatorInterface $translator) + { + $this->entityManager = $entityManager; + $this->translator = $translator; + } + /** * Lists all IgnoreOriginInstanceRule entities. * * @Route("/", name="ignore_origin_instance_rules_index", methods={"GET"}) */ - public function indexAction() + public function indexAction(IgnoreOriginInstanceRuleRepository $repository) { - $rules = $this->get(IgnoreOriginInstanceRuleRepository::class)->findAll(); + $rules = $repository->findAll(); return $this->render('@WallabagCore/IgnoreOriginInstanceRule/index.html.twig', [ 'rules' => $rules, @@ -50,13 +59,12 @@ class IgnoreOriginInstanceRuleController extends Controller $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { - $em = $this->get('doctrine')->getManager(); - $em->persist($ignoreOriginInstanceRule); - $em->flush(); + $this->entityManager->persist($ignoreOriginInstanceRule); + $this->entityManager->flush(); - $this->get(SessionInterface::class)->getFlashBag()->add( + $this->addFlash( 'notice', - $this->get(TranslatorInterface::class)->trans('flashes.ignore_origin_instance_rule.notice.added') + $this->translator->trans('flashes.ignore_origin_instance_rule.notice.added') ); return $this->redirectToRoute('ignore_origin_instance_rules_index'); @@ -82,13 +90,12 @@ class IgnoreOriginInstanceRuleController extends Controller $editForm->handleRequest($request); if ($editForm->isSubmitted() && $editForm->isValid()) { - $em = $this->get('doctrine')->getManager(); - $em->persist($ignoreOriginInstanceRule); - $em->flush(); + $this->entityManager->persist($ignoreOriginInstanceRule); + $this->entityManager->flush(); - $this->get(SessionInterface::class)->getFlashBag()->add( + $this->addFlash( 'notice', - $this->get(TranslatorInterface::class)->trans('flashes.ignore_origin_instance_rule.notice.updated') + $this->translator->trans('flashes.ignore_origin_instance_rule.notice.updated') ); return $this->redirectToRoute('ignore_origin_instance_rules_index'); @@ -114,14 +121,13 @@ class IgnoreOriginInstanceRuleController extends Controller $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { - $this->get(SessionInterface::class)->getFlashBag()->add( + $this->addFlash( 'notice', - $this->get(TranslatorInterface::class)->trans('flashes.ignore_origin_instance_rule.notice.deleted') + $this->translator->trans('flashes.ignore_origin_instance_rule.notice.deleted') ); - $em = $this->get('doctrine')->getManager(); - $em->remove($ignoreOriginInstanceRule); - $em->flush(); + $this->entityManager->remove($ignoreOriginInstanceRule); + $this->entityManager->flush(); } return $this->redirectToRoute('ignore_origin_instance_rules_index'); diff --git a/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php b/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php index e2b44e3eb..4c3db4e0e 100644 --- a/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php +++ b/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php @@ -3,14 +3,14 @@ namespace Wallabag\CoreBundle\Controller; use Craue\ConfigBundle\Util\Config; +use Doctrine\ORM\EntityManagerInterface; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\Form\Form; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; -use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\Routing\Annotation\Route; -use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorInterface; use Wallabag\CoreBundle\Entity\SiteCredential; use Wallabag\CoreBundle\Form\Type\SiteCredentialType; use Wallabag\CoreBundle\Helper\CryptoProxy; @@ -24,16 +24,29 @@ use Wallabag\UserBundle\Entity\User; */ class SiteCredentialController extends Controller { + private EntityManagerInterface $entityManager; + private TranslatorInterface $translator; + private CryptoProxy $cryptoProxy; + private Config $craueConfig; + + public function __construct(EntityManagerInterface $entityManager, TranslatorInterface $translator, CryptoProxy $cryptoProxy, Config $craueConfig) + { + $this->entityManager = $entityManager; + $this->translator = $translator; + $this->cryptoProxy = $cryptoProxy; + $this->craueConfig = $craueConfig; + } + /** * Lists all User entities. * * @Route("/", name="site_credentials_index", methods={"GET"}) */ - public function indexAction() + public function indexAction(SiteCredentialRepository $repository) { $this->isSiteCredentialsEnabled(); - $credentials = $this->get(SiteCredentialRepository::class)->findByUser($this->getUser()); + $credentials = $repository->findByUser($this->getUser()); return $this->render('@WallabagCore/SiteCredential/index.html.twig', [ 'credentials' => $credentials, @@ -57,16 +70,15 @@ class SiteCredentialController extends Controller $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { - $credential->setUsername($this->get(CryptoProxy::class)->crypt($credential->getUsername())); - $credential->setPassword($this->get(CryptoProxy::class)->crypt($credential->getPassword())); + $credential->setUsername($this->cryptoProxy->crypt($credential->getUsername())); + $credential->setPassword($this->cryptoProxy->crypt($credential->getPassword())); - $em = $this->get('doctrine')->getManager(); - $em->persist($credential); - $em->flush(); + $this->entityManager->persist($credential); + $this->entityManager->flush(); - $this->get(SessionInterface::class)->getFlashBag()->add( + $this->addFlash( 'notice', - $this->get(TranslatorInterface::class)->trans('flashes.site_credential.notice.added', ['%host%' => $credential->getHost()]) + $this->translator->trans('flashes.site_credential.notice.added', ['%host%' => $credential->getHost()]) ); return $this->redirectToRoute('site_credentials_index'); @@ -96,16 +108,15 @@ class SiteCredentialController extends Controller $editForm->handleRequest($request); if ($editForm->isSubmitted() && $editForm->isValid()) { - $siteCredential->setUsername($this->get(CryptoProxy::class)->crypt($siteCredential->getUsername())); - $siteCredential->setPassword($this->get(CryptoProxy::class)->crypt($siteCredential->getPassword())); + $siteCredential->setUsername($this->cryptoProxy->crypt($siteCredential->getUsername())); + $siteCredential->setPassword($this->cryptoProxy->crypt($siteCredential->getPassword())); - $em = $this->get('doctrine')->getManager(); - $em->persist($siteCredential); - $em->flush(); + $this->entityManager->persist($siteCredential); + $this->entityManager->flush(); - $this->get(SessionInterface::class)->getFlashBag()->add( + $this->addFlash( 'notice', - $this->get(TranslatorInterface::class)->trans('flashes.site_credential.notice.updated', ['%host%' => $siteCredential->getHost()]) + $this->translator->trans('flashes.site_credential.notice.updated', ['%host%' => $siteCredential->getHost()]) ); return $this->redirectToRoute('site_credentials_index'); @@ -135,14 +146,13 @@ class SiteCredentialController extends Controller $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { - $this->get(SessionInterface::class)->getFlashBag()->add( + $this->addFlash( 'notice', - $this->get(TranslatorInterface::class)->trans('flashes.site_credential.notice.deleted', ['%host%' => $siteCredential->getHost()]) + $this->translator->trans('flashes.site_credential.notice.deleted', ['%host%' => $siteCredential->getHost()]) ); - $em = $this->get('doctrine')->getManager(); - $em->remove($siteCredential); - $em->flush(); + $this->entityManager->remove($siteCredential); + $this->entityManager->flush(); } return $this->redirectToRoute('site_credentials_index'); @@ -153,7 +163,7 @@ class SiteCredentialController extends Controller */ private function isSiteCredentialsEnabled() { - if (!$this->get(Config::class)->get('restricted_access')) { + if (!$this->craueConfig->get('restricted_access')) { throw $this->createNotFoundException('Feature "restricted_access" is disabled, controllers too.'); } } diff --git a/src/Wallabag/CoreBundle/Controller/StaticController.php b/src/Wallabag/CoreBundle/Controller/StaticController.php index 0284f4794..6aa566a3c 100644 --- a/src/Wallabag/CoreBundle/Controller/StaticController.php +++ b/src/Wallabag/CoreBundle/Controller/StaticController.php @@ -12,7 +12,7 @@ class StaticController extends Controller */ public function howtoAction() { - $addonsUrl = $this->container->getParameter('addons_url'); + $addonsUrl = $this->getParameter('addons_url'); return $this->render( '@WallabagCore/Static/howto.html.twig', diff --git a/src/Wallabag/CoreBundle/Controller/TagController.php b/src/Wallabag/CoreBundle/Controller/TagController.php index 53ce07c98..c868066ce 100644 --- a/src/Wallabag/CoreBundle/Controller/TagController.php +++ b/src/Wallabag/CoreBundle/Controller/TagController.php @@ -2,6 +2,7 @@ namespace Wallabag\CoreBundle\Controller; +use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\QueryBuilder; use Pagerfanta\Adapter\ArrayAdapter; use Pagerfanta\Exception\OutOfRangeCurrentPageException; @@ -9,7 +10,6 @@ use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; -use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\Routing\Annotation\Route; use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Tag; @@ -23,6 +23,17 @@ use Wallabag\CoreBundle\Repository\TagRepository; class TagController extends Controller { + private EntityManagerInterface $entityManager; + private TagsAssigner $tagsAssigner; + private Redirect $redirectHelper; + + public function __construct(EntityManagerInterface $entityManager, TagsAssigner $tagsAssigner, Redirect $redirectHelper) + { + $this->entityManager = $entityManager; + $this->tagsAssigner = $tagsAssigner; + $this->redirectHelper = $redirectHelper; + } + /** * @Route("/new-tag/{entry}", requirements={"entry" = "\d+"}, name="new_tag") * @@ -34,16 +45,15 @@ class TagController extends Controller $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { - $this->get(TagsAssigner::class)->assignTagsToEntry( + $this->tagsAssigner->assignTagsToEntry( $entry, $form->get('label')->getData() ); - $em = $this->get('doctrine')->getManager(); - $em->persist($entry); - $em->flush(); + $this->entityManager->persist($entry); + $this->entityManager->flush(); - $this->get(SessionInterface::class)->getFlashBag()->add( + $this->addFlash( 'notice', 'flashes.tag.notice.tag_added' ); @@ -67,16 +77,15 @@ class TagController extends Controller public function removeTagFromEntry(Request $request, Entry $entry, Tag $tag) { $entry->removeTag($tag); - $em = $this->get('doctrine')->getManager(); - $em->flush(); + $this->entityManager->flush(); // remove orphan tag in case no entries are associated to it if (0 === \count($tag->getEntries())) { - $em->remove($tag); - $em->flush(); + $this->entityManager->remove($tag); + $this->entityManager->flush(); } - $redirectUrl = $this->get(Redirect::class)->to($request->headers->get('referer'), '', true); + $redirectUrl = $this->redirectHelper->to($request->headers->get('referer'), '', true); return $this->redirect($redirectUrl); } @@ -88,12 +97,10 @@ class TagController extends Controller * * @return Response */ - public function showTagAction() + public function showTagAction(TagRepository $tagRepository, EntryRepository $entryRepository) { - $tags = $this->get(TagRepository::class) - ->findAllFlatTagsWithNbEntries($this->getUser()->getId()); - $nbEntriesUntagged = $this->get(EntryRepository::class) - ->countUntaggedEntriesByUser($this->getUser()->getId()); + $tags = $tagRepository->findAllFlatTagsWithNbEntries($this->getUser()->getId()); + $nbEntriesUntagged = $entryRepository->countUntaggedEntriesByUser($this->getUser()->getId()); $renameForms = []; foreach ($tags as $tag) { @@ -115,16 +122,16 @@ class TagController extends Controller * * @return Response */ - public function showEntriesForTagAction(Tag $tag, $page, Request $request) + public function showEntriesForTagAction(Tag $tag, EntryRepository $entryRepository, PreparePagerForEntries $preparePagerForEntries, $page, Request $request) { - $entriesByTag = $this->get(EntryRepository::class)->findAllByTagId( + $entriesByTag = $entryRepository->findAllByTagId( $this->getUser()->getId(), $tag->getId() ); $pagerAdapter = new ArrayAdapter($entriesByTag); - $entries = $this->get(PreparePagerForEntries::class)->prepare($pagerAdapter); + $entries = $preparePagerForEntries->prepare($pagerAdapter); try { $entries->setCurrentPage($page); @@ -154,12 +161,12 @@ class TagController extends Controller * * @return Response */ - public function renameTagAction(Tag $tag, Request $request) + public function renameTagAction(Tag $tag, Request $request, TagRepository $tagRepository, EntryRepository $entryRepository) { $form = $this->createForm(RenameTagType::class, new Tag()); $form->handleRequest($request); - $redirectUrl = $this->get(Redirect::class)->to($request->headers->get('referer'), '', true); + $redirectUrl = $this->redirectHelper->to($request->headers->get('referer'), '', true); if ($form->isSubmitted() && $form->isValid()) { $newTag = new Tag(); @@ -169,18 +176,18 @@ class TagController extends Controller return $this->redirect($redirectUrl); } - $tagFromRepo = $this->get(TagRepository::class)->findOneByLabel($newTag->getLabel()); + $tagFromRepo = $tagRepository->findOneByLabel($newTag->getLabel()); if (null !== $tagFromRepo) { $newTag = $tagFromRepo; } - $entries = $this->get(EntryRepository::class)->findAllByTagId( + $entries = $entryRepository->findAllByTagId( $this->getUser()->getId(), $tag->getId() ); foreach ($entries as $entry) { - $this->get(TagsAssigner::class)->assignTagsToEntry( + $this->tagsAssigner->assignTagsToEntry( $entry, $newTag->getLabel(), [$newTag] @@ -188,9 +195,9 @@ class TagController extends Controller $entry->removeTag($tag); } - $this->get('doctrine')->getManager()->flush(); + $this->entityManager->flush(); - $this->get(SessionInterface::class)->getFlashBag()->add( + $this->addFlash( 'notice', 'flashes.tag.notice.tag_renamed' ); @@ -206,28 +213,27 @@ class TagController extends Controller * * @return Response */ - public function tagThisSearchAction($filter, Request $request) + public function tagThisSearchAction($filter, Request $request, EntryRepository $entryRepository) { $currentRoute = $request->query->has('currentRoute') ? $request->query->get('currentRoute') : ''; /** @var QueryBuilder $qb */ - $qb = $this->get(EntryRepository::class)->getBuilderForSearchByUser($this->getUser()->getId(), $filter, $currentRoute); - $em = $this->get('doctrine')->getManager(); + $qb = $entryRepository->getBuilderForSearchByUser($this->getUser()->getId(), $filter, $currentRoute); $entries = $qb->getQuery()->getResult(); foreach ($entries as $entry) { - $this->get(TagsAssigner::class)->assignTagsToEntry( + $this->tagsAssigner->assignTagsToEntry( $entry, $filter ); - $em->persist($entry); + $this->entityManager->persist($entry); } - $em->flush(); + $this->entityManager->flush(); - return $this->redirect($this->get(Redirect::class)->to($request->headers->get('referer'), '', true)); + return $this->redirect($this->redirectHelper->to($request->headers->get('referer'), '', true)); } /** @@ -238,20 +244,19 @@ class TagController extends Controller * * @return Response */ - public function removeTagAction(Tag $tag, Request $request) + public function removeTagAction(Tag $tag, Request $request, EntryRepository $entryRepository) { foreach ($tag->getEntriesByUserId($this->getUser()->getId()) as $entry) { - $this->get(EntryRepository::class)->removeTag($this->getUser()->getId(), $tag); + $entryRepository->removeTag($this->getUser()->getId(), $tag); } // remove orphan tag in case no entries are associated to it if (0 === \count($tag->getEntries())) { - $em = $this->get('doctrine')->getManager(); - $em->remove($tag); - $em->flush(); + $this->entityManager->remove($tag); + $this->entityManager->flush(); } - $redirectUrl = $this->get(Redirect::class)->to($request->headers->get('referer'), '', true); + $redirectUrl = $this->redirectHelper->to($request->headers->get('referer'), '', true); return $this->redirect($redirectUrl); } diff --git a/src/Wallabag/CoreBundle/Helper/EntriesExport.php b/src/Wallabag/CoreBundle/Helper/EntriesExport.php index b39fcf257..7fec209da 100644 --- a/src/Wallabag/CoreBundle/Helper/EntriesExport.php +++ b/src/Wallabag/CoreBundle/Helper/EntriesExport.php @@ -9,7 +9,7 @@ use PHPePub\Core\EPub; use PHPePub\Core\Structure\OPF\DublinCore; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; -use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorInterface; use Wallabag\CoreBundle\Entity\Entry; use Wallabag\UserBundle\Entity\User; diff --git a/src/Wallabag/CoreBundle/ParamConverter/UsernameFeedTokenConverter.php b/src/Wallabag/CoreBundle/ParamConverter/UsernameFeedTokenConverter.php index 754d24680..e61b2eca9 100644 --- a/src/Wallabag/CoreBundle/ParamConverter/UsernameFeedTokenConverter.php +++ b/src/Wallabag/CoreBundle/ParamConverter/UsernameFeedTokenConverter.php @@ -77,6 +77,10 @@ class UsernameFeedTokenConverter implements ParamConverterInterface // Get actual entity manager for class $em = $this->registry->getManagerForClass($configuration->getClass()); + if (null === $em) { + return false; + } + /** @var UserRepository $userRepository */ $userRepository = $em->getRepository($configuration->getClass()); diff --git a/src/Wallabag/CoreBundle/Twig/WallabagExtension.php b/src/Wallabag/CoreBundle/Twig/WallabagExtension.php index 69011ffa0..3fad85d61 100644 --- a/src/Wallabag/CoreBundle/Twig/WallabagExtension.php +++ b/src/Wallabag/CoreBundle/Twig/WallabagExtension.php @@ -3,7 +3,7 @@ namespace Wallabag\CoreBundle\Twig; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; -use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorInterface; use Twig\Extension\AbstractExtension; use Twig\Extension\GlobalsInterface; use Twig\TwigFilter; diff --git a/src/Wallabag/ImportBundle/Controller/BrowserController.php b/src/Wallabag/ImportBundle/Controller/BrowserController.php index 52b4cd392..326ae7279 100644 --- a/src/Wallabag/ImportBundle/Controller/BrowserController.php +++ b/src/Wallabag/ImportBundle/Controller/BrowserController.php @@ -2,23 +2,22 @@ namespace Wallabag\ImportBundle\Controller; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; +use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; -use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\Routing\Annotation\Route; -use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorInterface; use Wallabag\ImportBundle\Form\Type\UploadImportType; use Wallabag\ImportBundle\Import\ImportInterface; -abstract class BrowserController extends Controller +abstract class BrowserController extends AbstractController { /** * @Route("/browser", name="import_browser") * * @return Response */ - public function indexAction(Request $request) + public function indexAction(Request $request, TranslatorInterface $translator) { $form = $this->createForm(UploadImportType::class); $form->handleRequest($request); @@ -41,13 +40,13 @@ abstract class BrowserController extends Controller if (true === $res) { $summary = $wallabag->getSummary(); - $message = $this->get(TranslatorInterface::class)->trans('flashes.import.notice.summary', [ + $message = $translator->trans('flashes.import.notice.summary', [ '%imported%' => $summary['imported'], '%skipped%' => $summary['skipped'], ]); if (0 < $summary['queued']) { - $message = $this->get(TranslatorInterface::class)->trans('flashes.import.notice.summary_with_queue', [ + $message = $translator->trans('flashes.import.notice.summary_with_queue', [ '%queued%' => $summary['queued'], ]); } @@ -55,17 +54,11 @@ abstract class BrowserController extends Controller unlink($this->getParameter('wallabag_import.resource_dir') . '/' . $name); } - $this->get(SessionInterface::class)->getFlashBag()->add( - 'notice', - $message - ); + $this->addFlash('notice', $message); return $this->redirect($this->generateUrl('homepage')); } - $this->get(SessionInterface::class)->getFlashBag()->add( - 'notice', - 'flashes.import.notice.failed_on_file' - ); + $this->addFlash('notice', 'flashes.import.notice.failed_on_file'); } return $this->render($this->getImportTemplate(), [ diff --git a/src/Wallabag/ImportBundle/Controller/ChromeController.php b/src/Wallabag/ImportBundle/Controller/ChromeController.php index 4d7cbaf00..c4c3f3a5c 100644 --- a/src/Wallabag/ImportBundle/Controller/ChromeController.php +++ b/src/Wallabag/ImportBundle/Controller/ChromeController.php @@ -3,18 +3,34 @@ namespace Wallabag\ImportBundle\Controller; use Craue\ConfigBundle\Util\Config; +use OldSound\RabbitMqBundle\RabbitMq\Producer as RabbitMqProducer; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; +use Symfony\Contracts\Translation\TranslatorInterface; use Wallabag\ImportBundle\Import\ChromeImport; +use Wallabag\ImportBundle\Redis\Producer as RedisProducer; class ChromeController extends BrowserController { + private ChromeImport $chromeImport; + private Config $craueConfig; + private RabbitMqProducer $rabbitMqProducer; + private RedisProducer $redisProducer; + + public function __construct(ChromeImport $chromeImport, Config $craueConfig, RabbitMqProducer $rabbitMqProducer, RedisProducer $redisProducer) + { + $this->chromeImport = $chromeImport; + $this->craueConfig = $craueConfig; + $this->rabbitMqProducer = $rabbitMqProducer; + $this->redisProducer = $redisProducer; + } + /** * @Route("/chrome", name="import_chrome") */ - public function indexAction(Request $request) + public function indexAction(Request $request, TranslatorInterface $translator) { - return parent::indexAction($request); + return parent::indexAction($request, $translator); } /** @@ -22,15 +38,13 @@ class ChromeController extends BrowserController */ protected function getImportService() { - $service = $this->get(ChromeImport::class); - - if ($this->get(Config::class)->get('import_with_rabbitmq')) { - $service->setProducer($this->get('old_sound_rabbit_mq.import_chrome_producer')); - } elseif ($this->get(Config::class)->get('import_with_redis')) { - $service->setProducer($this->get('wallabag_import.producer.redis.chrome')); + if ($this->craueConfig->get('import_with_rabbitmq')) { + $this->chromeImport->setProducer($this->rabbitMqProducer); + } elseif ($this->craueConfig->get('import_with_redis')) { + $this->chromeImport->setProducer($this->redisProducer); } - return $service; + return $this->chromeImport; } /** diff --git a/src/Wallabag/ImportBundle/Controller/DeliciousController.php b/src/Wallabag/ImportBundle/Controller/DeliciousController.php index 6891e59ba..bed54498b 100644 --- a/src/Wallabag/ImportBundle/Controller/DeliciousController.php +++ b/src/Wallabag/ImportBundle/Controller/DeliciousController.php @@ -3,31 +3,40 @@ namespace Wallabag\ImportBundle\Controller; use Craue\ConfigBundle\Util\Config; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; +use OldSound\RabbitMqBundle\RabbitMq\Producer as RabbitMqProducer; +use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\Routing\Annotation\Route; -use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorInterface; use Wallabag\ImportBundle\Form\Type\UploadImportType; use Wallabag\ImportBundle\Import\DeliciousImport; +use Wallabag\ImportBundle\Redis\Producer as RedisProducer; -class DeliciousController extends Controller +class DeliciousController extends AbstractController { + private RabbitMqProducer $rabbitMqProducer; + private RedisProducer $redisProducer; + + public function __construct(RabbitMqProducer $rabbitMqProducer, RedisProducer $redisProducer) + { + $this->rabbitMqProducer = $rabbitMqProducer; + $this->redisProducer = $redisProducer; + } + /** * @Route("/delicious", name="import_delicious") */ - public function indexAction(Request $request) + public function indexAction(Request $request, DeliciousImport $delicious, Config $craueConfig, TranslatorInterface $translator) { $form = $this->createForm(UploadImportType::class); $form->handleRequest($request); - $delicious = $this->get(DeliciousImport::class); $delicious->setUser($this->getUser()); - if ($this->get(Config::class)->get('import_with_rabbitmq')) { - $delicious->setProducer($this->get('old_sound_rabbit_mq.import_delicious_producer')); - } elseif ($this->get(Config::class)->get('import_with_redis')) { - $delicious->setProducer($this->get('wallabag_import.producer.redis.delicious')); + if ($craueConfig->get('import_with_rabbitmq')) { + $delicious->setProducer($this->rabbitMqProducer); + } elseif ($craueConfig->get('import_with_redis')) { + $delicious->setProducer($this->redisProducer); } if ($form->isSubmitted() && $form->isValid()) { @@ -45,13 +54,13 @@ class DeliciousController extends Controller if (true === $res) { $summary = $delicious->getSummary(); - $message = $this->get(TranslatorInterface::class)->trans('flashes.import.notice.summary', [ + $message = $translator->trans('flashes.import.notice.summary', [ '%imported%' => $summary['imported'], '%skipped%' => $summary['skipped'], ]); if (0 < $summary['queued']) { - $message = $this->get(TranslatorInterface::class)->trans('flashes.import.notice.summary_with_queue', [ + $message = $translator->trans('flashes.import.notice.summary_with_queue', [ '%queued%' => $summary['queued'], ]); } @@ -59,18 +68,12 @@ class DeliciousController extends Controller unlink($this->getParameter('wallabag_import.resource_dir') . '/' . $name); } - $this->get(SessionInterface::class)->getFlashBag()->add( - 'notice', - $message - ); + $this->addFlash('notice', $message); return $this->redirect($this->generateUrl('homepage')); } - $this->get(SessionInterface::class)->getFlashBag()->add( - 'notice', - 'flashes.import.notice.failed_on_file' - ); + $this->addFlash('notice', 'flashes.import.notice.failed_on_file'); } return $this->render('@WallabagImport/Delicious/index.html.twig', [ diff --git a/src/Wallabag/ImportBundle/Controller/ElcuratorController.php b/src/Wallabag/ImportBundle/Controller/ElcuratorController.php index 7806caecb..990334cc2 100644 --- a/src/Wallabag/ImportBundle/Controller/ElcuratorController.php +++ b/src/Wallabag/ImportBundle/Controller/ElcuratorController.php @@ -3,18 +3,34 @@ namespace Wallabag\ImportBundle\Controller; use Craue\ConfigBundle\Util\Config; +use OldSound\RabbitMqBundle\RabbitMq\Producer as RabbitMqProducer; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; +use Symfony\Contracts\Translation\TranslatorInterface; use Wallabag\ImportBundle\Import\ElcuratorImport; +use Wallabag\ImportBundle\Redis\Producer as RedisProducer; class ElcuratorController extends WallabagController { + private ElcuratorImport $elcuratorImport; + private Config $craueConfig; + private RabbitMqProducer $rabbitMqProducer; + private RedisProducer $redisProducer; + + public function __construct(ElcuratorImport $elcuratorImport, Config $craueConfig, RabbitMqProducer $rabbitMqProducer, RedisProducer $redisProducer) + { + $this->elcuratorImport = $elcuratorImport; + $this->craueConfig = $craueConfig; + $this->rabbitMqProducer = $rabbitMqProducer; + $this->redisProducer = $redisProducer; + } + /** * @Route("/elcurator", name="import_elcurator") */ - public function indexAction(Request $request) + public function indexAction(Request $request, TranslatorInterface $translator) { - return parent::indexAction($request); + return parent::indexAction($request, $translator); } /** @@ -22,15 +38,13 @@ class ElcuratorController extends WallabagController */ protected function getImportService() { - $service = $this->get(ElcuratorImport::class); - - if ($this->get(Config::class)->get('import_with_rabbitmq')) { - $service->setProducer($this->get('old_sound_rabbit_mq.import_elcurator_producer')); - } elseif ($this->get(Config::class)->get('import_with_redis')) { - $service->setProducer($this->get('wallabag_import.producer.redis.elcurator')); + if ($this->craueConfig->get('import_with_rabbitmq')) { + $this->elcuratorImport->setProducer($this->rabbitMqProducer); + } elseif ($this->craueConfig->get('import_with_redis')) { + $this->elcuratorImport->setProducer($this->redisProducer); } - return $service; + return $this->elcuratorImport; } /** diff --git a/src/Wallabag/ImportBundle/Controller/FirefoxController.php b/src/Wallabag/ImportBundle/Controller/FirefoxController.php index cbe5c8380..4fbc84b78 100644 --- a/src/Wallabag/ImportBundle/Controller/FirefoxController.php +++ b/src/Wallabag/ImportBundle/Controller/FirefoxController.php @@ -3,18 +3,34 @@ namespace Wallabag\ImportBundle\Controller; use Craue\ConfigBundle\Util\Config; +use OldSound\RabbitMqBundle\RabbitMq\Producer as RabbitMqProducer; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; +use Symfony\Contracts\Translation\TranslatorInterface; use Wallabag\ImportBundle\Import\FirefoxImport; +use Wallabag\ImportBundle\Redis\Producer as RedisProducer; class FirefoxController extends BrowserController { + private FirefoxImport $firefoxImport; + private Config $craueConfig; + private RabbitMqProducer $rabbitMqProducer; + private RedisProducer $redisProducer; + + public function __construct(FirefoxImport $firefoxImport, Config $craueConfig, RabbitMqProducer $rabbitMqProducer, RedisProducer $redisProducer) + { + $this->firefoxImport = $firefoxImport; + $this->craueConfig = $craueConfig; + $this->rabbitMqProducer = $rabbitMqProducer; + $this->redisProducer = $redisProducer; + } + /** * @Route("/firefox", name="import_firefox") */ - public function indexAction(Request $request) + public function indexAction(Request $request, TranslatorInterface $translator) { - return parent::indexAction($request); + return parent::indexAction($request, $translator); } /** @@ -22,15 +38,13 @@ class FirefoxController extends BrowserController */ protected function getImportService() { - $service = $this->get(FirefoxImport::class); - - if ($this->get(Config::class)->get('import_with_rabbitmq')) { - $service->setProducer($this->get('old_sound_rabbit_mq.import_firefox_producer')); - } elseif ($this->get(Config::class)->get('import_with_redis')) { - $service->setProducer($this->get('wallabag_import.producer.redis.firefox')); + if ($this->craueConfig->get('import_with_rabbitmq')) { + $this->firefoxImport->setProducer($this->rabbitMqProducer); + } elseif ($this->craueConfig->get('import_with_redis')) { + $this->firefoxImport->setProducer($this->redisProducer); } - return $service; + return $this->firefoxImport; } /** diff --git a/src/Wallabag/ImportBundle/Controller/InstapaperController.php b/src/Wallabag/ImportBundle/Controller/InstapaperController.php index 25f6d07da..03d562916 100644 --- a/src/Wallabag/ImportBundle/Controller/InstapaperController.php +++ b/src/Wallabag/ImportBundle/Controller/InstapaperController.php @@ -3,31 +3,40 @@ namespace Wallabag\ImportBundle\Controller; use Craue\ConfigBundle\Util\Config; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; +use OldSound\RabbitMqBundle\RabbitMq\Producer as RabbitMqProducer; +use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\Routing\Annotation\Route; -use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorInterface; use Wallabag\ImportBundle\Form\Type\UploadImportType; use Wallabag\ImportBundle\Import\InstapaperImport; +use Wallabag\ImportBundle\Redis\Producer as RedisProducer; -class InstapaperController extends Controller +class InstapaperController extends AbstractController { + private RabbitMqProducer $rabbitMqProducer; + private RedisProducer $redisProducer; + + public function __construct(RabbitMqProducer $rabbitMqProducer, RedisProducer $redisProducer) + { + $this->rabbitMqProducer = $rabbitMqProducer; + $this->redisProducer = $redisProducer; + } + /** * @Route("/instapaper", name="import_instapaper") */ - public function indexAction(Request $request) + public function indexAction(Request $request, InstapaperImport $instapaper, Config $craueConfig, TranslatorInterface $translator) { $form = $this->createForm(UploadImportType::class); $form->handleRequest($request); - $instapaper = $this->get(InstapaperImport::class); $instapaper->setUser($this->getUser()); - if ($this->get(Config::class)->get('import_with_rabbitmq')) { - $instapaper->setProducer($this->get('old_sound_rabbit_mq.import_instapaper_producer')); - } elseif ($this->get(Config::class)->get('import_with_redis')) { - $instapaper->setProducer($this->get('wallabag_import.producer.redis.instapaper')); + if ($craueConfig->get('import_with_rabbitmq')) { + $instapaper->setProducer($this->rabbitMqProducer); + } elseif ($craueConfig->get('import_with_redis')) { + $instapaper->setProducer($this->redisProducer); } if ($form->isSubmitted() && $form->isValid()) { @@ -45,13 +54,13 @@ class InstapaperController extends Controller if (true === $res) { $summary = $instapaper->getSummary(); - $message = $this->get(TranslatorInterface::class)->trans('flashes.import.notice.summary', [ + $message = $translator->trans('flashes.import.notice.summary', [ '%imported%' => $summary['imported'], '%skipped%' => $summary['skipped'], ]); if (0 < $summary['queued']) { - $message = $this->get(TranslatorInterface::class)->trans('flashes.import.notice.summary_with_queue', [ + $message = $translator->trans('flashes.import.notice.summary_with_queue', [ '%queued%' => $summary['queued'], ]); } @@ -59,18 +68,12 @@ class InstapaperController extends Controller unlink($this->getParameter('wallabag_import.resource_dir') . '/' . $name); } - $this->get(SessionInterface::class)->getFlashBag()->add( - 'notice', - $message - ); + $this->addFlash('notice', $message); return $this->redirect($this->generateUrl('homepage')); } - $this->get(SessionInterface::class)->getFlashBag()->add( - 'notice', - 'flashes.import.notice.failed_on_file' - ); + $this->addFlash('notice', 'flashes.import.notice.failed_on_file'); } return $this->render('@WallabagImport/Instapaper/index.html.twig', [ diff --git a/src/Wallabag/ImportBundle/Controller/PinboardController.php b/src/Wallabag/ImportBundle/Controller/PinboardController.php index 523ea52bc..6c81e8eb6 100644 --- a/src/Wallabag/ImportBundle/Controller/PinboardController.php +++ b/src/Wallabag/ImportBundle/Controller/PinboardController.php @@ -3,31 +3,40 @@ namespace Wallabag\ImportBundle\Controller; use Craue\ConfigBundle\Util\Config; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; +use OldSound\RabbitMqBundle\RabbitMq\Producer as RabbitMqProducer; +use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\Routing\Annotation\Route; -use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorInterface; use Wallabag\ImportBundle\Form\Type\UploadImportType; use Wallabag\ImportBundle\Import\PinboardImport; +use Wallabag\ImportBundle\Redis\Producer as RedisProducer; -class PinboardController extends Controller +class PinboardController extends AbstractController { + private RabbitMqProducer $rabbitMqProducer; + private RedisProducer $redisProducer; + + public function __construct(RabbitMqProducer $rabbitMqProducer, RedisProducer $redisProducer) + { + $this->rabbitMqProducer = $rabbitMqProducer; + $this->redisProducer = $redisProducer; + } + /** * @Route("/pinboard", name="import_pinboard") */ - public function indexAction(Request $request) + public function indexAction(Request $request, PinboardImport $pinboard, Config $craueConfig, TranslatorInterface $translator) { $form = $this->createForm(UploadImportType::class); $form->handleRequest($request); - $pinboard = $this->get(PinboardImport::class); $pinboard->setUser($this->getUser()); - if ($this->get(Config::class)->get('import_with_rabbitmq')) { - $pinboard->setProducer($this->get('old_sound_rabbit_mq.import_pinboard_producer')); - } elseif ($this->get(Config::class)->get('import_with_redis')) { - $pinboard->setProducer($this->get('wallabag_import.producer.redis.pinboard')); + if ($craueConfig->get('import_with_rabbitmq')) { + $pinboard->setProducer($this->rabbitMqProducer); + } elseif ($craueConfig->get('import_with_redis')) { + $pinboard->setProducer($this->redisProducer); } if ($form->isSubmitted() && $form->isValid()) { @@ -45,13 +54,13 @@ class PinboardController extends Controller if (true === $res) { $summary = $pinboard->getSummary(); - $message = $this->get(TranslatorInterface::class)->trans('flashes.import.notice.summary', [ + $message = $translator->trans('flashes.import.notice.summary', [ '%imported%' => $summary['imported'], '%skipped%' => $summary['skipped'], ]); if (0 < $summary['queued']) { - $message = $this->get(TranslatorInterface::class)->trans('flashes.import.notice.summary_with_queue', [ + $message = $translator->trans('flashes.import.notice.summary_with_queue', [ '%queued%' => $summary['queued'], ]); } @@ -59,18 +68,12 @@ class PinboardController extends Controller unlink($this->getParameter('wallabag_import.resource_dir') . '/' . $name); } - $this->get(SessionInterface::class)->getFlashBag()->add( - 'notice', - $message - ); + $this->addFlash('notice', $message); return $this->redirect($this->generateUrl('homepage')); } - $this->get(SessionInterface::class)->getFlashBag()->add( - 'notice', - 'flashes.import.notice.failed_on_file' - ); + $this->addFlash('notice', 'flashes.import.notice.failed_on_file'); } return $this->render('@WallabagImport/Pinboard/index.html.twig', [ diff --git a/src/Wallabag/ImportBundle/Controller/PocketController.php b/src/Wallabag/ImportBundle/Controller/PocketController.php index b403db74c..2ca509bc1 100644 --- a/src/Wallabag/ImportBundle/Controller/PocketController.php +++ b/src/Wallabag/ImportBundle/Controller/PocketController.php @@ -3,23 +3,39 @@ namespace Wallabag\ImportBundle\Controller; use Craue\ConfigBundle\Util\Config; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; +use OldSound\RabbitMqBundle\RabbitMq\Producer as RabbitMqProducer; +use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; -use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorInterface; use Wallabag\ImportBundle\Import\PocketImport; +use Wallabag\ImportBundle\Redis\Producer as RedisProducer; -class PocketController extends Controller +class PocketController extends AbstractController { + private Config $craueConfig; + private RabbitMqProducer $rabbitMqProducer; + private RedisProducer $redisProducer; + private SessionInterface $session; + + public function __construct(Config $craueConfig, RabbitMqProducer $rabbitMqProducer, RedisProducer $redisProducer, SessionInterface $session) + { + $this->craueConfig = $craueConfig; + $this->rabbitMqProducer = $rabbitMqProducer; + $this->redisProducer = $redisProducer; + $this->session = $session; + } + /** * @Route("/pocket", name="import_pocket") */ - public function indexAction() + public function indexAction(PocketImport $pocketImport) { - $pocket = $this->getPocketImportService(); + $pocket = $this->getPocketImportService($pocketImport); + $form = $this->createFormBuilder($pocket) ->add('mark_as_read', CheckboxType::class, [ 'label' => 'import.form.mark_as_read_label', @@ -28,7 +44,7 @@ class PocketController extends Controller ->getForm(); return $this->render('@WallabagImport/Pocket/index.html.twig', [ - 'import' => $this->getPocketImportService(), + 'import' => $pocket, 'has_consumer_key' => '' === trim($this->getUser()->getConfig()->getPocketConsumerKey()) ? false : true, 'form' => $form->createView(), ]); @@ -37,13 +53,13 @@ class PocketController extends Controller /** * @Route("/pocket/auth", name="import_pocket_auth") */ - public function authAction(Request $request) + public function authAction(Request $request, PocketImport $pocketImport) { - $requestToken = $this->getPocketImportService() + $requestToken = $this->getPocketImportService($pocketImport) ->getRequestToken($this->generateUrl('import', [], UrlGeneratorInterface::ABSOLUTE_URL)); if (false === $requestToken) { - $this->get(SessionInterface::class)->getFlashBag()->add( + $this->addFlash( 'notice', 'flashes.import.notice.failed' ); @@ -53,9 +69,9 @@ class PocketController extends Controller $form = $request->request->get('form'); - $this->get(SessionInterface::class)->set('import.pocket.code', $requestToken); + $this->session->set('import.pocket.code', $requestToken); if (null !== $form && \array_key_exists('mark_as_read', $form)) { - $this->get(SessionInterface::class)->set('mark_as_read', $form['mark_as_read']); + $this->session->set('mark_as_read', $form['mark_as_read']); } return $this->redirect( @@ -67,62 +83,53 @@ class PocketController extends Controller /** * @Route("/pocket/callback", name="import_pocket_callback") */ - public function callbackAction() + public function callbackAction(PocketImport $pocketImport, TranslatorInterface $translator) { $message = 'flashes.import.notice.failed'; - $pocket = $this->getPocketImportService(); + $pocket = $this->getPocketImportService($pocketImport); - $markAsRead = $this->get(SessionInterface::class)->get('mark_as_read'); - $this->get(SessionInterface::class)->remove('mark_as_read'); + $markAsRead = $this->session->get('mark_as_read'); + $this->session->remove('mark_as_read'); // something bad happend on pocket side - if (false === $pocket->authorize($this->get(SessionInterface::class)->get('import.pocket.code'))) { - $this->get(SessionInterface::class)->getFlashBag()->add( - 'notice', - $message - ); + if (false === $pocket->authorize($this->session->get('import.pocket.code'))) { + $this->addFlash('notice', $message); return $this->redirect($this->generateUrl('import_pocket')); } if (true === $pocket->setMarkAsRead($markAsRead)->import()) { $summary = $pocket->getSummary(); - $message = $this->get(TranslatorInterface::class)->trans('flashes.import.notice.summary', [ + $message = $translator->trans('flashes.import.notice.summary', [ '%imported%' => null !== $summary && \array_key_exists('imported', $summary) ? $summary['imported'] : 0, '%skipped%' => null !== $summary && \array_key_exists('skipped', $summary) ? $summary['skipped'] : 0, ]); if (null !== $summary && \array_key_exists('queued', $summary) && 0 < $summary['queued']) { - $message = $this->get(TranslatorInterface::class)->trans('flashes.import.notice.summary_with_queue', [ + $message = $translator->trans('flashes.import.notice.summary_with_queue', [ '%queued%' => $summary['queued'], ]); } } - $this->get(SessionInterface::class)->getFlashBag()->add( - 'notice', - $message - ); + $this->addFlash('notice', $message); return $this->redirect($this->generateUrl('homepage')); } /** * Return Pocket Import Service with or without RabbitMQ enabled. - * - * @return PocketImport */ - private function getPocketImportService() + private function getPocketImportService(PocketImport $pocketImport): PocketImport { - $pocket = $this->get(PocketImport::class); - $pocket->setUser($this->getUser()); + $pocketImport->setUser($this->getUser()); - if ($this->get(Config::class)->get('import_with_rabbitmq')) { - $pocket->setProducer($this->get('old_sound_rabbit_mq.import_pocket_producer')); - } elseif ($this->get(Config::class)->get('import_with_redis')) { - $pocket->setProducer($this->get('wallabag_import.producer.redis.pocket')); + if ($this->craueConfig->get('import_with_rabbitmq')) { + $pocketImport->setProducer($this->rabbitMqProducer); + } elseif ($this->craueConfig->get('import_with_redis')) { + $pocketImport->setProducer($this->redisProducer); } - return $pocket; + return $pocketImport; } } diff --git a/src/Wallabag/ImportBundle/Controller/ReadabilityController.php b/src/Wallabag/ImportBundle/Controller/ReadabilityController.php index 1c257f895..fb2c22262 100644 --- a/src/Wallabag/ImportBundle/Controller/ReadabilityController.php +++ b/src/Wallabag/ImportBundle/Controller/ReadabilityController.php @@ -3,31 +3,40 @@ namespace Wallabag\ImportBundle\Controller; use Craue\ConfigBundle\Util\Config; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; +use OldSound\RabbitMqBundle\RabbitMq\Producer as RabbitMqProducer; +use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\Routing\Annotation\Route; -use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorInterface; use Wallabag\ImportBundle\Form\Type\UploadImportType; use Wallabag\ImportBundle\Import\ReadabilityImport; +use Wallabag\ImportBundle\Redis\Producer as RedisProducer; -class ReadabilityController extends Controller +class ReadabilityController extends AbstractController { + private RabbitMqProducer $rabbitMqProducer; + private RedisProducer $redisProducer; + + public function __construct(RabbitMqProducer $rabbitMqProducer, RedisProducer $redisProducer) + { + $this->rabbitMqProducer = $rabbitMqProducer; + $this->redisProducer = $redisProducer; + } + /** * @Route("/readability", name="import_readability") */ - public function indexAction(Request $request) + public function indexAction(Request $request, ReadabilityImport $readability, Config $craueConfig, TranslatorInterface $translator) { $form = $this->createForm(UploadImportType::class); $form->handleRequest($request); - $readability = $this->get(ReadabilityImport::class); $readability->setUser($this->getUser()); - if ($this->get(Config::class)->get('import_with_rabbitmq')) { - $readability->setProducer($this->get('old_sound_rabbit_mq.import_readability_producer')); - } elseif ($this->get(Config::class)->get('import_with_redis')) { - $readability->setProducer($this->get('wallabag_import.producer.redis.readability')); + if ($craueConfig->get('import_with_rabbitmq')) { + $readability->setProducer($this->rabbitMqProducer); + } elseif ($craueConfig->get('import_with_redis')) { + $readability->setProducer($this->redisProducer); } if ($form->isSubmitted() && $form->isValid()) { @@ -45,13 +54,13 @@ class ReadabilityController extends Controller if (true === $res) { $summary = $readability->getSummary(); - $message = $this->get(TranslatorInterface::class)->trans('flashes.import.notice.summary', [ + $message = $translator->trans('flashes.import.notice.summary', [ '%imported%' => $summary['imported'], '%skipped%' => $summary['skipped'], ]); if (0 < $summary['queued']) { - $message = $this->get(TranslatorInterface::class)->trans('flashes.import.notice.summary_with_queue', [ + $message = $translator->trans('flashes.import.notice.summary_with_queue', [ '%queued%' => $summary['queued'], ]); } @@ -59,18 +68,12 @@ class ReadabilityController extends Controller unlink($this->getParameter('wallabag_import.resource_dir') . '/' . $name); } - $this->get(SessionInterface::class)->getFlashBag()->add( - 'notice', - $message - ); + $this->addFlash('notice', $message); return $this->redirect($this->generateUrl('homepage')); } - $this->get(SessionInterface::class)->getFlashBag()->add( - 'notice', - 'flashes.import.notice.failed_on_file' - ); + $this->addFlash('notice', 'flashes.import.notice.failed_on_file'); } return $this->render('@WallabagImport/Readability/index.html.twig', [ diff --git a/src/Wallabag/ImportBundle/Controller/WallabagController.php b/src/Wallabag/ImportBundle/Controller/WallabagController.php index db78e671c..fd22c8eec 100644 --- a/src/Wallabag/ImportBundle/Controller/WallabagController.php +++ b/src/Wallabag/ImportBundle/Controller/WallabagController.php @@ -2,26 +2,25 @@ namespace Wallabag\ImportBundle\Controller; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; +use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; -use Symfony\Component\HttpFoundation\Session\SessionInterface; -use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorInterface; use Wallabag\ImportBundle\Form\Type\UploadImportType; use Wallabag\ImportBundle\Import\ImportInterface; /** * Define Wallabag import for v1 and v2, since there are very similar. */ -abstract class WallabagController extends Controller +abstract class WallabagController extends AbstractController { /** * Handle import request. * * @return Response|RedirectResponse */ - public function indexAction(Request $request) + public function indexAction(Request $request, TranslatorInterface $translator) { $form = $this->createForm(UploadImportType::class); $form->handleRequest($request); @@ -44,13 +43,13 @@ abstract class WallabagController extends Controller if (true === $res) { $summary = $wallabag->getSummary(); - $message = $this->get(TranslatorInterface::class)->trans('flashes.import.notice.summary', [ + $message = $translator->trans('flashes.import.notice.summary', [ '%imported%' => $summary['imported'], '%skipped%' => $summary['skipped'], ]); if (0 < $summary['queued']) { - $message = $this->get(TranslatorInterface::class)->trans('flashes.import.notice.summary_with_queue', [ + $message = $translator->trans('flashes.import.notice.summary_with_queue', [ '%queued%' => $summary['queued'], ]); } @@ -58,18 +57,12 @@ abstract class WallabagController extends Controller unlink($this->getParameter('wallabag_import.resource_dir') . '/' . $name); } - $this->get(SessionInterface::class)->getFlashBag()->add( - 'notice', - $message - ); + $this->addFlash('notice', $message); return $this->redirect($this->generateUrl('homepage')); } - $this->get(SessionInterface::class)->getFlashBag()->add( - 'notice', - 'flashes.import.notice.failed_on_file' - ); + $this->addFlash('notice', 'flashes.import.notice.failed_on_file'); } return $this->render($this->getImportTemplate(), [ diff --git a/src/Wallabag/ImportBundle/Controller/WallabagV1Controller.php b/src/Wallabag/ImportBundle/Controller/WallabagV1Controller.php index cff632fee..c5257fc3f 100644 --- a/src/Wallabag/ImportBundle/Controller/WallabagV1Controller.php +++ b/src/Wallabag/ImportBundle/Controller/WallabagV1Controller.php @@ -3,18 +3,34 @@ namespace Wallabag\ImportBundle\Controller; use Craue\ConfigBundle\Util\Config; +use OldSound\RabbitMqBundle\RabbitMq\Producer as RabbitMqProducer; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; +use Symfony\Contracts\Translation\TranslatorInterface; use Wallabag\ImportBundle\Import\WallabagV1Import; +use Wallabag\ImportBundle\Redis\Producer as RedisProducer; class WallabagV1Controller extends WallabagController { + private WallabagV1Import $wallabagImport; + private Config $craueConfig; + private RabbitMqProducer $rabbitMqProducer; + private RedisProducer $redisProducer; + + public function __construct(WallabagV1Import $wallabagImport, Config $craueConfig, RabbitMqProducer $rabbitMqProducer, RedisProducer $redisProducer) + { + $this->wallabagImport = $wallabagImport; + $this->craueConfig = $craueConfig; + $this->rabbitMqProducer = $rabbitMqProducer; + $this->redisProducer = $redisProducer; + } + /** * @Route("/wallabag-v1", name="import_wallabag_v1") */ - public function indexAction(Request $request) + public function indexAction(Request $request, TranslatorInterface $translator) { - return parent::indexAction($request); + return parent::indexAction($request, $translator); } /** @@ -22,15 +38,13 @@ class WallabagV1Controller extends WallabagController */ protected function getImportService() { - $service = $this->get(WallabagV1Import::class); - - if ($this->get(Config::class)->get('import_with_rabbitmq')) { - $service->setProducer($this->get('old_sound_rabbit_mq.import_wallabag_v1_producer')); - } elseif ($this->get(Config::class)->get('import_with_redis')) { - $service->setProducer($this->get('wallabag_import.producer.redis.wallabag_v1')); + if ($this->craueConfig->get('import_with_rabbitmq')) { + $this->wallabagImport->setProducer($this->rabbitMqProducer); + } elseif ($this->craueConfig->get('import_with_redis')) { + $this->wallabagImport->setProducer($this->redisProducer); } - return $service; + return $this->wallabagImport; } /** diff --git a/src/Wallabag/ImportBundle/Controller/WallabagV2Controller.php b/src/Wallabag/ImportBundle/Controller/WallabagV2Controller.php index 07eebb92a..ae006b12d 100644 --- a/src/Wallabag/ImportBundle/Controller/WallabagV2Controller.php +++ b/src/Wallabag/ImportBundle/Controller/WallabagV2Controller.php @@ -3,18 +3,34 @@ namespace Wallabag\ImportBundle\Controller; use Craue\ConfigBundle\Util\Config; +use OldSound\RabbitMqBundle\RabbitMq\Producer as RabbitMqProducer; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; +use Symfony\Contracts\Translation\TranslatorInterface; use Wallabag\ImportBundle\Import\WallabagV2Import; +use Wallabag\ImportBundle\Redis\Producer as RedisProducer; class WallabagV2Controller extends WallabagController { + private WallabagV2Import $wallabagImport; + private Config $craueConfig; + private RabbitMqProducer $rabbitMqProducer; + private RedisProducer $redisProducer; + + public function __construct(WallabagV2Import $wallabagImport, Config $craueConfig, RabbitMqProducer $rabbitMqProducer, RedisProducer $redisProducer) + { + $this->wallabagImport = $wallabagImport; + $this->craueConfig = $craueConfig; + $this->rabbitMqProducer = $rabbitMqProducer; + $this->redisProducer = $redisProducer; + } + /** * @Route("/wallabag-v2", name="import_wallabag_v2") */ - public function indexAction(Request $request) + public function indexAction(Request $request, TranslatorInterface $translator) { - return parent::indexAction($request); + return parent::indexAction($request, $translator); } /** @@ -22,15 +38,13 @@ class WallabagV2Controller extends WallabagController */ protected function getImportService() { - $service = $this->get(WallabagV2Import::class); - - if ($this->get(Config::class)->get('import_with_rabbitmq')) { - $service->setProducer($this->get('old_sound_rabbit_mq.import_wallabag_v2_producer')); - } elseif ($this->get(Config::class)->get('import_with_redis')) { - $service->setProducer($this->get('wallabag_import.producer.redis.wallabag_v2')); + if ($this->craueConfig->get('import_with_rabbitmq')) { + $this->wallabagImport->setProducer($this->rabbitMqProducer); + } elseif ($this->craueConfig->get('import_with_redis')) { + $this->wallabagImport->setProducer($this->redisProducer); } - return $service; + return $this->wallabagImport; } /** diff --git a/src/Wallabag/UserBundle/Controller/ManageController.php b/src/Wallabag/UserBundle/Controller/ManageController.php index 0ccc7921d..06e7c8466 100644 --- a/src/Wallabag/UserBundle/Controller/ManageController.php +++ b/src/Wallabag/UserBundle/Controller/ManageController.php @@ -2,6 +2,7 @@ namespace Wallabag\UserBundle\Controller; +use Doctrine\ORM\EntityManagerInterface; use FOS\UserBundle\Event\UserEvent; use FOS\UserBundle\FOSUserEvents; use FOS\UserBundle\Model\UserManagerInterface; @@ -9,33 +10,40 @@ use Pagerfanta\Doctrine\ORM\QueryAdapter as DoctrineORMAdapter; use Pagerfanta\Exception\OutOfRangeCurrentPageException; use Pagerfanta\Pagerfanta; use Scheb\TwoFactorBundle\Security\TwoFactor\Provider\Google\GoogleAuthenticatorInterface; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; +use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\Form\Form; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; -use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\Routing\Annotation\Route; -use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorInterface; use Wallabag\UserBundle\Entity\User; use Wallabag\UserBundle\Form\NewUserType; use Wallabag\UserBundle\Form\SearchUserType; use Wallabag\UserBundle\Form\UserType; +use Wallabag\UserBundle\Repository\UserRepository; /** * User controller. */ -class ManageController extends Controller +class ManageController extends AbstractController { + private EntityManagerInterface $entityManager; + private TranslatorInterface $translator; + + public function __construct(EntityManagerInterface $entityManager, TranslatorInterface $translator) + { + $this->entityManager = $entityManager; + $this->translator = $translator; + } + /** * Creates a new User entity. * * @Route("/new", name="user_new", methods={"GET", "POST"}) */ - public function newAction(Request $request) + public function newAction(Request $request, UserManagerInterface $userManager, EventDispatcherInterface $eventDispatcher) { - $userManager = $this->container->get(UserManagerInterface::class); - $user = $userManager->createUser(); \assert($user instanceof User); // enable created user by default @@ -49,11 +57,11 @@ class ManageController extends Controller // dispatch a created event so the associated config will be created $event = new UserEvent($user, $request); - $this->get(EventDispatcherInterface::class)->dispatch($event, FOSUserEvents::USER_CREATED); + $eventDispatcher->dispatch($event, FOSUserEvents::USER_CREATED); - $this->get(SessionInterface::class)->getFlashBag()->add( + $this->addFlash( 'notice', - $this->get(TranslatorInterface::class)->trans('flashes.user.notice.added', ['%username%' => $user->getUsername()]) + $this->translator->trans('flashes.user.notice.added', ['%username%' => $user->getUsername()]) ); return $this->redirectToRoute('user_edit', ['id' => $user->getId()]); @@ -70,10 +78,8 @@ class ManageController extends Controller * * @Route("/{id}/edit", name="user_edit", methods={"GET", "POST"}) */ - public function editAction(Request $request, User $user) + public function editAction(Request $request, User $user, UserManagerInterface $userManager, GoogleAuthenticatorInterface $googleAuthenticator) { - $userManager = $this->container->get(UserManagerInterface::class); - $deleteForm = $this->createDeleteForm($user); $form = $this->createForm(UserType::class, $user); $form->handleRequest($request); @@ -87,7 +93,7 @@ class ManageController extends Controller // handle creation / reset of the OTP secret if checkbox changed from the previous state if ($this->getParameter('twofactor_auth')) { if (true === $form->get('googleTwoFactor')->getData() && false === $user->isGoogleAuthenticatorEnabled()) { - $user->setGoogleAuthenticatorSecret($this->get(GoogleAuthenticatorInterface::class)->generateSecret()); + $user->setGoogleAuthenticatorSecret($googleAuthenticator->generateSecret()); $user->setEmailTwoFactor(false); } elseif (false === $form->get('googleTwoFactor')->getData() && true === $user->isGoogleAuthenticatorEnabled()) { $user->setGoogleAuthenticatorSecret(null); @@ -96,9 +102,9 @@ class ManageController extends Controller $userManager->updateUser($user); - $this->get(SessionInterface::class)->getFlashBag()->add( + $this->addFlash( 'notice', - $this->get(TranslatorInterface::class)->trans('flashes.user.notice.updated', ['%username%' => $user->getUsername()]) + $this->translator->trans('flashes.user.notice.updated', ['%username%' => $user->getUsername()]) ); return $this->redirectToRoute('user_edit', ['id' => $user->getId()]); @@ -123,14 +129,13 @@ class ManageController extends Controller $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { - $this->get(SessionInterface::class)->getFlashBag()->add( + $this->addFlash( 'notice', - $this->get(TranslatorInterface::class)->trans('flashes.user.notice.deleted', ['%username%' => $user->getUsername()]) + $this->translator->trans('flashes.user.notice.deleted', ['%username%' => $user->getUsername()]) ); - $em = $this->get('doctrine')->getManager(); - $em->remove($user); - $em->flush(); + $this->entityManager->remove($user); + $this->entityManager->flush(); } return $this->redirectToRoute('user_index'); @@ -146,10 +151,9 @@ class ManageController extends Controller * * @return Response */ - public function searchFormAction(Request $request, $page = 1) + public function searchFormAction(Request $request, UserRepository $userRepository, $page = 1) { - $em = $this->get('doctrine')->getManager(); - $qb = $em->getRepository(User::class)->createQueryBuilder('u'); + $qb = $userRepository->createQueryBuilder('u'); $form = $this->createForm(SearchUserType::class); $form->handleRequest($request); @@ -157,7 +161,7 @@ class ManageController extends Controller if ($form->isSubmitted() && $form->isValid()) { $searchTerm = (isset($request->get('search_user')['term']) ? $request->get('search_user')['term'] : ''); - $qb = $em->getRepository(User::class)->getQueryBuilderForSearch($searchTerm); + $qb = $userRepository->getQueryBuilderForSearch($searchTerm); } $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false); diff --git a/tests/Wallabag/CoreBundle/Twig/WallabagExtensionTest.php b/tests/Wallabag/CoreBundle/Twig/WallabagExtensionTest.php index ddb4806b0..824f7a54c 100644 --- a/tests/Wallabag/CoreBundle/Twig/WallabagExtensionTest.php +++ b/tests/Wallabag/CoreBundle/Twig/WallabagExtensionTest.php @@ -4,7 +4,7 @@ namespace Tests\Wallabag\CoreBundle\Twig; use PHPUnit\Framework\TestCase; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; -use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorInterface; use Wallabag\CoreBundle\Repository\EntryRepository; use Wallabag\CoreBundle\Repository\TagRepository; use Wallabag\CoreBundle\Twig\WallabagExtension;