point-tools/src/Skobkin/Bundle/PointToolsBundle/Command/UpdateSubscriptionsCommand.php

295 lines
8.9 KiB
PHP
Raw Normal View History

<?php
namespace Skobkin\Bundle\PointToolsBundle\Command;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Skobkin\Bundle\PointToolsBundle\Entity\Subscription;
use Skobkin\Bundle\PointToolsBundle\Entity\User;
2017-01-17 21:58:53 +00:00
use Skobkin\Bundle\PointToolsBundle\Exception\Api\UserNotFoundException;
use Skobkin\Bundle\PointToolsBundle\Repository\UserRepository;
use Skobkin\Bundle\PointToolsBundle\Service\SubscriptionsManager;
use Skobkin\Bundle\PointToolsBundle\Service\Api\UserApi;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @todo https://symfony.com/doc/current/console/lockable_trait.html
*/
class UpdateSubscriptionsCommand extends ContainerAwareCommand
{
/**
* @var EntityManagerInterface
*/
private $em;
/**
* @var LoggerInterface
*/
private $logger;
/**
* @var UserRepository
*/
private $userRepo;
/**
* @var InputInterface
*/
private $input;
/**
* @var UserApi
*/
private $api;
/**
* @var int
*/
private $apiDelay = 500000;
/**
* @var SubscriptionsManager
*/
private $subscriptionManager;
/**
* @var ProgressBar
*/
private $progress;
2017-01-12 23:02:25 +00:00
public function setLogger(LoggerInterface $logger): void
{
$this->logger = $logger;
}
2017-01-12 23:02:25 +00:00
public function setEntityManager(EntityManagerInterface $em): void
{
$this->em = $em;
}
2017-01-12 23:02:25 +00:00
public function setUserRepository(UserRepository $repository): void
{
$this->userRepo = $repository;
}
2017-01-12 23:02:25 +00:00
public function setApiClient(UserApi $userApi): void
{
$this->api = $userApi;
}
2017-01-12 23:02:25 +00:00
public function setApiDelay(int $microSecs): void
{
$this->apiDelay = $microSecs;
}
2017-01-12 23:02:25 +00:00
public function setSubscriptionManager(SubscriptionsManager $subscriptionsManager): void
{
$this->subscriptionManager = $subscriptionsManager;
}
protected function configure()
{
$this
->setName('point:update:subscriptions')
->setDescription('Update subscriptions of users subscribed to service')
->addOption(
'all-users',
null,
InputOption::VALUE_NONE,
'If set, command will check subscribers of all service users instead of service subscribers only'
)
->addOption(
'check-only',
null,
InputOption::VALUE_NONE,
'If set, command will not perform write operations in the database'
)
// @todo add option for checking only selected user
;
}
2015-05-30 22:50:35 +00:00
/**
* @param InputInterface $input
* @param OutputInterface $output
*
* @return int
2015-05-30 22:50:35 +00:00
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->input = $input;
2015-05-30 22:50:35 +00:00
$this->logger->debug('UpdateSubscriptionsCommand started.');
2015-06-02 01:59:07 +00:00
try {
$appUserId = $this->getContainer()->getParameter('point_id');
2015-06-02 01:59:07 +00:00
} catch (\InvalidArgumentException $e) {
$this->logger->alert('Could not get point_id parameter from config file', ['exception_message' => $e->getMessage()]);
return 1;
2015-06-02 01:59:07 +00:00
}
$this->progress = new ProgressBar($output);
$this->progress->setFormat('debug');
// Beginning transaction for all changes
$this->em->beginTransaction();
$this->progress->setMessage('Getting service subscribers');
try {
$usersForUpdate = $this->getUsersForUpdate($appUserId);
} catch (\Exception $e) {
$this->logger->error('Error while getting service subscribers', ['exception' => get_class($e), 'message' => $e->getMessage()]);
return 1;
}
2015-05-30 22:50:35 +00:00
if (0 === count($usersForUpdate)) {
$this->logger->info('No local subscribers. Finishing.');
return 0;
}
$this->logger->info('Processing users subscribers');
$this->progress->setMessage('Processing users subscribers');
$this->progress->start(count($usersForUpdate));
$this->updateUsersSubscribers($usersForUpdate);
$this->progress->finish();
// Flushing all changes at once to database
$this->em->flush();
$this->em->commit();
$this->logger->debug('Finished');
return 0;
}
/**
* @param User[] $users
*/
2017-01-12 23:02:25 +00:00
private function updateUsersSubscribers(array $users): void
{
// Updating users subscribers
foreach ($users as $user) {
usleep($this->apiDelay);
$this->progress->advance();
$this->logger->info('Processing @'.$user->getLogin());
try {
$userCurrentSubscribers = $this->api->getUserSubscribersById($user->getId());
2017-01-17 21:58:53 +00:00
} catch (UserNotFoundException $e) {
$this->logger->warning('User not found. Marking as removed', ['login' => $user->getLogin(), 'user_id' => $user->getId()]);
$user->markAsRemoved();
continue;
} catch (\Exception $e) {
$this->logger->error(
'Error while getting subscribers. Skipping.',
[
'user_login' => $user->getLogin(),
'user_id' => $user->getId(),
'message' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
]
);
2015-05-30 22:50:35 +00:00
continue;
2015-06-02 02:39:09 +00:00
}
$this->logger->debug('Updating user subscribers');
try {
// Updating user subscribers
$this->subscriptionManager->updateUserSubscribers($user, $userCurrentSubscribers);
} catch (\Exception $e) {
$this->logger->error(
'Error while updating user subscribers',
[
'user_login' => $user->getLogin(),
'user_id' => $user->getId(),
'message' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
]
);
}
2015-05-30 22:50:35 +00:00
}
}
private function getUsersForUpdate(int $appUserId): array
{
2017-01-17 21:58:53 +00:00
$usersForUpdate = [];
if ($this->input->getOption('all-users')) {
2017-01-17 21:58:53 +00:00
$usersForUpdate = $this->userRepo->findBy(['removed' => false]);
} else {
/** @var User $serviceUser */
2017-01-17 21:58:53 +00:00
$serviceUser = $this->userRepo->findActiveUserWithSubscribers($appUserId);
if (!$serviceUser) {
2017-01-17 21:58:53 +00:00
$this->logger->critical('Service user not found or marked as removed');
// @todo Retrieving user
throw new \RuntimeException('Service user not found in the database');
}
$this->logger->info('Getting service subscribers');
try {
$usersForUpdate = $this->api->getUserSubscribersById($appUserId);
2017-01-17 21:58:53 +00:00
} catch (UserNotFoundException $e) {
$this->logger->critical('Service user deleted or API response is invalid');
throw $e;
} catch (\Exception $e) {
$this->logger->warning(
'Error while getting service subscribers. Fallback to local list.',
[
'user_login' => $serviceUser->getLogin(),
'user_id' => $serviceUser->getId(),
'message' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
]
);
2015-05-30 22:50:35 +00:00
/** @var Subscription $subscription */
foreach ((array) $serviceUser->getSubscribers() as $subscription) {
$usersForUpdate[] = $subscription->getSubscriber();
}
}
$this->logger->debug('Updating service subscribers');
// Updating service subscribers
2015-05-30 22:50:35 +00:00
try {
$this->subscriptionManager->updateUserSubscribers($serviceUser, $usersForUpdate);
2015-05-30 22:50:35 +00:00
} catch (\Exception $e) {
$this->logger->error(
'Error while updating service subscribers',
[
'user_login' => $serviceUser->getLogin(),
'user_id' => $serviceUser->getId(),
'message' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
]
);
throw $e;
}
}
return $usersForUpdate;
}
}