Unverified Commit 35fe47dc authored by Sebastian Castro's avatar Sebastian Castro
Browse files

Fixs commands and other services

parent 37e034e2
doctrine:
orm:
auto_generate_proxy_classes: false
metadata_cache_driver:
type: pool
pool: doctrine.system_cache_pool
query_cache_driver:
type: pool
pool: doctrine.system_cache_pool
result_cache_driver:
type: pool
pool: doctrine.result_cache_pool
framework:
cache:
pools:
......
......@@ -37,15 +37,35 @@ services:
resource: '../src/Controller'
tags: ['controller.service_arguments']
# ----- GOGO SERVICES ------
App\Services\UploadDirectoryNamer:
class: App\Services\UploadDirectoryNamer
arguments: []
App\Services\GoGoCartoJsService:
arguments:
$baseProtocol: '%base_protocol%'
App\Services\AsyncService:
arguments:
$rootDir: '%kernel.root_dir%'
$env: '%kernel.environment%'
App\Services\WebhookService:
arguments:
$baseUrl: '%base_url%'
$basePath: '%base_path%'
App\Services\MailService:
arguments:
$basePath: '%base_path%'
$baseUrl: '%base_url%'
$saas: '%use_as_saas%'
$instanceName: '%instance_name%'
$fromEmail: '%from_email%'
$basePath: '%base_path%'
$baseUrl: '%base_url%'
$saas: '%use_as_saas%'
$instanceName: '%instance_name%'
$fromEmail: '%from_email%'
# TODO: fix auto wiring of following services
gogo.authentication_handler:
class: App\Application\Sonata\UserBundle\Security\AuthenticationHandler
public: true
......@@ -72,11 +92,20 @@ services:
- "@fos_user.util.token_generator"
- "@bazinga_geocoder.geocoder"
custom.sonata.security.handler.role:
public: true
class: App\Application\Sonata\UserBundle\Security\CustomRoleSecurityHandler
arguments:
- "@security.authorization_checker"
- [ROLE_SUPER_ADMIN]
my_user_provider:
class: App\Application\Sonata\UserBundle\Security\FOSUBUserProvider
public: true
arguments: ["@fos_user.user_manager",{facebook: facebookUid, gplus: gplusUid, communs: communsUid}]
# ----- VENDOR CONFIG (double check if it's neededn and move them into packages/)
jms_serializer.naming_strategy_camelCase:
public: true
class: 'JMS\Serializer\Naming\IdenticalPropertyNamingStrategy'
......@@ -95,18 +124,6 @@ services:
class: 'JMS\Serializer\Expression\ExpressionEvaluator'
arguments : ['@jms_serializer.expression_language']
custom.sonata.security.handler.role:
public: true
class: App\Application\Sonata\UserBundle\Security\CustomRoleSecurityHandler
arguments:
- "@security.authorization_checker"
- [ROLE_SUPER_ADMIN]
App\Services\UploadDirectoryNamer:
class: App\Services\UploadDirectoryNamer
public: true
arguments: []
gedmo.listener.sortable:
class: Gedmo\Sortable\SortableListener
calls:
......@@ -114,54 +131,30 @@ services:
tags:
- { name: doctrine.event_subscriber, connection: default }
App\Services\GoGoCartoJsService:
arguments:
$baseProtocol: '%base_protocol%'
gogo.async.factory:
class: App\Services\AsyncServiceFactory
arguments:
$rootDir: '%kernel.root_dir%'
gogo.async:
class: App\Services\AsyncService
factory: 'gogo.async.factory:createAsyncService'
# --------- EVENT LISTENERS -----------
gogo.image_resizer:
class: App\EventListener\ImageResizer
App\EventListener\ImageResizer:
arguments:
- '%env(IMAGE_RESIZE_WIDTH)%'
tags:
- { name: doctrine_mongodb.odm.event_listener, event: postPersist }
gogo.config_listener:
class: App\EventListener\ConfigurationListener
App\EventListener\ConfigurationListener:
tags:
- { name: doctrine_mongodb.odm.event_listener, event: preUpdate }
arguments: [ "@gogo.async" ]
gogo.element_json_generator:
class: App\EventListener\ElementJsonGenerator
public: true
App\EventListener\ElementJsonGenerator:
tags:
- { name: doctrine_mongodb.odm.event_listener, event: preFlush }
gogo.taxonomy_json_generator:
class: App\EventListener\TaxonomyJsonGenerator
public: true
arguments: [ '@jms_serializer' ]
App\EventListener\TaxonomyJsonGenerator:
tags:
- { name: doctrine_mongodb.odm.event_listener, event: postPersist }
- { name: doctrine_mongodb.odm.event_listener, event: postFlush }
- { name: doctrine_mongodb.odm.event_listener, event: preFlush }
- { name: doctrine_mongodb.odm.event_listener, event: postUpdate }
gogo.db_integrity:
class: App\EventListener\DatabaseIntegrityWatcher
public: true
arguments: ["@gogo.async"]
App\EventListener\DatabaseIntegrityWatcher:
tags:
- { name: doctrine_mongodb.odm.event_listener, event: preRemove }
- { name: doctrine_mongodb.odm.event_listener, event: preFlush }
......
......@@ -44,7 +44,7 @@ class CategoryAdmin extends AbstractAdmin
protected function configureFormFields(FormMapper $formMapper)
{
// prevent circular reference, i.e setting a child as parent
$dm = $this->admin->getModelManager()->getDocumentManager('App\Document\Configuration');
$dm = $this->getModelManager()->getDocumentManager('App\Document\Configuration');
$repo = $dm->getRepository('App\Document\Option');
$parentQuery = $repo->createQueryBuilder()
->field('id')->notIn($this->subject->getAllOptionsIds());
......
......@@ -24,7 +24,7 @@ class ConfigurationAPIAdmin extends ConfigurationAbstractAdmin
protected function configureFormFields(FormMapper $formMapper)
{
$dm = $this->admin->getModelManager()->getDocumentManager('App\Document\Configuration');
$dm = $this->getModelManager()->getDocumentManager('App\Document\Configuration');
$apiProperties = $dm->getRepository('App\Document\Element')->findAllCustomProperties();
$apiPropertiesChanged = [];
......
......@@ -32,7 +32,7 @@ class ConfigurationAdmin extends ConfigurationAbstractAdmin
$featureFormOption = ['delete' => false, 'required'=> false, 'label_attr'=> ['style'=> 'display:none']];
$featureFormTypeOption = ['edit' => 'inline'];
$dm = $this->admin->getModelManager()->getDocumentManager('App\Document\Configuration');
$dm = $this->getModelManager()->getDocumentManager('App\Document\Configuration');
$apiProperties = $dm->getRepository('App\Document\Element')->findAllCustomProperties();
$formMapper
......
......@@ -27,7 +27,7 @@ class ConfigurationInfoBarAdmin extends ConfigurationAbstractAdmin
{
$featureFormOption = ['delete' => false, 'required'=> false, 'label_attr'=> ['style'=> 'display:none']];
$dm = $this->admin->getModelManager()->getDocumentManager('App\Document\Configuration');
$dm = $this->getModelManager()->getDocumentManager('App\Document\Configuration');
$apiProperties = $dm->getRepository('App\Document\Element')->findAllCustomProperties();
$propertiesText = implode($apiProperties, ',');
......
......@@ -22,7 +22,7 @@ class ConfigurationMailAdmin extends ConfigurationAbstractAdmin
protected function configureFormFields(FormMapper $formMapper)
{
$dm = $this->admin->getModelManager()->getDocumentManager('App\Document\Configuration');
$dm = $this->getModelManager()->getDocumentManager('App\Document\Configuration');
$repo = $dm->getRepository('App\Document\Configuration');
$config = $repo->findConfiguration();
$router = $this->getConfigurationPool()->getContainer()->get('router');
......
......@@ -30,7 +30,7 @@ class ConfigurationMapAdmin extends ConfigurationAbstractAdmin
$featureStyle = array('class' => 'col-md-6 col-lg-3 gogo-feature');
$featureFormOption = ['delete' => false, 'required'=> false, 'label_attr'=> ['style'=> 'display:none']];
$featureFormTypeOption = ['edit' => 'inline'];
$dm = $this->admin->getModelManager()->getDocumentManager('App\Document\Configuration');
$dm = $this->getModelManager()->getDocumentManager('App\Document\Configuration');
$config = $dm->getRepository('App\Document\Configuration')->findConfiguration();
$formMapper
......
......@@ -17,7 +17,7 @@ class ElementAdmin extends ElementAdminShowEdit
{
public function getExportFields()
{
$dm = $this->admin->getModelManager()->getDocumentManager('App\Document\Configuration');
$dm = $this->getModelManager()->getDocumentManager('App\Document\Configuration');
$basicFields = [
'id' => 'id',
'name' => 'name',
......
......@@ -68,7 +68,7 @@ class ElementAdminAbstract extends AbstractAdmin
{
parent::initialize();
$dm = $this->admin->getModelManager()->getDocumentManager('App\Document\Configuration');
$dm = $this->getModelManager()->getDocumentManager('App\Document\Configuration');
$repo = $dm->getRepository('App\Document\Option');
$this->optionList = $repo->createQueryBuilder()->hydrate(false)->getQuery()->execute()->toArray();
......
......@@ -29,7 +29,7 @@ class ImportAdmin extends AbstractAdmin
protected function configureFormFields(FormMapper $formMapper)
{
$dm = $this->admin->getModelManager()->getDocumentManager('App\Document\Configuration');
$dm = $this->getModelManager()->getDocumentManager('App\Document\Configuration');
$repo = $dm->getRepository('App\Document\Element');
$formProperties = json_encode($repo->findFormProperties());
$elementProperties = json_encode($repo->findDataCustomProperties());
......@@ -147,7 +147,7 @@ Transformer un attribut
protected function configureListFields(ListMapper $listMapper)
{
$dm = $this->admin->getModelManager()->getDocumentManager('App\Document\Configuration');
$dm = $this->getModelManager()->getDocumentManager('App\Document\Configuration');
$deletedElementsCount = $dm->getRepository('App\Document\Element')->findDeletedElementsByImportIdCount();
$isDynamic = $this->getClass() == "App\Document\ImportDynamic";
......
......@@ -43,7 +43,7 @@ class OptionAdmin extends AbstractAdmin
protected function configureFormFields(FormMapper $formMapper)
{
// prevent circular reference, i.e setting a child as parent
$dm = $this->admin->getModelManager()->getDocumentManager('App\Document\Configuration');
$dm = $this->getModelManager()->getDocumentManager('App\Document\Configuration');
$repo = $dm->getRepository('App\Document\Category');
$parentQuery = $repo->createQueryBuilder()
->field('id')->notIn($this->subject->getAllSubcategoriesIds());
......
<?php
namespace App\Command;
use App\Command\GoGoAbstractCommand;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Class CallServiceCommand
* @package Krlove\AsyncServiceCallBundle\Command
*/
class CallServiceCommand extends GoGoAbstractCommand
{
/**
* @inheritdoc
*/
protected function gogoConfigure()
{
$this
->setName('krlove:service:call')
->setDescription('Calls a service method with arguments')
->addArgument('service', InputArgument::REQUIRED, 'Service ID')
->addArgument('method', InputArgument::REQUIRED, 'Method to call on the service')
->addOption('args', null, InputOption::VALUE_OPTIONAL, 'Arguments to supply to the method');
}
/**
* @inheritdoc
*/
protected function gogoExecute($dm, InputInterface $input, OutputInterface $output)
{
$logger = $this->getContainer()->get('logger');
try {
$serviceId = $input->getArgument('service');
$service = $this->getContainer()->get($serviceId);
$logger->error("execute command");
$method = $input->getArgument('method');
if (!method_exists($service, $method)) {
throw new InvalidArgumentException(
sprintf('Method %s doesn\'t exist on class %s', $method, get_class($service))
);
}
$serviceArgs = unserialize(base64_decode($input->getOption('args')));
if ($serviceArgs) {
call_user_func_array([$service, $method], $serviceArgs);
} else {
call_user_func([$service, $method]);
}
} catch (\Exception $e) {
$logger->error($e->getMessage());
}
}
}
\ No newline at end of file
......@@ -7,11 +7,22 @@ use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use App\Document\ImportState;
use App\Document\ElementStatus;
use App\Services\ElementImportService;
use App\Command\GoGoAbstractCommand;
use Doctrine\ODM\MongoDB\DocumentManager;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class CheckExternalSourceToUpdateCommand extends GoGoAbstractCommand
{
public function __construct(DocumentManager $dm, LoggerInterface $commandsLogger,
TokenStorageInterface $security,
ElementImportService $importService)
{
$this->importService = $importService;
parent::__construct($dm, $commandsLogger, $security);
}
protected function gogoConfigure()
{
$this
......@@ -27,7 +38,6 @@ class CheckExternalSourceToUpdateCommand extends GoGoAbstractCommand
$dynamicImports = $qb->field('refreshFrequencyInDays')->gt(0)
->field('nextRefresh')->lte(new \DateTime())
->getQuery()->execute();
$importService = $this->getContainer()->get('gogo.element_import');
$this->log('CheckExternalSourceToUpdate : Nombre de sources à mettre à jour : ' . $dynamicImports->count());
......@@ -35,7 +45,7 @@ class CheckExternalSourceToUpdateCommand extends GoGoAbstractCommand
{
$this->log('Updating source : ' . $import->getSourceName());
try {
$this->log($importService->startImport($import));
$this->log($this->importService->startImport($import));
} catch (\Exception $e) {
$this->dm->persist($import);
$import->setCurrState(ImportState::Failed);
......
......@@ -5,13 +5,23 @@ use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use App\Document\ElementStatus;
use App\Command\GoGoAbstractCommand;
use Doctrine\ODM\MongoDB\DocumentManager;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use App\Services\ElementVoteService;
class CheckVoteCommand extends GoGoAbstractCommand
{
public function __construct(DocumentManager $dm, LoggerInterface $commandsLogger,
TokenStorageInterface $security,
ElementVoteService $voteService)
{
$this->voteService = $voteService;
parent::__construct($dm, $commandsLogger, $security);
}
protected function gogoConfigure()
{
$this
......@@ -25,11 +35,9 @@ class CheckVoteCommand extends GoGoAbstractCommand
$elementRepo = $dm->getRepository('App\Document\Element');
$elements = $elementRepo->findPendings();
$voteService = $this->getContainer()->get('gogo.element_vote_service');
foreach ($elements as $key => $element)
{
$voteService->checkVotes($element);
$this->voteService->checkVotes($element);
$dm->persist($element);
}
......
......@@ -7,9 +7,21 @@ use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use App\Command\GoGoAbstractCommand;
use Doctrine\ODM\MongoDB\DocumentManager;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use App\Services\RandomCreationService;
class GenerateElementsCommand extends GoGoAbstractCommand
{
public function __construct(DocumentManager $dm, LoggerInterface $commandsLogger,
TokenStorageInterface $security,
RandomCreationService $randomService)
{
$this->randomService = $randomService;
parent::__construct($dm, $commandsLogger, $security);
}
protected function gogoConfigure()
{
$this
......@@ -25,7 +37,7 @@ class GenerateElementsCommand extends GoGoAbstractCommand
{
$this->output = $output;
$this->getContainer()->get('gogo.random_creation_service')->generate($input->getArgument('number'), $input->getArgument('generateVotes'));
$randomService->generate($input->getArgument('number'), $input->getArgument('generateVotes'));
$this->log('Element générés !');
}
......
......@@ -10,12 +10,22 @@ use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use App\Document\GoGoLog;
use App\Document\GoGoLogLevel;
use Doctrine\ODM\MongoDB\DocumentManager;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class GoGoAbstractCommand extends Command
{
protected $logger;
protected $output;
public function __construct(DocumentManager $dm, LoggerInterface $commandsLogger,
TokenStorageInterface $tokenStorage)
{
$this->dm = $dm;
$this->logger = $commandsLogger;
$this->security = $tokenStorage;
parent::__construct();
}
protected function configure()
{
$this->setName('app:abstract:command');
......@@ -23,19 +33,16 @@ class GoGoAbstractCommand extends Command
$this->addArgument('dbname', InputArgument::OPTIONAL, 'Db name');
}
protected function execute(InputInterface $input, OutputInterface $output, DocumentManager $dm)
protected function execute(InputInterface $input, OutputInterface $output)
{
try {
$this->dm = $dm;
$this->logger = $this->getContainer()->get('monolog.logger.commands');
$this->output = $output;
if ($input->getArgument('dbname')) $this->dm->getConfiguration()->setDefaultDB($input->getArgument('dbname'));
// create dummy user, as some code called from command will maybe need the current user informations
$token = new AnonymousToken('admin', 'GoGo Gadget au Bot', ['ROLE_ADMIN']);
$this->getContainer()->get('security.token_storage')->setToken($token);
$this->security->setToken($token);
$this->gogoExecute($this->dm, $input, $output);
} catch (\Exception $e) {
......
......@@ -7,6 +7,7 @@ use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\ArrayInput;
use Doctrine\ODM\MongoDB\DocumentManager;
use Psr\Log\LoggerInterface;
/*
* For SAAS Instance, this command is executed every minute, and check if there is a command to execute
......@@ -22,21 +23,26 @@ class GoGoMainCommand extends Command
"app:webhooks:post" => "5M" // 5 minuutes
];
public function __construct(DocumentManager $dm, LoggerInterface $commandsLogger)
{
$this->dm = $dm;
$this->logger = $commandsLogger;
parent::__construct();
}
protected function configure()
{
$this->setName('app:main-command');
}
protected function execute(InputInterface $input, OutputInterface $output, DocumentManager $dm)
protected function execute(InputInterface $input, OutputInterface $output)
{
$qb = $dm->createQueryBuilder('App\Document\ScheduledCommand');
$qb = $this->dm->createQueryBuilder('App\Document\ScheduledCommand');
$commandToExecute = $qb->field('nextExecutionAt')->lte(new \DateTime())
->sort('nextExecutionAt', 'ASC')
->getQuery()->getSingleResult();
$logger = $this->getContainer()->get('monolog.logger.commands');
if ($commandToExecute !== null)
{
// Updating next execution time
......@@ -44,16 +50,16 @@ class GoGoMainCommand extends Command
$dateNow->setTimestamp(time());
$interval = new \DateInterval('PT' . $this->scheduledCommands[$commandToExecute->getCommandName()]);
$commandToExecute->setNextExecutionAt($dateNow->add($interval));
$dm->persist($commandToExecute);
$dm->flush();
$this->dm->persist($commandToExecute);
$this->dm->flush();
try {
$logger->info('---- Running command ' . $commandToExecute->getCommandName() . ' for project : ' . $commandToExecute->getProject()->getName());
$this->logger->info('---- Running command ' . $commandToExecute->getCommandName() . ' for project : ' . $commandToExecute->getProject()->getName());
} catch (\Exception $e) {
// the project has been deleted
$logger->info('---- DELETEING command ' . $commandToExecute->getCommandName());
$dm->remove($commandToExecute);
$dm->flush();
$this->logger->info('---- DELETEING command ' . $commandToExecute->getCommandName());
$this->dm->remove($commandToExecute);
$this->dm->flush();
return;
}
$command = $this->getApplication()->find($commandToExecute->getCommandNAme());
......@@ -65,7 +71,7 @@ class GoGoMainCommand extends Command
$input = new ArrayInput($arguments);
try { $command->run($input, $output); }
catch (\Exception $e) { $logger->error($e->getMessage()); }
catch (\Exception $e) { $this->logger->error($e->getMessage()); }
}
}
}
\ No newline at end of file
......@@ -9,9 +9,21 @@ use App\Document\ImportState;
use App\Document\ElementStatus;
use App\Command\GoGoAbstractCommand;
use Doctrine\ODM\MongoDB\DocumentManager;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use App\Services\ElementImportService;
class ImportSourceCommand extends GoGoAbstractCommand
{
public function __construct(DocumentManager $dm, LoggerInterface $commandsLogger,
TokenStorageInterface $security,
ElementImportService $importService)
{
$this->importService = $importService;
parent::__construct($dm, $commandsLogger, $security);
}
protected function gogoConfigure()
{
$this
......@@ -35,7 +47,6 @@ class ImportSourceCommand extends GoGoAbstractCommand
}
$this->log('Updating source ' . $import->getSourceName() . ' for project ' . $input->getArgument('dbname') . ' begins...');
$importService = $this->getContainer()->get('gogo.element_import');
$result = $importService->startImport($import);
$this->log($result);
} catch (\Exception $e) {
......
......@@ -9,6 +9,11 @@ use App\Document\MigrationState;
use App\Document\GoGoLogUpdate;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Process\Process;
use Doctrine\ODM\MongoDB\DocumentManager;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use App\Services\AsyncService;
/**
* Command to update database when schema need migration
* Also provide some update message in the admin dashboard
......@@ -52,6 +57,13 @@ class MigrationCommand extends GoGoAbstractCommand
"Il est maintenant possible de <b>téléverser des images et des fichiers</b> depuis le formulaire d'ajout d'un élément ! Paramétrez ces nouveaux champs dans Modèle de Données -> Formulaire"
];
public function __construct(DocumentManager $dm, LoggerInterface $commandsLogger,
TokenStorageInterface $security,
AsyncService $asyncService)
{
$this->asyncService = $asyncService;
parent::__construct($dm, $commandsLogger, $security);
}
protected function gogoConfigure()