From f808b01692a835673f328d7221ba8c212caa9b61 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Sat, 1 Jul 2017 09:52:38 +0200 Subject: Add a real configuration for CS-Fixer --- .../Controller/WallabagAnnotationController.php | 2 +- .../AnnotationBundle/Entity/Annotation.php | 10 +- .../Repository/AnnotationRepository.php | 32 +-- .../Controller/AnnotationRestController.php | 4 +- .../ApiBundle/Controller/DeveloperController.php | 4 +- .../ApiBundle/Controller/EntryRestController.php | 18 +- .../ApiBundle/Controller/TagRestController.php | 2 +- .../ApiBundle/Controller/UserRestController.php | 4 +- .../Controller/WallabagRestController.php | 4 +- src/Wallabag/ApiBundle/Entity/Client.php | 4 +- src/Wallabag/ApiBundle/Form/Type/ClientType.php | 2 +- .../CoreBundle/Command/CleanDuplicatesCommand.php | 4 +- src/Wallabag/CoreBundle/Command/ExportCommand.php | 2 +- src/Wallabag/CoreBundle/Command/InstallCommand.php | 22 +- .../CoreBundle/Controller/ConfigController.php | 140 ++++++----- .../CoreBundle/Controller/EntryController.php | 260 ++++++++++----------- .../CoreBundle/Controller/ExceptionController.php | 2 +- .../CoreBundle/Controller/ExportController.php | 4 +- .../CoreBundle/Controller/RssController.php | 18 +- .../Controller/SiteCredentialController.php | 8 +- .../CoreBundle/Controller/StaticController.php | 7 +- .../CoreBundle/Controller/TagController.php | 2 +- .../DataFixtures/ORM/LoadSettingData.php | 2 +- .../DependencyInjection/WallabagCoreExtension.php | 2 +- src/Wallabag/CoreBundle/Entity/Entry.php | 10 +- src/Wallabag/CoreBundle/Entity/SiteCredential.php | 2 +- src/Wallabag/CoreBundle/Entity/Tag.php | 2 +- .../Event/Subscriber/DownloadImagesSubscriber.php | 8 +- .../Subscriber/SQLiteCascadeDeleteSubscriber.php | 2 +- .../Event/Subscriber/TablePrefixSubscriber.php | 4 +- .../CoreBundle/Form/Type/EntryFilterType.php | 16 +- .../GrabySiteConfigBuilder.php | 4 +- src/Wallabag/CoreBundle/Helper/ContentProxy.php | 10 +- src/Wallabag/CoreBundle/Helper/CryptoProxy.php | 12 +- .../CoreBundle/Helper/DetectActiveTheme.php | 2 +- src/Wallabag/CoreBundle/Helper/DownloadImages.php | 44 ++-- src/Wallabag/CoreBundle/Helper/EntriesExport.php | 46 ++-- .../CoreBundle/Helper/HttpClientFactory.php | 2 +- .../CoreBundle/Helper/PreparePagerForEntries.php | 2 +- src/Wallabag/CoreBundle/Helper/RuleBasedTagger.php | 2 +- .../CoreBundle/Repository/EntryRepository.php | 34 +-- src/Wallabag/CoreBundle/Twig/WallabagExtension.php | 12 +- .../ImportBundle/Command/ImportCommand.php | 10 +- .../ImportBundle/Command/RedisWorkerCommand.php | 12 +- .../ImportBundle/Consumer/AbstractConsumer.php | 10 +- .../ImportBundle/Controller/BrowserController.php | 43 ++-- .../ImportBundle/Controller/ChromeController.php | 16 +- .../ImportBundle/Controller/FirefoxController.php | 16 +- .../ImportBundle/Controller/ImportController.php | 6 +- .../Controller/InstapaperController.php | 20 +- .../ImportBundle/Controller/PinboardController.php | 20 +- .../ImportBundle/Controller/PocketController.php | 46 ++-- .../Controller/ReadabilityController.php | 20 +- .../ImportBundle/Controller/WallabagController.php | 46 ++-- .../Controller/WallabagV1Controller.php | 16 +- .../Controller/WallabagV2Controller.php | 16 +- .../WallabagImportExtension.php | 6 +- .../ImportBundle/Form/Type/UploadImportType.php | 6 +- .../ImportBundle/Import/AbstractImport.php | 52 ++--- src/Wallabag/ImportBundle/Import/BrowserImport.php | 150 ++++++------ src/Wallabag/ImportBundle/Import/ChromeImport.php | 2 +- src/Wallabag/ImportBundle/Import/FirefoxImport.php | 2 +- .../ImportBundle/Import/ImportCompilerPass.php | 2 +- .../ImportBundle/Import/InstapaperImport.php | 2 +- src/Wallabag/ImportBundle/Import/PocketImport.php | 13 +- .../ImportBundle/Import/WallabagV1Import.php | 4 +- src/Wallabag/ImportBundle/Redis/Producer.php | 2 +- src/Wallabag/ImportBundle/WallabagImportBundle.php | 2 +- .../UserBundle/Controller/ManageController.php | 48 ++-- .../DependencyInjection/WallabagUserExtension.php | 6 +- src/Wallabag/UserBundle/Entity/User.php | 36 +-- .../AuthenticationFailureListener.php | 2 +- .../EventListener/PasswordResettingListener.php | 2 +- src/Wallabag/UserBundle/Form/UserType.php | 10 +- src/Wallabag/UserBundle/Mailer/AuthCodeMailer.php | 2 +- .../UserBundle/Repository/UserRepository.php | 2 +- 76 files changed, 703 insertions(+), 718 deletions(-) (limited to 'src') diff --git a/src/Wallabag/AnnotationBundle/Controller/WallabagAnnotationController.php b/src/Wallabag/AnnotationBundle/Controller/WallabagAnnotationController.php index 2b4b0e8d..8d7b6ee9 100644 --- a/src/Wallabag/AnnotationBundle/Controller/WallabagAnnotationController.php +++ b/src/Wallabag/AnnotationBundle/Controller/WallabagAnnotationController.php @@ -3,9 +3,9 @@ namespace Wallabag\AnnotationBundle\Controller; use FOS\RestBundle\Controller\FOSRestController; +use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; -use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Wallabag\AnnotationBundle\Entity\Annotation; use Wallabag\AnnotationBundle\Form\EditAnnotationType; use Wallabag\AnnotationBundle\Form\NewAnnotationType; diff --git a/src/Wallabag/AnnotationBundle/Entity/Annotation.php b/src/Wallabag/AnnotationBundle/Entity/Annotation.php index c8e41649..04d83001 100644 --- a/src/Wallabag/AnnotationBundle/Entity/Annotation.php +++ b/src/Wallabag/AnnotationBundle/Entity/Annotation.php @@ -3,14 +3,14 @@ namespace Wallabag\AnnotationBundle\Entity; use Doctrine\ORM\Mapping as ORM; -use JMS\Serializer\Annotation\ExclusionPolicy; use JMS\Serializer\Annotation\Exclude; -use JMS\Serializer\Annotation\VirtualProperty; -use JMS\Serializer\Annotation\SerializedName; +use JMS\Serializer\Annotation\ExclusionPolicy; use JMS\Serializer\Annotation\Groups; +use JMS\Serializer\Annotation\SerializedName; +use JMS\Serializer\Annotation\VirtualProperty; use Symfony\Component\Validator\Constraints as Assert; -use Wallabag\UserBundle\Entity\User; use Wallabag\CoreBundle\Entity\Entry; +use Wallabag\UserBundle\Entity\User; /** * Annotation. @@ -139,7 +139,7 @@ class Annotation */ public function timestamps() { - if (is_null($this->createdAt)) { + if (null === $this->createdAt) { $this->createdAt = new \DateTime(); } $this->updatedAt = new \DateTime(); diff --git a/src/Wallabag/AnnotationBundle/Repository/AnnotationRepository.php b/src/Wallabag/AnnotationBundle/Repository/AnnotationRepository.php index da361308..014c29b6 100644 --- a/src/Wallabag/AnnotationBundle/Repository/AnnotationRepository.php +++ b/src/Wallabag/AnnotationBundle/Repository/AnnotationRepository.php @@ -9,22 +9,6 @@ use Doctrine\ORM\EntityRepository; */ class AnnotationRepository extends EntityRepository { - /** - * Return a query builder to used by other getBuilderFor* method. - * - * @param int $userId - * - * @return QueryBuilder - */ - private function getBuilderByUser($userId) - { - return $this->createQueryBuilder('a') - ->leftJoin('a.user', 'u') - ->andWhere('u.id = :userId')->setParameter('userId', $userId) - ->orderBy('a.id', 'desc') - ; - } - /** * Retrieves all annotations for a user. * @@ -139,4 +123,20 @@ class AnnotationRepository extends EntityRepository ->getQuery() ->getResult(); } + + /** + * Return a query builder to used by other getBuilderFor* method. + * + * @param int $userId + * + * @return QueryBuilder + */ + private function getBuilderByUser($userId) + { + return $this->createQueryBuilder('a') + ->leftJoin('a.user', 'u') + ->andWhere('u.id = :userId')->setParameter('userId', $userId) + ->orderBy('a.id', 'desc') + ; + } } diff --git a/src/Wallabag/ApiBundle/Controller/AnnotationRestController.php b/src/Wallabag/ApiBundle/Controller/AnnotationRestController.php index 2dd26c07..28d55ba9 100644 --- a/src/Wallabag/ApiBundle/Controller/AnnotationRestController.php +++ b/src/Wallabag/ApiBundle/Controller/AnnotationRestController.php @@ -4,10 +4,10 @@ namespace Wallabag\ApiBundle\Controller; use Nelmio\ApiDocBundle\Annotation\ApiDoc; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; -use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; -use Wallabag\CoreBundle\Entity\Entry; +use Symfony\Component\HttpFoundation\Request; use Wallabag\AnnotationBundle\Entity\Annotation; +use Wallabag\CoreBundle\Entity\Entry; class AnnotationRestController extends WallabagRestController { diff --git a/src/Wallabag/ApiBundle/Controller/DeveloperController.php b/src/Wallabag/ApiBundle/Controller/DeveloperController.php index 9cb73f4c..c8a1c635 100644 --- a/src/Wallabag/ApiBundle/Controller/DeveloperController.php +++ b/src/Wallabag/ApiBundle/Controller/DeveloperController.php @@ -3,8 +3,8 @@ namespace Wallabag\ApiBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; -use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\Controller; +use Symfony\Component\HttpFoundation\Request; use Wallabag\ApiBundle\Entity\Client; use Wallabag\ApiBundle\Form\Type\ClientType; @@ -75,7 +75,7 @@ class DeveloperController extends Controller */ public function deleteClientAction(Client $client) { - if (null === $this->getUser() || $client->getUser()->getId() != $this->getUser()->getId()) { + if (null === $this->getUser() || $client->getUser()->getId() !== $this->getUser()->getId()) { throw $this->createAccessDeniedException('You can not access this client.'); } diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index c7938633..ca460c84 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -6,14 +6,14 @@ use Hateoas\Configuration\Route; use Hateoas\Representation\Factory\PagerfantaFactory; use JMS\Serializer\SerializationContext; use Nelmio\ApiDocBundle\Annotation\ApiDoc; -use Symfony\Component\HttpKernel\Exception\HttpException; -use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Tag; -use Wallabag\CoreBundle\Event\EntrySavedEvent; use Wallabag\CoreBundle\Event\EntryDeletedEvent; +use Wallabag\CoreBundle\Event\EntrySavedEvent; class EntryRestController extends WallabagRestController { @@ -59,7 +59,7 @@ class EntryRestController extends WallabagRestController $url = $request->query->get('url', ''); if (empty($url)) { - throw $this->createAccessDeniedException('URL is empty?, logged user id: '.$this->getUser()->getId()); + throw $this->createAccessDeniedException('URL is empty?, logged user id: ' . $this->getUser()->getId()); } $res = $this->getDoctrine() @@ -239,9 +239,9 @@ class EntryRestController extends WallabagRestController * } * ) * - * @return JsonResponse - * * @throws HttpException When limit is reached + * + * @return JsonResponse */ public function postEntriesListAction(Request $request) { @@ -678,11 +678,11 @@ class EntryRestController extends WallabagRestController ]); } - if (!is_null($isArchived)) { + if (null !== $isArchived) { $entry->setArchived((bool) $isArchived); } - if (!is_null($isStarred)) { + if (null !== $isStarred) { $entry->setStarred((bool) $isStarred); } @@ -690,7 +690,7 @@ class EntryRestController extends WallabagRestController $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags); } - if (!is_null($isPublic)) { + if (null !== $isPublic) { if (true === (bool) $isPublic && null === $entry->getUid()) { $entry->generateUid(); } elseif (false === (bool) $isPublic) { diff --git a/src/Wallabag/ApiBundle/Controller/TagRestController.php b/src/Wallabag/ApiBundle/Controller/TagRestController.php index 354187a0..efa4e8cf 100644 --- a/src/Wallabag/ApiBundle/Controller/TagRestController.php +++ b/src/Wallabag/ApiBundle/Controller/TagRestController.php @@ -3,8 +3,8 @@ namespace Wallabag\ApiBundle\Controller; use Nelmio\ApiDocBundle\Annotation\ApiDoc; -use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; +use Symfony\Component\HttpFoundation\Request; use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Tag; diff --git a/src/Wallabag/ApiBundle/Controller/UserRestController.php b/src/Wallabag/ApiBundle/Controller/UserRestController.php index 7471f5f6..6f47cff0 100644 --- a/src/Wallabag/ApiBundle/Controller/UserRestController.php +++ b/src/Wallabag/ApiBundle/Controller/UserRestController.php @@ -6,10 +6,10 @@ use FOS\UserBundle\Event\UserEvent; use FOS\UserBundle\FOSUserEvents; use JMS\Serializer\SerializationContext; use Nelmio\ApiDocBundle\Annotation\ApiDoc; -use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; -use Wallabag\UserBundle\Entity\User; +use Symfony\Component\HttpFoundation\Request; use Wallabag\ApiBundle\Entity\Client; +use Wallabag\UserBundle\Entity\User; class UserRestController extends WallabagRestController { diff --git a/src/Wallabag/ApiBundle/Controller/WallabagRestController.php b/src/Wallabag/ApiBundle/Controller/WallabagRestController.php index b1e08ca4..71da2a64 100644 --- a/src/Wallabag/ApiBundle/Controller/WallabagRestController.php +++ b/src/Wallabag/ApiBundle/Controller/WallabagRestController.php @@ -40,8 +40,8 @@ class WallabagRestController extends FOSRestController protected function validateUserAccess($requestUserId) { $user = $this->get('security.token_storage')->getToken()->getUser(); - if ($requestUserId != $user->getId()) { - throw $this->createAccessDeniedException('Access forbidden. Entry user id: '.$requestUserId.', logged user id: '.$user->getId()); + if ($requestUserId !== $user->getId()) { + throw $this->createAccessDeniedException('Access forbidden. Entry user id: ' . $requestUserId . ', logged user id: ' . $user->getId()); } } } diff --git a/src/Wallabag/ApiBundle/Entity/Client.php b/src/Wallabag/ApiBundle/Entity/Client.php index c15fd3fa..e6f98f98 100644 --- a/src/Wallabag/ApiBundle/Entity/Client.php +++ b/src/Wallabag/ApiBundle/Entity/Client.php @@ -4,10 +4,10 @@ namespace Wallabag\ApiBundle\Entity; use Doctrine\ORM\Mapping as ORM; use FOS\OAuthServerBundle\Entity\Client as BaseClient; -use Wallabag\UserBundle\Entity\User; use JMS\Serializer\Annotation\Groups; use JMS\Serializer\Annotation\SerializedName; use JMS\Serializer\Annotation\VirtualProperty; +use Wallabag\UserBundle\Entity\User; /** * @ORM\Table("oauth2_clients") @@ -99,6 +99,6 @@ class Client extends BaseClient */ public function getClientId() { - return $this->getId().'_'.$this->getRandomId(); + return $this->getId() . '_' . $this->getRandomId(); } } diff --git a/src/Wallabag/ApiBundle/Form/Type/ClientType.php b/src/Wallabag/ApiBundle/Form/Type/ClientType.php index eaea4feb..fc22538f 100644 --- a/src/Wallabag/ApiBundle/Form/Type/ClientType.php +++ b/src/Wallabag/ApiBundle/Form/Type/ClientType.php @@ -5,8 +5,8 @@ namespace Wallabag\ApiBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\CallbackTransformer; use Symfony\Component\Form\Extension\Core\Type\SubmitType; -use Symfony\Component\Form\Extension\Core\Type\UrlType; use Symfony\Component\Form\Extension\Core\Type\TextType; +use Symfony\Component\Form\Extension\Core\Type\UrlType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; diff --git a/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php b/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php index 74da1e5f..d964439d 100644 --- a/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php +++ b/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php @@ -76,7 +76,7 @@ class CleanDuplicatesCommand extends ContainerAwareCommand $url = $this->similarUrl($entry['url']); /* @var $entry Entry */ - if (in_array($url, $urls)) { + if (in_array($url, $urls, true)) { ++$duplicatesCount; $em->remove($repo->find($entry['id'])); @@ -93,7 +93,7 @@ class CleanDuplicatesCommand extends ContainerAwareCommand private function similarUrl($url) { - if (in_array(substr($url, -1), ['/', '#'])) { // get rid of "/" and "#" and the end of urls + if (in_array(substr($url, -1), ['/', '#'], true)) { // get rid of "/" and "#" and the end of urls return substr($url, 0, strlen($url)); } diff --git a/src/Wallabag/CoreBundle/Command/ExportCommand.php b/src/Wallabag/CoreBundle/Command/ExportCommand.php index ebb2b4cf..0dacb734 100644 --- a/src/Wallabag/CoreBundle/Command/ExportCommand.php +++ b/src/Wallabag/CoreBundle/Command/ExportCommand.php @@ -49,7 +49,7 @@ class ExportCommand extends ContainerAwareCommand $filePath = $input->getArgument('filepath'); if (!$filePath) { - $filePath = $this->getContainer()->getParameter('kernel.root_dir').'/../'.sprintf('%s-export.json', $user->getUsername()); + $filePath = $this->getContainer()->getParameter('kernel.root_dir') . '/../' . sprintf('%s-export.json', $user->getUsername()); } try { diff --git a/src/Wallabag/CoreBundle/Command/InstallCommand.php b/src/Wallabag/CoreBundle/Command/InstallCommand.php index eb725a59..50551480 100644 --- a/src/Wallabag/CoreBundle/Command/InstallCommand.php +++ b/src/Wallabag/CoreBundle/Command/InstallCommand.php @@ -2,6 +2,7 @@ namespace Wallabag\CoreBundle\Command; +use Craue\ConfigBundle\Entity\Setting; use FOS\UserBundle\Event\UserEvent; use FOS\UserBundle\FOSUserEvents; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; @@ -14,7 +15,6 @@ use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Question\ConfirmationQuestion; use Symfony\Component\Console\Question\Question; use Wallabag\CoreBundle\Entity\Config; -use Craue\ConfigBundle\Entity\Setting; class InstallCommand extends ContainerAwareCommand { @@ -86,7 +86,7 @@ class InstallCommand extends ContainerAwareCommand if (!extension_loaded($this->getContainer()->getParameter('database_driver'))) { $fulfilled = false; $status = 'ERROR!'; - $help = 'Database driver "'.$this->getContainer()->getParameter('database_driver').'" is not installed.'; + $help = 'Database driver "' . $this->getContainer()->getParameter('database_driver') . '" is not installed.'; } $rows[] = [sprintf($label, $this->getContainer()->getParameter('database_driver')), $status, $help]; @@ -101,10 +101,10 @@ class InstallCommand extends ContainerAwareCommand $conn->connect(); } catch (\Exception $e) { if (false === strpos($e->getMessage(), 'Unknown database') - && false === strpos($e->getMessage(), 'database "'.$this->getContainer()->getParameter('database_name').'" does not exist')) { + && false === strpos($e->getMessage(), 'database "' . $this->getContainer()->getParameter('database_name') . '" does not exist')) { $fulfilled = false; $status = 'ERROR!'; - $help = 'Can\'t connect to the database: '.$e->getMessage(); + $help = 'Can\'t connect to the database: ' . $e->getMessage(); } } @@ -123,7 +123,7 @@ class InstallCommand extends ContainerAwareCommand if (false === version_compare($version, $minimalVersion, '>')) { $fulfilled = false; $status = 'ERROR!'; - $help = 'Your MySQL version ('.$version.') is too old, consider upgrading ('.$minimalVersion.'+).'; + $help = 'Your MySQL version (' . $version . ') is too old, consider upgrading (' . $minimalVersion . '+).'; } } @@ -137,21 +137,21 @@ class InstallCommand extends ContainerAwareCommand if (isset($matches[1]) & version_compare($matches[1], '9.2.0', '<')) { $fulfilled = false; $status = 'ERROR!'; - $help = 'PostgreSQL should be greater than 9.1 (actual version: '.$matches[1].')'; + $help = 'PostgreSQL should be greater than 9.1 (actual version: ' . $matches[1] . ')'; } } $rows[] = [$label, $status, $help]; foreach ($this->functionExists as $functionRequired) { - $label = ''.$functionRequired.''; + $label = '' . $functionRequired . ''; $status = 'OK!'; $help = ''; if (!function_exists($functionRequired)) { $fulfilled = false; $status = 'ERROR!'; - $help = 'You need the '.$functionRequired.' function activated'; + $help = 'You need the ' . $functionRequired . ' function activated'; } $rows[] = [$label, $status, $help]; @@ -351,8 +351,8 @@ class InstallCommand extends ContainerAwareCommand $this->getApplication()->setAutoExit(true); throw new \RuntimeException( - 'The command "'.$command."\" generates some errors: \n\n" - .$output->fetch()); + 'The command "' . $command . "\" generates some errors: \n\n" + . $output->fetch()); } return $this; @@ -396,7 +396,7 @@ class InstallCommand extends ContainerAwareCommand } try { - return in_array($databaseName, $schemaManager->listDatabases()); + return in_array($databaseName, $schemaManager->listDatabases(), true); } catch (\Doctrine\DBAL\Exception\DriverException $e) { // it means we weren't able to get database list, assume the database doesn't exist diff --git a/src/Wallabag/CoreBundle/Controller/ConfigController.php b/src/Wallabag/CoreBundle/Controller/ConfigController.php index d4170d39..7e39992d 100644 --- a/src/Wallabag/CoreBundle/Controller/ConfigController.php +++ b/src/Wallabag/CoreBundle/Controller/ConfigController.php @@ -10,8 +10,8 @@ use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Wallabag\CoreBundle\Entity\Config; use Wallabag\CoreBundle\Entity\TaggingRule; -use Wallabag\CoreBundle\Form\Type\ConfigType; use Wallabag\CoreBundle\Form\Type\ChangePasswordType; +use Wallabag\CoreBundle\Form\Type\ConfigType; use Wallabag\CoreBundle\Form\Type\RssType; use Wallabag\CoreBundle\Form\Type\TaggingRuleType; use Wallabag\CoreBundle\Form\Type\UserInformationType; @@ -54,7 +54,7 @@ class ConfigController extends Controller } // handle changing password - $pwdForm = $this->createForm(ChangePasswordType::class, null, ['action' => $this->generateUrl('config').'#set4']); + $pwdForm = $this->createForm(ChangePasswordType::class, null, ['action' => $this->generateUrl('config') . '#set4']); $pwdForm->handleRequest($request); if ($pwdForm->isSubmitted() && $pwdForm->isValid()) { @@ -69,13 +69,13 @@ class ConfigController extends Controller $this->get('session')->getFlashBag()->add('notice', $message); - return $this->redirect($this->generateUrl('config').'#set4'); + return $this->redirect($this->generateUrl('config') . '#set4'); } // handle changing user information $userForm = $this->createForm(UserInformationType::class, $user, [ 'validation_groups' => ['Profile'], - 'action' => $this->generateUrl('config').'#set3', + 'action' => $this->generateUrl('config') . '#set3', ]); $userForm->handleRequest($request); @@ -87,11 +87,11 @@ class ConfigController extends Controller 'flashes.config.notice.user_updated' ); - return $this->redirect($this->generateUrl('config').'#set3'); + return $this->redirect($this->generateUrl('config') . '#set3'); } // handle rss information - $rssForm = $this->createForm(RssType::class, $config, ['action' => $this->generateUrl('config').'#set2']); + $rssForm = $this->createForm(RssType::class, $config, ['action' => $this->generateUrl('config') . '#set2']); $rssForm->handleRequest($request); if ($rssForm->isSubmitted() && $rssForm->isValid()) { @@ -103,12 +103,12 @@ class ConfigController extends Controller 'flashes.config.notice.rss_updated' ); - return $this->redirect($this->generateUrl('config').'#set2'); + return $this->redirect($this->generateUrl('config') . '#set2'); } // handle tagging rule $taggingRule = new TaggingRule(); - $action = $this->generateUrl('config').'#set5'; + $action = $this->generateUrl('config') . '#set5'; if ($request->query->has('tagging-rule')) { $taggingRule = $this->getDoctrine() @@ -119,7 +119,7 @@ class ConfigController extends Controller return $this->redirect($action); } - $action = $this->generateUrl('config').'?tagging-rule='.$taggingRule->getId().'#set5'; + $action = $this->generateUrl('config') . '?tagging-rule=' . $taggingRule->getId() . '#set5'; } $newTaggingRule = $this->createForm(TaggingRuleType::class, $taggingRule, ['action' => $action]); @@ -135,7 +135,7 @@ class ConfigController extends Controller 'flashes.config.notice.tagging_rules_updated' ); - return $this->redirect($this->generateUrl('config').'#set5'); + return $this->redirect($this->generateUrl('config') . '#set5'); } return $this->render('WallabagCoreBundle:Config:index.html.twig', [ @@ -182,7 +182,7 @@ class ConfigController extends Controller 'flashes.config.notice.rss_token_updated' ); - return $this->redirect($this->generateUrl('config').'#set2'); + return $this->redirect($this->generateUrl('config') . '#set2'); } /** @@ -207,7 +207,7 @@ class ConfigController extends Controller 'flashes.config.notice.tagging_rules_deleted' ); - return $this->redirect($this->generateUrl('config').'#set5'); + return $this->redirect($this->generateUrl('config') . '#set5'); } /** @@ -223,7 +223,7 @@ class ConfigController extends Controller { $this->validateRuleAction($rule); - return $this->redirect($this->generateUrl('config').'?tagging-rule='.$rule->getId().'#set5'); + return $this->redirect($this->generateUrl('config') . '?tagging-rule=' . $rule->getId() . '#set5'); } /** @@ -241,11 +241,9 @@ class ConfigController extends Controller ->getRepository('WallabagAnnotationBundle:Annotation') ->removeAllByUserId($this->getUser()->getId()); break; - case 'tags': $this->removeAllTagsByUserId($this->getUser()->getId()); break; - case 'entries': // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff // otherwise they won't be removed ... @@ -272,10 +270,63 @@ class ConfigController extends Controller $this->get('session')->getFlashBag()->add( 'notice', - 'flashes.config.notice.'.$type.'_reset' + 'flashes.config.notice.' . $type . '_reset' ); - return $this->redirect($this->generateUrl('config').'#set3'); + return $this->redirect($this->generateUrl('config') . '#set3'); + } + + /** + * Delete account for current user. + * + * @Route("/account/delete", name="delete_account") + * + * @param Request $request + * + * @throws AccessDeniedHttpException + * + * @return \Symfony\Component\HttpFoundation\RedirectResponse + */ + public function deleteAccountAction(Request $request) + { + $enabledUsers = $this->get('wallabag_user.user_repository') + ->getSumEnabledUsers(); + + if ($enabledUsers <= 1) { + throw new AccessDeniedHttpException(); + } + + $user = $this->getUser(); + + // logout current user + $this->get('security.token_storage')->setToken(null); + $request->getSession()->invalidate(); + + $em = $this->get('fos_user.user_manager'); + $em->deleteUser($user); + + return $this->redirect($this->generateUrl('fos_user_security_login')); + } + + /** + * Switch view mode for current user. + * + * @Route("/config/view-mode", name="switch_view_mode") + * + * @param Request $request + * + * @return \Symfony\Component\HttpFoundation\RedirectResponse + */ + public function changeViewModeAction(Request $request) + { + $user = $this->getUser(); + $user->getConfig()->setListMode(!$user->getConfig()->getListMode()); + + $em = $this->getDoctrine()->getManager(); + $em->persist($user); + $em->flush(); + + return $this->redirect($request->headers->get('referer')); } /** @@ -349,7 +400,7 @@ class ConfigController extends Controller */ private function validateRuleAction(TaggingRule $rule) { - if ($this->getUser()->getId() != $rule->getConfig()->getUser()->getId()) { + if ($this->getUser()->getId() !== $rule->getConfig()->getUser()->getId()) { throw $this->createAccessDeniedException('You can not access this tagging rule.'); } } @@ -373,57 +424,4 @@ class ConfigController extends Controller return $config; } - - /** - * Delete account for current user. - * - * @Route("/account/delete", name="delete_account") - * - * @param Request $request - * - * @throws AccessDeniedHttpException - * - * @return \Symfony\Component\HttpFoundation\RedirectResponse - */ - public function deleteAccountAction(Request $request) - { - $enabledUsers = $this->get('wallabag_user.user_repository') - ->getSumEnabledUsers(); - - if ($enabledUsers <= 1) { - throw new AccessDeniedHttpException(); - } - - $user = $this->getUser(); - - // logout current user - $this->get('security.token_storage')->setToken(null); - $request->getSession()->invalidate(); - - $em = $this->get('fos_user.user_manager'); - $em->deleteUser($user); - - return $this->redirect($this->generateUrl('fos_user_security_login')); - } - - /** - * Switch view mode for current user. - * - * @Route("/config/view-mode", name="switch_view_mode") - * - * @param Request $request - * - * @return \Symfony\Component\HttpFoundation\RedirectResponse - */ - public function changeViewModeAction(Request $request) - { - $user = $this->getUser(); - $user->getConfig()->setListMode(!$user->getConfig()->getListMode()); - - $em = $this->getDoctrine()->getManager(); - $em->persist($user); - $em->flush(); - - return $this->redirect($request->headers->get('referer')); - } } diff --git a/src/Wallabag/CoreBundle/Controller/EntryController.php b/src/Wallabag/CoreBundle/Controller/EntryController.php index fafa49f1..445cfeeb 100644 --- a/src/Wallabag/CoreBundle/Controller/EntryController.php +++ b/src/Wallabag/CoreBundle/Controller/EntryController.php @@ -4,17 +4,17 @@ namespace Wallabag\CoreBundle\Controller; use Pagerfanta\Adapter\DoctrineORMAdapter; use Pagerfanta\Exception\OutOfRangeCurrentPageException; +use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Wallabag\CoreBundle\Entity\Entry; -use Wallabag\CoreBundle\Form\Type\EntryFilterType; +use Wallabag\CoreBundle\Event\EntryDeletedEvent; +use Wallabag\CoreBundle\Event\EntrySavedEvent; use Wallabag\CoreBundle\Form\Type\EditEntryType; +use Wallabag\CoreBundle\Form\Type\EntryFilterType; use Wallabag\CoreBundle\Form\Type\NewEntryType; -use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache; -use Wallabag\CoreBundle\Event\EntrySavedEvent; -use Wallabag\CoreBundle\Event\EntryDeletedEvent; use Wallabag\CoreBundle\Form\Type\SearchEntryType; class EntryController extends Controller @@ -51,31 +51,6 @@ class EntryController extends Controller ]); } - /** - * Fetch content and update entry. - * In case it fails, $entry->getContent will return an error message. - * - * @param Entry $entry - * @param string $prefixMessage Should be the translation key: entry_saved or entry_reloaded - */ - private function updateEntry(Entry $entry, $prefixMessage = 'entry_saved') - { - $message = 'flashes.entry.notice.'.$prefixMessage; - - try { - $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl()); - } catch (\Exception $e) { - $this->get('logger')->error('Error while saving an entry', [ - 'exception' => $e, - 'entry' => $entry, - ]); - - $message = 'flashes.entry.notice.'.$prefixMessage.'_failed'; - } - - $this->get('session')->getFlashBag()->add('notice', $message); - } - /** * @param Request $request * @@ -220,7 +195,7 @@ class EntryController extends Controller public function showUnreadAction(Request $request, $page) { // load the quickstart if no entry in database - if ($page == 1 && $this->get('wallabag_core.entry_repository')->countAllEntriesByUser($this->getUser()->getId()) == 0) { + if ($page === 1 && $this->get('wallabag_core.entry_repository')->countAllEntriesByUser($this->getUser()->getId()) === 0) { return $this->redirect($this->generateUrl('quickstart')); } @@ -257,83 +232,6 @@ class EntryController extends Controller return $this->showEntries('starred', $request, $page); } - /** - * Global method to retrieve entries depending on the given type - * It returns the response to be send. - * - * @param string $type Entries type: unread, starred or archive - * @param Request $request - * @param int $page - * - * @return \Symfony\Component\HttpFoundation\Response - */ - private function showEntries($type, Request $request, $page) - { - $repository = $this->get('wallabag_core.entry_repository'); - $searchTerm = (isset($request->get('search_entry')['term']) ? $request->get('search_entry')['term'] : ''); - $currentRoute = (!is_null($request->query->get('currentRoute')) ? $request->query->get('currentRoute') : ''); - - switch ($type) { - case 'search': - $qb = $repository->getBuilderForSearchByUser($this->getUser()->getId(), $searchTerm, $currentRoute); - - break; - case 'untagged': - $qb = $repository->getBuilderForUntaggedByUser($this->getUser()->getId()); - - break; - case 'starred': - $qb = $repository->getBuilderForStarredByUser($this->getUser()->getId()); - break; - - case 'archive': - $qb = $repository->getBuilderForArchiveByUser($this->getUser()->getId()); - break; - - case 'unread': - $qb = $repository->getBuilderForUnreadByUser($this->getUser()->getId()); - break; - - case 'all': - $qb = $repository->getBuilderForAllByUser($this->getUser()->getId()); - break; - - default: - throw new \InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type)); - } - - $form = $this->createForm(EntryFilterType::class); - - if ($request->query->has($form->getName())) { - // manually bind values from the request - $form->submit($request->query->get($form->getName())); - - // build the query from the given form object - $this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($form, $qb); - } - - $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false); - - $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries')->prepare($pagerAdapter); - - try { - $entries->setCurrentPage($page); - } catch (OutOfRangeCurrentPageException $e) { - if ($page > 1) { - return $this->redirect($this->generateUrl($type, ['page' => $entries->getNbPages()]), 302); - } - } - - return $this->render( - 'WallabagCoreBundle:Entry:entries.html.twig', [ - 'form' => $form->createView(), - 'entries' => $entries, - 'currentPage' => $page, - 'searchTerm' => $searchTerm, - ] - ); - } - /** * Shows entry content. * @@ -487,37 +385,13 @@ class EntryController extends Controller // don't redirect user to the deleted entry (check that the referer doesn't end with the same url) $referer = $request->headers->get('referer'); - $to = (1 !== preg_match('#'.$url.'$#i', $referer) ? $referer : null); + $to = (1 !== preg_match('#' . $url . '$#i', $referer) ? $referer : null); $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($to); return $this->redirect($redirectUrl); } - /** - * Check if the logged user can manage the given entry. - * - * @param Entry $entry - */ - private function checkUserAction(Entry $entry) - { - if (null === $this->getUser() || $this->getUser()->getId() != $entry->getUser()->getId()) { - throw $this->createAccessDeniedException('You can not access this entry.'); - } - } - - /** - * Check for existing entry, if it exists, redirect to it with a message. - * - * @param Entry $entry - * - * @return Entry|bool - */ - private function checkIfEntryAlreadyExists(Entry $entry) - { - return $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($entry->getUrl(), $this->getUser()->getId()); - } - /** * Get public URL for entry (and generate it if necessary). * @@ -604,4 +478,126 @@ class EntryController extends Controller { return $this->showEntries('untagged', $request, $page); } + + /** + * Fetch content and update entry. + * In case it fails, $entry->getContent will return an error message. + * + * @param Entry $entry + * @param string $prefixMessage Should be the translation key: entry_saved or entry_reloaded + */ + private function updateEntry(Entry $entry, $prefixMessage = 'entry_saved') + { + $message = 'flashes.entry.notice.' . $prefixMessage; + + try { + $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl()); + } catch (\Exception $e) { + $this->get('logger')->error('Error while saving an entry', [ + 'exception' => $e, + 'entry' => $entry, + ]); + + $message = 'flashes.entry.notice.' . $prefixMessage . '_failed'; + } + + $this->get('session')->getFlashBag()->add('notice', $message); + } + + /** + * Global method to retrieve entries depending on the given type + * It returns the response to be send. + * + * @param string $type Entries type: unread, starred or archive + * @param Request $request + * @param int $page + * + * @return \Symfony\Component\HttpFoundation\Response + */ + private function showEntries($type, Request $request, $page) + { + $repository = $this->get('wallabag_core.entry_repository'); + $searchTerm = (isset($request->get('search_entry')['term']) ? $request->get('search_entry')['term'] : ''); + $currentRoute = (null !== $request->query->get('currentRoute') ? $request->query->get('currentRoute') : ''); + + switch ($type) { + case 'search': + $qb = $repository->getBuilderForSearchByUser($this->getUser()->getId(), $searchTerm, $currentRoute); + + break; + case 'untagged': + $qb = $repository->getBuilderForUntaggedByUser($this->getUser()->getId()); + + break; + case 'starred': + $qb = $repository->getBuilderForStarredByUser($this->getUser()->getId()); + break; + case 'archive': + $qb = $repository->getBuilderForArchiveByUser($this->getUser()->getId()); + break; + case 'unread': + $qb = $repository->getBuilderForUnreadByUser($this->getUser()->getId()); + break; + case 'all': + $qb = $repository->getBuilderForAllByUser($this->getUser()->getId()); + break; + default: + throw new \InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type)); + } + + $form = $this->createForm(EntryFilterType::class); + + if ($request->query->has($form->getName())) { + // manually bind values from the request + $form->submit($request->query->get($form->getName())); + + // build the query from the given form object + $this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($form, $qb); + } + + $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false); + + $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries')->prepare($pagerAdapter); + + try { + $entries->setCurrentPage($page); + } catch (OutOfRangeCurrentPageException $e) { + if ($page > 1) { + return $this->redirect($this->generateUrl($type, ['page' => $entries->getNbPages()]), 302); + } + } + + return $this->render( + 'WallabagCoreBundle:Entry:entries.html.twig', [ + 'form' => $form->createView(), + 'entries' => $entries, + 'currentPage' => $page, + 'searchTerm' => $searchTerm, + ] + ); + } + + /** + * Check if the logged user can manage the given entry. + * + * @param Entry $entry + */ + private function checkUserAction(Entry $entry) + { + if (null === $this->getUser() || $this->getUser()->getId() !== $entry->getUser()->getId()) { + throw $this->createAccessDeniedException('You can not access this entry.'); + } + } + + /** + * Check for existing entry, if it exists, redirect to it with a message. + * + * @param Entry $entry + * + * @return Entry|bool + */ + private function checkIfEntryAlreadyExists(Entry $entry) + { + return $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($entry->getUrl(), $this->getUser()->getId()); + } } diff --git a/src/Wallabag/CoreBundle/Controller/ExceptionController.php b/src/Wallabag/CoreBundle/Controller/ExceptionController.php index abfa9c2f..461309ea 100644 --- a/src/Wallabag/CoreBundle/Controller/ExceptionController.php +++ b/src/Wallabag/CoreBundle/Controller/ExceptionController.php @@ -14,7 +14,7 @@ class ExceptionController extends BaseExceptionController protected function findTemplate(Request $request, $format, $code, $showException) { $name = $showException ? 'exception' : 'error'; - if ($showException && 'html' == $format) { + if ($showException && 'html' === $format) { $name = 'exception_full'; } diff --git a/src/Wallabag/CoreBundle/Controller/ExportController.php b/src/Wallabag/CoreBundle/Controller/ExportController.php index fda04cfb..6fad122e 100644 --- a/src/Wallabag/CoreBundle/Controller/ExportController.php +++ b/src/Wallabag/CoreBundle/Controller/ExportController.php @@ -55,10 +55,10 @@ class ExportController extends Controller public function downloadEntriesAction(Request $request, $format, $category) { $method = ucfirst($category); - $methodBuilder = 'getBuilderFor'.$method.'ByUser'; + $methodBuilder = 'getBuilderFor' . $method . 'ByUser'; $repository = $this->get('wallabag_core.entry_repository'); - if ($category == 'tag_entries') { + if ($category === 'tag_entries') { $tag = $this->get('wallabag_core.tag_repository')->findOneBySlug($request->query->get('tag')); $entries = $repository->findAllByTagId( diff --git a/src/Wallabag/CoreBundle/Controller/RssController.php b/src/Wallabag/CoreBundle/Controller/RssController.php index e87dd9a1..e84044b1 100644 --- a/src/Wallabag/CoreBundle/Controller/RssController.php +++ b/src/Wallabag/CoreBundle/Controller/RssController.php @@ -2,19 +2,19 @@ namespace Wallabag\CoreBundle\Controller; -use Pagerfanta\Adapter\DoctrineORMAdapter; use Pagerfanta\Adapter\ArrayAdapter; +use Pagerfanta\Adapter\DoctrineORMAdapter; use Pagerfanta\Exception\OutOfRangeCurrentPageException; use Pagerfanta\Pagerfanta; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; +use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; +use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Tag; use Wallabag\UserBundle\Entity\User; -use Symfony\Component\Routing\Generator\UrlGeneratorInterface; class RssController extends Controller { @@ -113,7 +113,7 @@ class RssController extends Controller $entries->setCurrentPage($page); } catch (OutOfRangeCurrentPageException $e) { if ($page > 1) { - return $this->redirect($url.'?page='.$entries->getNbPages(), 302); + return $this->redirect($url . '?page=' . $entries->getNbPages(), 302); } } @@ -121,7 +121,7 @@ class RssController extends Controller '@WallabagCore/themes/common/Entry/entries.xml.twig', [ 'url_html' => $this->generateUrl('tag_entries', ['slug' => $tag->getSlug()], UrlGeneratorInterface::ABSOLUTE_URL), - 'type' => 'tag ('.$tag->getLabel().')', + 'type' => 'tag (' . $tag->getLabel() . ')', 'url' => $url, 'entries' => $entries, ], @@ -147,19 +147,15 @@ class RssController extends Controller case 'starred': $qb = $repository->getBuilderForStarredByUser($user->getId()); break; - case 'archive': $qb = $repository->getBuilderForArchiveByUser($user->getId()); break; - case 'unread': $qb = $repository->getBuilderForUnreadByUser($user->getId()); break; - case 'all': $qb = $repository->getBuilderForAllByUser($user->getId()); break; - default: throw new \InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type)); } @@ -171,7 +167,7 @@ class RssController extends Controller $entries->setMaxPerPage($perPage); $url = $this->generateUrl( - $type.'_rss', + $type . '_rss', [ 'username' => $user->getUsername(), 'token' => $user->getConfig()->getRssToken(), @@ -183,7 +179,7 @@ class RssController extends Controller $entries->setCurrentPage((int) $page); } catch (OutOfRangeCurrentPageException $e) { if ($page > 1) { - return $this->redirect($url.'?page='.$entries->getNbPages(), 302); + return $this->redirect($url . '?page=' . $entries->getNbPages(), 302); } } diff --git a/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php b/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php index 98781dab..fa2066dc 100644 --- a/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php +++ b/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php @@ -2,12 +2,12 @@ namespace Wallabag\CoreBundle\Controller; -use Symfony\Component\HttpFoundation\Request; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; -use Wallabag\UserBundle\Entity\User; +use Symfony\Bundle\FrameworkBundle\Controller\Controller; +use Symfony\Component\HttpFoundation\Request; use Wallabag\CoreBundle\Entity\SiteCredential; +use Wallabag\UserBundle\Entity\User; /** * SiteCredential controller. @@ -167,7 +167,7 @@ class SiteCredentialController extends Controller */ private function checkUserAction(SiteCredential $siteCredential) { - if (null === $this->getUser() || $this->getUser()->getId() != $siteCredential->getUser()->getId()) { + if (null === $this->getUser() || $this->getUser()->getId() !== $siteCredential->getUser()->getId()) { throw $this->createAccessDeniedException('You can not access this site credential.'); } } diff --git a/src/Wallabag/CoreBundle/Controller/StaticController.php b/src/Wallabag/CoreBundle/Controller/StaticController.php index 82714217..318af303 100644 --- a/src/Wallabag/CoreBundle/Controller/StaticController.php +++ b/src/Wallabag/CoreBundle/Controller/StaticController.php @@ -16,7 +16,9 @@ class StaticController extends Controller return $this->render( '@WallabagCore/themes/common/Static/howto.html.twig', - ['addonsUrl' => $addonsUrl] + [ + 'addonsUrl' => $addonsUrl, + ] ); } @@ -40,8 +42,7 @@ class StaticController extends Controller public function quickstartAction() { return $this->render( - '@WallabagCore/themes/common/Static/quickstart.html.twig', - [] + '@WallabagCore/themes/common/Static/quickstart.html.twig' ); } } diff --git a/src/Wallabag/CoreBundle/Controller/TagController.php b/src/Wallabag/CoreBundle/Controller/TagController.php index a8b1eadd..f2ca58c6 100644 --- a/src/Wallabag/CoreBundle/Controller/TagController.php +++ b/src/Wallabag/CoreBundle/Controller/TagController.php @@ -4,13 +4,13 @@ namespace Wallabag\CoreBundle\Controller; use Pagerfanta\Adapter\ArrayAdapter; use Pagerfanta\Exception\OutOfRangeCurrentPageException; +use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Tag; use Wallabag\CoreBundle\Form\Type\NewTagType; -use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; class TagController extends Controller { diff --git a/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSettingData.php b/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSettingData.php index a52288e6..3fe88e7f 100644 --- a/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSettingData.php +++ b/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSettingData.php @@ -2,10 +2,10 @@ namespace Wallabag\CoreBundle\DataFixtures\ORM; +use Craue\ConfigBundle\Entity\Setting; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use Doctrine\Common\Persistence\ObjectManager; -use Craue\ConfigBundle\Entity\Setting; use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerInterface; diff --git a/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php b/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php index 532ce238..a3ef2b53 100644 --- a/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php +++ b/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php @@ -31,7 +31,7 @@ class WallabagCoreExtension extends Extension $container->setParameter('wallabag_core.default_internal_settings', $config['default_internal_settings']); $container->setParameter('wallabag_core.site_credentials.encryption_key_path', $config['encryption_key_path']); - $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); + $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('services.yml'); $loader->load('parameters.yml'); } diff --git a/src/Wallabag/CoreBundle/Entity/Entry.php b/src/Wallabag/CoreBundle/Entity/Entry.php index a0503c39..581e8906 100644 --- a/src/Wallabag/CoreBundle/Entity/Entry.php +++ b/src/Wallabag/CoreBundle/Entity/Entry.php @@ -5,14 +5,14 @@ namespace Wallabag\CoreBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; use Hateoas\Configuration\Annotation as Hateoas; -use JMS\Serializer\Annotation\Groups; -use JMS\Serializer\Annotation\XmlRoot; use JMS\Serializer\Annotation\Exclude; -use JMS\Serializer\Annotation\VirtualProperty; +use JMS\Serializer\Annotation\Groups; use JMS\Serializer\Annotation\SerializedName; +use JMS\Serializer\Annotation\VirtualProperty; +use JMS\Serializer\Annotation\XmlRoot; use Symfony\Component\Validator\Constraints as Assert; -use Wallabag\UserBundle\Entity\User; use Wallabag\AnnotationBundle\Entity\Annotation; +use Wallabag\UserBundle\Entity\User; /** * Entry. @@ -478,7 +478,7 @@ class Entry */ public function timestamps() { - if (is_null($this->createdAt)) { + if (null === $this->createdAt) { $this->createdAt = new \DateTime(); } diff --git a/src/Wallabag/CoreBundle/Entity/SiteCredential.php b/src/Wallabag/CoreBundle/Entity/SiteCredential.php index 58075e92..380f820d 100644 --- a/src/Wallabag/CoreBundle/Entity/SiteCredential.php +++ b/src/Wallabag/CoreBundle/Entity/SiteCredential.php @@ -188,7 +188,7 @@ class SiteCredential */ public function timestamps() { - if (is_null($this->createdAt)) { + if (null === $this->createdAt) { $this->createdAt = new \DateTime(); } } diff --git a/src/Wallabag/CoreBundle/Entity/Tag.php b/src/Wallabag/CoreBundle/Entity/Tag.php index 4b480ff1..c19023af 100644 --- a/src/Wallabag/CoreBundle/Entity/Tag.php +++ b/src/Wallabag/CoreBundle/Entity/Tag.php @@ -4,9 +4,9 @@ namespace Wallabag\CoreBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; +use Gedmo\Mapping\Annotation as Gedmo; use JMS\Serializer\Annotation\ExclusionPolicy; use JMS\Serializer\Annotation\Expose; -use Gedmo\Mapping\Annotation as Gedmo; use JMS\Serializer\Annotation\XmlRoot; /** diff --git a/src/Wallabag/CoreBundle/Event/Subscriber/DownloadImagesSubscriber.php b/src/Wallabag/CoreBundle/Event/Subscriber/DownloadImagesSubscriber.php index 4ebe837b..1dd0a1a4 100644 --- a/src/Wallabag/CoreBundle/Event/Subscriber/DownloadImagesSubscriber.php +++ b/src/Wallabag/CoreBundle/Event/Subscriber/DownloadImagesSubscriber.php @@ -2,13 +2,13 @@ namespace Wallabag\CoreBundle\Event\Subscriber; -use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Doctrine\ORM\EntityManager; use Psr\Log\LoggerInterface; -use Wallabag\CoreBundle\Helper\DownloadImages; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Wallabag\CoreBundle\Entity\Entry; -use Wallabag\CoreBundle\Event\EntrySavedEvent; use Wallabag\CoreBundle\Event\EntryDeletedEvent; -use Doctrine\ORM\EntityManager; +use Wallabag\CoreBundle\Event\EntrySavedEvent; +use Wallabag\CoreBundle\Helper\DownloadImages; class DownloadImagesSubscriber implements EventSubscriberInterface { diff --git a/src/Wallabag/CoreBundle/Event/Subscriber/SQLiteCascadeDeleteSubscriber.php b/src/Wallabag/CoreBundle/Event/Subscriber/SQLiteCascadeDeleteSubscriber.php index 5e6af8cc..9c1d8a1d 100644 --- a/src/Wallabag/CoreBundle/Event/Subscriber/SQLiteCascadeDeleteSubscriber.php +++ b/src/Wallabag/CoreBundle/Event/Subscriber/SQLiteCascadeDeleteSubscriber.php @@ -2,10 +2,10 @@ namespace Wallabag\CoreBundle\Event\Subscriber; +use Doctrine\Bundle\DoctrineBundle\Registry; use Doctrine\Common\EventSubscriber; use Doctrine\ORM\Event\LifecycleEventArgs; use Wallabag\CoreBundle\Entity\Entry; -use Doctrine\Bundle\DoctrineBundle\Registry; /** * SQLite doesn't care about cascading remove, so we need to manually remove associated stuf for an Entry. diff --git a/src/Wallabag/CoreBundle/Event/Subscriber/TablePrefixSubscriber.php b/src/Wallabag/CoreBundle/Event/Subscriber/TablePrefixSubscriber.php index 711c3bf8..35902654 100644 --- a/src/Wallabag/CoreBundle/Event/Subscriber/TablePrefixSubscriber.php +++ b/src/Wallabag/CoreBundle/Event/Subscriber/TablePrefixSubscriber.php @@ -39,12 +39,12 @@ class TablePrefixSubscriber implements EventSubscriber return; } - $classMetadata->setPrimaryTable(['name' => $this->prefix.$classMetadata->getTableName()]); + $classMetadata->setPrimaryTable(['name' => $this->prefix . $classMetadata->getTableName()]); foreach ($classMetadata->getAssociationMappings() as $fieldName => $mapping) { if ($mapping['type'] === ClassMetadataInfo::MANY_TO_MANY && isset($classMetadata->associationMappings[$fieldName]['joinTable']['name'])) { $mappedTableName = $classMetadata->associationMappings[$fieldName]['joinTable']['name']; - $classMetadata->associationMappings[$fieldName]['joinTable']['name'] = $this->prefix.$mappedTableName; + $classMetadata->associationMappings[$fieldName]['joinTable']['name'] = $this->prefix . $mappedTableName; } } } diff --git a/src/Wallabag/CoreBundle/Form/Type/EntryFilterType.php b/src/Wallabag/CoreBundle/Form/Type/EntryFilterType.php index 6a4c485f..6f8c9e27 100644 --- a/src/Wallabag/CoreBundle/Form/Type/EntryFilterType.php +++ b/src/Wallabag/CoreBundle/Form/Type/EntryFilterType.php @@ -4,12 +4,12 @@ namespace Wallabag\CoreBundle\Form\Type; use Doctrine\ORM\EntityRepository; use Lexik\Bundle\FormFilterBundle\Filter\FilterOperands; -use Lexik\Bundle\FormFilterBundle\Filter\Query\QueryInterface; -use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\NumberRangeFilterType; -use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\DateRangeFilterType; -use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\TextFilterType; use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\CheckboxFilterType; use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\ChoiceFilterType; +use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\DateRangeFilterType; +use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\NumberRangeFilterType; +use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\TextFilterType; +use Lexik\Bundle\FormFilterBundle\Filter\Query\QueryInterface; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\HttpFoundation\Response; @@ -99,7 +99,7 @@ class EntryFilterType extends AbstractType if (strlen($value) <= 2 || empty($value)) { return; } - $expression = $filterQuery->getExpr()->like($field, $filterQuery->getExpr()->lower($filterQuery->getExpr()->literal('%'.$value.'%'))); + $expression = $filterQuery->getExpr()->like($field, $filterQuery->getExpr()->lower($filterQuery->getExpr()->literal('%' . $value . '%'))); return $filterQuery->createCondition($expression); }, @@ -113,8 +113,8 @@ class EntryFilterType extends AbstractType } $paramName = sprintf('%s', str_replace('.', '_', $field)); - $expression = $filterQuery->getExpr()->eq($field, ':'.$paramName); - $parameters = array($paramName => $value); + $expression = $filterQuery->getExpr()->eq($field, ':' . $paramName); + $parameters = [$paramName => $value]; return $filterQuery->createCondition($expression, $parameters); }, @@ -158,7 +158,7 @@ class EntryFilterType extends AbstractType // is_public isn't a real field // we should use the "uid" field to determine if the entry has been made public - $expression = $filterQuery->getExpr()->isNotNull($values['alias'].'.uid'); + $expression = $filterQuery->getExpr()->isNotNull($values['alias'] . '.uid'); return $filterQuery->createCondition($expression); }, diff --git a/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php b/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php index a79e6ebe..10689c62 100644 --- a/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php +++ b/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php @@ -6,8 +6,8 @@ use BD\GuzzleSiteAuthenticator\SiteConfig\SiteConfig; use BD\GuzzleSiteAuthenticator\SiteConfig\SiteConfigBuilder; use Graby\SiteConfig\ConfigBuilder; use Psr\Log\LoggerInterface; -use Wallabag\CoreBundle\Repository\SiteCredentialRepository; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; +use Wallabag\CoreBundle\Repository\SiteCredentialRepository; class GrabySiteConfigBuilder implements SiteConfigBuilder { @@ -57,7 +57,7 @@ class GrabySiteConfigBuilder implements SiteConfigBuilder { // required by credentials below $host = strtolower($host); - if (substr($host, 0, 4) == 'www.') { + if (substr($host, 0, 4) === 'www.') { $host = substr($host, 4); } diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index 51bb2ca2..ddecd6f4 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -4,12 +4,12 @@ namespace Wallabag\CoreBundle\Helper; use Graby\Graby; use Psr\Log\LoggerInterface; -use Wallabag\CoreBundle\Entity\Entry; -use Wallabag\CoreBundle\Tools\Utils; use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser; use Symfony\Component\Validator\Constraints\Locale as LocaleConstraint; use Symfony\Component\Validator\Constraints\Url as UrlConstraint; use Symfony\Component\Validator\Validator\ValidatorInterface; +use Wallabag\CoreBundle\Entity\Entry; +use Wallabag\CoreBundle\Tools\Utils; /** * This kind of proxy class take care of getting the content from an url @@ -100,7 +100,7 @@ class ContentProxy // is it a timestamp? if (filter_var($date, FILTER_VALIDATE_INT) !== false) { - $date = '@'.$content['date']; + $date = '@' . $content['date']; } try { @@ -189,7 +189,7 @@ class ContentProxy return; } - $this->logger->warning('Language validation failed. '.(string) $errors); + $this->logger->warning('Language validation failed. ' . (string) $errors); } /** @@ -211,6 +211,6 @@ class ContentProxy return; } - $this->logger->warning('PreviewPicture validation failed. '.(string) $errors); + $this->logger->warning('PreviewPicture validation failed. ' . (string) $errors); } } diff --git a/src/Wallabag/CoreBundle/Helper/CryptoProxy.php b/src/Wallabag/CoreBundle/Helper/CryptoProxy.php index e8b19cb9..7d8c9888 100644 --- a/src/Wallabag/CoreBundle/Helper/CryptoProxy.php +++ b/src/Wallabag/CoreBundle/Helper/CryptoProxy.php @@ -2,10 +2,10 @@ namespace Wallabag\CoreBundle\Helper; -use Psr\Log\LoggerInterface; -use Defuse\Crypto\Key; use Defuse\Crypto\Crypto; use Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException; +use Defuse\Crypto\Key; +use Psr\Log\LoggerInterface; /** * This is a proxy to crypt and decrypt password used by SiteCredential entity. @@ -39,7 +39,7 @@ class CryptoProxy */ public function crypt($secretValue) { - $this->logger->debug('Crypto: crypting value: '.$this->mask($secretValue)); + $this->logger->debug('Crypto: crypting value: ' . $this->mask($secretValue)); return Crypto::encrypt($secretValue, $this->loadKey()); } @@ -53,12 +53,12 @@ class CryptoProxy */ public function decrypt($cryptedValue) { - $this->logger->debug('Crypto: decrypting value: '.$this->mask($cryptedValue)); + $this->logger->debug('Crypto: decrypting value: ' . $this->mask($cryptedValue)); try { return Crypto::decrypt($cryptedValue, $this->loadKey()); } catch (WrongKeyOrModifiedCiphertextException $e) { - throw new \RuntimeException('Decrypt fail: '.$e->getMessage()); + throw new \RuntimeException('Decrypt fail: ' . $e->getMessage()); } } @@ -81,6 +81,6 @@ class CryptoProxy */ private function mask($value) { - return strlen($value) > 0 ? $value[0].'*****'.$value[strlen($value) - 1] : 'Empty value'; + return strlen($value) > 0 ? $value[0] . '*****' . $value[strlen($value) - 1] : 'Empty value'; } } diff --git a/src/Wallabag/CoreBundle/Helper/DetectActiveTheme.php b/src/Wallabag/CoreBundle/Helper/DetectActiveTheme.php index 23e98042..9f90ee3e 100644 --- a/src/Wallabag/CoreBundle/Helper/DetectActiveTheme.php +++ b/src/Wallabag/CoreBundle/Helper/DetectActiveTheme.php @@ -44,7 +44,7 @@ class DetectActiveTheme implements DeviceDetectionInterface { $token = $this->tokenStorage->getToken(); - if (is_null($token)) { + if (null === $token) { return $this->defaultTheme; } diff --git a/src/Wallabag/CoreBundle/Helper/DownloadImages.php b/src/Wallabag/CoreBundle/Helper/DownloadImages.php index ed888cdb..252ba57c 100644 --- a/src/Wallabag/CoreBundle/Helper/DownloadImages.php +++ b/src/Wallabag/CoreBundle/Helper/DownloadImages.php @@ -2,12 +2,12 @@ namespace Wallabag\CoreBundle\Helper; -use Psr\Log\LoggerInterface; -use Symfony\Component\DomCrawler\Crawler; use GuzzleHttp\Client; use GuzzleHttp\Message\Response; -use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser; +use Psr\Log\LoggerInterface; +use Symfony\Component\DomCrawler\Crawler; use Symfony\Component\Finder\Finder; +use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser; class DownloadImages { @@ -30,17 +30,6 @@ class DownloadImages $this->setFolder(); } - /** - * Setup base folder where all images are going to be saved. - */ - private function setFolder() - { - // if folder doesn't exist, attempt to create one and store the folder name in property $folder - if (!file_exists($this->baseFolder)) { - mkdir($this->baseFolder, 0755, true); - } - } - /** * Process the html and extract image from it, save them to local and return the updated html. * @@ -97,9 +86,9 @@ class DownloadImages $relativePath = $this->getRelativePath($entryId); } - $this->logger->debug('DownloadImages: working on image: '.$imagePath); + $this->logger->debug('DownloadImages: working on image: ' . $imagePath); - $folderPath = $this->baseFolder.'/'.$relativePath; + $folderPath = $this->baseFolder . '/' . $relativePath; // build image path $absolutePath = $this->getAbsoluteLink($url, $imagePath); @@ -123,7 +112,7 @@ class DownloadImages } $hashImage = hash('crc32', $absolutePath); - $localPath = $folderPath.'/'.$hashImage.'.'.$ext; + $localPath = $folderPath . '/' . $hashImage . '.' . $ext; try { $im = imagecreatefromstring($res->getBody()); @@ -156,7 +145,7 @@ class DownloadImages imagedestroy($im); - return $this->wallabagUrl.'/assets/images/'.$relativePath.'/'.$hashImage.'.'.$ext; + return $this->wallabagUrl . '/assets/images/' . $relativePath . '/' . $hashImage . '.' . $ext; } /** @@ -167,7 +156,7 @@ class DownloadImages public function removeImages($entryId) { $relativePath = $this->getRelativePath($entryId); - $folderPath = $this->baseFolder.'/'.$relativePath; + $folderPath = $this->baseFolder . '/' . $relativePath; $finder = new Finder(); $finder @@ -182,6 +171,17 @@ class DownloadImages @rmdir($folderPath); } + /** + * Setup base folder where all images are going to be saved. + */ + private function setFolder() + { + // if folder doesn't exist, attempt to create one and store the folder name in property $folder + if (!file_exists($this->baseFolder)) { + mkdir($this->baseFolder, 0755, true); + } + } + /** * Generate the folder where we are going to save images based on the entry url. * @@ -192,8 +192,8 @@ class DownloadImages private function getRelativePath($entryId) { $hashId = hash('crc32', $entryId); - $relativePath = $hashId[0].'/'.$hashId[1].'/'.$hashId; - $folderPath = $this->baseFolder.'/'.$relativePath; + $relativePath = $hashId[0] . '/' . $hashId[1] . '/' . $hashId; + $folderPath = $this->baseFolder . '/' . $relativePath; if (!file_exists($folderPath)) { mkdir($folderPath, 0777, true); @@ -270,7 +270,7 @@ class DownloadImages } if (!in_array($ext, ['jpeg', 'jpg', 'gif', 'png'], true)) { - $this->logger->error('DownloadImages: Processed image with not allowed extension. Skipping: '.$imagePath); + $this->logger->error('DownloadImages: Processed image with not allowed extension. Skipping: ' . $imagePath); return false; } diff --git a/src/Wallabag/CoreBundle/Helper/EntriesExport.php b/src/Wallabag/CoreBundle/Helper/EntriesExport.php index 3d36a4c8..cd74cc4f 100644 --- a/src/Wallabag/CoreBundle/Helper/EntriesExport.php +++ b/src/Wallabag/CoreBundle/Helper/EntriesExport.php @@ -63,7 +63,7 @@ class EntriesExport */ public function updateTitle($method) { - $this->title = $method.' articles'; + $this->title = $method . ' articles'; if ('entry' === $method) { $this->title = $this->entries[0]->getTitle(); @@ -81,7 +81,7 @@ class EntriesExport */ public function exportAs($format) { - $functionName = 'produce'.ucfirst($format); + $functionName = 'produce' . ucfirst($format); if (method_exists($this, $functionName)) { return $this->$functionName(); } @@ -106,12 +106,12 @@ class EntriesExport */ $content_start = "\n" - ."\n" - .'' - ."\n" - ."wallabag articles book\n" - ."\n" - ."\n"; + . "\n" + . '' + . "\n" + . "wallabag articles book\n" + . "\n" + . "\n"; $bookEnd = "\n\n"; @@ -164,11 +164,11 @@ class EntriesExport // in filenames, we limit to A-z/0-9 $filename = preg_replace('/[^A-Za-z0-9\-]/', '', $entry->getTitle()); - $chapter = $content_start.$entry->getContent().$bookEnd; - $book->addChapter($entry->getTitle(), htmlspecialchars($filename).'.html', $chapter, true, EPub::EXTERNAL_REF_ADD); + $chapter = $content_start . $entry->getContent() . $bookEnd; + $book->addChapter($entry->getTitle(), htmlspecialchars($filename) . '.html', $chapter, true, EPub::EXTERNAL_REF_ADD); } - $book->addChapter('Notices', 'Cover2.html', $content_start.$this->getExportInformation('PHPePub').$bookEnd); + $book->addChapter('Notices', 'Cover2.html', $content_start . $this->getExportInformation('PHPePub') . $bookEnd); return Response::create( $book->getBook(), @@ -176,7 +176,7 @@ class EntriesExport [ 'Content-Description' => 'File Transfer', 'Content-type' => 'application/epub+zip', - 'Content-Disposition' => 'attachment; filename="'.$this->title.'.epub"', + 'Content-Disposition' => 'attachment; filename="' . $this->title . '.epub"', 'Content-Transfer-Encoding' => 'binary', ] ); @@ -228,7 +228,7 @@ class EntriesExport 'Accept-Ranges' => 'bytes', 'Content-Description' => 'File Transfer', 'Content-type' => 'application/x-mobipocket-ebook', - 'Content-Disposition' => 'attachment; filename="'.$this->title.'.mobi"', + 'Content-Disposition' => 'attachment; filename="' . $this->title . '.mobi"', 'Content-Transfer-Encoding' => 'binary', ] ); @@ -256,7 +256,7 @@ class EntriesExport * Front page */ $pdf->AddPage(); - $intro = '

'.$this->title.'

'.$this->getExportInformation('tcpdf'); + $intro = '

' . $this->title . '

' . $this->getExportInformation('tcpdf'); $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true); @@ -269,7 +269,7 @@ class EntriesExport } $pdf->AddPage(); - $html = '

'.$entry->getTitle().'

'; + $html = '

' . $entry->getTitle() . '

'; $html .= $entry->getContent(); $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true); @@ -284,7 +284,7 @@ class EntriesExport [ 'Content-Description' => 'File Transfer', 'Content-type' => 'application/pdf', - 'Content-Disposition' => 'attachment; filename="'.$this->title.'.pdf"', + 'Content-Disposition' => 'attachment; filename="' . $this->title . '.pdf"', 'Content-Transfer-Encoding' => 'binary', ] ); @@ -330,7 +330,7 @@ class EntriesExport 200, [ 'Content-type' => 'application/csv', - 'Content-Disposition' => 'attachment; filename="'.$this->title.'.csv"', + 'Content-Disposition' => 'attachment; filename="' . $this->title . '.csv"', 'Content-Transfer-Encoding' => 'UTF-8', ] ); @@ -348,7 +348,7 @@ class EntriesExport 200, [ 'Content-type' => 'application/json', - 'Content-Disposition' => 'attachment; filename="'.$this->title.'.json"', + 'Content-Disposition' => 'attachment; filename="' . $this->title . '.json"', 'Content-Transfer-Encoding' => 'UTF-8', ] ); @@ -366,7 +366,7 @@ class EntriesExport 200, [ 'Content-type' => 'application/xml', - 'Content-Disposition' => 'attachment; filename="'.$this->title.'.xml"', + 'Content-Disposition' => 'attachment; filename="' . $this->title . '.xml"', 'Content-Transfer-Encoding' => 'UTF-8', ] ); @@ -382,8 +382,8 @@ class EntriesExport $content = ''; $bar = str_repeat('=', 100); foreach ($this->entries as $entry) { - $content .= "\n\n".$bar."\n\n".$entry->getTitle()."\n\n".$bar."\n\n"; - $content .= trim(preg_replace('/\s+/S', ' ', strip_tags($entry->getContent())))."\n\n"; + $content .= "\n\n" . $bar . "\n\n" . $entry->getTitle() . "\n\n" . $bar . "\n\n"; + $content .= trim(preg_replace('/\s+/S', ' ', strip_tags($entry->getContent()))) . "\n\n"; } return Response::create( @@ -391,7 +391,7 @@ class EntriesExport 200, [ 'Content-type' => 'text/plain', - 'Content-Disposition' => 'attachment; filename="'.$this->title.'.txt"', + 'Content-Disposition' => 'attachment; filename="' . $this->title . '.txt"', 'Content-Transfer-Encoding' => 'UTF-8', ] ); @@ -427,7 +427,7 @@ class EntriesExport $info = str_replace('%EXPORT_METHOD%', $type, $this->footerTemplate); if ('tcpdf' === $type) { - return str_replace('%IMAGE%', '', $info); + return str_replace('%IMAGE%', '', $info); } return str_replace('%IMAGE%', '', $info); diff --git a/src/Wallabag/CoreBundle/Helper/HttpClientFactory.php b/src/Wallabag/CoreBundle/Helper/HttpClientFactory.php index 43f5b119..4602a684 100644 --- a/src/Wallabag/CoreBundle/Helper/HttpClientFactory.php +++ b/src/Wallabag/CoreBundle/Helper/HttpClientFactory.php @@ -41,7 +41,7 @@ class HttpClientFactory */ public function buildHttpClient() { - $this->logger->log('debug', 'Restricted access config enabled?', array('enabled' => (int) $this->restrictedAccess)); + $this->logger->log('debug', 'Restricted access config enabled?', ['enabled' => (int) $this->restrictedAccess]); if (0 === (int) $this->restrictedAccess) { return; diff --git a/src/Wallabag/CoreBundle/Helper/PreparePagerForEntries.php b/src/Wallabag/CoreBundle/Helper/PreparePagerForEntries.php index 231a0b52..49c1ea41 100644 --- a/src/Wallabag/CoreBundle/Helper/PreparePagerForEntries.php +++ b/src/Wallabag/CoreBundle/Helper/PreparePagerForEntries.php @@ -4,9 +4,9 @@ namespace Wallabag\CoreBundle\Helper; use Pagerfanta\Adapter\AdapterInterface; use Pagerfanta\Pagerfanta; -use Wallabag\UserBundle\Entity\User; use Symfony\Component\Routing\Router; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; +use Wallabag\UserBundle\Entity\User; class PreparePagerForEntries { diff --git a/src/Wallabag/CoreBundle/Helper/RuleBasedTagger.php b/src/Wallabag/CoreBundle/Helper/RuleBasedTagger.php index 509d0dec..63f65067 100644 --- a/src/Wallabag/CoreBundle/Helper/RuleBasedTagger.php +++ b/src/Wallabag/CoreBundle/Helper/RuleBasedTagger.php @@ -2,13 +2,13 @@ namespace Wallabag\CoreBundle\Helper; +use Psr\Log\LoggerInterface; use RulerZ\RulerZ; use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Tag; use Wallabag\CoreBundle\Repository\EntryRepository; use Wallabag\CoreBundle\Repository\TagRepository; use Wallabag\UserBundle\Entity\User; -use Psr\Log\LoggerInterface; class RuleBasedTagger { diff --git a/src/Wallabag/CoreBundle/Repository/EntryRepository.php b/src/Wallabag/CoreBundle/Repository/EntryRepository.php index 9bda4e15..a65bfe3b 100644 --- a/src/Wallabag/CoreBundle/Repository/EntryRepository.php +++ b/src/Wallabag/CoreBundle/Repository/EntryRepository.php @@ -10,21 +10,6 @@ use Wallabag\CoreBundle\Entity\Tag; class EntryRepository extends EntityRepository { - /** - * Return a query builder to used by other getBuilderFor* method. - * - * @param int $userId - * - * @return QueryBuilder - */ - private function getBuilderByUser($userId) - { - return $this->createQueryBuilder('e') - ->andWhere('e.user = :userId')->setParameter('userId', $userId) - ->orderBy('e.createdAt', 'desc') - ; - } - /** * Retrieves all entries for a user. * @@ -108,7 +93,7 @@ class EntryRepository extends EntityRepository // We lower() all parts here because PostgreSQL 'LIKE' verb is case-sensitive $qb - ->andWhere('lower(e.content) LIKE lower(:term) OR lower(e.title) LIKE lower(:term) OR lower(e.url) LIKE lower(:term)')->setParameter('term', '%'.$term.'%') + ->andWhere('lower(e.content) LIKE lower(:term) OR lower(e.title) LIKE lower(:term) OR lower(e.url) LIKE lower(:term)')->setParameter('term', '%' . $term . '%') ->leftJoin('e.tags', 't') ->groupBy('e.id'); @@ -158,7 +143,7 @@ class EntryRepository extends EntityRepository } if (null !== $isPublic) { - $qb->andWhere('e.uid IS '.(true === $isPublic ? 'NOT' : '').' NULL'); + $qb->andWhere('e.uid IS ' . (true === $isPublic ? 'NOT' : '') . ' NULL'); } if ($since > 0) { @@ -414,4 +399,19 @@ class EntryRepository extends EntityRepository ->getQuery() ->getResult(); } + + /** + * Return a query builder to used by other getBuilderFor* method. + * + * @param int $userId + * + * @return QueryBuilder + */ + private function getBuilderByUser($userId) + { + return $this->createQueryBuilder('e') + ->andWhere('e.user = :userId')->setParameter('userId', $userId) + ->orderBy('e.createdAt', 'desc') + ; + } } diff --git a/src/Wallabag/CoreBundle/Twig/WallabagExtension.php b/src/Wallabag/CoreBundle/Twig/WallabagExtension.php index a305c53f..351172c4 100644 --- a/src/Wallabag/CoreBundle/Twig/WallabagExtension.php +++ b/src/Wallabag/CoreBundle/Twig/WallabagExtension.php @@ -3,9 +3,9 @@ namespace Wallabag\CoreBundle\Twig; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; +use Symfony\Component\Translation\TranslatorInterface; use Wallabag\CoreBundle\Repository\EntryRepository; use Wallabag\CoreBundle\Repository\TagRepository; -use Symfony\Component\Translation\TranslatorInterface; class WallabagExtension extends \Twig_Extension implements \Twig_Extension_GlobalsInterface { @@ -33,11 +33,11 @@ class WallabagExtension extends \Twig_Extension implements \Twig_Extension_Globa public function getFunctions() { - return array( + return [ new \Twig_SimpleFunction('count_entries', [$this, 'countEntries']), new \Twig_SimpleFunction('count_tags', [$this, 'countTags']), new \Twig_SimpleFunction('display_stats', [$this, 'displayStats']), - ); + ]; } public function removeWww($url) @@ -64,19 +64,15 @@ class WallabagExtension extends \Twig_Extension implements \Twig_Extension_Globa case 'starred': $qb = $this->entryRepository->getBuilderForStarredByUser($user->getId()); break; - case 'archive': $qb = $this->entryRepository->getBuilderForArchiveByUser($user->getId()); break; - case 'unread': $qb = $this->entryRepository->getBuilderForUnreadByUser($user->getId()); break; - case 'all': $qb = $this->entryRepository->getBuilderForAllByUser($user->getId()); break; - default: throw new \InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type)); } @@ -139,7 +135,7 @@ class WallabagExtension extends \Twig_Extension implements \Twig_Extension_Globa $nbDays = (int) $interval->format('%a') ?: 1; // force setlocale for date translation - setlocale(LC_TIME, strtolower($user->getConfig()->getLanguage()).'_'.strtoupper(strtolower($user->getConfig()->getLanguage()))); + setlocale(LC_TIME, strtolower($user->getConfig()->getLanguage()) . '_' . strtoupper(strtolower($user->getConfig()->getLanguage()))); return $this->translator->trans('footer.stats', [ '%user_creation%' => strftime('%e %B %Y', $user->getCreatedAt()->getTimestamp()), diff --git a/src/Wallabag/ImportBundle/Command/ImportCommand.php b/src/Wallabag/ImportBundle/Command/ImportCommand.php index 5f1ab0af..99056c2c 100644 --- a/src/Wallabag/ImportBundle/Command/ImportCommand.php +++ b/src/Wallabag/ImportBundle/Command/ImportCommand.php @@ -5,8 +5,8 @@ namespace Wallabag\ImportBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Config\Definition\Exception\Exception; use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class ImportCommand extends ContainerAwareCommand @@ -27,7 +27,7 @@ class ImportCommand extends ContainerAwareCommand protected function execute(InputInterface $input, OutputInterface $output) { - $output->writeln('Start : '.(new \DateTime())->format('d-m-Y G:i:s').' ---'); + $output->writeln('Start : ' . (new \DateTime())->format('d-m-Y G:i:s') . ' ---'); if (!file_exists($input->getArgument('filepath'))) { throw new Exception(sprintf('File "%s" not found', $input->getArgument('filepath'))); @@ -80,12 +80,12 @@ class ImportCommand extends ContainerAwareCommand if (true === $res) { $summary = $import->getSummary(); - $output->writeln(''.$summary['imported'].' imported'); - $output->writeln(''.$summary['skipped'].' already saved'); + $output->writeln('' . $summary['imported'] . ' imported'); + $output->writeln('' . $summary['skipped'] . ' already saved'); } $em->clear(); - $output->writeln('End : '.(new \DateTime())->format('d-m-Y G:i:s').' ---'); + $output->writeln('End : ' . (new \DateTime())->format('d-m-Y G:i:s') . ' ---'); } } diff --git a/src/Wallabag/ImportBundle/Command/RedisWorkerCommand.php b/src/Wallabag/ImportBundle/Command/RedisWorkerCommand.php index 2d06af44..d94900ad 100644 --- a/src/Wallabag/ImportBundle/Command/RedisWorkerCommand.php +++ b/src/Wallabag/ImportBundle/Command/RedisWorkerCommand.php @@ -2,13 +2,13 @@ namespace Wallabag\ImportBundle\Command; +use Simpleue\Worker\QueueWorker; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Config\Definition\Exception\Exception; use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use Simpleue\Worker\QueueWorker; class RedisWorkerCommand extends ContainerAwareCommand { @@ -24,18 +24,18 @@ class RedisWorkerCommand extends ContainerAwareCommand protected function execute(InputInterface $input, OutputInterface $output) { - $output->writeln('Worker started at: '.(new \DateTime())->format('d-m-Y G:i:s')); + $output->writeln('Worker started at: ' . (new \DateTime())->format('d-m-Y G:i:s')); $output->writeln('Waiting for message ...'); $serviceName = $input->getArgument('serviceName'); - if (!$this->getContainer()->has('wallabag_import.queue.redis.'.$serviceName) || !$this->getContainer()->has('wallabag_import.consumer.redis.'.$serviceName)) { + if (!$this->getContainer()->has('wallabag_import.queue.redis.' . $serviceName) || !$this->getContainer()->has('wallabag_import.consumer.redis.' . $serviceName)) { throw new Exception(sprintf('No queue or consumer found for service name: "%s"', $input->getArgument('serviceName'))); } $worker = new QueueWorker( - $this->getContainer()->get('wallabag_import.queue.redis.'.$serviceName), - $this->getContainer()->get('wallabag_import.consumer.redis.'.$serviceName), + $this->getContainer()->get('wallabag_import.queue.redis.' . $serviceName), + $this->getContainer()->get('wallabag_import.consumer.redis.' . $serviceName), (int) $input->getOption('maxIterations') ); diff --git a/src/Wallabag/ImportBundle/Consumer/AbstractConsumer.php b/src/Wallabag/ImportBundle/Consumer/AbstractConsumer.php index 992ce1ad..b035f5cc 100644 --- a/src/Wallabag/ImportBundle/Consumer/AbstractConsumer.php +++ b/src/Wallabag/ImportBundle/Consumer/AbstractConsumer.php @@ -3,14 +3,14 @@ namespace Wallabag\ImportBundle\Consumer; use Doctrine\ORM\EntityManager; -use Wallabag\ImportBundle\Import\AbstractImport; -use Wallabag\UserBundle\Repository\UserRepository; -use Wallabag\CoreBundle\Entity\Entry; -use Wallabag\CoreBundle\Entity\Tag; use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use Wallabag\CoreBundle\Entity\Entry; +use Wallabag\CoreBundle\Entity\Tag; use Wallabag\CoreBundle\Event\EntrySavedEvent; +use Wallabag\ImportBundle\Import\AbstractImport; +use Wallabag\UserBundle\Repository\UserRepository; abstract class AbstractConsumer { @@ -76,7 +76,7 @@ abstract class AbstractConsumer return false; } - $this->logger->info('Content with url imported! ('.$entry->getUrl().')'); + $this->logger->info('Content with url imported! (' . $entry->getUrl() . ')'); return true; } diff --git a/src/Wallabag/ImportBundle/Controller/BrowserController.php b/src/Wallabag/ImportBundle/Controller/BrowserController.php index e119098f..0753e318 100644 --- a/src/Wallabag/ImportBundle/Controller/BrowserController.php +++ b/src/Wallabag/ImportBundle/Controller/BrowserController.php @@ -2,28 +2,14 @@ namespace Wallabag\ImportBundle\Controller; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; +use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Wallabag\ImportBundle\Form\Type\UploadImportType; abstract class BrowserController extends Controller { - /** - * Return the service to handle the import. - * - * @return \Wallabag\ImportBundle\Import\ImportInterface - */ - abstract protected function getImportService(); - - /** - * Return the template used for the form. - * - * @return string - */ - abstract protected function getImportTemplate(); - /** * @Route("/browser", name="import_browser") * @@ -42,11 +28,11 @@ abstract class BrowserController extends Controller if ($form->isSubmitted() && $form->isValid()) { $file = $form->get('file')->getData(); $markAsRead = $form->get('mark_as_read')->getData(); - $name = $this->getUser()->getId().'.json'; + $name = $this->getUser()->getId() . '.json'; - if (null !== $file && in_array($file->getClientMimeType(), $this->getParameter('wallabag_import.allow_mimetypes')) && $file->move($this->getParameter('wallabag_import.resource_dir'), $name)) { + if (null !== $file && in_array($file->getClientMimeType(), $this->getParameter('wallabag_import.allow_mimetypes'), true) && $file->move($this->getParameter('wallabag_import.resource_dir'), $name)) { $res = $wallabag - ->setFilepath($this->getParameter('wallabag_import.resource_dir').'/'.$name) + ->setFilepath($this->getParameter('wallabag_import.resource_dir') . '/' . $name) ->setMarkAsRead($markAsRead) ->import(); @@ -65,7 +51,7 @@ abstract class BrowserController extends Controller ]); } - unlink($this->getParameter('wallabag_import.resource_dir').'/'.$name); + unlink($this->getParameter('wallabag_import.resource_dir') . '/' . $name); } $this->get('session')->getFlashBag()->add( @@ -74,12 +60,11 @@ abstract class BrowserController extends Controller ); return $this->redirect($this->generateUrl('homepage')); - } else { - $this->get('session')->getFlashBag()->add( + } + $this->get('session')->getFlashBag()->add( 'notice', 'flashes.import.notice.failed_on_file' ); - } } return $this->render($this->getImportTemplate(), [ @@ -87,4 +72,18 @@ abstract class BrowserController extends Controller 'import' => $wallabag, ]); } + + /** + * Return the service to handle the import. + * + * @return \Wallabag\ImportBundle\Import\ImportInterface + */ + abstract protected function getImportService(); + + /** + * Return the template used for the form. + * + * @return string + */ + abstract protected function getImportTemplate(); } diff --git a/src/Wallabag/ImportBundle/Controller/ChromeController.php b/src/Wallabag/ImportBundle/Controller/ChromeController.php index 454f3347..0cb418a1 100644 --- a/src/Wallabag/ImportBundle/Controller/ChromeController.php +++ b/src/Wallabag/ImportBundle/Controller/ChromeController.php @@ -7,6 +7,14 @@ use Symfony\Component\HttpFoundation\Request; class ChromeController extends BrowserController { + /** + * @Route("/chrome", name="import_chrome") + */ + public function indexAction(Request $request) + { + return parent::indexAction($request); + } + /** * {@inheritdoc} */ @@ -30,12 +38,4 @@ class ChromeController extends BrowserController { return 'WallabagImportBundle:Chrome:index.html.twig'; } - - /** - * @Route("/chrome", name="import_chrome") - */ - public function indexAction(Request $request) - { - return parent::indexAction($request); - } } diff --git a/src/Wallabag/ImportBundle/Controller/FirefoxController.php b/src/Wallabag/ImportBundle/Controller/FirefoxController.php index c329b9c4..88697f9d 100644 --- a/src/Wallabag/ImportBundle/Controller/FirefoxController.php +++ b/src/Wallabag/ImportBundle/Controller/FirefoxController.php @@ -7,6 +7,14 @@ use Symfony\Component\HttpFoundation\Request; class FirefoxController extends BrowserController { + /** + * @Route("/firefox", name="import_firefox") + */ + public function indexAction(Request $request) + { + return parent::indexAction($request); + } + /** * {@inheritdoc} */ @@ -30,12 +38,4 @@ class FirefoxController extends BrowserController { return 'WallabagImportBundle:Firefox:index.html.twig'; } - - /** - * @Route("/firefox", name="import_firefox") - */ - public function indexAction(Request $request) - { - return parent::indexAction($request); - } } diff --git a/src/Wallabag/ImportBundle/Controller/ImportController.php b/src/Wallabag/ImportBundle/Controller/ImportController.php index 237c748e..7e4fd174 100644 --- a/src/Wallabag/ImportBundle/Controller/ImportController.php +++ b/src/Wallabag/ImportBundle/Controller/ImportController.php @@ -2,8 +2,8 @@ namespace Wallabag\ImportBundle\Controller; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; +use Symfony\Bundle\FrameworkBundle\Controller\Controller; class ImportController extends Controller { @@ -86,9 +86,9 @@ class ImportController extends Controller private function getTotalMessageInRabbitQueue($importService) { $message = $this - ->get('old_sound_rabbit_mq.import_'.$importService.'_consumer') + ->get('old_sound_rabbit_mq.import_' . $importService . '_consumer') ->getChannel() - ->basic_get('wallabag.import.'.$importService); + ->basic_get('wallabag.import.' . $importService); if (null === $message) { return 0; diff --git a/src/Wallabag/ImportBundle/Controller/InstapaperController.php b/src/Wallabag/ImportBundle/Controller/InstapaperController.php index 0251acb9..550679c3 100644 --- a/src/Wallabag/ImportBundle/Controller/InstapaperController.php +++ b/src/Wallabag/ImportBundle/Controller/InstapaperController.php @@ -2,8 +2,8 @@ namespace Wallabag\ImportBundle\Controller; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; +use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Wallabag\ImportBundle\Form\Type\UploadImportType; @@ -29,11 +29,11 @@ class InstapaperController extends Controller if ($form->isSubmitted() && $form->isValid()) { $file = $form->get('file')->getData(); $markAsRead = $form->get('mark_as_read')->getData(); - $name = 'instapaper_'.$this->getUser()->getId().'.csv'; + $name = 'instapaper_' . $this->getUser()->getId() . '.csv'; - if (null !== $file && in_array($file->getClientMimeType(), $this->getParameter('wallabag_import.allow_mimetypes')) && $file->move($this->getParameter('wallabag_import.resource_dir'), $name)) { + if (null !== $file && in_array($file->getClientMimeType(), $this->getParameter('wallabag_import.allow_mimetypes'), true) && $file->move($this->getParameter('wallabag_import.resource_dir'), $name)) { $res = $instapaper - ->setFilepath($this->getParameter('wallabag_import.resource_dir').'/'.$name) + ->setFilepath($this->getParameter('wallabag_import.resource_dir') . '/' . $name) ->setMarkAsRead($markAsRead) ->import(); @@ -52,7 +52,7 @@ class InstapaperController extends Controller ]); } - unlink($this->getParameter('wallabag_import.resource_dir').'/'.$name); + unlink($this->getParameter('wallabag_import.resource_dir') . '/' . $name); } $this->get('session')->getFlashBag()->add( @@ -61,12 +61,12 @@ class InstapaperController extends Controller ); return $this->redirect($this->generateUrl('homepage')); - } else { - $this->get('session')->getFlashBag()->add( - 'notice', - 'flashes.import.notice.failed_on_file' - ); } + + $this->get('session')->getFlashBag()->add( + 'notice', + 'flashes.import.notice.failed_on_file' + ); } return $this->render('WallabagImportBundle:Instapaper:index.html.twig', [ diff --git a/src/Wallabag/ImportBundle/Controller/PinboardController.php b/src/Wallabag/ImportBundle/Controller/PinboardController.php index d0ad8aa8..0e57fd41 100644 --- a/src/Wallabag/ImportBundle/Controller/PinboardController.php +++ b/src/Wallabag/ImportBundle/Controller/PinboardController.php @@ -2,8 +2,8 @@ namespace Wallabag\ImportBundle\Controller; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; +use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Wallabag\ImportBundle\Form\Type\UploadImportType; @@ -29,11 +29,11 @@ class PinboardController extends Controller if ($form->isSubmitted() && $form->isValid()) { $file = $form->get('file')->getData(); $markAsRead = $form->get('mark_as_read')->getData(); - $name = 'pinboard_'.$this->getUser()->getId().'.json'; + $name = 'pinboard_' . $this->getUser()->getId() . '.json'; - if (null !== $file && in_array($file->getClientMimeType(), $this->getParameter('wallabag_import.allow_mimetypes')) && $file->move($this->getParameter('wallabag_import.resource_dir'), $name)) { + if (null !== $file && in_array($file->getClientMimeType(), $this->getParameter('wallabag_import.allow_mimetypes'), true) && $file->move($this->getParameter('wallabag_import.resource_dir'), $name)) { $res = $pinboard - ->setFilepath($this->getParameter('wallabag_import.resource_dir').'/'.$name) + ->setFilepath($this->getParameter('wallabag_import.resource_dir') . '/' . $name) ->setMarkAsRead($markAsRead) ->import(); @@ -52,7 +52,7 @@ class PinboardController extends Controller ]); } - unlink($this->getParameter('wallabag_import.resource_dir').'/'.$name); + unlink($this->getParameter('wallabag_import.resource_dir') . '/' . $name); } $this->get('session')->getFlashBag()->add( @@ -61,12 +61,12 @@ class PinboardController extends Controller ); return $this->redirect($this->generateUrl('homepage')); - } else { - $this->get('session')->getFlashBag()->add( - 'notice', - 'flashes.import.notice.failed_on_file' - ); } + + $this->get('session')->getFlashBag()->add( + 'notice', + 'flashes.import.notice.failed_on_file' + ); } return $this->render('WallabagImportBundle:Pinboard:index.html.twig', [ diff --git a/src/Wallabag/ImportBundle/Controller/PocketController.php b/src/Wallabag/ImportBundle/Controller/PocketController.php index 56be5cbf..9f28819a 100644 --- a/src/Wallabag/ImportBundle/Controller/PocketController.php +++ b/src/Wallabag/ImportBundle/Controller/PocketController.php @@ -2,33 +2,14 @@ namespace Wallabag\ImportBundle\Controller; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; -use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; -use Symfony\Component\HttpFoundation\Request; +use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\Routing\Generator\UrlGeneratorInterface; class PocketController extends Controller { - /** - * Return Pocket Import Service with or without RabbitMQ enabled. - * - * @return \Wallabag\ImportBundle\Import\PocketImport - */ - private function getPocketImportService() - { - $pocket = $this->get('wallabag_import.pocket.import'); - $pocket->setUser($this->getUser()); - - if ($this->get('craue_config')->get('import_with_rabbitmq')) { - $pocket->setProducer($this->get('old_sound_rabbit_mq.import_pocket_producer')); - } elseif ($this->get('craue_config')->get('import_with_redis')) { - $pocket->setProducer($this->get('wallabag_import.producer.redis.pocket')); - } - - return $pocket; - } - /** * @Route("/pocket", name="import_pocket") */ @@ -70,7 +51,7 @@ class PocketController extends Controller $this->get('session')->set('mark_as_read', $request->request->get('form')['mark_as_read']); return $this->redirect( - 'https://getpocket.com/auth/authorize?request_token='.$requestToken.'&redirect_uri='.$this->generateUrl('import_pocket_callback', [], UrlGeneratorInterface::ABSOLUTE_URL), + 'https://getpocket.com/auth/authorize?request_token=' . $requestToken . '&redirect_uri=' . $this->generateUrl('import_pocket_callback', [], UrlGeneratorInterface::ABSOLUTE_URL), 301 ); } @@ -117,4 +98,23 @@ class PocketController extends Controller return $this->redirect($this->generateUrl('homepage')); } + + /** + * Return Pocket Import Service with or without RabbitMQ enabled. + * + * @return \Wallabag\ImportBundle\Import\PocketImport + */ + private function getPocketImportService() + { + $pocket = $this->get('wallabag_import.pocket.import'); + $pocket->setUser($this->getUser()); + + if ($this->get('craue_config')->get('import_with_rabbitmq')) { + $pocket->setProducer($this->get('old_sound_rabbit_mq.import_pocket_producer')); + } elseif ($this->get('craue_config')->get('import_with_redis')) { + $pocket->setProducer($this->get('wallabag_import.producer.redis.pocket')); + } + + return $pocket; + } } diff --git a/src/Wallabag/ImportBundle/Controller/ReadabilityController.php b/src/Wallabag/ImportBundle/Controller/ReadabilityController.php index aa732ddd..59de24cb 100644 --- a/src/Wallabag/ImportBundle/Controller/ReadabilityController.php +++ b/src/Wallabag/ImportBundle/Controller/ReadabilityController.php @@ -2,8 +2,8 @@ namespace Wallabag\ImportBundle\Controller; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; +use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Wallabag\ImportBundle\Form\Type\UploadImportType; @@ -29,11 +29,11 @@ class ReadabilityController extends Controller if ($form->isSubmitted() && $form->isValid()) { $file = $form->get('file')->getData(); $markAsRead = $form->get('mark_as_read')->getData(); - $name = 'readability_'.$this->getUser()->getId().'.json'; + $name = 'readability_' . $this->getUser()->getId() . '.json'; - if (null !== $file && in_array($file->getClientMimeType(), $this->getParameter('wallabag_import.allow_mimetypes')) && $file->move($this->getParameter('wallabag_import.resource_dir'), $name)) { + if (null !== $file && in_array($file->getClientMimeType(), $this->getParameter('wallabag_import.allow_mimetypes'), true) && $file->move($this->getParameter('wallabag_import.resource_dir'), $name)) { $res = $readability - ->setFilepath($this->getParameter('wallabag_import.resource_dir').'/'.$name) + ->setFilepath($this->getParameter('wallabag_import.resource_dir') . '/' . $name) ->setMarkAsRead($markAsRead) ->import(); @@ -52,7 +52,7 @@ class ReadabilityController extends Controller ]); } - unlink($this->getParameter('wallabag_import.resource_dir').'/'.$name); + unlink($this->getParameter('wallabag_import.resource_dir') . '/' . $name); } $this->get('session')->getFlashBag()->add( @@ -61,12 +61,12 @@ class ReadabilityController extends Controller ); return $this->redirect($this->generateUrl('homepage')); - } else { - $this->get('session')->getFlashBag()->add( - 'notice', - 'flashes.import.notice.failed_on_file' - ); } + + $this->get('session')->getFlashBag()->add( + 'notice', + 'flashes.import.notice.failed_on_file' + ); } return $this->render('WallabagImportBundle:Readability:index.html.twig', [ diff --git a/src/Wallabag/ImportBundle/Controller/WallabagController.php b/src/Wallabag/ImportBundle/Controller/WallabagController.php index e81c1ca9..7b61805b 100644 --- a/src/Wallabag/ImportBundle/Controller/WallabagController.php +++ b/src/Wallabag/ImportBundle/Controller/WallabagController.php @@ -11,20 +11,6 @@ use Wallabag\ImportBundle\Form\Type\UploadImportType; */ abstract class WallabagController extends Controller { - /** - * Return the service to handle the import. - * - * @return \Wallabag\ImportBundle\Import\ImportInterface - */ - abstract protected function getImportService(); - - /** - * Return the template used for the form. - * - * @return string - */ - abstract protected function getImportTemplate(); - /** * Handle import request. * @@ -43,11 +29,11 @@ abstract class WallabagController extends Controller if ($form->isSubmitted() && $form->isValid()) { $file = $form->get('file')->getData(); $markAsRead = $form->get('mark_as_read')->getData(); - $name = $this->getUser()->getId().'.json'; + $name = $this->getUser()->getId() . '.json'; - if (null !== $file && in_array($file->getClientMimeType(), $this->getParameter('wallabag_import.allow_mimetypes')) && $file->move($this->getParameter('wallabag_import.resource_dir'), $name)) { + if (null !== $file && in_array($file->getClientMimeType(), $this->getParameter('wallabag_import.allow_mimetypes'), true) && $file->move($this->getParameter('wallabag_import.resource_dir'), $name)) { $res = $wallabag - ->setFilepath($this->getParameter('wallabag_import.resource_dir').'/'.$name) + ->setFilepath($this->getParameter('wallabag_import.resource_dir') . '/' . $name) ->setMarkAsRead($markAsRead) ->import(); @@ -66,7 +52,7 @@ abstract class WallabagController extends Controller ]); } - unlink($this->getParameter('wallabag_import.resource_dir').'/'.$name); + unlink($this->getParameter('wallabag_import.resource_dir') . '/' . $name); } $this->get('session')->getFlashBag()->add( @@ -75,12 +61,12 @@ abstract class WallabagController extends Controller ); return $this->redirect($this->generateUrl('homepage')); - } else { - $this->get('session')->getFlashBag()->add( - 'notice', - 'flashes.import.notice.failed_on_file' - ); } + + $this->get('session')->getFlashBag()->add( + 'notice', + 'flashes.import.notice.failed_on_file' + ); } return $this->render($this->getImportTemplate(), [ @@ -88,4 +74,18 @@ abstract class WallabagController extends Controller 'import' => $wallabag, ]); } + + /** + * Return the service to handle the import. + * + * @return \Wallabag\ImportBundle\Import\ImportInterface + */ + abstract protected function getImportService(); + + /** + * Return the template used for the form. + * + * @return string + */ + abstract protected function getImportTemplate(); } diff --git a/src/Wallabag/ImportBundle/Controller/WallabagV1Controller.php b/src/Wallabag/ImportBundle/Controller/WallabagV1Controller.php index 312c7a35..d700d8a8 100644 --- a/src/Wallabag/ImportBundle/Controller/WallabagV1Controller.php +++ b/src/Wallabag/ImportBundle/Controller/WallabagV1Controller.php @@ -7,6 +7,14 @@ use Symfony\Component\HttpFoundation\Request; class WallabagV1Controller extends WallabagController { + /** + * @Route("/wallabag-v1", name="import_wallabag_v1") + */ + public function indexAction(Request $request) + { + return parent::indexAction($request); + } + /** * {@inheritdoc} */ @@ -30,12 +38,4 @@ class WallabagV1Controller extends WallabagController { return 'WallabagImportBundle:WallabagV1:index.html.twig'; } - - /** - * @Route("/wallabag-v1", name="import_wallabag_v1") - */ - public function indexAction(Request $request) - { - return parent::indexAction($request); - } } diff --git a/src/Wallabag/ImportBundle/Controller/WallabagV2Controller.php b/src/Wallabag/ImportBundle/Controller/WallabagV2Controller.php index 45211fe6..ab26400c 100644 --- a/src/Wallabag/ImportBundle/Controller/WallabagV2Controller.php +++ b/src/Wallabag/ImportBundle/Controller/WallabagV2Controller.php @@ -7,6 +7,14 @@ use Symfony\Component\HttpFoundation\Request; class WallabagV2Controller extends WallabagController { + /** + * @Route("/wallabag-v2", name="import_wallabag_v2") + */ + public function indexAction(Request $request) + { + return parent::indexAction($request); + } + /** * {@inheritdoc} */ @@ -30,12 +38,4 @@ class WallabagV2Controller extends WallabagController { return 'WallabagImportBundle:WallabagV2:index.html.twig'; } - - /** - * @Route("/wallabag-v2", name="import_wallabag_v2") - */ - public function indexAction(Request $request) - { - return parent::indexAction($request); - } } diff --git a/src/Wallabag/ImportBundle/DependencyInjection/WallabagImportExtension.php b/src/Wallabag/ImportBundle/DependencyInjection/WallabagImportExtension.php index 3f23c36b..cab70297 100644 --- a/src/Wallabag/ImportBundle/DependencyInjection/WallabagImportExtension.php +++ b/src/Wallabag/ImportBundle/DependencyInjection/WallabagImportExtension.php @@ -2,10 +2,10 @@ namespace Wallabag\ImportBundle\DependencyInjection; -use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; -use Symfony\Component\HttpKernel\DependencyInjection\Extension; +use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader; +use Symfony\Component\HttpKernel\DependencyInjection\Extension; class WallabagImportExtension extends Extension { @@ -16,7 +16,7 @@ class WallabagImportExtension extends Extension $container->setParameter('wallabag_import.allow_mimetypes', $config['allow_mimetypes']); $container->setParameter('wallabag_import.resource_dir', $config['resource_dir']); - $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); + $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('services.yml'); } diff --git a/src/Wallabag/ImportBundle/Form/Type/UploadImportType.php b/src/Wallabag/ImportBundle/Form/Type/UploadImportType.php index f50424c1..c50ef8c9 100644 --- a/src/Wallabag/ImportBundle/Form/Type/UploadImportType.php +++ b/src/Wallabag/ImportBundle/Form/Type/UploadImportType.php @@ -3,10 +3,10 @@ namespace Wallabag\ImportBundle\Form\Type; use Symfony\Component\Form\AbstractType; -use Symfony\Component\Form\FormBuilderInterface; -use Symfony\Component\Form\Extension\Core\Type\SubmitType; -use Symfony\Component\Form\Extension\Core\Type\FileType; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; +use Symfony\Component\Form\Extension\Core\Type\FileType; +use Symfony\Component\Form\Extension\Core\Type\SubmitType; +use Symfony\Component\Form\FormBuilderInterface; class UploadImportType extends AbstractType { diff --git a/src/Wallabag/ImportBundle/Import/AbstractImport.php b/src/Wallabag/ImportBundle/Import/AbstractImport.php index 9b624296..cb46db09 100644 --- a/src/Wallabag/ImportBundle/Import/AbstractImport.php +++ b/src/Wallabag/ImportBundle/Import/AbstractImport.php @@ -2,17 +2,17 @@ namespace Wallabag\ImportBundle\Import; +use Doctrine\ORM\EntityManager; +use OldSound\RabbitMqBundle\RabbitMq\ProducerInterface; use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; -use Doctrine\ORM\EntityManager; -use Wallabag\CoreBundle\Helper\ContentProxy; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Tag; +use Wallabag\CoreBundle\Event\EntrySavedEvent; +use Wallabag\CoreBundle\Helper\ContentProxy; use Wallabag\CoreBundle\Helper\TagsAssigner; use Wallabag\UserBundle\Entity\User; -use OldSound\RabbitMqBundle\RabbitMq\ProducerInterface; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; -use Wallabag\CoreBundle\Event\EntrySavedEvent; abstract class AbstractImport implements ImportInterface { @@ -97,6 +97,27 @@ abstract class AbstractImport implements ImportInterface return $this; } + /** + * {@inheritdoc} + */ + public function getSummary() + { + return [ + 'skipped' => $this->skippedEntries, + 'imported' => $this->importedEntries, + 'queued' => $this->queuedEntries, + ]; + } + + /** + * Parse one entry. + * + * @param array $importedEntry + * + * @return Entry + */ + abstract public function parseEntry(array $importedEntry); + /** * Fetch content from the ContentProxy (using graby). * If it fails return the given entry to be saved in all case (to avoid user to loose the content). @@ -195,27 +216,6 @@ abstract class AbstractImport implements ImportInterface } } - /** - * {@inheritdoc} - */ - public function getSummary() - { - return [ - 'skipped' => $this->skippedEntries, - 'imported' => $this->importedEntries, - 'queued' => $this->queuedEntries, - ]; - } - - /** - * Parse one entry. - * - * @param array $importedEntry - * - * @return Entry - */ - abstract public function parseEntry(array $importedEntry); - /** * Set current imported entry to archived / read. * Implementation is different accross all imports. diff --git a/src/Wallabag/ImportBundle/Import/BrowserImport.php b/src/Wallabag/ImportBundle/Import/BrowserImport.php index 71e65e59..f1195824 100644 --- a/src/Wallabag/ImportBundle/Import/BrowserImport.php +++ b/src/Wallabag/ImportBundle/Import/BrowserImport.php @@ -3,8 +3,8 @@ namespace Wallabag\ImportBundle\Import; use Wallabag\CoreBundle\Entity\Entry; -use Wallabag\UserBundle\Entity\User; use Wallabag\CoreBundle\Event\EntrySavedEvent; +use Wallabag\UserBundle\Entity\User; abstract class BrowserImport extends AbstractImport { @@ -73,6 +73,80 @@ abstract class BrowserImport extends AbstractImport return $this; } + /** + * {@inheritdoc} + */ + public function parseEntry(array $importedEntry) + { + if ((!array_key_exists('guid', $importedEntry) || (!array_key_exists('id', $importedEntry))) && is_array(reset($importedEntry))) { + if ($this->producer) { + $this->parseEntriesForProducer($importedEntry); + + return; + } + + $this->parseEntries($importedEntry); + + return; + } + + if (array_key_exists('children', $importedEntry)) { + if ($this->producer) { + $this->parseEntriesForProducer($importedEntry['children']); + + return; + } + + $this->parseEntries($importedEntry['children']); + + return; + } + + if (!array_key_exists('uri', $importedEntry) && !array_key_exists('url', $importedEntry)) { + return; + } + + $url = array_key_exists('uri', $importedEntry) ? $importedEntry['uri'] : $importedEntry['url']; + + $existingEntry = $this->em + ->getRepository('WallabagCoreBundle:Entry') + ->findByUrlAndUserId($url, $this->user->getId()); + + if (false !== $existingEntry) { + ++$this->skippedEntries; + + return; + } + + $data = $this->prepareEntry($importedEntry); + + $entry = new Entry($this->user); + $entry->setUrl($data['url']); + $entry->setTitle($data['title']); + + // update entry with content (in case fetching failed, the given entry will be return) + $this->fetchContent($entry, $data['url'], $data); + + if (array_key_exists('tags', $data)) { + $this->tagsAssigner->assignTagsToEntry( + $entry, + $data['tags'] + ); + } + + $entry->setArchived($data['is_archived']); + + if (!empty($data['created_at'])) { + $dt = new \DateTime(); + $entry->setCreatedAt($dt->setTimestamp($data['created_at'])); + } + + $this->em->persist($entry); + ++$this->importedEntries; + + return $entry; + } + /** * Parse and insert all given entries. * @@ -149,80 +223,6 @@ abstract class BrowserImport extends AbstractImport } } - /** - * {@inheritdoc} - */ - public function parseEntry(array $importedEntry) - { - if ((!array_key_exists('guid', $importedEntry) || (!array_key_exists('id', $importedEntry))) && is_array(reset($importedEntry))) { - if ($this->producer) { - $this->parseEntriesForProducer($importedEntry); - - return; - } - - $this->parseEntries($importedEntry); - - return; - } - - if (array_key_exists('children', $importedEntry)) { - if ($this->producer) { - $this->parseEntriesForProducer($importedEntry['children']); - - return; - } - - $this->parseEntries($importedEntry['children']); - - return; - } - - if (!array_key_exists('uri', $importedEntry) && !array_key_exists('url', $importedEntry)) { - return; - } - - $url = array_key_exists('uri', $importedEntry) ? $importedEntry['uri'] : $importedEntry['url']; - - $existingEntry = $this->em - ->getRepository('WallabagCoreBundle:Entry') - ->findByUrlAndUserId($url, $this->user->getId()); - - if (false !== $existingEntry) { - ++$this->skippedEntries; - - return; - } - - $data = $this->prepareEntry($importedEntry); - - $entry = new Entry($this->user); - $entry->setUrl($data['url']); - $entry->setTitle($data['title']); - - // update entry with content (in case fetching failed, the given entry will be return) - $this->fetchContent($entry, $data['url'], $data); - - if (array_key_exists('tags', $data)) { - $this->tagsAssigner->assignTagsToEntry( - $entry, - $data['tags'] - ); - } - - $entry->setArchived($data['is_archived']); - - if (!empty($data['created_at'])) { - $dt = new \DateTime(); - $entry->setCreatedAt($dt->setTimestamp($data['created_at'])); - } - - $this->em->persist($entry); - ++$this->importedEntries; - - return $entry; - } - /** * {@inheritdoc} */ diff --git a/src/Wallabag/ImportBundle/Import/ChromeImport.php b/src/Wallabag/ImportBundle/Import/ChromeImport.php index 2667890f..e3ba636a 100644 --- a/src/Wallabag/ImportBundle/Import/ChromeImport.php +++ b/src/Wallabag/ImportBundle/Import/ChromeImport.php @@ -45,7 +45,7 @@ class ChromeImport extends BrowserImport 'created_at' => substr($entry['date_added'], 0, 10), ]; - if (array_key_exists('tags', $entry) && $entry['tags'] != '') { + if (array_key_exists('tags', $entry) && $entry['tags'] !== '') { $data['tags'] = $entry['tags']; } diff --git a/src/Wallabag/ImportBundle/Import/FirefoxImport.php b/src/Wallabag/ImportBundle/Import/FirefoxImport.php index c50c69b3..c18e7e93 100644 --- a/src/Wallabag/ImportBundle/Import/FirefoxImport.php +++ b/src/Wallabag/ImportBundle/Import/FirefoxImport.php @@ -45,7 +45,7 @@ class FirefoxImport extends BrowserImport 'created_at' => substr($entry['dateAdded'], 0, 10), ]; - if (array_key_exists('tags', $entry) && $entry['tags'] != '') { + if (array_key_exists('tags', $entry) && $entry['tags'] !== '') { $data['tags'] = $entry['tags']; } diff --git a/src/Wallabag/ImportBundle/Import/ImportCompilerPass.php b/src/Wallabag/ImportBundle/Import/ImportCompilerPass.php index a363a566..d7df0a83 100644 --- a/src/Wallabag/ImportBundle/Import/ImportCompilerPass.php +++ b/src/Wallabag/ImportBundle/Import/ImportCompilerPass.php @@ -2,8 +2,8 @@ namespace Wallabag\ImportBundle\Import; -use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; class ImportCompilerPass implements CompilerPassInterface diff --git a/src/Wallabag/ImportBundle/Import/InstapaperImport.php b/src/Wallabag/ImportBundle/Import/InstapaperImport.php index 3aa12f6f..7d70154a 100644 --- a/src/Wallabag/ImportBundle/Import/InstapaperImport.php +++ b/src/Wallabag/ImportBundle/Import/InstapaperImport.php @@ -72,7 +72,7 @@ class InstapaperImport extends AbstractImport // BUT it can also be the status (since status = folder in Instapaper) // and we don't want archive, unread & starred to become a tag $tags = null; - if (false === in_array($data[3], ['Archive', 'Unread', 'Starred'])) { + if (false === in_array($data[3], ['Archive', 'Unread', 'Starred'], true)) { $tags = [$data[3]]; } diff --git a/src/Wallabag/ImportBundle/Import/PocketImport.php b/src/Wallabag/ImportBundle/Import/PocketImport.php index c1d5b6da..7d38826b 100644 --- a/src/Wallabag/ImportBundle/Import/PocketImport.php +++ b/src/Wallabag/ImportBundle/Import/PocketImport.php @@ -8,11 +8,10 @@ use Wallabag\CoreBundle\Entity\Entry; class PocketImport extends AbstractImport { + const NB_ELEMENTS = 5000; private $client; private $accessToken; - const NB_ELEMENTS = 5000; - /** * Only used for test purpose. * @@ -176,7 +175,7 @@ class PocketImport extends AbstractImport */ public function parseEntry(array $importedEntry) { - $url = isset($importedEntry['resolved_url']) && $importedEntry['resolved_url'] != '' ? $importedEntry['resolved_url'] : $importedEntry['given_url']; + $url = isset($importedEntry['resolved_url']) && $importedEntry['resolved_url'] !== '' ? $importedEntry['resolved_url'] : $importedEntry['given_url']; $existingEntry = $this->em ->getRepository('WallabagCoreBundle:Entry') @@ -195,15 +194,15 @@ class PocketImport extends AbstractImport $this->fetchContent($entry, $url); // 0, 1, 2 - 1 if the item is archived - 2 if the item should be deleted - $entry->setArchived($importedEntry['status'] == 1 || $this->markAsRead); + $entry->setArchived($importedEntry['status'] === 1 || $this->markAsRead); // 0 or 1 - 1 If the item is starred - $entry->setStarred($importedEntry['favorite'] == 1); + $entry->setStarred($importedEntry['favorite'] === 1); $title = 'Untitled'; - if (isset($importedEntry['resolved_title']) && $importedEntry['resolved_title'] != '') { + if (isset($importedEntry['resolved_title']) && $importedEntry['resolved_title'] !== '') { $title = $importedEntry['resolved_title']; - } elseif (isset($importedEntry['given_title']) && $importedEntry['given_title'] != '') { + } elseif (isset($importedEntry['given_title']) && $importedEntry['given_title'] !== '') { $title = $importedEntry['given_title']; } diff --git a/src/Wallabag/ImportBundle/Import/WallabagV1Import.php b/src/Wallabag/ImportBundle/Import/WallabagV1Import.php index 1f0df646..d585d44d 100644 --- a/src/Wallabag/ImportBundle/Import/WallabagV1Import.php +++ b/src/Wallabag/ImportBundle/Import/WallabagV1Import.php @@ -56,12 +56,12 @@ class WallabagV1Import extends WallabagImport // In case of a bad fetch in v1, replace title and content with v2 error strings // If fetching fails again, they will get this instead of the v1 strings - if (in_array($entry['title'], $this->untitled)) { + if (in_array($entry['title'], $this->untitled, true)) { $data['title'] = $this->fetchingErrorMessageTitle; $data['html'] = $this->fetchingErrorMessage; } - if (array_key_exists('tags', $entry) && $entry['tags'] != '') { + if (array_key_exists('tags', $entry) && $entry['tags'] !== '') { $data['tags'] = $entry['tags']; } diff --git a/src/Wallabag/ImportBundle/Redis/Producer.php b/src/Wallabag/ImportBundle/Redis/Producer.php index fedc3e57..c77b5174 100644 --- a/src/Wallabag/ImportBundle/Redis/Producer.php +++ b/src/Wallabag/ImportBundle/Redis/Producer.php @@ -29,7 +29,7 @@ class Producer implements ProducerInterface * @param string $routingKey NOT USED * @param array $additionalProperties NOT USED */ - public function publish($msgBody, $routingKey = '', $additionalProperties = array()) + public function publish($msgBody, $routingKey = '', $additionalProperties = []) { $this->queue->sendJob($msgBody); } diff --git a/src/Wallabag/ImportBundle/WallabagImportBundle.php b/src/Wallabag/ImportBundle/WallabagImportBundle.php index a5ddc1b4..98c2f97b 100644 --- a/src/Wallabag/ImportBundle/WallabagImportBundle.php +++ b/src/Wallabag/ImportBundle/WallabagImportBundle.php @@ -2,8 +2,8 @@ namespace Wallabag\ImportBundle; -use Symfony\Component\HttpKernel\Bundle\Bundle; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\HttpKernel\Bundle\Bundle; use Wallabag\ImportBundle\Import\ImportCompilerPass; class WallabagImportBundle extends Bundle diff --git a/src/Wallabag/UserBundle/Controller/ManageController.php b/src/Wallabag/UserBundle/Controller/ManageController.php index 084f2c67..f3de656f 100644 --- a/src/Wallabag/UserBundle/Controller/ManageController.php +++ b/src/Wallabag/UserBundle/Controller/ManageController.php @@ -7,10 +7,10 @@ use FOS\UserBundle\FOSUserEvents; use Pagerfanta\Adapter\DoctrineORMAdapter; use Pagerfanta\Exception\OutOfRangeCurrentPageException; use Pagerfanta\Pagerfanta; -use Symfony\Component\HttpFoundation\Request; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; +use Symfony\Bundle\FrameworkBundle\Controller\Controller; +use Symfony\Component\HttpFoundation\Request; use Wallabag\UserBundle\Entity\User; use Wallabag\UserBundle\Form\SearchUserType; @@ -48,13 +48,13 @@ class ManageController extends Controller $this->get('translator')->trans('flashes.user.notice.added', ['%username%' => $user->getUsername()]) ); - return $this->redirectToRoute('user_edit', array('id' => $user->getId())); + return $this->redirectToRoute('user_edit', ['id' => $user->getId()]); } - return $this->render('WallabagUserBundle:Manage:new.html.twig', array( + return $this->render('WallabagUserBundle:Manage:new.html.twig', [ 'user' => $user, 'form' => $form->createView(), - )); + ]); } /** @@ -79,15 +79,15 @@ class ManageController extends Controller $this->get('translator')->trans('flashes.user.notice.updated', ['%username%' => $user->getUsername()]) ); - return $this->redirectToRoute('user_edit', array('id' => $user->getId())); + return $this->redirectToRoute('user_edit', ['id' => $user->getId()]); } - return $this->render('WallabagUserBundle:Manage:edit.html.twig', array( + return $this->render('WallabagUserBundle:Manage:edit.html.twig', [ 'user' => $user, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), 'twofactor_auth' => $this->getParameter('twofactor_auth'), - )); + ]); } /** @@ -115,22 +115,6 @@ class ManageController extends Controller return $this->redirectToRoute('user_index'); } - /** - * Creates a form to delete a User entity. - * - * @param User $user The User entity - * - * @return \Symfony\Component\Form\Form The form - */ - private function createDeleteForm(User $user) - { - return $this->createFormBuilder() - ->setAction($this->generateUrl('user_delete', array('id' => $user->getId()))) - ->setMethod('DELETE') - ->getForm() - ; - } - /** * @param Request $request * @param int $page @@ -175,4 +159,20 @@ class ManageController extends Controller 'users' => $pagerFanta, ]); } + + /** + * Creates a form to delete a User entity. + * + * @param User $user The User entity + * + * @return \Symfony\Component\Form\Form The form + */ + private function createDeleteForm(User $user) + { + return $this->createFormBuilder() + ->setAction($this->generateUrl('user_delete', ['id' => $user->getId()])) + ->setMethod('DELETE') + ->getForm() + ; + } } diff --git a/src/Wallabag/UserBundle/DependencyInjection/WallabagUserExtension.php b/src/Wallabag/UserBundle/DependencyInjection/WallabagUserExtension.php index 99040f69..5ca3482e 100644 --- a/src/Wallabag/UserBundle/DependencyInjection/WallabagUserExtension.php +++ b/src/Wallabag/UserBundle/DependencyInjection/WallabagUserExtension.php @@ -2,10 +2,10 @@ namespace Wallabag\UserBundle\DependencyInjection; -use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; -use Symfony\Component\HttpKernel\DependencyInjection\Extension; +use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader; +use Symfony\Component\HttpKernel\DependencyInjection\Extension; class WallabagUserExtension extends Extension { @@ -14,7 +14,7 @@ class WallabagUserExtension extends Extension $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); - $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); + $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('services.yml'); $container->setParameter('wallabag_user.registration_enabled', $config['registration_enabled']); } diff --git a/src/Wallabag/UserBundle/Entity/User.php b/src/Wallabag/UserBundle/Entity/User.php index aba76ca7..20aca298 100644 --- a/src/Wallabag/UserBundle/Entity/User.php +++ b/src/Wallabag/UserBundle/Entity/User.php @@ -4,12 +4,12 @@ namespace Wallabag\UserBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; +use FOS\UserBundle\Model\User as BaseUser; +use JMS\Serializer\Annotation\Accessor; use JMS\Serializer\Annotation\Groups; use JMS\Serializer\Annotation\XmlRoot; -use JMS\Serializer\Annotation\Accessor; use Scheb\TwoFactorBundle\Model\Email\TwoFactorInterface; use Scheb\TwoFactorBundle\Model\TrustedComputerInterface; -use FOS\UserBundle\Model\User as BaseUser; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Component\Security\Core\User\UserInterface; use Wallabag\ApiBundle\Entity\Client; @@ -93,36 +93,36 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf protected $config; /** - * @ORM\Column(type="integer", nullable=true) + * @var ArrayCollection + * + * @ORM\OneToMany(targetEntity="Wallabag\ApiBundle\Entity\Client", mappedBy="user", cascade={"remove"}) */ - private $authCode; + protected $clients; /** - * @var bool + * @see getFirstClient() below * - * @ORM\Column(type="boolean") + * @Groups({"user_api_with_client"}) + * @Accessor(getter="getFirstClient") */ - private $twoFactorAuthentication = false; + protected $default_client; /** - * @ORM\Column(type="json_array", nullable=true) + * @ORM\Column(type="integer", nullable=true) */ - private $trusted; + private $authCode; /** - * @var ArrayCollection + * @var bool * - * @ORM\OneToMany(targetEntity="Wallabag\ApiBundle\Entity\Client", mappedBy="user", cascade={"remove"}) + * @ORM\Column(type="boolean") */ - protected $clients; + private $twoFactorAuthentication = false; /** - * @see getFirstClient() below - * - * @Groups({"user_api_with_client"}) - * @Accessor(getter="getFirstClient") + * @ORM\Column(type="json_array", nullable=true) */ - protected $default_client; + private $trusted; public function __construct() { @@ -137,7 +137,7 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf */ public function timestamps() { - if (is_null($this->createdAt)) { + if (null === $this->createdAt) { $this->createdAt = new \DateTime(); } diff --git a/src/Wallabag/UserBundle/EventListener/AuthenticationFailureListener.php b/src/Wallabag/UserBundle/EventListener/AuthenticationFailureListener.php index 10f13233..18f14a3a 100644 --- a/src/Wallabag/UserBundle/EventListener/AuthenticationFailureListener.php +++ b/src/Wallabag/UserBundle/EventListener/AuthenticationFailureListener.php @@ -35,6 +35,6 @@ class AuthenticationFailureListener implements EventSubscriberInterface { $request = $this->requestStack->getMasterRequest(); - $this->logger->error('Authentication failure for user "'.$request->request->get('_username').'", from IP "'.$request->getClientIp().'", with UA: "'.$request->server->get('HTTP_USER_AGENT').'".'); + $this->logger->error('Authentication failure for user "' . $request->request->get('_username') . '", from IP "' . $request->getClientIp() . '", with UA: "' . $request->server->get('HTTP_USER_AGENT') . '".'); } } diff --git a/src/Wallabag/UserBundle/EventListener/PasswordResettingListener.php b/src/Wallabag/UserBundle/EventListener/PasswordResettingListener.php index 3a7f2637..7df093f1 100644 --- a/src/Wallabag/UserBundle/EventListener/PasswordResettingListener.php +++ b/src/Wallabag/UserBundle/EventListener/PasswordResettingListener.php @@ -2,8 +2,8 @@ namespace Wallabag\UserBundle\EventListener; -use FOS\UserBundle\FOSUserEvents; use FOS\UserBundle\Event\FormEvent; +use FOS\UserBundle\FOSUserEvents; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; diff --git a/src/Wallabag/UserBundle/Form/UserType.php b/src/Wallabag/UserBundle/Form/UserType.php index d8cdbaf9..56fea640 100644 --- a/src/Wallabag/UserBundle/Form/UserType.php +++ b/src/Wallabag/UserBundle/Form/UserType.php @@ -3,12 +3,12 @@ namespace Wallabag\UserBundle\Form; use Symfony\Component\Form\AbstractType; -use Symfony\Component\Form\FormBuilderInterface; -use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; +use Symfony\Component\Form\Extension\Core\Type\EmailType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\TextType; -use Symfony\Component\Form\Extension\Core\Type\EmailType; +use Symfony\Component\Form\FormBuilderInterface; +use Symfony\Component\OptionsResolver\OptionsResolver; class UserType extends AbstractType { @@ -50,8 +50,8 @@ class UserType extends AbstractType */ public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'data_class' => 'Wallabag\UserBundle\Entity\User', - )); + ]); } } diff --git a/src/Wallabag/UserBundle/Mailer/AuthCodeMailer.php b/src/Wallabag/UserBundle/Mailer/AuthCodeMailer.php index 961208f2..aed805c9 100644 --- a/src/Wallabag/UserBundle/Mailer/AuthCodeMailer.php +++ b/src/Wallabag/UserBundle/Mailer/AuthCodeMailer.php @@ -2,8 +2,8 @@ namespace Wallabag\UserBundle\Mailer; -use Scheb\TwoFactorBundle\Model\Email\TwoFactorInterface; use Scheb\TwoFactorBundle\Mailer\AuthCodeMailerInterface; +use Scheb\TwoFactorBundle\Model\Email\TwoFactorInterface; /** * Custom mailer for TwoFactorBundle email. diff --git a/src/Wallabag/UserBundle/Repository/UserRepository.php b/src/Wallabag/UserBundle/Repository/UserRepository.php index 6adbe329..b1d753d2 100644 --- a/src/Wallabag/UserBundle/Repository/UserRepository.php +++ b/src/Wallabag/UserBundle/Repository/UserRepository.php @@ -63,6 +63,6 @@ class UserRepository extends EntityRepository public function getQueryBuilderForSearch($term) { return $this->createQueryBuilder('u') - ->andWhere('lower(u.username) LIKE lower(:term) OR lower(u.email) LIKE lower(:term) OR lower(u.name) LIKE lower(:term)')->setParameter('term', '%'.$term.'%'); + ->andWhere('lower(u.username) LIKE lower(:term) OR lower(u.email) LIKE lower(:term) OR lower(u.name) LIKE lower(:term)')->setParameter('term', '%' . $term . '%'); } } -- cgit v1.2.3