Add a real configuration for CS-Fixer

This commit is contained in:
Jeremy Benoist 2017-07-01 09:52:38 +02:00
parent 822c877949
commit f808b01692
No known key found for this signature in database
GPG key ID: BCA73962457ACC3C
170 changed files with 3147 additions and 3120 deletions

1
.gitignore vendored
View file

@ -13,6 +13,7 @@
/bin/* /bin/*
!/bin/console !/bin/console
!/bin/symfony_requirements !/bin/symfony_requirements
.php_cs.cache
# Parameters # Parameters
/app/config/parameters.yml /app/config/parameters.yml

47
.php_cs Normal file
View file

@ -0,0 +1,47 @@
<?php
return PhpCsFixer\Config::create()
->setRiskyAllowed(true)
->setRules([
'@Symfony' => true,
'@Symfony:risky' => true,
'array_syntax' => [
'syntax' => 'short'
],
'combine_consecutive_unsets' => true,
'heredoc_to_nowdoc' => true,
'no_extra_consecutive_blank_lines' => [
'break',
'continue',
'extra',
'return',
'throw',
'use',
'parenthesis_brace_block',
'square_brace_block',
'curly_brace_block'
],
'no_unreachable_default_argument_value' => true,
'no_useless_else' => true,
'no_useless_return' => true,
'ordered_class_elements' => true,
'ordered_imports' => true,
'php_unit_strict' => true,
'phpdoc_order' => true,
// 'psr4' => true,
'strict_comparison' => true,
'strict_param' => true,
'concat_space' => [
'spacing' => 'one'
],
])
->setFinder(
PhpCsFixer\Finder::create()
->exclude([
'vendor',
'var',
'web'
])
->in(__DIR__)
)
;

View file

@ -1,7 +1,7 @@
<?php <?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\HttpKernel\Kernel;
class AppKernel extends Kernel class AppKernel extends Kernel
{ {
@ -64,17 +64,17 @@ class AppKernel extends Kernel
public function getCacheDir() public function getCacheDir()
{ {
return dirname(__DIR__).'/var/cache/'.$this->getEnvironment(); return dirname(__DIR__) . '/var/cache/' . $this->getEnvironment();
} }
public function getLogDir() public function getLogDir()
{ {
return dirname(__DIR__).'/var/logs'; return dirname(__DIR__) . '/var/logs';
} }
public function registerContainerConfiguration(LoaderInterface $loader) public function registerContainerConfiguration(LoaderInterface $loader)
{ {
$loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml'); $loader->load($this->getRootDir() . '/config/config_' . $this->getEnvironment() . '.yml');
$loader->load(function ($container) { $loader->load(function ($container) {
if ($container->getParameter('use_webpack_dev_server')) { if ($container->getParameter('use_webpack_dev_server')) {
$container->loadFromExtension('framework', [ $container->loadFromExtension('framework', [

View file

@ -22,11 +22,6 @@ class Version20160410190541 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -44,10 +39,10 @@ class Version20160410190541 extends AbstractMigration implements ContainerAwareI
$sharePublic = $this->container $sharePublic = $this->container
->get('doctrine.orm.default_entity_manager') ->get('doctrine.orm.default_entity_manager')
->getConnection() ->getConnection()
->fetchArray('SELECT * FROM '.$this->getTable('craue_config_setting')." WHERE name = 'share_public'"); ->fetchArray('SELECT * FROM ' . $this->getTable('craue_config_setting') . " WHERE name = 'share_public'");
if (false === $sharePublic) { if (false === $sharePublic) {
$this->addSql('INSERT INTO '.$this->getTable('craue_config_setting')." (name, value, section) VALUES ('share_public', '1', 'entry')"); $this->addSql('INSERT INTO ' . $this->getTable('craue_config_setting') . " (name, value, section) VALUES ('share_public', '1', 'entry')");
} }
} }
@ -59,6 +54,11 @@ class Version20160410190541 extends AbstractMigration implements ContainerAwareI
$entryTable = $schema->getTable($this->getTable('entry')); $entryTable = $schema->getTable($this->getTable('entry'));
$entryTable->dropColumn('uid'); $entryTable->dropColumn('uid');
$this->addSql('DELETE FROM '.$this->getTable('craue_config_setting')." WHERE name = 'share_public'"); $this->addSql('DELETE FROM ' . $this->getTable('craue_config_setting') . " WHERE name = 'share_public'");
}
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
} }
} }

View file

@ -22,11 +22,6 @@ class Version20160812120952 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -46,4 +41,9 @@ class Version20160812120952 extends AbstractMigration implements ContainerAwareI
$clientsTable = $schema->getTable($this->getTable('oauth2_clients')); $clientsTable = $schema->getTable($this->getTable('oauth2_clients'));
$clientsTable->dropColumn('name'); $clientsTable->dropColumn('name');
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
}
} }

View file

@ -22,11 +22,6 @@ class Version20160911214952 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -35,19 +30,19 @@ class Version20160911214952 extends AbstractMigration implements ContainerAwareI
$redis = $this->container $redis = $this->container
->get('doctrine.orm.default_entity_manager') ->get('doctrine.orm.default_entity_manager')
->getConnection() ->getConnection()
->fetchArray('SELECT * FROM '.$this->getTable('craue_config_setting')." WHERE name = 'import_with_redis'"); ->fetchArray('SELECT * FROM ' . $this->getTable('craue_config_setting') . " WHERE name = 'import_with_redis'");
if (false === $redis) { if (false === $redis) {
$this->addSql('INSERT INTO '.$this->getTable('craue_config_setting')." (name, value, section) VALUES ('import_with_redis', 0, 'import')"); $this->addSql('INSERT INTO ' . $this->getTable('craue_config_setting') . " (name, value, section) VALUES ('import_with_redis', 0, 'import')");
} }
$rabbitmq = $this->container $rabbitmq = $this->container
->get('doctrine.orm.default_entity_manager') ->get('doctrine.orm.default_entity_manager')
->getConnection() ->getConnection()
->fetchArray('SELECT * FROM '.$this->getTable('craue_config_setting')." WHERE name = 'import_with_rabbitmq'"); ->fetchArray('SELECT * FROM ' . $this->getTable('craue_config_setting') . " WHERE name = 'import_with_rabbitmq'");
if (false === $rabbitmq) { if (false === $rabbitmq) {
$this->addSql('INSERT INTO '.$this->getTable('craue_config_setting')." (name, value, section) VALUES ('import_with_rabbitmq', 0, 'import')"); $this->addSql('INSERT INTO ' . $this->getTable('craue_config_setting') . " (name, value, section) VALUES ('import_with_rabbitmq', 0, 'import')");
} }
$this->skipIf(false !== $rabbitmq && false !== $redis, 'It seems that you already played this migration.'); $this->skipIf(false !== $rabbitmq && false !== $redis, 'It seems that you already played this migration.');
@ -58,7 +53,12 @@ class Version20160911214952 extends AbstractMigration implements ContainerAwareI
*/ */
public function down(Schema $schema) public function down(Schema $schema)
{ {
$this->addSql('DELETE FROM '.$this->getTable('craue_config_setting')." WHERE name = 'import_with_redis';"); $this->addSql('DELETE FROM ' . $this->getTable('craue_config_setting') . " WHERE name = 'import_with_redis';");
$this->addSql('DELETE FROM '.$this->getTable('craue_config_setting')." WHERE name = 'import_with_rabbitmq';"); $this->addSql('DELETE FROM ' . $this->getTable('craue_config_setting') . " WHERE name = 'import_with_rabbitmq';");
}
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
} }
} }

View file

