Move to controller as a service

Mostly using autowiring to inject deps.
The only tricky part was for import because all producer use the same class and have a different alias. So we must write them down in the service definition, autowiring doesn't work in that case.

Usually:
- if a controller has a constructor, it means injected services are at least re-used once in actions
- otherwise, service are injected per action
This commit is contained in:
Jeremy Benoist
2022-12-19 10:37:22 +01:00
parent 39f603e015
commit 6aca334d53
36 changed files with 855 additions and 699 deletions

View File

@ -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'])

View File

@ -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'));

View File

@ -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();
}
}

View File

@ -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);

View File

@ -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();
}
}

View File

@ -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;

View File

@ -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);
}