@ -22,11 +22,6 @@ class Version20160916201049 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -37,7 +32,7 @@ class Version20160916201049 extends AbstractMigration implements ContainerAwareI
$this->skipIf($configTable->hasColumn('pocket_consumer_key'), 'It seems that you already played this migration.'); $this->skipIf($configTable->hasColumn('pocket_consumer_key'), 'It seems that you already played this migration.');
$configTable->addColumn('pocket_consumer_key', 'string', ['notnull' => false]); $configTable->addColumn('pocket_consumer_key', 'string', ['notnull' => false]);
$this->addSql('DELETE FROM '.$this->getTable('craue_config_setting')." WHERE name = 'pocket_consumer_key';"); $this->addSql('DELETE FROM ' . $this->getTable('craue_config_setting') . " WHERE name = 'pocket_consumer_key';");
} }
/** /**
@ -47,6 +42,11 @@ class Version20160916201049 extends AbstractMigration implements ContainerAwareI
{ {
$configTable = $schema->getTable($this->getTable('config')); $configTable = $schema->getTable($this->getTable('config'));
$configTable->dropColumn('pocket_consumer_key'); $configTable->dropColumn('pocket_consumer_key');
$this->addSql('INSERT INTO '.$this->getTable('craue_config_setting')." (name, value, section) VALUES ('pocket_consumer_key', NULL, 'import')"); $this->addSql('INSERT INTO ' . $this->getTable('craue_config_setting') . " (name, value, section) VALUES ('pocket_consumer_key', NULL, 'import')");
}
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
} }
} }

View file

@ -3,10 +3,10 @@
namespace Application\Migrations; namespace Application\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration; use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Migrations\SkipMigrationException;
use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\Schema;
use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\DBAL\Migrations\SkipMigrationException;
/** /**
* Added pocket_consumer_key field on wallabag_config. * Added pocket_consumer_key field on wallabag_config.
@ -23,17 +23,12 @@ class Version20161001072726 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
public function up(Schema $schema) public function up(Schema $schema)
{ {
$this->skipIf($this->connection->getDatabasePlatform()->getName() == 'sqlite', 'Migration can only be executed safely on \'mysql\' or \'postgresql\'.'); $this->skipIf($this->connection->getDatabasePlatform()->getName() === 'sqlite', 'Migration can only be executed safely on \'mysql\' or \'postgresql\'.');
// remove all FK from entry_tag // remove all FK from entry_tag
switch ($this->connection->getDatabasePlatform()->getName()) { switch ($this->connection->getDatabasePlatform()->getName()) {
@ -41,16 +36,15 @@ class Version20161001072726 extends AbstractMigration implements ContainerAwareI
$query = $this->connection->query(" $query = $this->connection->query("
SELECT CONSTRAINT_NAME SELECT CONSTRAINT_NAME
FROM information_schema.key_column_usage FROM information_schema.key_column_usage
WHERE TABLE_NAME = '".$this->getTable('entry_tag')."' AND CONSTRAINT_NAME LIKE 'FK_%' WHERE TABLE_NAME = '" . $this->getTable('entry_tag') . "' AND CONSTRAINT_NAME LIKE 'FK_%'
AND TABLE_SCHEMA = '".$this->connection->getDatabase()."'" AND TABLE_SCHEMA = '" . $this->connection->getDatabase() . "'"
); );
$query->execute(); $query->execute();
foreach ($query->fetchAll() as $fk) { foreach ($query->fetchAll() as $fk) {
$this->addSql('ALTER TABLE '.$this->getTable('entry_tag').' DROP FOREIGN KEY '.$fk['CONSTRAINT_NAME']); $this->addSql('ALTER TABLE ' . $this->getTable('entry_tag') . ' DROP FOREIGN KEY ' . $fk['CONSTRAINT_NAME']);
} }
break; break;
case 'postgresql': case 'postgresql':
// http://dba.stackexchange.com/questions/36979/retrieving-all-pk-and-fk // http://dba.stackexchange.com/questions/36979/retrieving-all-pk-and-fk
$query = $this->connection->query(" $query = $this->connection->query("
@ -60,19 +54,19 @@ class Version20161001072726 extends AbstractMigration implements ContainerAwareI
FROM pg_constraint c FROM pg_constraint c
JOIN pg_namespace n ON n.oid = c.connamespace JOIN pg_namespace n ON n.oid = c.connamespace
WHERE contype = 'f' WHERE contype = 'f'
AND conrelid::regclass::text = '".$this->getTable('entry_tag')."' AND conrelid::regclass::text = '" . $this->getTable('entry_tag') . "'
AND n.nspname = 'public';" AND n.nspname = 'public';"
); );
$query->execute(); $query->execute();
foreach ($query->fetchAll() as $fk) { foreach ($query->fetchAll() as $fk) {
$this->addSql('ALTER TABLE '.$this->getTable('entry_tag').' DROP CONSTRAINT '.$fk['conname']); $this->addSql('ALTER TABLE ' . $this->getTable('entry_tag') . ' DROP CONSTRAINT ' . $fk['conname']);
} }
break; break;
} }
$this->addSql('ALTER TABLE '.$this->getTable('entry_tag').' ADD CONSTRAINT FK_entry_tag_entry FOREIGN KEY (entry_id) REFERENCES '.$this->getTable('entry').' (id) ON DELETE CASCADE'); $this->addSql('ALTER TABLE ' . $this->getTable('entry_tag') . ' ADD CONSTRAINT FK_entry_tag_entry FOREIGN KEY (entry_id) REFERENCES ' . $this->getTable('entry') . ' (id) ON DELETE CASCADE');
$this->addSql('ALTER TABLE '.$this->getTable('entry_tag').' ADD CONSTRAINT FK_entry_tag_tag FOREIGN KEY (tag_id) REFERENCES '.$this->getTable('tag').' (id) ON DELETE CASCADE'); $this->addSql('ALTER TABLE ' . $this->getTable('entry_tag') . ' ADD CONSTRAINT FK_entry_tag_tag FOREIGN KEY (tag_id) REFERENCES ' . $this->getTable('tag') . ' (id) ON DELETE CASCADE');
// remove entry FK from annotation // remove entry FK from annotation
@ -81,18 +75,17 @@ class Version20161001072726 extends AbstractMigration implements ContainerAwareI
$query = $this->connection->query(" $query = $this->connection->query("
SELECT CONSTRAINT_NAME SELECT CONSTRAINT_NAME
FROM information_schema.key_column_usage FROM information_schema.key_column_usage
WHERE TABLE_NAME = '".$this->getTable('annotation')."' WHERE TABLE_NAME = '" . $this->getTable('annotation') . "'
AND CONSTRAINT_NAME LIKE 'FK_%' AND CONSTRAINT_NAME LIKE 'FK_%'
AND COLUMN_NAME = 'entry_id' AND COLUMN_NAME = 'entry_id'
AND TABLE_SCHEMA = '".$this->connection->getDatabase()."'" AND TABLE_SCHEMA = '" . $this->connection->getDatabase() . "'"
); );
$query->execute(); $query->execute();
foreach ($query->fetchAll() as $fk) { foreach ($query->fetchAll() as $fk) {
$this->addSql('ALTER TABLE '.$this->getTable('annotation').' DROP FOREIGN KEY '.$fk['CONSTRAINT_NAME']); $this->addSql('ALTER TABLE ' . $this->getTable('annotation') . ' DROP FOREIGN KEY ' . $fk['CONSTRAINT_NAME']);
} }
break; break;
case 'postgresql': case 'postgresql':
// http://dba.stackexchange.com/questions/36979/retrieving-all-pk-and-fk // http://dba.stackexchange.com/questions/36979/retrieving-all-pk-and-fk
$query = $this->connection->query(" $query = $this->connection->query("
@ -102,19 +95,19 @@ class Version20161001072726 extends AbstractMigration implements ContainerAwareI
FROM pg_constraint c FROM pg_constraint c
JOIN pg_namespace n ON n.oid = c.connamespace JOIN pg_namespace n ON n.oid = c.connamespace
WHERE contype = 'f' WHERE contype = 'f'
AND conrelid::regclass::text = '".$this->getTable('annotation')."' AND conrelid::regclass::text = '" . $this->getTable('annotation') . "'
AND n.nspname = 'public' AND n.nspname = 'public'
AND pg_get_constraintdef(c.oid) LIKE '%entry_id%';" AND pg_get_constraintdef(c.oid) LIKE '%entry_id%';"
); );
$query->execute(); $query->execute();
foreach ($query->fetchAll() as $fk) { foreach ($query->fetchAll() as $fk) {
$this->addSql('ALTER TABLE '.$this->getTable('annotation').' DROP CONSTRAINT '.$fk['conname']); $this->addSql('ALTER TABLE ' . $this->getTable('annotation') . ' DROP CONSTRAINT ' . $fk['conname']);
} }
break; break;
} }
$this->addSql('ALTER TABLE '.$this->getTable('annotation').' ADD CONSTRAINT FK_annotation_entry FOREIGN KEY (entry_id) REFERENCES '.$this->getTable('entry').' (id) ON DELETE CASCADE'); $this->addSql('ALTER TABLE ' . $this->getTable('annotation') . ' ADD CONSTRAINT FK_annotation_entry FOREIGN KEY (entry_id) REFERENCES ' . $this->getTable('entry') . ' (id) ON DELETE CASCADE');
} }
/** /**
@ -124,4 +117,9 @@ class Version20161001072726 extends AbstractMigration implements ContainerAwareI
{ {
throw new SkipMigrationException('Too complex ...'); throw new SkipMigrationException('Too complex ...');
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
}
} }

View file

@ -22,11 +22,6 @@ class Version20161022134138 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -34,28 +29,28 @@ class Version20161022134138 extends AbstractMigration implements ContainerAwareI
{ {
$this->skipIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'This migration only apply to MySQL'); $this->skipIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'This migration only apply to MySQL');
$this->addSql('ALTER DATABASE '.$this->connection->getParams()['dbname'].' CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;'); $this->addSql('ALTER DATABASE ' . $this->connection->getParams()['dbname'] . ' CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;');
// convert field length for utf8mb4 // convert field length for utf8mb4
// http://stackoverflow.com/a/31474509/569101 // http://stackoverflow.com/a/31474509/569101
$this->addSql('ALTER TABLE '.$this->getTable('user').' CHANGE confirmation_token confirmation_token VARCHAR(180) DEFAULT NULL;'); $this->addSql('ALTER TABLE ' . $this->getTable('user') . ' CHANGE confirmation_token confirmation_token VARCHAR(180) DEFAULT NULL;');
$this->addSql('ALTER TABLE '.$this->getTable('user').' CHANGE salt salt VARCHAR(180) NOT NULL;'); $this->addSql('ALTER TABLE ' . $this->getTable('user') . ' CHANGE salt salt VARCHAR(180) NOT NULL;');
$this->addSql('ALTER TABLE '.$this->getTable('user').' CHANGE password password VARCHAR(180) NOT NULL;'); $this->addSql('ALTER TABLE ' . $this->getTable('user') . ' CHANGE password password VARCHAR(180) NOT NULL;');
$this->addSql('ALTER TABLE '.$this->getTable('annotation').' CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;'); $this->addSql('ALTER TABLE ' . $this->getTable('annotation') . ' CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;');
$this->addSql('ALTER TABLE '.$this->getTable('entry').' CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;'); $this->addSql('ALTER TABLE ' . $this->getTable('entry') . ' CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;');
$this->addSql('ALTER TABLE '.$this->getTable('tag').' CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;'); $this->addSql('ALTER TABLE ' . $this->getTable('tag') . ' CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;');
$this->addSql('ALTER TABLE '.$this->getTable('user').' CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;'); $this->addSql('ALTER TABLE ' . $this->getTable('user') . ' CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;');
$this->addSql('ALTER TABLE '.$this->getTable('annotation').' CHANGE `text` `text` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;'); $this->addSql('ALTER TABLE ' . $this->getTable('annotation') . ' CHANGE `text` `text` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;');
$this->addSql('ALTER TABLE '.$this->getTable('annotation').' CHANGE `quote` `quote` VARCHAR(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;'); $this->addSql('ALTER TABLE ' . $this->getTable('annotation') . ' CHANGE `quote` `quote` VARCHAR(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;');
$this->addSql('ALTER TABLE '.$this->getTable('entry').' CHANGE `title` `title` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;'); $this->addSql('ALTER TABLE ' . $this->getTable('entry') . ' CHANGE `title` `title` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;');
$this->addSql('ALTER TABLE '.$this->getTable('entry').' CHANGE `content` `content` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;'); $this->addSql('ALTER TABLE ' . $this->getTable('entry') . ' CHANGE `content` `content` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;');
$this->addSql('ALTER TABLE '.$this->getTable('tag').' CHANGE `label` `label` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;'); $this->addSql('ALTER TABLE ' . $this->getTable('tag') . ' CHANGE `label` `label` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;');
$this->addSql('ALTER TABLE '.$this->getTable('user').' CHANGE `name` `name` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;'); $this->addSql('ALTER TABLE ' . $this->getTable('user') . ' CHANGE `name` `name` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;');
} }
/** /**
@ -65,21 +60,26 @@ class Version20161022134138 extends AbstractMigration implements ContainerAwareI
{ {
$this->skipIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'This migration only apply to MySQL'); $this->skipIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'This migration only apply to MySQL');
$this->addSql('ALTER DATABASE '.$this->connection->getParams()['dbname'].' CHARACTER SET = utf8 COLLATE = utf8_unicode_ci;'); $this->addSql('ALTER DATABASE ' . $this->connection->getParams()['dbname'] . ' CHARACTER SET = utf8 COLLATE = utf8_unicode_ci;');
$this->addSql('ALTER TABLE '.$this->getTable('annotation').' CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;'); $this->addSql('ALTER TABLE ' . $this->getTable('annotation') . ' CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;');
$this->addSql('ALTER TABLE '.$this->getTable('entry').' CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;'); $this->addSql('ALTER TABLE ' . $this->getTable('entry') . ' CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;');
$this->addSql('ALTER TABLE '.$this->getTable('tag').' CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;'); $this->addSql('ALTER TABLE ' . $this->getTable('tag') . ' CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;');
$this->addSql('ALTER TABLE '.$this->getTable('user').' CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;'); $this->addSql('ALTER TABLE ' . $this->getTable('user') . ' CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;');
$this->addSql('ALTER TABLE '.$this->getTable('annotation').' CHANGE `text` `text` longtext CHARACTER SET utf8 COLLATE utf8_unicode_ci;'); $this->addSql('ALTER TABLE ' . $this->getTable('annotation') . ' CHANGE `text` `text` longtext CHARACTER SET utf8 COLLATE utf8_unicode_ci;');
$this->addSql('ALTER TABLE '.$this->getTable('annotation').' CHANGE `quote` `quote` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci;'); $this->addSql('ALTER TABLE ' . $this->getTable('annotation') . ' CHANGE `quote` `quote` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci;');
$this->addSql('ALTER TABLE '.$this->getTable('entry').' CHANGE `title` `title` longtext CHARACTER SET utf8 COLLATE utf8_unicode_ci;'); $this->addSql('ALTER TABLE ' . $this->getTable('entry') . ' CHANGE `title` `title` longtext CHARACTER SET utf8 COLLATE utf8_unicode_ci;');
$this->addSql('ALTER TABLE '.$this->getTable('entry').' CHANGE `content` `content` longtext CHARACTER SET utf8 COLLATE utf8_unicode_ci;'); $this->addSql('ALTER TABLE ' . $this->getTable('entry') . ' CHANGE `content` `content` longtext CHARACTER SET utf8 COLLATE utf8_unicode_ci;');
$this->addSql('ALTER TABLE '.$this->getTable('tag').' CHANGE `label` `label` longtext CHARACTER SET utf8 COLLATE utf8_unicode_ci;'); $this->addSql('ALTER TABLE ' . $this->getTable('tag') . ' CHANGE `label` `label` longtext CHARACTER SET utf8 COLLATE utf8_unicode_ci;');
$this->addSql('ALTER TABLE '.$this->getTable('user').' CHANGE `name` `name` longtext CHARACTER SET utf8 COLLATE utf8_unicode_ci;'); $this->addSql('ALTER TABLE ' . $this->getTable('user') . ' CHANGE `name` `name` longtext CHARACTER SET utf8 COLLATE utf8_unicode_ci;');
}
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
} }
} }

View file

@ -24,11 +24,6 @@ class Version20161024212538 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -60,8 +55,13 @@ class Version20161024212538 extends AbstractMigration implements ContainerAwareI
$clientsTable->dropColumn('user_id', 'integer'); $clientsTable->dropColumn('user_id', 'integer');
if ($this->connection->getDatabasePlatform()->getName() != 'sqlite') { if ($this->connection->getDatabasePlatform()->getName() !== 'sqlite') {
$clientsTable->removeForeignKey($this->constraintName); $clientsTable->removeForeignKey($this->constraintName);
} }
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
}
} }

View file

@ -22,11 +22,6 @@ class Version20161031132655 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -35,11 +30,11 @@ class Version20161031132655 extends AbstractMigration implements ContainerAwareI
$images = $this->container $images = $this->container
->get('doctrine.orm.default_entity_manager') ->get('doctrine.orm.default_entity_manager')
->getConnection() ->getConnection()
->fetchArray('SELECT * FROM '.$this->getTable('craue_config_setting')." WHERE name = 'download_images_enabled'"); ->fetchArray('SELECT * FROM ' . $this->getTable('craue_config_setting') . " WHERE name = 'download_images_enabled'");
$this->skipIf(false !== $images, 'It seems that you already played this migration.'); $this->skipIf(false !== $images, 'It seems that you already played this migration.');
$this->addSql('INSERT INTO '.$this->getTable('craue_config_setting')." (name, value, section) VALUES ('download_images_enabled', 0, 'misc')"); $this->addSql('INSERT INTO ' . $this->getTable('craue_config_setting') . " (name, value, section) VALUES ('download_images_enabled', 0, 'misc')");
} }
/** /**
@ -47,6 +42,11 @@ class Version20161031132655 extends AbstractMigration implements ContainerAwareI
*/ */
public function down(Schema $schema) public function down(Schema $schema)
{ {
$this->addSql('DELETE FROM '.$this->getTable('craue_config_setting')." WHERE name = 'download_images_enabled';"); $this->addSql('DELETE FROM ' . $this->getTable('craue_config_setting') . " WHERE name = 'download_images_enabled';");
}
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
} }
} }

View file

@ -24,11 +24,6 @@ class Version20161104073720 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -50,4 +45,9 @@ class Version20161104073720 extends AbstractMigration implements ContainerAwareI
$entryTable->dropIndex($this->indexName); $entryTable->dropIndex($this->indexName);
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
}
} }

View file

@ -22,11 +22,6 @@ class Version20161106113822 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -53,4 +48,9 @@ class Version20161106113822 extends AbstractMigration implements ContainerAwareI
$configTable->dropColumn('action_mark_as_read'); $configTable->dropColumn('action_mark_as_read');
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
}
} }

View file

@ -22,11 +22,6 @@ class Version20161117071626 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -35,19 +30,19 @@ class Version20161117071626 extends AbstractMigration implements ContainerAwareI
$share = $this->container $share = $this->container
->get('doctrine.orm.default_entity_manager') ->get('doctrine.orm.default_entity_manager')
->getConnection() ->getConnection()
->fetchArray('SELECT * FROM '.$this->getTable('craue_config_setting')." WHERE name = 'share_unmark'"); ->fetchArray('SELECT * FROM ' . $this->getTable('craue_config_setting') . " WHERE name = 'share_unmark'");
if (false === $share) { if (false === $share) {
$this->addSql('INSERT INTO '.$this->getTable('craue_config_setting')." (name, value, section) VALUES ('share_unmark', 0, 'entry')"); $this->addSql('INSERT INTO ' . $this->getTable('craue_config_setting') . " (name, value, section) VALUES ('share_unmark', 0, 'entry')");
} }
$unmark = $this->container $unmark = $this->container
->get('doctrine.orm.default_entity_manager') ->get('doctrine.orm.default_entity_manager')
->getConnection() ->getConnection()
->fetchArray('SELECT * FROM '.$this->getTable('craue_config_setting')." WHERE name = 'unmark_url'"); ->fetchArray('SELECT * FROM ' . $this->getTable('craue_config_setting') . " WHERE name = 'unmark_url'");
if (false === $unmark) { if (false === $unmark) {
$this->addSql('INSERT INTO '.$this->getTable('craue_config_setting')." (name, value, section) VALUES ('unmark_url', 'https://unmark.it', 'entry')"); $this->addSql('INSERT INTO ' . $this->getTable('craue_config_setting') . " (name, value, section) VALUES ('unmark_url', 'https://unmark.it', 'entry')");
} }
$this->skipIf(false !== $share && false !== $unmark, 'It seems that you already played this migration.'); $this->skipIf(false !== $share && false !== $unmark, 'It seems that you already played this migration.');
@ -58,7 +53,12 @@ class Version20161117071626 extends AbstractMigration implements ContainerAwareI
*/ */
public function down(Schema $schema) public function down(Schema $schema)
{ {
$this->addSql('DELETE FROM '.$this->getTable('craue_config_setting')." WHERE name = 'share_unmark';"); $this->addSql('DELETE FROM ' . $this->getTable('craue_config_setting') . " WHERE name = 'share_unmark';");
$this->addSql('DELETE FROM '.$this->getTable('craue_config_setting')." WHERE name = 'unmark_url';"); $this->addSql('DELETE FROM ' . $this->getTable('craue_config_setting') . " WHERE name = 'unmark_url';");
}
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
} }
} }

View file

@ -22,11 +22,6 @@ class Version20161118134328 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -53,4 +48,9 @@ class Version20161118134328 extends AbstractMigration implements ContainerAwareI
$entryTable->dropColumn('http_status'); $entryTable->dropColumn('http_status');
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
}
} }

View file

@ -22,11 +22,6 @@ class Version20161122144743 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -35,11 +30,11 @@ class Version20161122144743 extends AbstractMigration implements ContainerAwareI
$access = $this->container $access = $this->container
->get('doctrine.orm.default_entity_manager') ->get('doctrine.orm.default_entity_manager')
->getConnection() ->getConnection()
->fetchArray('SELECT * FROM '.$this->getTable('craue_config_setting')." WHERE name = 'restricted_access'"); ->fetchArray('SELECT * FROM ' . $this->getTable('craue_config_setting') . " WHERE name = 'restricted_access'");
$this->skipIf(false !== $access, 'It seems that you already played this migration.'); $this->skipIf(false !== $access, 'It seems that you already played this migration.');
$this->addSql('INSERT INTO '.$this->getTable('craue_config_setting')." (name, value, section) VALUES ('restricted_access', 0, 'entry')"); $this->addSql('INSERT INTO ' . $this->getTable('craue_config_setting') . " (name, value, section) VALUES ('restricted_access', 0, 'entry')");
} }
/** /**
@ -47,6 +42,11 @@ class Version20161122144743 extends AbstractMigration implements ContainerAwareI
*/ */
public function down(Schema $schema) public function down(Schema $schema)
{ {
$this->addSql('DELETE FROM '.$this->getTable('craue_config_setting')." WHERE name = 'restricted_access';"); $this->addSql('DELETE FROM ' . $this->getTable('craue_config_setting') . " WHERE name = 'restricted_access';");
}
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
} }
} }

View file

@ -30,11 +30,6 @@ class Version20161122203647 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -60,4 +55,9 @@ class Version20161122203647 extends AbstractMigration implements ContainerAwareI
$userTable->addColumn('expired', 'smallint', ['notnull' => false]); $userTable->addColumn('expired', 'smallint', ['notnull' => false]);
$userTable->addColumn('credentials_expired', 'smallint', ['notnull' => false]); $userTable->addColumn('credentials_expired', 'smallint', ['notnull' => false]);
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
}
} }

View file

@ -22,11 +22,6 @@ class Version20161128084725 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -46,4 +41,9 @@ class Version20161128084725 extends AbstractMigration implements ContainerAwareI
$configTable = $schema->getTable($this->getTable('config')); $configTable = $schema->getTable($this->getTable('config'));
$configTable->dropColumn('list_mode'); $configTable->dropColumn('list_mode');
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
}
} }

View file

@ -28,11 +28,6 @@ class Version20161128131503 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -58,4 +53,9 @@ class Version20161128131503 extends AbstractMigration implements ContainerAwareI
$userTable->addColumn($field, $type, ['notnull' => false]); $userTable->addColumn($field, $type, ['notnull' => false]);
} }
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
}
} }

View file

@ -22,11 +22,6 @@ class Version20161214094402 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -38,17 +33,17 @@ class Version20161214094402 extends AbstractMigration implements ContainerAwareI
switch ($this->connection->getDatabasePlatform()->getName()) { switch ($this->connection->getDatabasePlatform()->getName()) {
case 'sqlite': case 'sqlite':
$this->addSql('CREATE TEMPORARY TABLE __temp__wallabag_entry AS SELECT id, user_id, uuid, title, url, is_archived, is_starred, content, created_at, updated_at, mimetype, language, reading_time, domain_name, preview_picture, is_public FROM '.$this->getTable('entry')); $this->addSql('CREATE TEMPORARY TABLE __temp__wallabag_entry AS SELECT id, user_id, uuid, title, url, is_archived, is_starred, content, created_at, updated_at, mimetype, language, reading_time, domain_name, preview_picture, is_public FROM ' . $this->getTable('entry'));
$this->addSql('DROP TABLE '.$this->getTable('entry')); $this->addSql('DROP TABLE ' . $this->getTable('entry'));
$this->addSql('CREATE TABLE '.$this->getTable('entry').' (id INTEGER NOT NULL, user_id INTEGER DEFAULT NULL, uid CLOB DEFAULT NULL COLLATE BINARY, title CLOB DEFAULT NULL COLLATE BINARY, url CLOB DEFAULT NULL COLLATE BINARY, is_archived BOOLEAN NOT NULL, is_starred BOOLEAN NOT NULL, content CLOB DEFAULT NULL COLLATE BINARY, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL, mimetype CLOB DEFAULT NULL COLLATE BINARY, language CLOB DEFAULT NULL COLLATE BINARY, reading_time INTEGER DEFAULT NULL, domain_name CLOB DEFAULT NULL COLLATE BINARY, preview_picture CLOB DEFAULT NULL COLLATE BINARY, is_public BOOLEAN DEFAULT "0", PRIMARY KEY(id));'); $this->addSql('CREATE TABLE ' . $this->getTable('entry') . ' (id INTEGER NOT NULL, user_id INTEGER DEFAULT NULL, uid CLOB DEFAULT NULL COLLATE BINARY, title CLOB DEFAULT NULL COLLATE BINARY, url CLOB DEFAULT NULL COLLATE BINARY, is_archived BOOLEAN NOT NULL, is_starred BOOLEAN NOT NULL, content CLOB DEFAULT NULL COLLATE BINARY, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL, mimetype CLOB DEFAULT NULL COLLATE BINARY, language CLOB DEFAULT NULL COLLATE BINARY, reading_time INTEGER DEFAULT NULL, domain_name CLOB DEFAULT NULL COLLATE BINARY, preview_picture CLOB DEFAULT NULL COLLATE BINARY, is_public BOOLEAN DEFAULT "0", PRIMARY KEY(id));');
$this->addSql('INSERT INTO '.$this->getTable('entry').' (id, user_id, uid, title, url, is_archived, is_starred, content, created_at, updated_at, mimetype, language, reading_time, domain_name, preview_picture, is_public) SELECT id, user_id, uuid, title, url, is_archived, is_starred, content, created_at, updated_at, mimetype, language, reading_time, domain_name, preview_picture, is_public FROM __temp__wallabag_entry;'); $this->addSql('INSERT INTO ' . $this->getTable('entry') . ' (id, user_id, uid, title, url, is_archived, is_starred, content, created_at, updated_at, mimetype, language, reading_time, domain_name, preview_picture, is_public) SELECT id, user_id, uuid, title, url, is_archived, is_starred, content, created_at, updated_at, mimetype, language, reading_time, domain_name, preview_picture, is_public FROM __temp__wallabag_entry;');
$this->addSql('DROP TABLE __temp__wallabag_entry'); $this->addSql('DROP TABLE __temp__wallabag_entry');
break; break;
case 'mysql': case 'mysql':
$this->addSql('ALTER TABLE '.$this->getTable('entry').' CHANGE uuid uid VARCHAR(23)'); $this->addSql('ALTER TABLE ' . $this->getTable('entry') . ' CHANGE uuid uid VARCHAR(23)');
break; break;
case 'postgresql': case 'postgresql':
$this->addSql('ALTER TABLE '.$this->getTable('entry').' RENAME uuid TO uid'); $this->addSql('ALTER TABLE ' . $this->getTable('entry') . ' RENAME uuid TO uid');
} }
} }
@ -66,10 +61,15 @@ class Version20161214094402 extends AbstractMigration implements ContainerAwareI
throw new SkipMigrationException('Too complex ...'); throw new SkipMigrationException('Too complex ...');
break; break;
case 'mysql': case 'mysql':
$this->addSql('ALTER TABLE '.$this->getTable('entry').' CHANGE uid uuid VARCHAR(23)'); $this->addSql('ALTER TABLE ' . $this->getTable('entry') . ' CHANGE uid uuid VARCHAR(23)');
break; break;
case 'postgresql': case 'postgresql':
$this->addSql('ALTER TABLE '.$this->getTable('entry').' RENAME uid TO uuid'); $this->addSql('ALTER TABLE ' . $this->getTable('entry') . ' RENAME uid TO uuid');
} }
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
}
} }

View file

@ -24,11 +24,6 @@ class Version20161214094403 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -50,4 +45,9 @@ class Version20161214094403 extends AbstractMigration implements ContainerAwareI
$entryTable->dropIndex($this->indexName); $entryTable->dropIndex($this->indexName);
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
}
} }

View file

@ -25,11 +25,6 @@ class Version20170127093841 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -53,4 +48,9 @@ class Version20170127093841 extends AbstractMigration implements ContainerAwareI
$entryTable->dropIndex($this->indexStarredName); $entryTable->dropIndex($this->indexStarredName);
$entryTable->dropIndex($this->indexArchivedName); $entryTable->dropIndex($this->indexArchivedName);
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
}
} }

View file

@ -22,11 +22,6 @@ class Version20170327194233 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -35,12 +30,12 @@ class Version20170327194233 extends AbstractMigration implements ContainerAwareI
$scuttle = $this->container $scuttle = $this->container
->get('doctrine.orm.default_entity_manager') ->get('doctrine.orm.default_entity_manager')
->getConnection() ->getConnection()
->fetchArray('SELECT * FROM '.$this->getTable('craue_config_setting')." WHERE name = 'share_scuttle'"); ->fetchArray('SELECT * FROM ' . $this->getTable('craue_config_setting') . " WHERE name = 'share_scuttle'");
$this->skipIf(false !== $scuttle, 'It seems that you already played this migration.'); $this->skipIf(false !== $scuttle, 'It seems that you already played this migration.');
$this->addSql('INSERT INTO '.$this->getTable('craue_config_setting')." (name, value, section) VALUES ('share_scuttle', '1', 'entry')"); $this->addSql('INSERT INTO ' . $this->getTable('craue_config_setting') . " (name, value, section) VALUES ('share_scuttle', '1', 'entry')");
$this->addSql('INSERT INTO '.$this->getTable('craue_config_setting')." (name, value, section) VALUES ('scuttle_url', 'http://scuttle.org', 'entry')"); $this->addSql('INSERT INTO ' . $this->getTable('craue_config_setting') . " (name, value, section) VALUES ('scuttle_url', 'http://scuttle.org', 'entry')");
} }
/** /**
@ -48,7 +43,12 @@ class Version20170327194233 extends AbstractMigration implements ContainerAwareI
*/ */
public function down(Schema $schema) public function down(Schema $schema)
{ {
$this->addSql('DELETE FROM '.$this->getTable('craue_config_setting')." WHERE name = 'share_scuttle';"); $this->addSql('DELETE FROM ' . $this->getTable('craue_config_setting') . " WHERE name = 'share_scuttle';");
$this->addSql('DELETE FROM '.$this->getTable('craue_config_setting')." WHERE name = 'scuttle_url';"); $this->addSql('DELETE FROM ' . $this->getTable('craue_config_setting') . " WHERE name = 'scuttle_url';");
}
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
} }
} }

View file

@ -22,11 +22,6 @@ class Version20170405182620 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -62,4 +57,9 @@ class Version20170405182620 extends AbstractMigration implements ContainerAwareI
$entryTable->dropColumn('published_by'); $entryTable->dropColumn('published_by');
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
}
} }

View file

@ -22,11 +22,6 @@ class Version20170407200919 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -48,4 +43,9 @@ class Version20170407200919 extends AbstractMigration implements ContainerAwareI
$entryTable->addColumn('is_public', 'boolean', ['notnull' => false, 'default' => 0]); $entryTable->addColumn('is_public', 'boolean', ['notnull' => false, 'default' => 0]);
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
}
} }

View file

@ -22,17 +22,12 @@ class Version20170420134133 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
public function up(Schema $schema) public function up(Schema $schema)
{ {
$this->addSql('DELETE FROM '.$this->getTable('craue_config_setting')." WHERE name = 'download_pictures';"); $this->addSql('DELETE FROM ' . $this->getTable('craue_config_setting') . " WHERE name = 'download_pictures';");
} }
/** /**
@ -43,10 +38,15 @@ class Version20170420134133 extends AbstractMigration implements ContainerAwareI
$downloadPictures = $this->container $downloadPictures = $this->container
->get('doctrine.orm.default_entity_manager') ->get('doctrine.orm.default_entity_manager')
->getConnection() ->getConnection()
->fetchArray('SELECT * FROM '.$this->getTable('craue_config_setting')." WHERE name = 'download_pictures'"); ->fetchArray('SELECT * FROM ' . $this->getTable('craue_config_setting') . " WHERE name = 'download_pictures'");
$this->skipIf(false !== $downloadPictures, 'It seems that you already played this migration.'); $this->skipIf(false !== $downloadPictures, 'It seems that you already played this migration.');
$this->addSql('INSERT INTO '.$this->getTable('craue_config_setting')." (name, value, section) VALUES ('download_pictures', '1', 'entry')"); $this->addSql('INSERT INTO ' . $this->getTable('craue_config_setting') . " (name, value, section) VALUES ('download_pictures', '1', 'entry')");
}
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
} }
} }

View file

@ -8,7 +8,7 @@ use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerInterface;
/** /**
* Add site credential table to store username & password for some website (behind authentication or paywall) * Add site credential table to store username & password for some website (behind authentication or paywall).
*/ */
class Version20170501115751 extends AbstractMigration implements ContainerAwareInterface class Version20170501115751 extends AbstractMigration implements ContainerAwareInterface
{ {
@ -22,11 +22,6 @@ class Version20170501115751 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -58,4 +53,9 @@ class Version20170501115751 extends AbstractMigration implements ContainerAwareI
{ {
$schema->dropTable($this->getTable('site_credential')); $schema->dropTable($this->getTable('site_credential'));
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
}
} }

View file

@ -29,11 +29,6 @@ class Version20170510082609 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -42,7 +37,7 @@ class Version20170510082609 extends AbstractMigration implements ContainerAwareI
$this->skipIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'This migration only apply to MySQL'); $this->skipIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'This migration only apply to MySQL');
foreach ($this->fields as $field) { foreach ($this->fields as $field) {
$this->addSql('ALTER TABLE '.$this->getTable('user').' CHANGE '.$field.' '.$field.' VARCHAR(180) NOT NULL;'); $this->addSql('ALTER TABLE ' . $this->getTable('user') . ' CHANGE ' . $field . ' ' . $field . ' VARCHAR(180) NOT NULL;');
} }
} }
@ -54,7 +49,12 @@ class Version20170510082609 extends AbstractMigration implements ContainerAwareI
$this->skipIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'This migration only apply to MySQL'); $this->skipIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'This migration only apply to MySQL');
foreach ($this->fields as $field) { foreach ($this->fields as $field) {
$this->addSql('ALTER TABLE '.$this->getTable('user').' CHANGE '.$field.' '.$field.' VARCHAR(255) NOT NULL;'); $this->addSql('ALTER TABLE ' . $this->getTable('user') . ' CHANGE ' . $field . ' ' . $field . ' VARCHAR(255) NOT NULL;');
} }
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
}
} }

View file

@ -22,11 +22,6 @@ class Version20170511115400 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -52,4 +47,9 @@ class Version20170511115400 extends AbstractMigration implements ContainerAwareI
$entryTable->dropColumn('headers'); $entryTable->dropColumn('headers');
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
}
} }

View file

@ -9,7 +9,7 @@ use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerInterface;
/** /**
* Increase the length of the "quote" column of "annotation" table * Increase the length of the "quote" column of "annotation" table.
*/ */
class Version20170511211659 extends AbstractMigration implements ContainerAwareInterface class Version20170511211659 extends AbstractMigration implements ContainerAwareInterface
{ {
@ -23,11 +23,6 @@ class Version20170511211659 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
}
public function up(Schema $schema) public function up(Schema $schema)
{ {
$tableName = $this->getTable('annotation'); $tableName = $this->getTable('annotation');
@ -68,13 +63,11 @@ EOD
); );
$this->addSql('DROP TABLE __temp__wallabag_annotation'); $this->addSql('DROP TABLE __temp__wallabag_annotation');
break; break;
case 'mysql': case 'mysql':
$this->addSql('ALTER TABLE '.$tableName.' MODIFY quote TEXT NOT NULL'); $this->addSql('ALTER TABLE ' . $tableName . ' MODIFY quote TEXT NOT NULL');
break; break;
case 'postgresql': case 'postgresql':
$this->addSql('ALTER TABLE '.$tableName.' ALTER COLUMN quote TYPE TEXT'); $this->addSql('ALTER TABLE ' . $tableName . ' ALTER COLUMN quote TYPE TEXT');
break; break;
} }
} }
@ -87,14 +80,17 @@ EOD
case 'sqlite': case 'sqlite':
throw new SkipMigrationException('Too complex ...'); throw new SkipMigrationException('Too complex ...');
break; break;
case 'mysql': case 'mysql':
$this->addSql('ALTER TABLE '.$tableName.' MODIFY quote VARCHAR(255) NOT NULL'); $this->addSql('ALTER TABLE ' . $tableName . ' MODIFY quote VARCHAR(255) NOT NULL');
break; break;
case 'postgresql': case 'postgresql':
$this->addSql('ALTER TABLE '.$tableName.' ALTER COLUMN quote TYPE VARCHAR(255)'); $this->addSql('ALTER TABLE ' . $tableName . ' ALTER COLUMN quote TYPE VARCHAR(255)');
break; break;
} }
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
}
} }

View file

@ -22,11 +22,6 @@ class Version20170602075214 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -35,11 +30,11 @@ class Version20170602075214 extends AbstractMigration implements ContainerAwareI
$apiUserRegistration = $this->container $apiUserRegistration = $this->container
->get('doctrine.orm.default_entity_manager') ->get('doctrine.orm.default_entity_manager')
->getConnection() ->getConnection()
->fetchArray('SELECT * FROM '.$this->getTable('craue_config_setting')." WHERE name = 'api_user_registration'"); ->fetchArray('SELECT * FROM ' . $this->getTable('craue_config_setting') . " WHERE name = 'api_user_registration'");
$this->skipIf(false !== $apiUserRegistration, 'It seems that you already played this migration.'); $this->skipIf(false !== $apiUserRegistration, 'It seems that you already played this migration.');
$this->addSql('INSERT INTO '.$this->getTable('craue_config_setting')." (name, value, section) VALUES ('api_user_registration', '0', 'api')"); $this->addSql('INSERT INTO ' . $this->getTable('craue_config_setting') . " (name, value, section) VALUES ('api_user_registration', '0', 'api')");
} }
/** /**
@ -47,6 +42,11 @@ class Version20170602075214 extends AbstractMigration implements ContainerAwareI
*/ */
public function down(Schema $schema) public function down(Schema $schema)
{ {
$this->addSql('DELETE FROM '.$this->getTable('craue_config_setting')." WHERE name = 'api_user_registration';"); $this->addSql('DELETE FROM ' . $this->getTable('craue_config_setting') . " WHERE name = 'api_user_registration';");
}
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
} }
} }

View file

@ -9,7 +9,7 @@ use Symfony\Component\DependencyInjection\ContainerInterface;
/** /**
* Remove wallabag_url from craue_config_setting. * Remove wallabag_url from craue_config_setting.
* It has been moved into the parameters.yml * It has been moved into the parameters.yml.
*/ */
class Version20170606155640 extends AbstractMigration implements ContainerAwareInterface class Version20170606155640 extends AbstractMigration implements ContainerAwareInterface
{ {
@ -23,11 +23,6 @@ class Version20170606155640 extends AbstractMigration implements ContainerAwareI
$this->container = $container; $this->container = $container;
} }
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix').$tableName;
}
/** /**
* @param Schema $schema * @param Schema $schema
*/ */
@ -36,11 +31,11 @@ class Version20170606155640 extends AbstractMigration implements ContainerAwareI
$apiUserRegistration = $this->container $apiUserRegistration = $this->container
->get('doctrine.orm.default_entity_manager') ->get('doctrine.orm.default_entity_manager')
->getConnection() ->getConnection()
->fetchArray('SELECT * FROM '.$this->getTable('craue_config_setting')." WHERE name = 'wallabag_url'"); ->fetchArray('SELECT * FROM ' . $this->getTable('craue_config_setting') . " WHERE name = 'wallabag_url'");
$this->skipIf(false === $apiUserRegistration, 'It seems that you already played this migration.'); $this->skipIf(false === $apiUserRegistration, 'It seems that you already played this migration.');
$this->addSql('DELETE FROM '.$this->getTable('craue_config_setting')." WHERE name = 'wallabag_url'"); $this->addSql('DELETE FROM ' . $this->getTable('craue_config_setting') . " WHERE name = 'wallabag_url'");
} }
/** /**
@ -48,6 +43,11 @@ class Version20170606155640 extends AbstractMigration implements ContainerAwareI
*/ */
public function down(Schema $schema) public function down(Schema $schema)
{ {
$this->addSql('INSERT INTO '.$this->getTable('craue_config_setting')." (name, value, section) VALUES ('wallabag_url', 'wallabag.me', 'misc')"); $this->addSql('INSERT INTO ' . $this->getTable('craue_config_setting') . " (name, value, section) VALUES ('wallabag_url', 'wallabag.me', 'misc')");
}
private function getTable($tableName)
{
return $this->container->getParameter('database_table_prefix') . $tableName;
} }
} }

View file

@ -1,12 +1,12 @@
<?php <?php
use Doctrine\Common\Annotations\AnnotationRegistry;
use Composer\Autoload\ClassLoader; use Composer\Autoload\ClassLoader;
use Doctrine\Common\Annotations\AnnotationRegistry;
/** /**
* @var ClassLoader $loader * @var ClassLoader
*/ */
$loader = require __DIR__.'/../vendor/autoload.php'; $loader = require __DIR__ . '/../vendor/autoload.php';
AnnotationRegistry::registerLoader([$loader, 'loadClass']); AnnotationRegistry::registerLoader([$loader, 'loadClass']);

View file

@ -91,7 +91,7 @@
"doctrine/data-fixtures": "~1.1.1", "doctrine/data-fixtures": "~1.1.1",
"sensio/generator-bundle": "^3.0", "sensio/generator-bundle": "^3.0",
"symfony/phpunit-bridge": "^3.3", "symfony/phpunit-bridge": "^3.3",
"friendsofphp/php-cs-fixer": "~1.9", "friendsofphp/php-cs-fixer": "~2.0",
"m6web/redis-mock": "^2.0", "m6web/redis-mock": "^2.0",
"dama/doctrine-test-bundle": "^1.0" "dama/doctrine-test-bundle": "^1.0"
}, },

View file

@ -3,9 +3,9 @@
namespace Wallabag\AnnotationBundle\Controller; namespace Wallabag\AnnotationBundle\Controller;
use FOS\RestBundle\Controller\FOSRestController; use FOS\RestBundle\Controller\FOSRestController;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Wallabag\AnnotationBundle\Entity\Annotation; use Wallabag\AnnotationBundle\Entity\Annotation;
use Wallabag\AnnotationBundle\Form\EditAnnotationType; use Wallabag\AnnotationBundle\Form\EditAnnotationType;
use Wallabag\AnnotationBundle\Form\NewAnnotationType; use Wallabag\AnnotationBundle\Form\NewAnnotationType;

View file

@ -3,14 +3,14 @@
namespace Wallabag\AnnotationBundle\Entity; namespace Wallabag\AnnotationBundle\Entity;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Exclude; use JMS\Serializer\Annotation\Exclude;
use JMS\Serializer\Annotation\VirtualProperty; use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\SerializedName;
use JMS\Serializer\Annotation\Groups; use JMS\Serializer\Annotation\Groups;
use JMS\Serializer\Annotation\SerializedName;
use JMS\Serializer\Annotation\VirtualProperty;
use Symfony\Component\Validator\Constraints as Assert; use Symfony\Component\Validator\Constraints as Assert;
use Wallabag\UserBundle\Entity\User;
use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Entry;
use Wallabag\UserBundle\Entity\User;
/** /**
* Annotation. * Annotation.
@ -139,7 +139,7 @@ class Annotation
*/ */
public function timestamps() public function timestamps()
{ {
if (is_null($this->createdAt)) { if (null === $this->createdAt) {
$this->createdAt = new \DateTime(); $this->createdAt = new \DateTime();
} }
$this->updatedAt = new \DateTime(); $this->updatedAt = new \DateTime();

View file

@ -9,22 +9,6 @@ use Doctrine\ORM\EntityRepository;
*/ */
class AnnotationRepository extends 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. * Retrieves all annotations for a user.
* *
@ -139,4 +123,20 @@ class AnnotationRepository extends EntityRepository
->getQuery() ->getQuery()
->getResult(); ->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')
;
}
} }

View file

@ -4,10 +4,10 @@ namespace Wallabag\ApiBundle\Controller;
use Nelmio\ApiDocBundle\Annotation\ApiDoc; use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\JsonResponse;
use Wallabag\CoreBundle\Entity\Entry; use Symfony\Component\HttpFoundation\Request;
use Wallabag\AnnotationBundle\Entity\Annotation; use Wallabag\AnnotationBundle\Entity\Annotation;
use Wallabag\CoreBundle\Entity\Entry;
class AnnotationRestController extends WallabagRestController class AnnotationRestController extends WallabagRestController
{ {

View file

@ -3,8 +3,8 @@
namespace Wallabag\ApiBundle\Controller; namespace Wallabag\ApiBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Wallabag\ApiBundle\Entity\Client; use Wallabag\ApiBundle\Entity\Client;
use Wallabag\ApiBundle\Form\Type\ClientType; use Wallabag\ApiBundle\Form\Type\ClientType;
@ -75,7 +75,7 @@ class DeveloperController extends Controller
*/ */
public function deleteClientAction(Client $client) 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.'); throw $this->createAccessDeniedException('You can not access this client.');
} }

View file

@ -6,14 +6,14 @@ use Hateoas\Configuration\Route;
use Hateoas\Representation\Factory\PagerfantaFactory; use Hateoas\Representation\Factory\PagerfantaFactory;
use JMS\Serializer\SerializationContext; use JMS\Serializer\SerializationContext;
use Nelmio\ApiDocBundle\Annotation\ApiDoc; 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\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Entry;
use Wallabag\CoreBundle\Entity\Tag; use Wallabag\CoreBundle\Entity\Tag;
use Wallabag\CoreBundle\Event\EntrySavedEvent;
use Wallabag\CoreBundle\Event\EntryDeletedEvent; use Wallabag\CoreBundle\Event\EntryDeletedEvent;
use Wallabag\CoreBundle\Event\EntrySavedEvent;
class EntryRestController extends WallabagRestController class EntryRestController extends WallabagRestController
{ {
@ -59,7 +59,7 @@ class EntryRestController extends WallabagRestController
$url = $request->query->get('url', ''); $url = $request->query->get('url', '');
if (empty($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() $res = $this->getDoctrine()
@ -239,9 +239,9 @@ class EntryRestController extends WallabagRestController
* } * }
* ) * )
* *
* @return JsonResponse
*
* @throws HttpException When limit is reached * @throws HttpException When limit is reached
*
* @return JsonResponse
*/ */
public function postEntriesListAction(Request $request) public function postEntriesListAction(Request $request)
{ {
@ -678,11 +678,11 @@ class EntryRestController extends WallabagRestController
]); ]);
} }
if (!is_null($isArchived)) { if (null !== $isArchived) {
$entry->setArchived((bool) $isArchived); $entry->setArchived((bool) $isArchived);
} }
if (!is_null($isStarred)) { if (null !== $isStarred) {
$entry->setStarred((bool) $isStarred); $entry->setStarred((bool) $isStarred);
} }
@ -690,7 +690,7 @@ class EntryRestController extends WallabagRestController
$this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags); $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
} }
if (!is_null($isPublic)) { if (null !== $isPublic) {
if (true === (bool) $isPublic && null === $entry->getUid()) { if (true === (bool) $isPublic && null === $entry->getUid()) {
$entry->generateUid(); $entry->generateUid();
} elseif (false === (bool) $isPublic) { } elseif (false === (bool) $isPublic) {

View file

@ -3,8 +3,8 @@
namespace Wallabag\ApiBundle\Controller; namespace Wallabag\ApiBundle\Controller;
use Nelmio\ApiDocBundle\Annotation\ApiDoc; use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Entry;
use Wallabag\CoreBundle\Entity\Tag; use Wallabag\CoreBundle\Entity\Tag;

View file

@ -6,10 +6,10 @@ use FOS\UserBundle\Event\UserEvent;
use FOS\UserBundle\FOSUserEvents; use FOS\UserBundle\FOSUserEvents;
use JMS\Serializer\SerializationContext; use JMS\Serializer\SerializationContext;
use Nelmio\ApiDocBundle\Annotation\ApiDoc; use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\JsonResponse;
use Wallabag\UserBundle\Entity\User; use Symfony\Component\HttpFoundation\Request;
use Wallabag\ApiBundle\Entity\Client; use Wallabag\ApiBundle\Entity\Client;
use Wallabag\UserBundle\Entity\User;
class UserRestController extends WallabagRestController class UserRestController extends WallabagRestController
{ {

View file

@ -40,8 +40,8 @@ class WallabagRestController extends FOSRestController
protected function validateUserAccess($requestUserId) protected function validateUserAccess($requestUserId)
{ {
$user = $this->get('security.token_storage')->getToken()->getUser(); $user = $this->get('security.token_storage')->getToken()->getUser();
if ($requestUserId != $user->getId()) { if ($requestUserId !== $user->getId()) {
throw $this->createAccessDeniedException('Access forbidden. Entry user id: '.$requestUserId.', logged user id: '.$user->getId()); throw $this->createAccessDeniedException('Access forbidden. Entry user id: ' . $requestUserId . ', logged user id: ' . $user->getId());
} }
} }
} }

View file

@ -4,10 +4,10 @@ namespace Wallabag\ApiBundle\Entity;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use FOS\OAuthServerBundle\Entity\Client as BaseClient; use FOS\OAuthServerBundle\Entity\Client as BaseClient;
use Wallabag\UserBundle\Entity\User;
use JMS\Serializer\Annotation\Groups; use JMS\Serializer\Annotation\Groups;
use JMS\Serializer\Annotation\SerializedName; use JMS\Serializer\Annotation\SerializedName;
use JMS\Serializer\Annotation\VirtualProperty; use JMS\Serializer\Annotation\VirtualProperty;
use Wallabag\UserBundle\Entity\User;
/** /**
* @ORM\Table("oauth2_clients") * @ORM\Table("oauth2_clients")
@ -99,6 +99,6 @@ class Client extends BaseClient
*/ */
public function getClientId() public function getClientId()
{ {
return $this->getId().'_'.$this->getRandomId(); return $this->getId() . '_' . $this->getRandomId();
} }
} }

View file

@ -5,8 +5,8 @@ namespace Wallabag\ApiBundle\Form\Type;
use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\CallbackTransformer; use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\Extension\Core\Type\SubmitType; 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\TextType;
use Symfony\Component\Form\Extension\Core\Type\UrlType;
use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\OptionsResolver\OptionsResolver;

View file

@ -76,7 +76,7 @@ class CleanDuplicatesCommand extends ContainerAwareCommand
$url = $this->similarUrl($entry['url']); $url = $this->similarUrl($entry['url']);
/* @var $entry Entry */ /* @var $entry Entry */
if (in_array($url, $urls)) { if (in_array($url, $urls, true)) {
++$duplicatesCount; ++$duplicatesCount;
$em->remove($repo->find($entry['id'])); $em->remove($repo->find($entry['id']));
@ -93,7 +93,7 @@ class CleanDuplicatesCommand extends ContainerAwareCommand
private function similarUrl($url) 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)); return substr($url, 0, strlen($url));
} }

View file

@ -49,7 +49,7 @@ class ExportCommand extends ContainerAwareCommand
$filePath = $input->getArgument('filepath'); $filePath = $input->getArgument('filepath');
if (!$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 { try {

View file

@ -2,6 +2,7 @@
namespace Wallabag\CoreBundle\Command; namespace Wallabag\CoreBundle\Command;
use Craue\ConfigBundle\Entity\Setting;
use FOS\UserBundle\Event\UserEvent; use FOS\UserBundle\Event\UserEvent;
use FOS\UserBundle\FOSUserEvents; use FOS\UserBundle\FOSUserEvents;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; 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\ConfirmationQuestion;
use Symfony\Component\Console\Question\Question; use Symfony\Component\Console\Question\Question;
use Wallabag\CoreBundle\Entity\Config; use Wallabag\CoreBundle\Entity\Config;
use Craue\ConfigBundle\Entity\Setting;
class InstallCommand extends ContainerAwareCommand class InstallCommand extends ContainerAwareCommand
{ {
@ -86,7 +86,7 @@ class InstallCommand extends ContainerAwareCommand
if (!extension_loaded($this->getContainer()->getParameter('database_driver'))) { if (!extension_loaded($this->getContainer()->getParameter('database_driver'))) {
$fulfilled = false; $fulfilled = false;
$status = '<error>ERROR!</error>'; $status = '<error>ERROR!</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]; $rows[] = [sprintf($label, $this->getContainer()->getParameter('database_driver')), $status, $help];
@ -101,10 +101,10 @@ class InstallCommand extends ContainerAwareCommand
$conn->connect(); $conn->connect();
} catch (\Exception $e) { } catch (\Exception $e) {
if (false === strpos($e->getMessage(), 'Unknown database') 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; $fulfilled = false;
$status = '<error>ERROR!</error>'; $status = '<error>ERROR!</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, '>')) { if (false === version_compare($version, $minimalVersion, '>')) {
$fulfilled = false; $fulfilled = false;
$status = '<error>ERROR!</error>'; $status = '<error>ERROR!</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', '<')) { if (isset($matches[1]) & version_compare($matches[1], '9.2.0', '<')) {
$fulfilled = false; $fulfilled = false;
$status = '<error>ERROR!</error>'; $status = '<error>ERROR!</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]; $rows[] = [$label, $status, $help];
foreach ($this->functionExists as $functionRequired) { foreach ($this->functionExists as $functionRequired) {
$label = '<comment>'.$functionRequired.'</comment>'; $label = '<comment>' . $functionRequired . '</comment>';
$status = '<info>OK!</info>'; $status = '<info>OK!</info>';
$help = ''; $help = '';
if (!function_exists($functionRequired)) { if (!function_exists($functionRequired)) {
$fulfilled = false; $fulfilled = false;
$status = '<error>ERROR!</error>'; $status = '<error>ERROR!</error>';
$help = 'You need the '.$functionRequired.' function activated'; $help = 'You need the ' . $functionRequired . ' function activated';
} }
$rows[] = [$label, $status, $help]; $rows[] = [$label, $status, $help];
@ -351,8 +351,8 @@ class InstallCommand extends ContainerAwareCommand
$this->getApplication()->setAutoExit(true); $this->getApplication()->setAutoExit(true);
throw new \RuntimeException( throw new \RuntimeException(
'The command "'.$command."\" generates some errors: \n\n" 'The command "' . $command . "\" generates some errors: \n\n"
.$output->fetch()); . $output->fetch());
} }
return $this; return $this;
@ -396,7 +396,7 @@ class InstallCommand extends ContainerAwareCommand
} }
try { try {
return in_array($databaseName, $schemaManager->listDatabases()); return in_array($databaseName, $schemaManager->listDatabases(), true);
} catch (\Doctrine\DBAL\Exception\DriverException $e) { } catch (\Doctrine\DBAL\Exception\DriverException $e) {
// it means we weren't able to get database list, assume the database doesn't exist // it means we weren't able to get database list, assume the database doesn't exist

View file

@ -10,8 +10,8 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Wallabag\CoreBundle\Entity\Config; use Wallabag\CoreBundle\Entity\Config;
use Wallabag\CoreBundle\Entity\TaggingRule; use Wallabag\CoreBundle\Entity\TaggingRule;
use Wallabag\CoreBundle\Form\Type\ConfigType;
use Wallabag\CoreBundle\Form\Type\ChangePasswordType; use Wallabag\CoreBundle\Form\Type\ChangePasswordType;
use Wallabag\CoreBundle\Form\Type\ConfigType;
use Wallabag\CoreBundle\Form\Type\RssType; use Wallabag\CoreBundle\Form\Type\RssType;
use Wallabag\CoreBundle\Form\Type\TaggingRuleType; use Wallabag\CoreBundle\Form\Type\TaggingRuleType;
use Wallabag\CoreBundle\Form\Type\UserInformationType; use Wallabag\CoreBundle\Form\Type\UserInformationType;
@ -54,7 +54,7 @@ class ConfigController extends Controller
} }
// handle changing password // 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); $pwdForm->handleRequest($request);
if ($pwdForm->isSubmitted() && $pwdForm->isValid()) { if ($pwdForm->isSubmitted() && $pwdForm->isValid()) {
@ -69,13 +69,13 @@ class ConfigController extends Controller
$this->get('session')->getFlashBag()->add('notice', $message); $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 // handle changing user information
$userForm = $this->createForm(UserInformationType::class, $user, [ $userForm = $this->createForm(UserInformationType::class, $user, [
'validation_groups' => ['Profile'], 'validation_groups' => ['Profile'],
'action' => $this->generateUrl('config').'#set3', 'action' => $this->generateUrl('config') . '#set3',
]); ]);
$userForm->handleRequest($request); $userForm->handleRequest($request);
@ -87,11 +87,11 @@ class ConfigController extends Controller
'flashes.config.notice.user_updated' 'flashes.config.notice.user_updated'
); );
return $this->redirect($this->generateUrl('config').'#set3'); return $this->redirect($this->generateUrl('config') . '#set3');
} }
// handle rss information // 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); $rssForm->handleRequest($request);
if ($rssForm->isSubmitted() && $rssForm->isValid()) { if ($rssForm->isSubmitted() && $rssForm->isValid()) {
@ -103,12 +103,12 @@ class ConfigController extends Controller
'flashes.config.notice.rss_updated' 'flashes.config.notice.rss_updated'
); );
return $this->redirect($this->generateUrl('config').'#set2'); return $this->redirect($this->generateUrl('config') . '#set2');
} }
// handle tagging rule // handle tagging rule
$taggingRule = new TaggingRule(); $taggingRule = new TaggingRule();
$action = $this->generateUrl('config').'#set5'; $action = $this->generateUrl('config') . '#set5';
if ($request->query->has('tagging-rule')) { if ($request->query->has('tagging-rule')) {
$taggingRule = $this->getDoctrine() $taggingRule = $this->getDoctrine()
@ -119,7 +119,7 @@ class ConfigController extends Controller
return $this->redirect($action); 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]); $newTaggingRule = $this->createForm(TaggingRuleType::class, $taggingRule, ['action' => $action]);
@ -135,7 +135,7 @@ class ConfigController extends Controller
'flashes.config.notice.tagging_rules_updated' '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', [ return $this->render('WallabagCoreBundle:Config:index.html.twig', [
@ -182,7 +182,7 @@ class ConfigController extends Controller
'flashes.config.notice.rss_token_updated' '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' '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); $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') ->getRepository('WallabagAnnotationBundle:Annotation')
->removeAllByUserId($this->getUser()->getId()); ->removeAllByUserId($this->getUser()->getId());
break; break;
case 'tags': case 'tags':
$this->removeAllTagsByUserId($this->getUser()->getId()); $this->removeAllTagsByUserId($this->getUser()->getId());
break; break;
case 'entries': case 'entries':
// SQLite doesn't care about cascading remove, so we need to manually remove associated stuff // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff
// otherwise they won't be removed ... // otherwise they won't be removed ...
@ -272,10 +270,63 @@ class ConfigController extends Controller
$this->get('session')->getFlashBag()->add( $this->get('session')->getFlashBag()->add(
'notice', '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) 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.'); throw $this->createAccessDeniedException('You can not access this tagging rule.');
} }
} }
@ -373,57 +424,4 @@ class ConfigController extends Controller
return $config; 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'));
}
} }

View file

@ -4,17 +4,17 @@ namespace Wallabag\CoreBundle\Controller;
use Pagerfanta\Adapter\DoctrineORMAdapter; use Pagerfanta\Adapter\DoctrineORMAdapter;
use Pagerfanta\Exception\OutOfRangeCurrentPageException; use Pagerfanta\Exception\OutOfRangeCurrentPageException;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Entry;
use Wallabag\CoreBundle\Form\Type\EntryFilterType;
use Wallabag\CoreBundle\Form\Type\EditEntryType;
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\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 Wallabag\CoreBundle\Form\Type\SearchEntryType; use Wallabag\CoreBundle\Form\Type\SearchEntryType;
class EntryController extends Controller 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 * @param Request $request
* *
@ -220,7 +195,7 @@ class EntryController extends Controller
public function showUnreadAction(Request $request, $page) public function showUnreadAction(Request $request, $page)
{ {
// load the quickstart if no entry in database // 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')); return $this->redirect($this->generateUrl('quickstart'));
} }
@ -257,83 +232,6 @@ class EntryController extends Controller
return $this->showEntries('starred', $request, $page); 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. * 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) // don't redirect user to the deleted entry (check that the referer doesn't end with the same url)
$referer = $request->headers->get('referer'); $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); $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($to);
return $this->redirect($redirectUrl); 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). * Get public URL for entry (and generate it if necessary).
* *
@ -604,4 +478,126 @@ class EntryController extends Controller
{ {
return $this->showEntries('untagged', $request, $page); 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());
}
} }

View file

@ -14,7 +14,7 @@ class ExceptionController extends BaseExceptionController
protected function findTemplate(Request $request, $format, $code, $showException) protected function findTemplate(Request $request, $format, $code, $showException)
{ {
$name = $showException ? 'exception' : 'error'; $name = $showException ? 'exception' : 'error';
if ($showException && 'html' == $format) { if ($showException && 'html' === $format) {
$name = 'exception_full'; $name = 'exception_full';
} }

View file

@ -55,10 +55,10 @@ class ExportController extends Controller
public function downloadEntriesAction(Request $request, $format, $category) public function downloadEntriesAction(Request $request, $format, $category)
{ {
$method = ucfirst($category); $method = ucfirst($category);
$methodBuilder = 'getBuilderFor'.$method.'ByUser'; $methodBuilder = 'getBuilderFor' . $method . 'ByUser';
$repository = $this->get('wallabag_core.entry_repository'); $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')); $tag = $this->get('wallabag_core.tag_repository')->findOneBySlug($request->query->get('tag'));
$entries = $repository->findAllByTagId( $entries = $repository->findAllByTagId(

View file

@ -2,19 +2,19 @@
namespace Wallabag\CoreBundle\Controller; namespace Wallabag\CoreBundle\Controller;
use Pagerfanta\Adapter\DoctrineORMAdapter;
use Pagerfanta\Adapter\ArrayAdapter; use Pagerfanta\Adapter\ArrayAdapter;
use Pagerfanta\Adapter\DoctrineORMAdapter;
use Pagerfanta\Exception\OutOfRangeCurrentPageException; use Pagerfanta\Exception\OutOfRangeCurrentPageException;
use Pagerfanta\Pagerfanta; use Pagerfanta\Pagerfanta;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; 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\Entry;
use Wallabag\CoreBundle\Entity\Tag; use Wallabag\CoreBundle\Entity\Tag;
use Wallabag\UserBundle\Entity\User; use Wallabag\UserBundle\Entity\User;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class RssController extends Controller class RssController extends Controller
{ {
@ -113,7 +113,7 @@ class RssController extends Controller
$entries->setCurrentPage($page); $entries->setCurrentPage($page);
} catch (OutOfRangeCurrentPageException $e) { } catch (OutOfRangeCurrentPageException $e) {
if ($page > 1) { 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', '@WallabagCore/themes/common/Entry/entries.xml.twig',
[ [
'url_html' => $this->generateUrl('tag_entries', ['slug' => $tag->getSlug()], UrlGeneratorInterface::ABSOLUTE_URL), 'url_html' => $this->generateUrl('tag_entries', ['slug' => $tag->getSlug()], UrlGeneratorInterface::ABSOLUTE_URL),
'type' => 'tag ('.$tag->getLabel().')', 'type' => 'tag (' . $tag->getLabel() . ')',
'url' => $url, 'url' => $url,
'entries' => $entries, 'entries' => $entries,
], ],
@ -147,19 +147,15 @@ class RssController extends Controller
case 'starred': case 'starred':
$qb = $repository->getBuilderForStarredByUser($user->getId()); $qb = $repository->getBuilderForStarredByUser($user->getId());
break; break;
case 'archive': case 'archive':
$qb = $repository->getBuilderForArchiveByUser($user->getId()); $qb = $repository->getBuilderForArchiveByUser($user->getId());
break; break;
case 'unread': case 'unread':
$qb = $repository->getBuilderForUnreadByUser($user->getId()); $qb = $repository->getBuilderForUnreadByUser($user->getId());
break; break;
case 'all': case 'all':
$qb = $repository->getBuilderForAllByUser($user->getId()); $qb = $repository->getBuilderForAllByUser($user->getId());
break; break;
default: default:
throw new \InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type)); throw new \InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type));
} }
@ -171,7 +167,7 @@ class RssController extends Controller
$entries->setMaxPerPage($perPage); $entries->setMaxPerPage($perPage);
$url = $this->generateUrl( $url = $this->generateUrl(
$type.'_rss', $type . '_rss',
[ [
'username' => $user->getUsername(), 'username' => $user->getUsername(),
'token' => $user->getConfig()->getRssToken(), 'token' => $user->getConfig()->getRssToken(),
@ -183,7 +179,7 @@ class RssController extends Controller
$entries->setCurrentPage((int) $page); $entries->setCurrentPage((int) $page);
} catch (OutOfRangeCurrentPageException $e) { } catch (OutOfRangeCurrentPageException $e) {
if ($page > 1) { if ($page > 1) {
return $this->redirect($url.'?page='.$entries->getNbPages(), 302); return $this->redirect($url . '?page=' . $entries->getNbPages(), 302);
} }
} }

View file

@ -2,12 +2,12 @@
namespace Wallabag\CoreBundle\Controller; 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\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; 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\CoreBundle\Entity\SiteCredential;
use Wallabag\UserBundle\Entity\User;
/** /**
* SiteCredential controller. * SiteCredential controller.
@ -167,7 +167,7 @@ class SiteCredentialController extends Controller
*/ */
private function checkUserAction(SiteCredential $siteCredential) 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.'); throw $this->createAccessDeniedException('You can not access this site credential.');
} }
} }

View file

@ -16,7 +16,9 @@ class StaticController extends Controller
return $this->render( return $this->render(
'@WallabagCore/themes/common/Static/howto.html.twig', '@WallabagCore/themes/common/Static/howto.html.twig',
['addonsUrl' => $addonsUrl] [
'addonsUrl' => $addonsUrl,
]
); );
} }
@ -40,8 +42,7 @@ class StaticController extends Controller
public function quickstartAction() public function quickstartAction()
{ {
return $this->render( return $this->render(
'@WallabagCore/themes/common/Static/quickstart.html.twig', '@WallabagCore/themes/common/Static/quickstart.html.twig'
[]
); );
} }
} }

View file

@ -4,13 +4,13 @@ namespace Wallabag\CoreBundle\Controller;
use Pagerfanta\Adapter\ArrayAdapter; use Pagerfanta\Adapter\ArrayAdapter;
use Pagerfanta\Exception\OutOfRangeCurrentPageException; use Pagerfanta\Exception\OutOfRangeCurrentPageException;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Entry;
use Wallabag\CoreBundle\Entity\Tag; use Wallabag\CoreBundle\Entity\Tag;
use Wallabag\CoreBundle\Form\Type\NewTagType; use Wallabag\CoreBundle\Form\Type\NewTagType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
class TagController extends Controller class TagController extends Controller
{ {

View file

@ -2,10 +2,10 @@
namespace Wallabag\CoreBundle\DataFixtures\ORM; namespace Wallabag\CoreBundle\DataFixtures\ORM;
use Craue\ConfigBundle\Entity\Setting;
use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\Persistence\ObjectManager;
use Craue\ConfigBundle\Entity\Setting;
use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerInterface;

View file

@ -31,7 +31,7 @@ class WallabagCoreExtension extends Extension
$container->setParameter('wallabag_core.default_internal_settings', $config['default_internal_settings']); $container->setParameter('wallabag_core.default_internal_settings', $config['default_internal_settings']);
$container->setParameter('wallabag_core.site_credentials.encryption_key_path', $config['encryption_key_path']); $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('services.yml');
$loader->load('parameters.yml'); $loader->load('parameters.yml');
} }

View file

@ -5,14 +5,14 @@ namespace Wallabag\CoreBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use Hateoas\Configuration\Annotation as Hateoas; 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\Exclude;
use JMS\Serializer\Annotation\VirtualProperty; use JMS\Serializer\Annotation\Groups;
use JMS\Serializer\Annotation\SerializedName; use JMS\Serializer\Annotation\SerializedName;
use JMS\Serializer\Annotation\VirtualProperty;
use JMS\Serializer\Annotation\XmlRoot;
use Symfony\Component\Validator\Constraints as Assert; use Symfony\Component\Validator\Constraints as Assert;
use Wallabag\UserBundle\Entity\User;
use Wallabag\AnnotationBundle\Entity\Annotation; use Wallabag\AnnotationBundle\Entity\Annotation;
use Wallabag\UserBundle\Entity\User;
/** /**
* Entry. * Entry.
@ -478,7 +478,7 @@ class Entry
*/ */
public function timestamps() public function timestamps()
{ {
if (is_null($this->createdAt)) { if (null === $this->createdAt) {
$this->createdAt = new \DateTime(); $this->createdAt = new \DateTime();
} }

View file

@ -188,7 +188,7 @@ class SiteCredential
*/ */
public function timestamps() public function timestamps()
{ {
if (is_null($this->createdAt)) { if (null === $this->createdAt) {
$this->createdAt = new \DateTime(); $this->createdAt = new \DateTime();
} }
} }

View file

@ -4,9 +4,9 @@ namespace Wallabag\CoreBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use JMS\Serializer\Annotation\ExclusionPolicy; use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Expose; use JMS\Serializer\Annotation\Expose;
use Gedmo\Mapping\Annotation as Gedmo;
use JMS\Serializer\Annotation\XmlRoot; use JMS\Serializer\Annotation\XmlRoot;
/** /**

View file

@ -2,13 +2,13 @@
namespace Wallabag\CoreBundle\Event\Subscriber; namespace Wallabag\CoreBundle\Event\Subscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Psr\Log\LoggerInterface;
use Wallabag\CoreBundle\Helper\DownloadImages;
use Wallabag\CoreBundle\Entity\Entry;
use Wallabag\CoreBundle\Event\EntrySavedEvent;
use Wallabag\CoreBundle\Event\EntryDeletedEvent;
use Doctrine\ORM\EntityManager; use Doctrine\ORM\EntityManager;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Wallabag\CoreBundle\Entity\Entry;
use Wallabag\CoreBundle\Event\EntryDeletedEvent;
use Wallabag\CoreBundle\Event\EntrySavedEvent;
use Wallabag\CoreBundle\Helper\DownloadImages;
class DownloadImagesSubscriber implements EventSubscriberInterface class DownloadImagesSubscriber implements EventSubscriberInterface
{ {

View file

@ -2,10 +2,10 @@
namespace Wallabag\CoreBundle\Event\Subscriber; namespace Wallabag\CoreBundle\Event\Subscriber;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Doctrine\Common\EventSubscriber; use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs; use Doctrine\ORM\Event\LifecycleEventArgs;
use Wallabag\CoreBundle\Entity\Entry; 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. * SQLite doesn't care about cascading remove, so we need to manually remove associated stuf for an Entry.

View file

@ -39,12 +39,12 @@ class TablePrefixSubscriber implements EventSubscriber
return; return;
} }
$classMetadata->setPrimaryTable(['name' => $this->prefix.$classMetadata->getTableName()]); $classMetadata->setPrimaryTable(['name' => $this->prefix . $classMetadata->getTableName()]);
foreach ($classMetadata->getAssociationMappings() as $fieldName => $mapping) { foreach ($classMetadata->getAssociationMappings() as $fieldName => $mapping) {
if ($mapping['type'] === ClassMetadataInfo::MANY_TO_MANY && isset($classMetadata->associationMappings[$fieldName]['joinTable']['name'])) { if ($mapping['type'] === ClassMetadataInfo::MANY_TO_MANY && isset($classMetadata->associationMappings[$fieldName]['joinTable']['name'])) {
$mappedTableName = $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;
} }
} }
} }

View file

@ -4,12 +4,12 @@ namespace Wallabag\CoreBundle\Form\Type;
use Doctrine\ORM\EntityRepository; use Doctrine\ORM\EntityRepository;
use Lexik\Bundle\FormFilterBundle\Filter\FilterOperands; 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\CheckboxFilterType;
use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\ChoiceFilterType; 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\AbstractType;
use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
@ -99,7 +99,7 @@ class EntryFilterType extends AbstractType
if (strlen($value) <= 2 || empty($value)) { if (strlen($value) <= 2 || empty($value)) {
return; 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); return $filterQuery->createCondition($expression);
}, },
@ -113,8 +113,8 @@ class EntryFilterType extends AbstractType
} }
$paramName = sprintf('%s', str_replace('.', '_', $field)); $paramName = sprintf('%s', str_replace('.', '_', $field));
$expression = $filterQuery->getExpr()->eq($field, ':'.$paramName); $expression = $filterQuery->getExpr()->eq($field, ':' . $paramName);
$parameters = array($paramName => $value); $parameters = [$paramName => $value];
return $filterQuery->createCondition($expression, $parameters); return $filterQuery->createCondition($expression, $parameters);
}, },
@ -158,7 +158,7 @@ class EntryFilterType extends AbstractType
// is_public isn't a real field // is_public isn't a real field
// we should use the "uid" field to determine if the entry has been made public // 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); return $filterQuery->createCondition($expression);
}, },

View file

@ -6,8 +6,8 @@ use BD\GuzzleSiteAuthenticator\SiteConfig\SiteConfig;
use BD\GuzzleSiteAuthenticator\SiteConfig\SiteConfigBuilder; use BD\GuzzleSiteAuthenticator\SiteConfig\SiteConfigBuilder;
use Graby\SiteConfig\ConfigBuilder; use Graby\SiteConfig\ConfigBuilder;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Wallabag\CoreBundle\Repository\SiteCredentialRepository;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Wallabag\CoreBundle\Repository\SiteCredentialRepository;
class GrabySiteConfigBuilder implements SiteConfigBuilder class GrabySiteConfigBuilder implements SiteConfigBuilder
{ {
@ -57,7 +57,7 @@ class GrabySiteConfigBuilder implements SiteConfigBuilder
{ {
// required by credentials below // required by credentials below
$host = strtolower($host); $host = strtolower($host);
if (substr($host, 0, 4) == 'www.') { if (substr($host, 0, 4) === 'www.') {
$host = substr($host, 4); $host = substr($host, 4);
} }

View file

@ -4,12 +4,12 @@ namespace Wallabag\CoreBundle\Helper;
use Graby\Graby; use Graby\Graby;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Wallabag\CoreBundle\Entity\Entry;
use Wallabag\CoreBundle\Tools\Utils;
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser; use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser;
use Symfony\Component\Validator\Constraints\Locale as LocaleConstraint; use Symfony\Component\Validator\Constraints\Locale as LocaleConstraint;
use Symfony\Component\Validator\Constraints\Url as UrlConstraint; use Symfony\Component\Validator\Constraints\Url as UrlConstraint;
use Symfony\Component\Validator\Validator\ValidatorInterface; 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 * This kind of proxy class take care of getting the content from an url
@ -100,7 +100,7 @@ class ContentProxy
// is it a timestamp? // is it a timestamp?
if (filter_var($date, FILTER_VALIDATE_INT) !== false) { if (filter_var($date, FILTER_VALIDATE_INT) !== false) {
$date = '@'.$content['date']; $date = '@' . $content['date'];
} }
try { try {
@ -189,7 +189,7 @@ class ContentProxy
return; return;
} }
$this->logger->warning('Language validation failed. '.(string) $errors); $this->logger->warning('Language validation failed. ' . (string) $errors);
} }
/** /**
@ -211,6 +211,6 @@ class ContentProxy
return; return;
} }
$this->logger->warning('PreviewPicture validation failed. '.(string) $errors); $this->logger->warning('PreviewPicture validation failed. ' . (string) $errors);
} }
} }

View file

@ -2,10 +2,10 @@
namespace Wallabag\CoreBundle\Helper; namespace Wallabag\CoreBundle\Helper;
use Psr\Log\LoggerInterface;
use Defuse\Crypto\Key;
use Defuse\Crypto\Crypto; use Defuse\Crypto\Crypto;
use Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException; 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. * This is a proxy to crypt and decrypt password used by SiteCredential entity.
@ -39,7 +39,7 @@ class CryptoProxy
*/ */
public function crypt($secretValue) 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()); return Crypto::encrypt($secretValue, $this->loadKey());
} }
@ -53,12 +53,12 @@ class CryptoProxy
*/ */
public function decrypt($cryptedValue) public function decrypt($cryptedValue)
{ {
$this->logger->debug('Crypto: decrypting value: '.$this->mask($cryptedValue)); $this->logger->debug('Crypto: decrypting value: ' . $this->mask($cryptedValue));
try { try {
return Crypto::decrypt($cryptedValue, $this->loadKey()); return Crypto::decrypt($cryptedValue, $this->loadKey());
} catch (WrongKeyOrModifiedCiphertextException $e) { } 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) 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';
} }
} }

View file

@ -44,7 +44,7 @@ class DetectActiveTheme implements DeviceDetectionInterface
{ {
$token = $this->tokenStorage->getToken(); $token = $this->tokenStorage->getToken();
if (is_null($token)) { if (null === $token) {
return $this->defaultTheme; return $this->defaultTheme;
} }

View file

@ -2,12 +2,12 @@
namespace Wallabag\CoreBundle\Helper; namespace Wallabag\CoreBundle\Helper;
use Psr\Log\LoggerInterface;
use Symfony\Component\DomCrawler\Crawler;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\Message\Response; 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\Finder\Finder;
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser;
class DownloadImages class DownloadImages
{ {
@ -30,17 +30,6 @@ class DownloadImages
$this->setFolder(); $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. * 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); $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 // build image path
$absolutePath = $this->getAbsoluteLink($url, $imagePath); $absolutePath = $this->getAbsoluteLink($url, $imagePath);
@ -123,7 +112,7 @@ class DownloadImages
} }
$hashImage = hash('crc32', $absolutePath); $hashImage = hash('crc32', $absolutePath);
$localPath = $folderPath.'/'.$hashImage.'.'.$ext; $localPath = $folderPath . '/' . $hashImage . '.' . $ext;
try { try {
$im = imagecreatefromstring($res->getBody()); $im = imagecreatefromstring($res->getBody());
@ -156,7 +145,7 @@ class DownloadImages
imagedestroy($im); 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) public function removeImages($entryId)
{ {
$relativePath = $this->getRelativePath($entryId); $relativePath = $this->getRelativePath($entryId);
$folderPath = $this->baseFolder.'/'.$relativePath; $folderPath = $this->baseFolder . '/' . $relativePath;
$finder = new Finder(); $finder = new Finder();
$finder $finder
@ -182,6 +171,17 @@ class DownloadImages
@rmdir($folderPath); @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. * 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) private function getRelativePath($entryId)
{ {
$hashId = hash('crc32', $entryId); $hashId = hash('crc32', $entryId);
$relativePath = $hashId[0].'/'.$hashId[1].'/'.$hashId; $relativePath = $hashId[0] . '/' . $hashId[1] . '/' . $hashId;
$folderPath = $this->baseFolder.'/'.$relativePath; $folderPath = $this->baseFolder . '/' . $relativePath;
if (!file_exists($folderPath)) { if (!file_exists($folderPath)) {
mkdir($folderPath, 0777, true); mkdir($folderPath, 0777, true);
@ -270,7 +270,7 @@ class DownloadImages
} }
if (!in_array($ext, ['jpeg', 'jpg', 'gif', 'png'], true)) { 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; return false;
} }

View file

@ -63,7 +63,7 @@ class EntriesExport
*/ */
public function updateTitle($method) public function updateTitle($method)
{ {
$this->title = $method.' articles'; $this->title = $method . ' articles';
if ('entry' === $method) { if ('entry' === $method) {
$this->title = $this->entries[0]->getTitle(); $this->title = $this->entries[0]->getTitle();
@ -81,7 +81,7 @@ class EntriesExport
*/ */
public function exportAs($format) public function exportAs($format)
{ {
$functionName = 'produce'.ucfirst($format); $functionName = 'produce' . ucfirst($format);
if (method_exists($this, $functionName)) { if (method_exists($this, $functionName)) {
return $this->$functionName(); return $this->$functionName();
} }
@ -106,12 +106,12 @@ class EntriesExport
*/ */
$content_start = $content_start =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
."<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n" . "<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n"
.'<head>' . '<head>'
."<meta http-equiv=\"Default-Style\" content=\"text/html; charset=utf-8\" />\n" . "<meta http-equiv=\"Default-Style\" content=\"text/html; charset=utf-8\" />\n"
."<title>wallabag articles book</title>\n" . "<title>wallabag articles book</title>\n"
."</head>\n" . "</head>\n"
."<body>\n"; . "<body>\n";
$bookEnd = "</body>\n</html>\n"; $bookEnd = "</body>\n</html>\n";
@ -164,11 +164,11 @@ class EntriesExport
// in filenames, we limit to A-z/0-9 // in filenames, we limit to A-z/0-9
$filename = preg_replace('/[^A-Za-z0-9\-]/', '', $entry->getTitle()); $filename = preg_replace('/[^A-Za-z0-9\-]/', '', $entry->getTitle());
$chapter = $content_start.$entry->getContent().$bookEnd; $chapter = $content_start . $entry->getContent() . $bookEnd;
$book->addChapter($entry->getTitle(), htmlspecialchars($filename).'.html', $chapter, true, EPub::EXTERNAL_REF_ADD); $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( return Response::create(
$book->getBook(), $book->getBook(),
@ -176,7 +176,7 @@ class EntriesExport
[ [
'Content-Description' => 'File Transfer', 'Content-Description' => 'File Transfer',
'Content-type' => 'application/epub+zip', 'Content-type' => 'application/epub+zip',
'Content-Disposition' => 'attachment; filename="'.$this->title.'.epub"', 'Content-Disposition' => 'attachment; filename="' . $this->title . '.epub"',
'Content-Transfer-Encoding' => 'binary', 'Content-Transfer-Encoding' => 'binary',
] ]
); );
@ -228,7 +228,7 @@ class EntriesExport
'Accept-Ranges' => 'bytes', 'Accept-Ranges' => 'bytes',
'Content-Description' => 'File Transfer', 'Content-Description' => 'File Transfer',
'Content-type' => 'application/x-mobipocket-ebook', 'Content-type' => 'application/x-mobipocket-ebook',
'Content-Disposition' => 'attachment; filename="'.$this->title.'.mobi"', 'Content-Disposition' => 'attachment; filename="' . $this->title . '.mobi"',
'Content-Transfer-Encoding' => 'binary', 'Content-Transfer-Encoding' => 'binary',
] ]
); );
@ -256,7 +256,7 @@ class EntriesExport
* Front page * Front page
*/ */
$pdf->AddPage(); $pdf->AddPage();
$intro = '<h1>'.$this->title.'</h1>'.$this->getExportInformation('tcpdf'); $intro = '<h1>' . $this->title . '</h1>' . $this->getExportInformation('tcpdf');
$pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true); $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true);
@ -269,7 +269,7 @@ class EntriesExport
} }
$pdf->AddPage(); $pdf->AddPage();
$html = '<h1>'.$entry->getTitle().'</h1>'; $html = '<h1>' . $entry->getTitle() . '</h1>';
$html .= $entry->getContent(); $html .= $entry->getContent();
$pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true); $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
@ -284,7 +284,7 @@ class EntriesExport
[ [
'Content-Description' => 'File Transfer', 'Content-Description' => 'File Transfer',
'Content-type' => 'application/pdf', 'Content-type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="'.$this->title.'.pdf"', 'Content-Disposition' => 'attachment; filename="' . $this->title . '.pdf"',
'Content-Transfer-Encoding' => 'binary', 'Content-Transfer-Encoding' => 'binary',
] ]
); );
@ -330,7 +330,7 @@ class EntriesExport
200, 200,
[ [
'Content-type' => 'application/csv', 'Content-type' => 'application/csv',
'Content-Disposition' => 'attachment; filename="'.$this->title.'.csv"', 'Content-Disposition' => 'attachment; filename="' . $this->title . '.csv"',
'Content-Transfer-Encoding' => 'UTF-8', 'Content-Transfer-Encoding' => 'UTF-8',
] ]
); );
@ -348,7 +348,7 @@ class EntriesExport
200, 200,
[ [
'Content-type' => 'application/json', 'Content-type' => 'application/json',
'Content-Disposition' => 'attachment; filename="'.$this->title.'.json"', 'Content-Disposition' => 'attachment; filename="' . $this->title . '.json"',
'Content-Transfer-Encoding' => 'UTF-8', 'Content-Transfer-Encoding' => 'UTF-8',
] ]
); );
@ -366,7 +366,7 @@ class EntriesExport
200, 200,
[ [
'Content-type' => 'application/xml', 'Content-type' => 'application/xml',
'Content-Disposition' => 'attachment; filename="'.$this->title.'.xml"', 'Content-Disposition' => 'attachment; filename="' . $this->title . '.xml"',
'Content-Transfer-Encoding' => 'UTF-8', 'Content-Transfer-Encoding' => 'UTF-8',
] ]
); );
@ -382,8 +382,8 @@ class EntriesExport
$content = ''; $content = '';
$bar = str_repeat('=', 100); $bar = str_repeat('=', 100);
foreach ($this->entries as $entry) { foreach ($this->entries as $entry) {
$content .= "\n\n".$bar."\n\n".$entry->getTitle()."\n\n".$bar."\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"; $content .= trim(preg_replace('/\s+/S', ' ', strip_tags($entry->getContent()))) . "\n\n";
} }
return Response::create( return Response::create(
@ -391,7 +391,7 @@ class EntriesExport
200, 200,
[ [
'Content-type' => 'text/plain', 'Content-type' => 'text/plain',
'Content-Disposition' => 'attachment; filename="'.$this->title.'.txt"', 'Content-Disposition' => 'attachment; filename="' . $this->title . '.txt"',
'Content-Transfer-Encoding' => 'UTF-8', 'Content-Transfer-Encoding' => 'UTF-8',
] ]
); );
@ -427,7 +427,7 @@ class EntriesExport
$info = str_replace('%EXPORT_METHOD%', $type, $this->footerTemplate); $info = str_replace('%EXPORT_METHOD%', $type, $this->footerTemplate);
if ('tcpdf' === $type) { if ('tcpdf' === $type) {
return str_replace('%IMAGE%', '<img src="'.$this->logoPath.'" />', $info); return str_replace('%IMAGE%', '<img src="' . $this->logoPath . '" />', $info);
} }
return str_replace('%IMAGE%', '', $info); return str_replace('%IMAGE%', '', $info);

View file

@ -41,7 +41,7 @@ class HttpClientFactory
*/ */
public function buildHttpClient() 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) { if (0 === (int) $this->restrictedAccess) {
return; return;

View file

@ -4,9 +4,9 @@ namespace Wallabag\CoreBundle\Helper;
use Pagerfanta\Adapter\AdapterInterface; use Pagerfanta\Adapter\AdapterInterface;
use Pagerfanta\Pagerfanta; use Pagerfanta\Pagerfanta;
use Wallabag\UserBundle\Entity\User;
use Symfony\Component\Routing\Router; use Symfony\Component\Routing\Router;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Wallabag\UserBundle\Entity\User;
class PreparePagerForEntries class PreparePagerForEntries
{ {

View file

@ -2,13 +2,13 @@
namespace Wallabag\CoreBundle\Helper; namespace Wallabag\CoreBundle\Helper;
use Psr\Log\LoggerInterface;
use RulerZ\RulerZ; use RulerZ\RulerZ;
use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Entry;
use Wallabag\CoreBundle\Entity\Tag; use Wallabag\CoreBundle\Entity\Tag;
use Wallabag\CoreBundle\Repository\EntryRepository; use Wallabag\CoreBundle\Repository\EntryRepository;
use Wallabag\CoreBundle\Repository\TagRepository; use Wallabag\CoreBundle\Repository\TagRepository;
use Wallabag\UserBundle\Entity\User; use Wallabag\UserBundle\Entity\User;
use Psr\Log\LoggerInterface;
class RuleBasedTagger class RuleBasedTagger
{ {

View file

@ -10,21 +10,6 @@ use Wallabag\CoreBundle\Entity\Tag;
class EntryRepository extends EntityRepository 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. * 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 // We lower() all parts here because PostgreSQL 'LIKE' verb is case-sensitive
$qb $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') ->leftJoin('e.tags', 't')
->groupBy('e.id'); ->groupBy('e.id');
@ -158,7 +143,7 @@ class EntryRepository extends EntityRepository
} }
if (null !== $isPublic) { if (null !== $isPublic) {
$qb->andWhere('e.uid IS '.(true === $isPublic ? 'NOT' : '').' NULL'); $qb->andWhere('e.uid IS ' . (true === $isPublic ? 'NOT' : '') . ' NULL');
} }
if ($since > 0) { if ($since > 0) {
@ -414,4 +399,19 @@ class EntryRepository extends EntityRepository
->getQuery() ->getQuery()
->getResult(); ->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')
;
}
} }

View file

@ -3,9 +3,9 @@
namespace Wallabag\CoreBundle\Twig; namespace Wallabag\CoreBundle\Twig;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Wallabag\CoreBundle\Repository\EntryRepository; use Wallabag\CoreBundle\Repository\EntryRepository;
use Wallabag\CoreBundle\Repository\TagRepository; use Wallabag\CoreBundle\Repository\TagRepository;
use Symfony\Component\Translation\TranslatorInterface;
class WallabagExtension extends \Twig_Extension implements \Twig_Extension_GlobalsInterface 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() public function getFunctions()
{ {
return array( return [
new \Twig_SimpleFunction('count_entries', [$this, 'countEntries']), new \Twig_SimpleFunction('count_entries', [$this, 'countEntries']),
new \Twig_SimpleFunction('count_tags', [$this, 'countTags']), new \Twig_SimpleFunction('count_tags', [$this, 'countTags']),
new \Twig_SimpleFunction('display_stats', [$this, 'displayStats']), new \Twig_SimpleFunction('display_stats', [$this, 'displayStats']),
); ];
} }
public function removeWww($url) public function removeWww($url)
@ -64,19 +64,15 @@ class WallabagExtension extends \Twig_Extension implements \Twig_Extension_Globa
case 'starred': case 'starred':
$qb = $this->entryRepository->getBuilderForStarredByUser($user->getId()); $qb = $this->entryRepository->getBuilderForStarredByUser($user->getId());
break; break;
case 'archive': case 'archive':
$qb = $this->entryRepository->getBuilderForArchiveByUser($user->getId()); $qb = $this->entryRepository->getBuilderForArchiveByUser($user->getId());
break; break;
case 'unread': case 'unread':
$qb = $this->entryRepository->getBuilderForUnreadByUser($user->getId()); $qb = $this->entryRepository->getBuilderForUnreadByUser($user->getId());
break; break;
case 'all': case 'all':
$qb = $this->entryRepository->getBuilderForAllByUser($user->getId()); $qb = $this->entryRepository->getBuilderForAllByUser($user->getId());
break; break;
default: default:
throw new \InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type)); 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; $nbDays = (int) $interval->format('%a') ?: 1;
// force setlocale for date translation // 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', [ return $this->translator->trans('footer.stats', [
'%user_creation%' => strftime('%e %B %Y', $user->getCreatedAt()->getTimestamp()), '%user_creation%' => strftime('%e %B %Y', $user->getCreatedAt()->getTimestamp()),

View file

@ -5,8 +5,8 @@ namespace Wallabag\ImportBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Config\Definition\Exception\Exception; use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\OutputInterface;
class ImportCommand extends ContainerAwareCommand class ImportCommand extends ContainerAwareCommand
@ -27,7 +27,7 @@ class ImportCommand extends ContainerAwareCommand
protected function execute(InputInterface $input, OutputInterface $output) 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'))) { if (!file_exists($input->getArgument('filepath'))) {
throw new Exception(sprintf('File "%s" not found', $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) { if (true === $res) {
$summary = $import->getSummary(); $summary = $import->getSummary();
$output->writeln('<info>'.$summary['imported'].' imported</info>'); $output->writeln('<info>' . $summary['imported'] . ' imported</info>');
$output->writeln('<comment>'.$summary['skipped'].' already saved</comment>'); $output->writeln('<comment>' . $summary['skipped'] . ' already saved</comment>');
} }
$em->clear(); $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') . ' ---');
} }
} }

View file

@ -2,13 +2,13 @@
namespace Wallabag\ImportBundle\Command; namespace Wallabag\ImportBundle\Command;
use Simpleue\Worker\QueueWorker;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Config\Definition\Exception\Exception; use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\OutputInterface;
use Simpleue\Worker\QueueWorker;
class RedisWorkerCommand extends ContainerAwareCommand class RedisWorkerCommand extends ContainerAwareCommand
{ {
@ -24,18 +24,18 @@ class RedisWorkerCommand extends ContainerAwareCommand
protected function execute(InputInterface $input, OutputInterface $output) 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 ...'); $output->writeln('Waiting for message ...');
$serviceName = $input->getArgument('serviceName'); $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'))); throw new Exception(sprintf('No queue or consumer found for service name: "%s"', $input->getArgument('serviceName')));
} }
$worker = new QueueWorker( $worker = new QueueWorker(
$this->getContainer()->get('wallabag_import.queue.redis.'.$serviceName), $this->getContainer()->get('wallabag_import.queue.redis.' . $serviceName),
$this->getContainer()->get('wallabag_import.consumer.redis.'.$serviceName), $this->getContainer()->get('wallabag_import.consumer.redis.' . $serviceName),
(int) $input->getOption('maxIterations') (int) $input->getOption('maxIterations')
); );

View file

@ -3,14 +3,14 @@
namespace Wallabag\ImportBundle\Consumer; namespace Wallabag\ImportBundle\Consumer;
use Doctrine\ORM\EntityManager; 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\LoggerInterface;
use Psr\Log\NullLogger; use Psr\Log\NullLogger;
use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Wallabag\CoreBundle\Entity\Entry;
use Wallabag\CoreBundle\Entity\Tag;
use Wallabag\CoreBundle\Event\EntrySavedEvent; use Wallabag\CoreBundle\Event\EntrySavedEvent;
use Wallabag\ImportBundle\Import\AbstractImport;
use Wallabag\UserBundle\Repository\UserRepository;
abstract class AbstractConsumer abstract class AbstractConsumer
{ {
@ -76,7 +76,7 @@ abstract class AbstractConsumer
return false; return false;
} }
$this->logger->info('Content with url imported! ('.$entry->getUrl().')'); $this->logger->info('Content with url imported! (' . $entry->getUrl() . ')');
return true; return true;
} }

View file

@ -2,28 +2,14 @@
namespace Wallabag\ImportBundle\Controller; namespace Wallabag\ImportBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Wallabag\ImportBundle\Form\Type\UploadImportType; use Wallabag\ImportBundle\Form\Type\UploadImportType;
abstract class BrowserController extends Controller 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") * @Route("/browser", name="import_browser")
* *
@ -42,11 +28,11 @@ abstract class BrowserController extends Controller
if ($form->isSubmitted() && $form->isValid()) { if ($form->isSubmitted() && $form->isValid()) {
$file = $form->get('file')->getData(); $file = $form->get('file')->getData();
$markAsRead = $form->get('mark_as_read')->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 $res = $wallabag
->setFilepath($this->getParameter('wallabag_import.resource_dir').'/'.$name) ->setFilepath($this->getParameter('wallabag_import.resource_dir') . '/' . $name)
->setMarkAsRead($markAsRead) ->setMarkAsRead($markAsRead)
->import(); ->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( $this->get('session')->getFlashBag()->add(
@ -74,17 +60,30 @@ abstract class BrowserController extends Controller
); );
return $this->redirect($this->generateUrl('homepage')); return $this->redirect($this->generateUrl('homepage'));
} else { }
$this->get('session')->getFlashBag()->add( $this->get('session')->getFlashBag()->add(
'notice', 'notice',
'flashes.import.notice.failed_on_file' 'flashes.import.notice.failed_on_file'
); );
} }
}
return $this->render($this->getImportTemplate(), [ return $this->render($this->getImportTemplate(), [
'form' => $form->createView(), 'form' => $form->createView(),
'import' => $wallabag, '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();
} }

View file

@ -7,6 +7,14 @@ use Symfony\Component\HttpFoundation\Request;
class ChromeController extends BrowserController class ChromeController extends BrowserController
{ {
/**
* @Route("/chrome", name="import_chrome")
*/
public function indexAction(Request $request)
{
return parent::indexAction($request);
}
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
@ -30,12 +38,4 @@ class ChromeController extends BrowserController
{ {
return 'WallabagImportBundle:Chrome:index.html.twig'; return 'WallabagImportBundle:Chrome:index.html.twig';
} }
/**
* @Route("/chrome", name="import_chrome")
*/
public function indexAction(Request $request)
{
return parent::indexAction($request);
}
} }

View file

@ -7,6 +7,14 @@ use Symfony\Component\HttpFoundation\Request;
class FirefoxController extends BrowserController class FirefoxController extends BrowserController
{ {
/**
* @Route("/firefox", name="import_firefox")
*/
public function indexAction(Request $request)
{
return parent::indexAction($request);
}
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
@ -30,12 +38,4 @@ class FirefoxController extends BrowserController
{ {
return 'WallabagImportBundle:Firefox:index.html.twig'; return 'WallabagImportBundle:Firefox:index.html.twig';
} }
/**
* @Route("/firefox", name="import_firefox")
*/
public function indexAction(Request $request)
{
return parent::indexAction($request);
}
} }

View file

@ -2,8 +2,8 @@
namespace Wallabag\ImportBundle\Controller; namespace Wallabag\ImportBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class ImportController extends Controller class ImportController extends Controller
{ {
@ -86,9 +86,9 @@ class ImportController extends Controller
private function getTotalMessageInRabbitQueue($importService) private function getTotalMessageInRabbitQueue($importService)
{ {
$message = $this $message = $this
->get('old_sound_rabbit_mq.import_'.$importService.'_consumer') ->get('old_sound_rabbit_mq.import_' . $importService . '_consumer')
->getChannel() ->getChannel()
->basic_get('wallabag.import.'.$importService); ->basic_get('wallabag.import.' . $importService);
if (null === $message) { if (null === $message) {
return 0; return 0;

View file

@ -2,8 +2,8 @@
namespace Wallabag\ImportBundle\Controller; namespace Wallabag\ImportBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Wallabag\ImportBundle\Form\Type\UploadImportType; use Wallabag\ImportBundle\Form\Type\UploadImportType;
@ -29,11 +29,11 @@ class InstapaperController extends Controller
if ($form->isSubmitted() && $form->isValid()) { if ($form->isSubmitted() && $form->isValid()) {
$file = $form->get('file')->getData(); $file = $form->get('file')->getData();
$markAsRead = $form->get('mark_as_read')->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 $res = $instapaper
->setFilepath($this->getParameter('wallabag_import.resource_dir').'/'.$name) ->setFilepath($this->getParameter('wallabag_import.resource_dir') . '/' . $name)
->setMarkAsRead($markAsRead) ->setMarkAsRead($markAsRead)
->import(); ->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( $this->get('session')->getFlashBag()->add(
@ -61,13 +61,13 @@ class InstapaperController extends Controller
); );
return $this->redirect($this->generateUrl('homepage')); return $this->redirect($this->generateUrl('homepage'));
} else { }
$this->get('session')->getFlashBag()->add( $this->get('session')->getFlashBag()->add(
'notice', 'notice',
'flashes.import.notice.failed_on_file' 'flashes.import.notice.failed_on_file'
); );
} }
}
return $this->render('WallabagImportBundle:Instapaper:index.html.twig', [ return $this->render('WallabagImportBundle:Instapaper:index.html.twig', [
'form' => $form->createView(), 'form' => $form->createView(),

View file

@ -2,8 +2,8 @@
namespace Wallabag\ImportBundle\Controller; namespace Wallabag\ImportBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Wallabag\ImportBundle\Form\Type\UploadImportType; use Wallabag\ImportBundle\Form\Type\UploadImportType;
@ -29,11 +29,11 @@ class PinboardController extends Controller
if ($form->isSubmitted() && $form->isValid()) { if ($form->isSubmitted() && $form->isValid()) {
$file = $form->get('file')->getData(); $file = $form->get('file')->getData();
$markAsRead = $form->get('mark_as_read')->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 $res = $pinboard
->setFilepath($this->getParameter('wallabag_import.resource_dir').'/'.$name) ->setFilepath($this->getParameter('wallabag_import.resource_dir') . '/' . $name)
->setMarkAsRead($markAsRead) ->setMarkAsRead($markAsRead)
->import(); ->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( $this->get('session')->getFlashBag()->add(
@ -61,13 +61,13 @@ class PinboardController extends Controller
); );
return $this->redirect($this->generateUrl('homepage')); return $this->redirect($this->generateUrl('homepage'));
} else { }
$this->get('session')->getFlashBag()->add( $this->get('session')->getFlashBag()->add(
'notice', 'notice',
'flashes.import.notice.failed_on_file' 'flashes.import.notice.failed_on_file'
); );
} }
}
return $this->render('WallabagImportBundle:Pinboard:index.html.twig', [ return $this->render('WallabagImportBundle:Pinboard:index.html.twig', [
'form' => $form->createView(), 'form' => $form->createView(),

View file

@ -2,33 +2,14 @@
namespace Wallabag\ImportBundle\Controller; namespace Wallabag\ImportBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; 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\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class PocketController extends Controller 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") * @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']); $this->get('session')->set('mark_as_read', $request->request->get('form')['mark_as_read']);
return $this->redirect( 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 301
); );
} }
@ -117,4 +98,23 @@ class PocketController extends Controller
return $this->redirect($this->generateUrl('homepage')); 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;
}
} }

View file

@ -2,8 +2,8 @@
namespace Wallabag\ImportBundle\Controller; namespace Wallabag\ImportBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Wallabag\ImportBundle\Form\Type\UploadImportType; use Wallabag\ImportBundle\Form\Type\UploadImportType;
@ -29,11 +29,11 @@ class ReadabilityController extends Controller
if ($form->isSubmitted() && $form->isValid()) { if ($form->isSubmitted() && $form->isValid()) {
$file = $form->get('file')->getData(); $file = $form->get('file')->getData();
$markAsRead = $form->get('mark_as_read')->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 $res = $readability
->setFilepath($this->getParameter('wallabag_import.resource_dir').'/'.$name) ->setFilepath($this->getParameter('wallabag_import.resource_dir') . '/' . $name)
->setMarkAsRead($markAsRead) ->setMarkAsRead($markAsRead)
->import(); ->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( $this->get('session')->getFlashBag()->add(
@ -61,13 +61,13 @@ class ReadabilityController extends Controller
); );
return $this->redirect($this->generateUrl('homepage')); return $this->redirect($this->generateUrl('homepage'));
} else { }
$this->get('session')->getFlashBag()->add( $this->get('session')->getFlashBag()->add(
'notice', 'notice',
'flashes.import.notice.failed_on_file' 'flashes.import.notice.failed_on_file'
); );
} }
}
return $this->render('WallabagImportBundle:Readability:index.html.twig', [ return $this->render('WallabagImportBundle:Readability:index.html.twig', [
'form' => $form->createView(), 'form' => $form->createView(),

View file

@ -11,20 +11,6 @@ use Wallabag\ImportBundle\Form\Type\UploadImportType;
*/ */
abstract class WallabagController extends Controller 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. * Handle import request.
* *
@ -43,11 +29,11 @@ abstract class WallabagController extends Controller
if ($form->isSubmitted() && $form->isValid()) { if ($form->isSubmitted() && $form->isValid()) {
$file = $form->get('file')->getData(); $file = $form->get('file')->getData();
$markAsRead = $form->get('mark_as_read')->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 $res = $wallabag
->setFilepath($this->getParameter('wallabag_import.resource_dir').'/'.$name) ->setFilepath($this->getParameter('wallabag_import.resource_dir') . '/' . $name)
->setMarkAsRead($markAsRead) ->setMarkAsRead($markAsRead)
->import(); ->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( $this->get('session')->getFlashBag()->add(
@ -75,17 +61,31 @@ abstract class WallabagController extends Controller
); );
return $this->redirect($this->generateUrl('homepage')); return $this->redirect($this->generateUrl('homepage'));
} else { }
$this->get('session')->getFlashBag()->add( $this->get('session')->getFlashBag()->add(
'notice', 'notice',
'flashes.import.notice.failed_on_file' 'flashes.import.notice.failed_on_file'
); );
} }
}
return $this->render($this->getImportTemplate(), [ return $this->render($this->getImportTemplate(), [
'form' => $form->createView(), 'form' => $form->createView(),
'import' => $wallabag, '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();
} }

View file

@ -7,6 +7,14 @@ use Symfony\Component\HttpFoundation\Request;
class WallabagV1Controller extends WallabagController class WallabagV1Controller extends WallabagController
{ {
/**
* @Route("/wallabag-v1", name="import_wallabag_v1")
*/
public function indexAction(Request $request)
{
return parent::indexAction($request);
}
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
@ -30,12 +38,4 @@ class WallabagV1Controller extends WallabagController
{ {
return 'WallabagImportBundle:WallabagV1:index.html.twig'; return 'WallabagImportBundle:WallabagV1:index.html.twig';
} }
/**
* @Route("/wallabag-v1", name="import_wallabag_v1")
*/
public function indexAction(Request $request)
{
return parent::indexAction($request);
}
} }

View file

@ -7,6 +7,14 @@ use Symfony\Component\HttpFoundation\Request;
class WallabagV2Controller extends WallabagController class WallabagV2Controller extends WallabagController
{ {
/**
* @Route("/wallabag-v2", name="import_wallabag_v2")
*/
public function indexAction(Request $request)
{
return parent::indexAction($request);
}
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
@ -30,12 +38,4 @@ class WallabagV2Controller extends WallabagController
{ {
return 'WallabagImportBundle:WallabagV2:index.html.twig'; return 'WallabagImportBundle:WallabagV2:index.html.twig';
} }
/**
* @Route("/wallabag-v2", name="import_wallabag_v2")
*/
public function indexAction(Request $request)
{
return parent::indexAction($request);
}
} }

View file

@ -2,10 +2,10 @@
namespace Wallabag\ImportBundle\DependencyInjection; namespace Wallabag\ImportBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator; use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader; use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
class WallabagImportExtension extends 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.allow_mimetypes', $config['allow_mimetypes']);
$container->setParameter('wallabag_import.resource_dir', $config['resource_dir']); $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'); $loader->load('services.yml');
} }

View file

@ -3,10 +3,10 @@
namespace Wallabag\ImportBundle\Form\Type; namespace Wallabag\ImportBundle\Form\Type;
use Symfony\Component\Form\AbstractType; 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\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 class UploadImportType extends AbstractType
{ {

View file

@ -2,17 +2,17 @@
namespace Wallabag\ImportBundle\Import; namespace Wallabag\ImportBundle\Import;
use Doctrine\ORM\EntityManager;
use OldSound\RabbitMqBundle\RabbitMq\ProducerInterface;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger; use Psr\Log\NullLogger;
use Doctrine\ORM\EntityManager; use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Wallabag\CoreBundle\Helper\ContentProxy;
use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Entry;
use Wallabag\CoreBundle\Entity\Tag; use Wallabag\CoreBundle\Entity\Tag;
use Wallabag\CoreBundle\Event\EntrySavedEvent;
use Wallabag\CoreBundle\Helper\ContentProxy;
use Wallabag\CoreBundle\Helper\TagsAssigner; use Wallabag\CoreBundle\Helper\TagsAssigner;
use Wallabag\UserBundle\Entity\User; 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 abstract class AbstractImport implements ImportInterface
{ {
@ -97,6 +97,27 @@ abstract class AbstractImport implements ImportInterface
return $this; 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). * 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). * 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. * Set current imported entry to archived / read.
* Implementation is different accross all imports. * Implementation is different accross all imports.

View file

@ -3,8 +3,8 @@
namespace Wallabag\ImportBundle\Import; namespace Wallabag\ImportBundle\Import;
use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Entry;
use Wallabag\UserBundle\Entity\User;
use Wallabag\CoreBundle\Event\EntrySavedEvent; use Wallabag\CoreBundle\Event\EntrySavedEvent;
use Wallabag\UserBundle\Entity\User;
abstract class BrowserImport extends AbstractImport abstract class BrowserImport extends AbstractImport
{ {
@ -73,6 +73,80 @@ abstract class BrowserImport extends AbstractImport
return $this; 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. * 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} * {@inheritdoc}
*/ */

View file

@ -45,7 +45,7 @@ class ChromeImport extends BrowserImport
'created_at' => substr($entry['date_added'], 0, 10), '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']; $data['tags'] = $entry['tags'];
} }

View file

@ -45,7 +45,7 @@ class FirefoxImport extends BrowserImport
'created_at' => substr($entry['dateAdded'], 0, 10), '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']; $data['tags'] = $entry['tags'];
} }

View file

@ -2,8 +2,8 @@
namespace Wallabag\ImportBundle\Import; namespace Wallabag\ImportBundle\Import;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Reference;
class ImportCompilerPass implements CompilerPassInterface class ImportCompilerPass implements CompilerPassInterface

View file

@ -72,7 +72,7 @@ class InstapaperImport extends AbstractImport
// BUT it can also be the status (since status = folder in Instapaper) // BUT it can also be the status (since status = folder in Instapaper)
// and we don't want archive, unread & starred to become a tag // and we don't want archive, unread & starred to become a tag
$tags = null; $tags = null;
if (false === in_array($data[3], ['Archive', 'Unread', 'Starred'])) { if (false === in_array($data[3], ['Archive', 'Unread', 'Starred'], true)) {
$tags = [$data[3]]; $tags = [$data[3]];
} }

View file

@ -8,11 +8,10 @@ use Wallabag\CoreBundle\Entity\Entry;
class PocketImport extends AbstractImport class PocketImport extends AbstractImport
{ {
const NB_ELEMENTS = 5000;
private $client; private $client;
private $accessToken; private $accessToken;
const NB_ELEMENTS = 5000;
/** /**
* Only used for test purpose. * Only used for test purpose.
* *
@ -176,7 +175,7 @@ class PocketImport extends AbstractImport
*/ */
public function parseEntry(array $importedEntry) 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 $existingEntry = $this->em
->getRepository('WallabagCoreBundle:Entry') ->getRepository('WallabagCoreBundle:Entry')
@ -195,15 +194,15 @@ class PocketImport extends AbstractImport
$this->fetchContent($entry, $url); $this->fetchContent($entry, $url);
// 0, 1, 2 - 1 if the item is archived - 2 if the item should be deleted // 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 // 0 or 1 - 1 If the item is starred
$entry->setStarred($importedEntry['favorite'] == 1); $entry->setStarred($importedEntry['favorite'] === 1);
$title = 'Untitled'; $title = 'Untitled';
if (isset($importedEntry['resolved_title']) && $importedEntry['resolved_title'] != '') { if (isset($importedEntry['resolved_title']) && $importedEntry['resolved_title'] !== '') {
$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']; $title = $importedEntry['given_title'];
} }

View file

@ -56,12 +56,12 @@ class WallabagV1Import extends WallabagImport
// In case of a bad fetch in v1, replace title and content with v2 error strings // 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 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['title'] = $this->fetchingErrorMessageTitle;
$data['html'] = $this->fetchingErrorMessage; $data['html'] = $this->fetchingErrorMessage;
} }
if (array_key_exists('tags', $entry) && $entry['tags'] != '') { if (array_key_exists('tags', $entry) && $entry['tags'] !== '') {
$data['tags'] = $entry['tags']; $data['tags'] = $entry['tags'];
} }

Some files were not shown because too many files have changed in this diff Show more