diff --git a/bin/validate b/bin/validate
index 46ed7db..b92cfb0 100755
--- a/bin/validate
+++ b/bin/validate
@@ -4,6 +4,7 @@ vendor/bin/rector process src --dry-run &&
vendor/bin/php-cs-fixer fix --allow-risky yes --dry-run -v &&
vendor/bin/phpstan analyse src -c phpstan.neon --level max &&
vendor/bin/phan --progress-bar &&
+phpunit &&
composer validate --strict --no-check-lock &&
composer outdated &&
vendor/bin/security-checker security:check
diff --git a/src/Admin/Sonata/Twig/CommandsQueuesExtension.php b/src/Admin/Sonata/Twig/CommandsQueuesExtension.php
index 6c9add3..1b05a53 100644
--- a/src/Admin/Sonata/Twig/CommandsQueuesExtension.php
+++ b/src/Admin/Sonata/Twig/CommandsQueuesExtension.php
@@ -18,7 +18,7 @@
namespace SerendipityHQ\Bundle\CommandsQueuesBundle\Admin\Sonata\Twig;
use Safe\Exceptions\StringsException;
-use Safe\sprintf;
+use function Safe\sprintf;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Entity\Job;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Twig\Extension\AbstractExtension;
@@ -60,11 +60,10 @@ public function getFilters(): array
public function getIdOptionValue(Job $job): ?string
{
$input = $job->getInput();
- if (false === array_key_exists('options', $input) && isset($input['options']['--id'])) {
- $url = $this->generator->generate('admin_serendipityhq_commandsqueues_job_show', ['id' => $input['options']['--id']], UrlGeneratorInterface::ABSOLUTE_PATH);
-
- return sprintf('#%s', $url, $input['options']['--id']);
+ if (null !== $input && false === array_key_exists('options', $input) && isset($input['options']['--id'])) {
+ $url = $this->generator->generate('admin_serendipityhq_commandsqueues_job_show', ['id' => $input['options']['--id']], UrlGeneratorInterface::ABSOLUTE_PATH);
+ return sprintf('#%s', $url, $input['options']['--id']);
}
return null;
diff --git a/src/Command/InternalMarkAsCancelledCommand.php b/src/Command/InternalMarkAsCancelledCommand.php
index 00df5b8..5644b3c 100644
--- a/src/Command/InternalMarkAsCancelledCommand.php
+++ b/src/Command/InternalMarkAsCancelledCommand.php
@@ -20,6 +20,7 @@
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use Safe\Exceptions\StringsException;
+use function Safe\sprintf;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Entity\Job;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Repository\JobRepository;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Util\JobsMarker;
@@ -103,7 +104,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
if (null === $failedJob) {
// The job may not exist anymore if it expired and so was deleted
- $this->getIoWriter()->infoLineNoBg(\Safe\sprintf("The job %s doesn't exist anymore.", $failedJob));
+ $this->getIoWriter()->infoLineNoBg(sprintf("The job %s doesn't exist anymore.", $failedJob));
return 0;
}
@@ -115,9 +116,9 @@ protected function execute(InputInterface $input, OutputInterface $output): int
}
// We only cancel childs and not the failed Job as the failed Job is marked as "failed" and we don't want to change its status)
- $this->cancelChildJobs($failedJob, $cancellingJob, \Safe\sprintf('Parent Job %s failed.', $failedJob->getId()));
+ $this->cancelChildJobs($failedJob, $cancellingJob, sprintf('Parent Job %s failed.', $failedJob->getId()));
- $this->getIoWriter()->successLineNoBg(\Safe\sprintf('All child jobs of Job %s and their respective child Jobs were marked as cancelled.', $failedJob->getId()));
+ $this->getIoWriter()->successLineNoBg(sprintf('All child jobs of Job %s and their respective child Jobs were marked as cancelled.', $failedJob->getId()));
return 0;
}
@@ -135,7 +136,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
*/
private function cancelChildJobs(Job $markedJob, Job $cancellingJob, string $cancellationReason, array $alreadyCancelledJobs = []): int
{
- $this->getIoWriter()->infoLineNoBg(\Safe\sprintf('Start cancelling child Jobs of Job #%s@%s.', $markedJob->getId(), $markedJob->getQueue()));
+ $this->getIoWriter()->infoLineNoBg(sprintf('Start cancelling child Jobs of Job #%s@%s.', $markedJob->getId(), $markedJob->getQueue()));
// "Security check", no child jobs: ...
if ($markedJob->getChildDependencies()->count() <= 0) {
@@ -151,7 +152,7 @@ private function cancelChildJobs(Job $markedJob, Job $cancellingJob, string $can
],
];
- $this->getIoWriter()->noteLineNoBg(\Safe\sprintf(
+ $this->getIoWriter()->noteLineNoBg(sprintf(
'[%s] Job #%s@%s: Found %s child dependencies. Start marking them.',
JobsUtil::getFormattedTime($markedJob, 'getClosedAt'), $markedJob->getId(), $markedJob->getQueue(), $markedJob->getChildDependencies()->count())
);
@@ -183,12 +184,12 @@ private function cancelChildJobs(Job $markedJob, Job $cancellingJob, string $can
// If this child has other childs on its own...
if ($childDependency->getChildDependencies()->count() > 0) {
// ... Mark as cancelled also the child Jobs of this child Job
- $this->cancelChildJobs($childDependency, $cancellingJob, \Safe\sprintf('Child Job "#%s" were cancelled.', $childDependency->getId()), $alreadyCancelledJobs);
+ $this->cancelChildJobs($childDependency, $cancellingJob, sprintf('Child Job "#%s" were cancelled.', $childDependency->getId()), $alreadyCancelledJobs);
}
}
$cancelledChilds = implode(', ', $cancelledChilds);
- $this->getIoWriter()->noteLineNoBg(\Safe\sprintf(
+ $this->getIoWriter()->noteLineNoBg(sprintf(
'[%s] Job #%s@%s: Cancelled childs are: %s', JobsUtil::getFormattedTime($markedJob, 'getClosedAt'), $markedJob->getId(), $markedJob->getQueue(), $cancelledChilds
));
diff --git a/src/Command/RunCommand.php b/src/Command/RunCommand.php
index a75e2d5..cd07e81 100644
--- a/src/Command/RunCommand.php
+++ b/src/Command/RunCommand.php
@@ -32,6 +32,7 @@
use Safe\Exceptions\PcntlException;
use Safe\Exceptions\StreamException;
use Safe\Exceptions\StringsException;
+use function Safe\sprintf;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Entity\Daemon;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Repository\DaemonRepository;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Service\QueuesDaemon;
@@ -175,7 +176,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
foreach ($this->daemon->getConfig()->getQueues() as $queueName) {
if (false === $this->daemon->canInitializeNewJobs($queueName)) {
if ($this->ioWriter->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) {
- $this->ioWriter->infoLineNoBg(\Safe\sprintf('The queue %s is already processing the max allowed number of concurrent Jobs.', $queueName));
+ $this->ioWriter->infoLineNoBg(sprintf('The queue %s is already processing the max allowed number of concurrent Jobs.', $queueName));
}
continue;
@@ -184,14 +185,14 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$jobsToLoad = $this->daemon->getJobsToLoad($queueName);
if (0 < $jobsToLoad) {
if ($this->ioWriter->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) {
- $this->ioWriter->infoLineNoBg(\Safe\sprintf('Trying to initialize %s new Jobs for queue %s...', $jobsToLoad, $queueName));
+ $this->ioWriter->infoLineNoBg(sprintf('Trying to initialize %s new Jobs for queue %s...', $jobsToLoad, $queueName));
$initializingJobs = ProgressBarFactory::createProgressBar(ProgressBarFactory::FORMAT_INITIALIZING_JOBS, $output, $jobsToLoad);
}
for ($i = 0; $i < $jobsToLoad; ++$i) {
// Start processing the next Job in the queue
if (false === $this->daemon->processNextJob($queueName)) {
if ($this->ioWriter->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) {
- $this->ioWriter->infoLineNoBg(\Safe\sprintf('Queue %s is empty: no more Jobs to initialize.', $queueName));
+ $this->ioWriter->infoLineNoBg(sprintf('Queue %s is empty: no more Jobs to initialize.', $queueName));
}
// The next Job is null: exit this queue and pass to the next one
@@ -249,7 +250,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
}
if ($this->ioWriter->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) {
- $this->ioWriter->infoLineNoBg(\Safe\sprintf(
+ $this->ioWriter->infoLineNoBg(sprintf(
'No Jobs to process. Idling for %s seconds...', $this->daemon->getConfig()->getSleepFor()
));
}
@@ -317,7 +318,7 @@ private function checkAliveDaemons(): void
return;
}
- $this->ioWriter->infoLineNoBg(\Safe\sprintf('Found %s struggler Daemon(s).', count($strugglers)));
+ $this->ioWriter->infoLineNoBg(sprintf('Found %s struggler Daemon(s).', count($strugglers)));
$this->ioWriter->commentLineNoBg('Their "diedOn" date is set to NOW and mortisCausa is "struggler".');
$table = [];
@@ -325,12 +326,12 @@ private function checkAliveDaemons(): void
$strugglerDaemonDieOn = $strugglerDaemon->getDiedOn();
if (null === $strugglerDaemonDieOn) {
- throw new RuntimeException(\Safe\sprintf("The daemon %s is being processed as struggler, but it hasn't a die date.", $strugglerDaemon->getId()));
+ throw new RuntimeException(sprintf("The daemon %s is being processed as struggler, but it hasn't a die date.", $strugglerDaemon->getId()));
}
$age = $strugglerDaemonDieOn->diff($strugglerDaemon->getBornOn());
$table[] = [
- \Safe\sprintf('<%s>%s>', 'success-nobg', "\xE2\x9C\x94"),
+ sprintf('<%s>%s>', 'success-nobg', "\xE2\x9C\x94"),
$strugglerDaemon->getPid(),
$strugglerDaemon->getHost(),
$strugglerDaemon->getBornOn()->format('Y-m-d H:i:s'),
@@ -359,7 +360,7 @@ private function checkAliveDaemons(): void
private function isDaemonStillRunning(Daemon $daemon): bool
{
// Get the running processes with the Daemon's PID
- exec(\Safe\sprintf('ps -ef | grep %s', $daemon->getPid()), $lines);
+ exec(sprintf('ps -ef | grep %s', $daemon->getPid()), $lines);
// Search the line with this command name: this indicates the process is still running
foreach ($lines as $line) {
@@ -383,7 +384,7 @@ private function processRunningJobs(string $queueName): void
{
$currentlyRunningProgress = null;
if ($this->ioWriter->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) {
- $this->ioWriter->infoLineNoBg(\Safe\sprintf(
+ $this->ioWriter->infoLineNoBg(sprintf(
'Checking %s running jobs on queue "%s"...',
$this->daemon->countRunningJobs($queueName), $queueName
));
diff --git a/src/Command/TestFakeCommand.php b/src/Command/TestFakeCommand.php
index 4e513ef..469a72f 100644
--- a/src/Command/TestFakeCommand.php
+++ b/src/Command/TestFakeCommand.php
@@ -20,6 +20,8 @@
use Exception;
use InvalidArgumentException;
use RuntimeException;
+use function Safe\sleep;
+use function Safe\sprintf;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
@@ -86,8 +88,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int
// Emulate a duration to execute the command
$rand = random_int(0, 10);
- $output->writeln(\Safe\sprintf("I'm so tired... I will sleep for %s seconds... Good bye, see you soon! :)", $rand));
- \Safe\sleep($rand);
+ $output->writeln(sprintf("I'm so tired... I will sleep for %s seconds... Good bye, see you soon! :)", $rand));
+ sleep($rand);
// Ok, all gone well (fingers crossed? :P )
$output->writeln('Hello! I just woke up! :) ... Finito.');
diff --git a/src/Command/TestRandomJobsCommand.php b/src/Command/TestRandomJobsCommand.php
index 3a2e2e9..6bad2fb 100644
--- a/src/Command/TestRandomJobsCommand.php
+++ b/src/Command/TestRandomJobsCommand.php
@@ -22,6 +22,7 @@
use Exception;
use Safe\Exceptions\ArrayException;
use Safe\Exceptions\StringsException;
+use function Safe\sprintf;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Entity\Job;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Util\JobsMarker;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Util\ProgressBarFactory;
@@ -119,7 +120,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
}
$this->getIoWriter()->title('SerendipityHQ Queue Bundle Daemon');
- $this->getIoWriter()->info(\Safe\sprintf('Starting generating %s random jobs...', $howManyJobs));
+ $this->getIoWriter()->info(sprintf('Starting generating %s random jobs...', $howManyJobs));
// Generate the random jobs
$progress = ProgressBarFactory::createProgressBar(ProgressBarFactory::FORMAT_CREATE_JOBS, $output, $howManyJobs);
@@ -182,7 +183,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$progress->finish();
$this->getIoWriter()->write("\n\n");
- $this->getIoWriter()->success(\Safe\sprintf('All done: %s random jobs generated!', $howManyJobs));
+ $this->getIoWriter()->success(sprintf('All done: %s random jobs generated!', $howManyJobs));
return 0;
}
diff --git a/src/DependencyInjection/Configuration.php b/src/DependencyInjection/Configuration.php
index c936989..3fabba3 100644
--- a/src/DependencyInjection/Configuration.php
+++ b/src/DependencyInjection/Configuration.php
@@ -19,6 +19,8 @@
use Safe\Exceptions\ArrayException;
use Safe\Exceptions\StringsException;
+use function Safe\ksort;
+use function Safe\sprintf;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Entity\Daemon;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
@@ -274,7 +276,7 @@ public function getConfigTreeBuilder(): TreeBuilder
private function validateConfiguration(array $tree): bool
{
if (1 > $tree[self::DAEMON_ALIVE_DAEMONS_CHECK_INTERVAL_KEY]) {
- throw new InvalidConfigurationException(\Safe\sprintf(
+ throw new InvalidConfigurationException(sprintf(
'The global "%s" config param MUST be greater than 0. You set it to "%s".', self::DAEMON_ALIVE_DAEMONS_CHECK_INTERVAL_KEY, $tree[self::DAEMON_ALIVE_DAEMONS_CHECK_INTERVAL_KEY]
));
}
@@ -282,7 +284,7 @@ private function validateConfiguration(array $tree): bool
foreach ($tree['daemons'] as $daemon => $config) {
// A Daemon MUST HAVE at least one queue assigned
if (empty($config['queues'])) {
- throw new InvalidConfigurationException(\Safe\sprintf(
+ throw new InvalidConfigurationException(sprintf(
'The "%s" daemon MUST specify at least one queue to process.', $daemon
));
}
@@ -290,7 +292,7 @@ private function validateConfiguration(array $tree): bool
// Check the queue is not already assigned
foreach ($config['queues'] as $queue) {
if (array_key_exists($queue, $this->foundQueues)) {
- throw new InvalidConfigurationException(\Safe\sprintf(
+ throw new InvalidConfigurationException(sprintf(
'Queue "%s" already assigned to daemon "%s". You cannot assign this queue also to daemon "%s".',
$queue, $this->foundQueues[$queue], $daemon
));
@@ -338,7 +340,7 @@ private function prepareConfiguration(array $tree): array
}
// Sort queues alphabetically
- \Safe\ksort($returnConfig['queues']);
+ ksort($returnConfig['queues']);
// Now configure the queues
foreach ($returnConfig['queues'] as $queue => $config) {
diff --git a/src/Entity/Job.php b/src/Entity/Job.php
index 701df2c..afad60d 100644
--- a/src/Entity/Job.php
+++ b/src/Entity/Job.php
@@ -17,7 +17,6 @@
namespace SerendipityHQ\Bundle\CommandsQueuesBundle\Entity;
-use BadMethodCallException;
use DateTime;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
@@ -25,8 +24,8 @@
use Exception;
use InvalidArgumentException;
use LogicException;
-use RuntimeException;
use Safe\Exceptions\StringsException;
+use function Safe\sprintf;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Command\InternalMarkAsCancelledCommand;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Util\InputParser;
use SerendipityHQ\Component\ThenWhen\Strategy\LiveStrategy;
@@ -105,7 +104,7 @@ class Job
public const STATUS_SUCCEEDED = 'succeeded';
/**
- * A failed Job that were retried and the retry Job were finished
+ * A failed Job that were retried and the retry Job were finished.
*
* @var string */
public const STATUS_RETRY_SUCCEEDED = 'retry_succeeded';
@@ -123,7 +122,7 @@ class Job
public const STATUS_FAILED = 'failed';
/**
- * A failed Job that were retried and the retry Job failed, too
+ * A failed Job that were retried and the retry Job failed, too.
*
* @var string */
public const STATUS_RETRY_FAILED = 'retry_failed';
@@ -349,15 +348,15 @@ class Job
/**
* @param string $command
- * @param array|string $arguments
+ * @param array|string $input
* @param string $queue
*
* @throws Exception
*/
- public function __construct(string $command, $arguments = [], string $queue = Daemon::DEFAULT_QUEUE_NAME)
+ public function __construct(string $command, $input = [], string $queue = Daemon::DEFAULT_QUEUE_NAME)
{
$this->command = $command;
- $this->input = InputParser::parseInput($arguments);
+ $this->input = InputParser::parseInput($input);
$this->priority = 1;
$this->queue = $queue;
$this->status = self::STATUS_NEW;
@@ -381,7 +380,7 @@ public function __construct(string $command, $arguments = [], string $queue = Da
public function addArgument(string $value): Job
{
if (false === InputParser::isArgument($value)) {
- throw new InvalidArgumentException('Job::addArgument() doesn\'t accept options nor shortcuts.');
+ throw new InvalidArgumentException("Job::addArgument() doesn't accept options nor shortcuts.");
}
$this->input['arguments'][] = $value;
@@ -395,8 +394,9 @@ public function addArgument(string $value): Job
* @param string $option
* @param string|null $value
*
- * @return Job
* @throws StringsException
+ *
+ * @return Job
*/
public function addOption(string $option, ?string $value = null): Job
{
@@ -409,7 +409,7 @@ public function addOption(string $option, ?string $value = null): Job
}
if (array_key_exists($option, $this->input['options'])) {
- throw new InvalidArgumentException(\Safe\sprintf('The option "%s" was already added to the command.', $option));
+ throw new InvalidArgumentException(sprintf('The option "%s" was already added to the command.', $option));
}
$this->input['options'][$option] = $value;
@@ -421,8 +421,9 @@ public function addOption(string $option, ?string $value = null): Job
* @param string $option
* @param string|null $value
*
- * @return Job
* @throws StringsException
+ *
+ * @return Job
*/
public function addShortcut(string $option, ?string $value = null): Job
{
@@ -435,7 +436,7 @@ public function addShortcut(string $option, ?string $value = null): Job
}
if (array_key_exists($option, $this->input['shortcuts'])) {
- throw new InvalidArgumentException(\Safe\sprintf('The shortcut "%s" was already added to the command.', $option));
+ throw new InvalidArgumentException(sprintf('The shortcut "%s" was already added to the command.', $option));
}
$this->input['shortcuts'][$option] = $value;
@@ -494,7 +495,7 @@ public function addParentDependency(Job $job): Job
$status = $this->getStatus();
if (self::STATUS_PENDING === $status || self::STATUS_RUNNING === $status) {
throw new LogicException(
- \Safe\sprintf(
+ sprintf(
'The Job %s has already started. You cannot add the parent dependency %s.',
$this->getId(), $job->getId()
)
@@ -502,7 +503,7 @@ public function addParentDependency(Job $job): Job
}
if (true === $this->childDependencies->contains($job)) {
- throw new LogicException(\Safe\sprintf(
+ throw new LogicException(sprintf(
'You cannot add a parent dependecy (%s) that is already a child dependency.'
. ' This will create an unresolvable circular reference.',
$job->getId()
@@ -536,8 +537,9 @@ public function createCancelChildsJob(): Job
}
/**
- * @return Job
* @throws Exception
+ *
+ * @return Job
*/
public function createRetryForFailed(): Job
{
@@ -548,7 +550,8 @@ public function createRetryForFailed(): Job
}
// Create a new Job that will retry the original one
- return (new Job($this->getCommand(), $this->getInput()))
+
+ return (new Job($this->getCommand(), $this->getInput() ?? []))
// First get the retry date
->setExecuteAfterTime($retryOn)
// Then we can increment the current number of attempts setting also the RetryStrategy
@@ -560,13 +563,14 @@ public function createRetryForFailed(): Job
}
/**
- * @return Job
* @throws Exception
+ *
+ * @return Job
*/
public function createRetryForStale(): Job
{
// Create a new Job that will retry the original one
- $retryJob = (new Job($this->getCommand(), $this->getInput()))
+ $retryJob = (new Job($this->getCommand(), $this->getInput() ?? []))
// Then we can increment the current number of attempts setting also the RetryStrategy
->setRetryStrategy($this->getRetryStrategy())
->setPriority($this->getPriority())
@@ -602,7 +606,7 @@ public function getCommand(): string
/**
* @return array|null
*/
- public function getInput():? array
+ public function getInput(): ? array
{
return $this->input;
}
@@ -793,39 +797,6 @@ public function getType(): string
return self::TYPE_JOB;
}
- /**
- * Returns the ID of the Job for which this one were created.
- *
- * For example, if this is a cancelling Job, it will cancel childs of the given Job: this method will return the ID
- * of this given Job.
- *
- * @throws StringsException
- * @throws RuntimeException
- *
- * @return int
- */
- public function getProcessedJobId(): int
- {
- if (false === $this->isTypeInternal()) {
- throw new BadMethodCallException(
- \Safe\sprintf(
- 'This Job #%s is not internal, so you cannot call the method self::getProcessedJobId().',
- $this->getId()
- )
- );
- }
-
- foreach ($this->getInput() as $argument) {
- if (false !== strpos($argument, '--id=')) {
- return (int) str_replace('--id=', '', $argument);
- }
- }
-
- throw new RuntimeException('Impossible to find the ID. This should never happen: investigate further.');
- // This should be never reached
- // This was "return false;". Modified with the exception
- }
-
/**
* @return string
*/
@@ -872,7 +843,7 @@ public function canBeDetached(): bool
$retriedBy = $this->getRetriedBy();
if (null !== $retriedBy && $this->isStatusRetried()) {
// It has to be flushed at the end
- $this->cannotBeDetachedBecause = \Safe\sprintf('is being retried by Job #%s (%s)', $retriedBy->getId(), $retriedBy->getStatus());
+ $this->cannotBeDetachedBecause = sprintf('is being retried by Job #%s (%s)', $retriedBy->getId(), $retriedBy->getStatus());
return false;
}
@@ -882,7 +853,7 @@ public function canBeDetached(): bool
switch ($parentJob->getStatus()) {
// Waiting dependencies
case self::STATUS_NEW:
- $this->cannotBeDetachedBecause = \Safe\sprintf(
+ $this->cannotBeDetachedBecause = sprintf(
'has parent Job #%s@%s that has to be processed (%s)',
$parentJob->getId(), $parentJob->getQueue(), $parentJob->getStatus()
);
@@ -890,7 +861,7 @@ public function canBeDetached(): bool
return false;
break;
case self::STATUS_RETRIED:
- $this->cannotBeDetachedBecause = \Safe\sprintf(
+ $this->cannotBeDetachedBecause = sprintf(
'has parent Job #%s@%s that were retried (%s)',
$parentJob->getId(), $parentJob->getQueue(), $parentJob->getStatus()
);
@@ -900,14 +871,14 @@ public function canBeDetached(): bool
// Working dependencies
case self::STATUS_PENDING:
- $this->cannotBeDetachedBecause = \Safe\sprintf(
+ $this->cannotBeDetachedBecause = sprintf(
'has parent Job #%s@%s that is being processed (%s)',
$parentJob->getId(), $parentJob->getQueue(), $parentJob->getStatus()
);
return false;
case self::STATUS_RUNNING:
- $this->cannotBeDetachedBecause = \Safe\sprintf(
+ $this->cannotBeDetachedBecause = sprintf(
'has parent Job #%s@%s that is running (%s)',
$parentJob->getId(), $parentJob->getQueue(), $parentJob->getStatus()
);
@@ -960,7 +931,7 @@ public function canRun(): bool
switch ($parentJob->getStatus()) {
// Waiting dependencies
case self::STATUS_NEW:
- $this->cannotRunBecause = \Safe\sprintf(
+ $this->cannotRunBecause = sprintf(
'has parent Job #%s@%s that has to be processed (%s)',
$parentJob->getId(), $parentJob->getQueue(), $parentJob->getStatus()
);
@@ -968,7 +939,7 @@ public function canRun(): bool
return false;
break;
case self::STATUS_RETRIED:
- $this->cannotRunBecause = \Safe\sprintf(
+ $this->cannotRunBecause = sprintf(
'has parent Job #%s@%s that were retried (%s)',
$parentJob->getId(), $parentJob->getQueue(), $parentJob->getStatus()
);
@@ -978,14 +949,14 @@ public function canRun(): bool
// Working dependencies
case self::STATUS_PENDING:
- $this->cannotRunBecause = \Safe\sprintf(
+ $this->cannotRunBecause = sprintf(
'has parent Job #%s@%s that is being processed (%s)',
$parentJob->getId(), $parentJob->getQueue(), $parentJob->getStatus()
);
return false;
case self::STATUS_RUNNING:
- $this->cannotRunBecause = \Safe\sprintf(
+ $this->cannotRunBecause = sprintf(
'has parent Job #%s@%s that is running (%s)',
$parentJob->getId(), $parentJob->getQueue(), $parentJob->getStatus()
);
@@ -1373,14 +1344,14 @@ public function setRetryOf(Job $retriedJob): Job
/**
* @ORM\PreFlush
*/
- public function reorderInputs():void
+ public function reorderInputs(): void
{
// Don't reorder the arguments as their order is relevant
- if (array_key_exists('options', $this->input) && null !== $this->input['options']) {
+ if (null !== $this->input && isset($this->input['options']) && is_array($this->input['options'])) {
ksort($this->input['options'], SORT_NATURAL);
}
- if (array_key_exists('shortcuts', $this->input) && null !== $this->input['shortcuts']) {
+ if (null !== $this->input && isset($this->input['shortcuts']) && is_array($this->input['shortcuts'])) {
ksort($this->input['shortcuts'], SORT_NATURAL);
}
}
diff --git a/src/Repository/JobRepository.php b/src/Repository/JobRepository.php
index 40b3251..1d66621 100644
--- a/src/Repository/JobRepository.php
+++ b/src/Repository/JobRepository.php
@@ -18,7 +18,6 @@
namespace SerendipityHQ\Bundle\CommandsQueuesBundle\Repository;
use DateTime;
-use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Types\Type;
use Doctrine\ORM\EntityRepository;
@@ -27,6 +26,7 @@
use Doctrine\ORM\QueryBuilder;
use RuntimeException;
use Safe\Exceptions\StringsException;
+use function Safe\sprintf;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Entity\Job;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Service\JobsManager;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Util\InputParser;
@@ -94,7 +94,7 @@ public function findNextRunnableJob(string $queueName): ? Job
$this->getEntityManager()->refresh($job);
if ($this->ioWriter->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) {
- $this->ioWriter->infoLineNoBg(\Safe\sprintf('Job #%s ready to run.', $job->getId()));
+ $this->ioWriter->infoLineNoBg(sprintf('Job #%s ready to run.', $job->getId()));
}
// ... Return it
@@ -102,7 +102,7 @@ public function findNextRunnableJob(string $queueName): ? Job
}
if ($this->ioWriter->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) {
- $this->ioWriter->infoLineNoBg(\Safe\sprintf('Job #%s cannot run because %s.', $job->getId(), $job->getCannotRunBecause()));
+ $this->ioWriter->infoLineNoBg(sprintf('Job #%s cannot run because %s.', $job->getId(), $job->getCannotRunBecause()));
}
// The Job cannot be run
@@ -198,7 +198,7 @@ public function findExpiredJobs(string $queueName, DateTime $maxRetentionDate):
public function findBySearch(string $command, ?array $input = [], string $queue = 'default', bool $fullSearch = false): ?array
{
$queryBuilder = $this->getEntityManager()->createQueryBuilder();
- $stringInput = InputParser::stringify($input);
+ $stringInput = InputParser::stringify($input);
$queryBuilder->select('j')->from(Job::class, 'j')
->where($queryBuilder->expr()->eq('j.command', ':command'))
diff --git a/src/Service/JobsManager.php b/src/Service/JobsManager.php
index 0294c93..5ece86c 100644
--- a/src/Service/JobsManager.php
+++ b/src/Service/JobsManager.php
@@ -26,7 +26,7 @@
use Doctrine\ORM\UnitOfWork;
use RuntimeException;
use Safe\Exceptions\StringsException;
-use Safe\sprintf;
+use function Safe\sprintf;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Entity\Job;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Util\InputParser;
use SerendipityHQ\Bundle\ConsoleStyles\Console\Style\SerendipityHQStyle;
diff --git a/src/Service/QueuesDaemon.php b/src/Service/QueuesDaemon.php
index fd7d6e8..1e61800 100644
--- a/src/Service/QueuesDaemon.php
+++ b/src/Service/QueuesDaemon.php
@@ -32,10 +32,10 @@
use RuntimeException;
use Safe\Exceptions\ArrayException;
use Safe\Exceptions\StringsException;
-use Safe\getmypid;
-use Safe\pcntl_signal_dispatch;
-use Safe\sleep;
-use Safe\sprintf;
+use function Safe\getmypid;
+use function Safe\pcntl_signal_dispatch;
+use function Safe\sleep;
+use function Safe\sprintf;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Config\DaemonConfig;
use SerendipityHQ\Bundle\CommandsQueuesBundle\DependencyInjection\Configuration;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Entity\Daemon;
@@ -216,7 +216,6 @@ public function requiescantInPace(): void
*
* @param bool $hitIteration the iteration has to be hit only from the RunCommand
*
- *
* @return bool
*/
public function isAlive(bool $hitIteration = false): bool
@@ -338,7 +337,7 @@ public function processNextJob(string $queueName): bool
$process->start();
} catch (Throwable $e) {
// Something went wrong starting the process: close it as failed
- $info['output'] = 'Failing start the process.';
+ $info['output'] = 'Failing start the process.';
$info['debug']['output_error'] = $e->getMessage();
// Check if it can be retried and if the retry were successful
@@ -556,7 +555,7 @@ public function processRunningJob(array $runningJob): bool
// If this is a cancelling Job or a retrying one, refresh the entire tree
if ($job->isTypeCancelling()) {
$startJobId = null;
- $input = $job->getInput();
+ $input = $job->getInput();
if (null !== $input && isset($input['options']['--id'])) {
$startJobId = $input['options']['--id'];
}
@@ -727,7 +726,6 @@ public function purgeExpiredJobs(string $queueName): void
/**
* Put the Daemon in sleep.
- *
*/
public function sleep(): void
{
diff --git a/src/Service/QueuesManager.php b/src/Service/QueuesManager.php
index 82d7f57..8c9e032 100644
--- a/src/Service/QueuesManager.php
+++ b/src/Service/QueuesManager.php
@@ -61,7 +61,7 @@ public function __construct(EntityManagerInterface $entityManager)
*
* @return bool
*/
- public function jobExists(Job $job):bool
+ public function jobExists(Job $job): bool
{
return $this->exists($job->getCommand(), $job->getInput(), $job->getQueue());
}
@@ -95,7 +95,7 @@ public function findByJob(Job $job): ?array
*
* @return bool
*/
- public function exists(string $command, $input = null, string $queue = Daemon::DEFAULT_QUEUE_NAME):bool
+ public function exists(string $command, $input = null, string $queue = Daemon::DEFAULT_QUEUE_NAME): bool
{
$exists = $this->find($command, $input, $queue);
@@ -111,7 +111,6 @@ public function exists(string $command, $input = null, string $queue = Daemon::D
* @param array|string|null $input
* @param string $queue
*
- *
* @return array|null
*/
public function find(string $command, $input = null, string $queue = Daemon::DEFAULT_QUEUE_NAME): ?array
diff --git a/src/Tests/Util/InputParserTest.php b/src/Tests/Util/InputParserTest.php
index fcd3dec..983dd94 100644
--- a/src/Tests/Util/InputParserTest.php
+++ b/src/Tests/Util/InputParserTest.php
@@ -2,65 +2,78 @@
declare(strict_types=1);
+/*
+ * This file is part of the SHQCommandsQueuesBundle.
+ *
+ * Copyright Adamo Aerendir Crespi 2017.
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ *
+ * @author Adamo Aerendir Crespi
+ * @copyright Copyright (C) 2017 Aerendir. All rights reserved.
+ * @license MIT License.
+ */
+
namespace SerendipityHQ\Bundle\CommandsQueuesBundle\Tests\Util;
use PHPUnit\Framework\TestCase;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Util\InputParser;
/**
- * {@inheritDoc}
+ * {@inheritdoc}
*/
class InputParserTest extends TestCase
{
- public function testIsArgument():void
+ public function testIsArgument(): void
{
self::assertTrue(InputParser::isArgument('argument'));
self::assertFalse(InputParser::isArgument('--option'));
self::assertFalse(InputParser::isArgument('-shortcut'));
}
- public function testIsOption():void
+ public function testIsOption(): void
{
self::assertFalse(InputParser::isOption('argument'));
self::assertTrue(InputParser::isOption('--option'));
self::assertFalse(InputParser::isOption('-shortcut'));
}
- public function testIsShortcut():void
+ public function testIsShortcut(): void
{
self::assertFalse(InputParser::isShortcut('argument'));
self::assertFalse(InputParser::isShortcut('--option'));
self::assertTrue(InputParser::isShortcut('-shortcut'));
}
- public function testParseStringWithCommand():void
+ public function testParseStringWithCommand(): void
{
- $test = 'command:name first_argument alphabetical_argument --option-without-equal option-value-without-equal 1 -sbool --option-with-equal=option-value-with-equal --option-boolean -s shortcut-value';
+ $test = 'command:name first_argument alphabetical_argument --option-without-equal option-value-without-equal 1 -sbool --option-with-equal=option-value-with-equal --option-boolean -s shortcut-value';
$result = InputParser::parseInput($test);
self::assertEquals($this->getExpected(), $result);
}
- public function testParseStringWithoutCommand():void
+ public function testParseStringWithoutCommand(): void
{
- $test = 'first_argument alphabetical_argument --option-without-equal option-value-without-equal 1 -sbool --option-with-equal=option-value-with-equal --option-boolean -s shortcut-value';
- $result = InputParser::parseInput($test, false);
- $expected = $this->getExpected();
+ $test = 'first_argument alphabetical_argument --option-without-equal option-value-without-equal 1 -sbool --option-with-equal=option-value-with-equal --option-boolean -s shortcut-value';
+ $result = InputParser::parseInput($test, false);
+ $expected = $this->getExpected();
$expected['command'] = null;
self::assertEquals($expected, $result);
}
- public function testParseAnArray():void
+ public function testParseAnArray(): void
{
$test = [
'command' => 'command:name',
'first_argument', 'alphabetical_argument', '1',
'--option-without-equal' => 'option-value-without-equal',
- '--option-with-equal' => 'option-value-with-equal',
- '--option-boolean' => null,
- '-sbool' => null,
- '-s' => 'shortcut-value',
+ '--option-with-equal' => 'option-value-with-equal',
+ '--option-boolean' => null,
+ '-sbool' => null,
+ '-s' => 'shortcut-value',
];
$result = InputParser::parseInput($test, false);
@@ -68,20 +81,18 @@ public function testParseAnArray():void
self::assertEquals($this->getExpected(), $result);
}
- public function testParseAMixedArray():void
+ public function testParseAMixedArray(): void
{
$test = [
'command' => 'command:name',
'first_argument', 'alphabetical_argument', '1',
- 'options' =>
- [
+ 'options' => [
'--option-without-equal' => 'option-value-without-equal',
- '--option-with-equal' => 'option-value-with-equal',
- '--option-boolean' => null,
+ '--option-with-equal' => 'option-value-with-equal',
+ '--option-boolean' => null,
],
- '-sbool' => null,
+ '-sbool' => null,
'-s' => 'shortcut-value',
-
];
$result = InputParser::parseInput($test, false);
@@ -89,9 +100,9 @@ public function testParseAMixedArray():void
self::assertEquals($this->getExpected(), $result);
}
- public function testParseWithAlreadyParsedInput():void
+ public function testParseWithAlreadyParsedInput(): void
{
- $expected = $this->getExpected();
+ $expected = $this->getExpected();
$expected['command'] = null;
$result = InputParser::parseInput($expected, false);
@@ -102,24 +113,21 @@ public function testParseWithAlreadyParsedInput():void
/**
* @return array
*/
- private function getExpected():array
+ private function getExpected(): array
{
return [
- 'command' => 'command:name',
- 'arguments' =>
- [
+ 'command' => 'command:name',
+ 'arguments' => [
'first_argument', 'alphabetical_argument', '1',
],
- 'options' =>
- [
+ 'options' => [
'--option-without-equal' => 'option-value-without-equal',
- '--option-with-equal' => 'option-value-with-equal',
- '--option-boolean' => null,
+ '--option-with-equal' => 'option-value-with-equal',
+ '--option-boolean' => null,
],
- 'shortcuts' =>
- [
+ 'shortcuts' => [
'-sbool' => null,
- '-s' => 'shortcut-value',
+ '-s' => 'shortcut-value',
],
];
}
diff --git a/src/Util/InputParser.php b/src/Util/InputParser.php
index 5972a9d..2fa51bb 100644
--- a/src/Util/InputParser.php
+++ b/src/Util/InputParser.php
@@ -17,6 +17,8 @@
namespace SerendipityHQ\Bundle\CommandsQueuesBundle\Util;
+use function Safe\sprintf;
+
/**
* An helper class to manage the input of a command.
*
@@ -32,7 +34,7 @@ class InputParser
/** @var string|null $foundOption */
private static $foundOption;
- /** @var null|string $foundShortcut */
+ /** @var string|null $foundShortcut */
private static $foundShortcut;
/** @var array|null $preparedInput */
@@ -40,9 +42,9 @@ class InputParser
/** @var array $preparedInput */
private static $defaultPreparedInput = [
- 'command' => null,
+ 'command' => null,
'arguments' => null,
- 'options' => null,
+ 'options' => null,
'shortcuts' => null,
];
@@ -51,15 +53,23 @@ class InputParser
* If a string is passed, it is transformed into an array.
* Then it reorder the arguments to get a unique signature to facilitate checks on existent Jobs.
*
- * @param array|string $input
- * @param bool $hasCommand If the input contains also the command name or not
+ * This suppresses a Phan error: check if it is fixed here https://github.com/phan/phan/issues/2706
+ *
+ * @param array|string|null $input
+ * @param bool $hasCommand If the input contains also the command name or not
+ *
+ * @suppress PhanTypeMismatchDimFetch
*
* @return array
*/
public static function parseInput($input = [], bool $hasCommand = true): array
{
self::$preparedInput = self::$defaultPreparedInput;
- $wasString = false;
+ $wasString = false;
+
+ if (null === $input) {
+ return self::$preparedInput;
+ }
if (is_string($input)) {
$input = str_replace('=', ' ', $input);
@@ -68,12 +78,12 @@ public static function parseInput($input = [], bool $hasCommand = true): array
$input = explode(' ', $input);
// And remove leading and trailing spaces
- $input = array_map('trim', $input);
+ $input = array_map('trim', $input);
$wasString = true;
}
if ($hasCommand && $wasString) {
- $commandKey = array_key_first($input);
+ $commandKey = array_key_first($input);
self::$preparedInput['command'] = $input[$commandKey];
unset($input[$commandKey]);
}
@@ -108,37 +118,39 @@ public static function parseInput($input = [], bool $hasCommand = true): array
}
}
- $preparedInput = self::$preparedInput;
- self::$preparedInput = null;
self::$foundArgument = null;
- self::$foundOption = null;
+ self::$foundOption = null;
self::$foundShortcut = null;
// Don't reorder the arguments as their order is relevant
- if (array_key_exists('options', $preparedInput) && null !== $preparedInput['options']) {
- ksort($preparedInput['options'], SORT_NATURAL);
+ if (array_key_exists('options', self::$preparedInput) && null !== self::$preparedInput['options']) {
+ ksort(self::$preparedInput['options'], SORT_NATURAL);
}
- if (array_key_exists('shortcuts', $preparedInput) && null !== $preparedInput['shortcuts']) {
- ksort($preparedInput['shortcuts'], SORT_NATURAL);
+ if (array_key_exists('shortcuts', self::$preparedInput) && null !== self::$preparedInput['shortcuts']) {
+ ksort(self::$preparedInput['shortcuts'], SORT_NATURAL);
}
- return $preparedInput;
+ return self::$preparedInput;
}
/**
* @param array|null $input
- * @param bool $withCommand
+ * @param bool $withCommand
*
* @return string|null
*/
- public static function stringify(?array $input = [], $withCommand = false):?string
+ public static function stringify(?array $input = [], $withCommand = false): ?string
{
- $preparedInput = '';
- $stringifyClosure = static function($value, $key) {
- return \Safe\sprintf('%s=%s', $key, $value);
+ $preparedInput = '';
+ $stringifyClosure = static function ($value, $key) {
+ return sprintf('%s=%s', $key, $value);
};
+ if (null === $input) {
+ return null;
+ }
+
if ($withCommand && array_key_exists('command', $input)) {
$preparedInput .= $input['command'];
}
@@ -150,15 +162,15 @@ public static function stringify(?array $input = [], $withCommand = false):?stri
if (array_key_exists('options', $input) && null !== $input['options']) {
$optionsKeys = array_keys($input['options']);
- $options = array_map($stringifyClosure, $input['options'], $optionsKeys);
- $options = implode(' ', $options);
+ $options = array_map($stringifyClosure, $input['options'], $optionsKeys);
+ $options = implode(' ', $options);
$preparedInput .= ' ' . $options;
}
if (array_key_exists('shortcuts', $input) && null !== $input['shortcuts']) {
$shortcutsKeys = array_keys($input['shortcuts']);
- $shortcuts = array_map($stringifyClosure, $input['shortcuts'], $shortcutsKeys);
- $shortcuts = implode(' ', $shortcuts);
+ $shortcuts = array_map($stringifyClosure, $input['shortcuts'], $shortcutsKeys);
+ $shortcuts = implode(' ', $shortcuts);
$preparedInput .= ' ' . $shortcuts;
}
@@ -172,7 +184,7 @@ public static function stringify(?array $input = [], $withCommand = false):?stri
*
* @return bool
*/
- public static function isArgument(string $argument):bool
+ public static function isArgument(string $argument): bool
{
return false === self::isOption($argument) && false === self::isShortcut($argument);
}
@@ -182,7 +194,7 @@ public static function isArgument(string $argument):bool
*
* @return bool
*/
- public static function isOption(string $option):bool
+ public static function isOption(string $option): bool
{
return 0 === strpos($option, '--');
}
@@ -192,7 +204,7 @@ public static function isOption(string $option):bool
*
* @return bool
*/
- public static function isShortcut(string $shortcut):bool
+ public static function isShortcut(string $shortcut): bool
{
return false === self::isOption($shortcut) && 0 === strpos($shortcut, '-');
}
@@ -200,7 +212,7 @@ public static function isShortcut(string $shortcut):bool
/**
* @param string $value
*/
- private static function parseValue(string $value):void
+ private static function parseValue(string $value): void
{
if (null === self::$foundOption && null === self::$foundShortcut && self::isArgument($value)) {
self::$foundArgument = $value;
@@ -208,29 +220,29 @@ private static function parseValue(string $value):void
if (self::isOption($value)) {
self::$preparedInput['options'][$value] = null;
- self::$foundOption = $value;
- self::$foundShortcut = null;
+ self::$foundOption = $value;
+ self::$foundShortcut = null;
}
if (self::isShortcut($value)) {
self::$preparedInput['shortcuts'][$value] = null;
- self::$foundShortcut = $value;
- self::$foundOption = null;
+ self::$foundShortcut = $value;
+ self::$foundOption = null;
}
if (null !== self::$foundArgument) {
self::$preparedInput['arguments'][] = self::$foundArgument;
- self::$foundArgument = null;
+ self::$foundArgument = null;
}
if (null !== self::$foundOption && self::$foundOption !== $value && false === self::isOption($value) && false === self::isShortcut($value)) {
self::$preparedInput['options'][self::$foundOption] = $value;
- self::$foundOption = null;
+ self::$foundOption = null;
}
if (null !== self::$foundShortcut && self::$foundShortcut !== $value && false === self::isOption($value) && false === self::isShortcut($value)) {
self::$preparedInput['shortcuts'][self::$foundShortcut] = $value;
- self::$foundShortcut = null;
+ self::$foundShortcut = null;
}
}
}
diff --git a/src/Util/JobsMarker.php b/src/Util/JobsMarker.php
index 6e0bcf8..7f82da5 100644
--- a/src/Util/JobsMarker.php
+++ b/src/Util/JobsMarker.php
@@ -30,6 +30,7 @@
use RuntimeException;
use Safe\Exceptions\ArrayException;
use Safe\Exceptions\StringsException;
+use function Safe\sprintf;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Entity\Daemon;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Entity\Job;
use SerendipityHQ\Bundle\ConsoleStyles\Console\Style\SerendipityHQStyle;
@@ -424,7 +425,7 @@ private static function updateJob(Job $job, string $status, array $info = [], Da
$reflectedProperty = $reflectedClass->getProperty('cancellationReason');
break;
default:
- throw new RuntimeException(\Safe\sprintf(
+ throw new RuntimeException(sprintf(
'The property %s is not managed. Manage it or verify its spelling is correct.',
$property
));
diff --git a/src/Util/Profiler.php b/src/Util/Profiler.php
index e491f5b..9b572a4 100644
--- a/src/Util/Profiler.php
+++ b/src/Util/Profiler.php
@@ -20,10 +20,17 @@
use DateTime;
use Doctrine\ORM\UnitOfWork;
use RuntimeException;
+use function Safe\asort;
use Safe\Exceptions\ArrayException;
use Safe\Exceptions\FilesystemException;
use Safe\Exceptions\StreamException;
use Safe\Exceptions\StringsException;
+use function Safe\fclose;
+use function Safe\fopen;
+use function Safe\fwrite;
+use function Safe\mkdir;
+use function Safe\sprintf;
+use function Safe\stream_get_contents;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Entity\Job;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Service\JobsManager;
use SerendipityHQ\Bundle\ConsoleStyles\Console\Style\SerendipityHQStyle;
@@ -107,7 +114,7 @@ public static function buildJobsList(): string
$managedEntities[] = '#' . $job->getId() . ' (' . $job->getStatus() . ') [Em: ' . JobsManager::guessJobEmState($job) . ']';
}
- \Safe\asort($managedEntities);
+ asort($managedEntities);
return implode(', ', $managedEntities);
}
@@ -132,13 +139,13 @@ public static function printUnitOfWork(string $where = null): void
{
if (self::$ioWriter->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
$count = isset(self::$uow->getIdentityMap()[Job::class]) ? count(self::$uow->getIdentityMap()[Job::class]) : 0;
- $message = \Safe\sprintf(
+ $message = sprintf(
'Currently there are %s Jobs managed (%s of %s)',
$count, Helper::formatMemory(memory_get_usage(false)), Helper::formatMemory(memory_get_usage(true))
);
if (null !== $where) {
- $message = \Safe\sprintf('[%s] %s', $where, $message);
+ $message = sprintf('[%s] %s', $where, $message);
}
self::$ioWriter->noteLineNoBg($message);
@@ -234,14 +241,14 @@ public function profile(): array
[
// If the difference is negative, then this is an increase in memory consumption
$memoryDifferenceReal >= 0
- ? \Safe\sprintf('<%s>%s>', 'success-nobg', "\xE2\x9C\x94")
- : \Safe\sprintf('<%s>%s>', 'error-nobg', "\xE2\x9C\x96"), 'Allocated Memory',
+ ? sprintf('<%s>%s>', 'success-nobg', "\xE2\x9C\x94")
+ : sprintf('<%s>%s>', 'error-nobg', "\xE2\x9C\x96"), 'Allocated Memory',
Helper::formatMemory($this->lastMemoryUsageReal) . ' => ' . Helper::formatMemory($currentMemoryUsageReal) . ' (' . ($memoryDifferenceReal <= 0 ? '+' : '-') . abs($memoryDifferenceReal) . '%)',
],
[
$memoryPeakDifferenceReal >= 0
- ? \Safe\sprintf('<%s>%s>', 'success-nobg', "\xE2\x9C\x94")
- : \Safe\sprintf('<%s>%s>', 'error-nobg', "\xE2\x9C\x96"),
+ ? sprintf('<%s>%s>', 'success-nobg', "\xE2\x9C\x94")
+ : sprintf('<%s>%s>', 'error-nobg', "\xE2\x9C\x96"),
'Allocated Memory Peak',
Helper::formatMemory($this->highestMemoryPeakReal) . ' => ' . Helper::formatMemory($currentMemoryPeakReal) . ' (' . ($memoryPeakDifferenceReal <= 0 ? '+' : '-') . abs($memoryPeakDifferenceReal) . '%)',
],
@@ -249,15 +256,15 @@ public function profile(): array
['', 'Memory info (memory_get_*(false))'],
[
$memoryDifference >= 0
- ? \Safe\sprintf('<%s>%s>', 'success-nobg', "\xE2\x9C\x94")
- : \Safe\sprintf('<%s>%s>', 'error-nobg', "\xE2\x9C\x96"),
+ ? sprintf('<%s>%s>', 'success-nobg', "\xE2\x9C\x94")
+ : sprintf('<%s>%s>', 'error-nobg', "\xE2\x9C\x96"),
'Memory Actually Used',
Helper::formatMemory($this->lastMemoryUsage) . ' => ' . Helper::formatMemory($currentMemoryUsage) . ' (' . ($memoryDifference <= 0 ? '+' : '-') . abs($memoryDifference) . '%)',
],
[
$memoryPeakDifference >= 0
- ? \Safe\sprintf('<%s>%s>', 'success-nobg', "\xE2\x9C\x94")
- : \Safe\sprintf('<%s>%s>', 'error-nobg', "\xE2\x9C\x96"),
+ ? sprintf('<%s>%s>', 'success-nobg', "\xE2\x9C\x94")
+ : sprintf('<%s>%s>', 'error-nobg', "\xE2\x9C\x96"),
'Memory Actual Peak',
Helper::formatMemory($this->highestMemoryPeak) . ' => ' . Helper::formatMemory($currentMemoryPeak) . ' (' . ($memoryPeakDifference <= 0 ? '+' : '-') . abs($memoryPeakDifference) . '%)',
],
@@ -265,15 +272,15 @@ public function profile(): array
['', 'UnitOfWork info'],
[
$uowSizeDifference >= 0
- ? \Safe\sprintf('<%s>%s>', 'success-nobg', "\xE2\x9C\x94")
- : \Safe\sprintf('<%s>%s>', 'error-nobg', "\xE2\x9C\x96"),
+ ? sprintf('<%s>%s>', 'success-nobg', "\xE2\x9C\x94")
+ : sprintf('<%s>%s>', 'error-nobg', "\xE2\x9C\x96"),
'Uow size',
$this->lastUowSize . ' => ' . $currentUowSize . ' (' . ($uowSizeDifference <= 0 ? '+' : '-') . abs($uowSizeDifference) . '%)',
],
[
$uowHighestSizeDifference >= 0
- ? \Safe\sprintf('<%s>%s>', 'success-nobg', "\xE2\x9C\x94")
- : \Safe\sprintf('<%s>%s>', 'error-nobg', "\xE2\x9C\x96"),
+ ? sprintf('<%s>%s>', 'success-nobg', "\xE2\x9C\x94")
+ : sprintf('<%s>%s>', 'error-nobg', "\xE2\x9C\x96"),
'Uow peak size',
$this->highestUowSize . ' => ' . $currentHighestUowSize . ' (' . ($uowHighestSizeDifference <= 0 ? '+' : '-') . abs($uowHighestSizeDifference) . '%)',
],
@@ -290,17 +297,17 @@ public function profile(): array
if (function_exists('memprof_dump_callgrind') && $this->isMemprofEnabled()) {
// Create the directory if it doesn't exist
if (false === file_exists('app/logs/callgrind')) {
- \Safe\mkdir('app/logs/callgrind', 0777, true);
+ mkdir('app/logs/callgrind', 0777, true);
}
- $callgrind = \Safe\fopen(
- \Safe\sprintf(
+ $callgrind = fopen(
+ sprintf(
'app/logs/callgrind/callgrind.out.%s.%s.%s',
(new DateTime())->format('Y-m-d'), $this->pid, $this->getCurrentIteration()
// "w": writing only; "b": binary safe
), 'wb');
memprof_dump_callgrind($callgrind);
- \Safe\fwrite($callgrind, \Safe\stream_get_contents($callgrind));
- \Safe\fclose($callgrind);
+ fwrite($callgrind, stream_get_contents($callgrind));
+ fclose($callgrind);
}
return $this->profilingInfo;
diff --git a/src/Util/ProgressBarFactory.php b/src/Util/ProgressBarFactory.php
index 99d0b04..543308f 100644
--- a/src/Util/ProgressBarFactory.php
+++ b/src/Util/ProgressBarFactory.php
@@ -18,6 +18,7 @@
namespace SerendipityHQ\Bundle\CommandsQueuesBundle\Util;
use Symfony\Component\Console\Helper\Helper;
+use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Output\OutputInterface;
/**
@@ -47,17 +48,17 @@ class ProgressBarFactory
* @param OutputInterface $output
* @param int $howManyJobs
*
- * @return \Symfony\Component\Console\Helper\ProgressBar
+ * @return ProgressBar
*/
- public static function createProgressBar(string $format, OutputInterface $output, int $howManyJobs = 0): \Symfony\Component\Console\Helper\ProgressBar
+ public static function createProgressBar(string $format, OutputInterface $output, int $howManyJobs = 0): ProgressBar
{
- \Symfony\Component\Console\Helper\ProgressBar::setPlaceholderFormatterDefinition(
+ ProgressBar::setPlaceholderFormatterDefinition(
'memory_nr',
- function (\Symfony\Component\Console\Helper\ProgressBar $bar, OutputInterface $output) {
+ function (ProgressBar $bar, OutputInterface $output) {
return Helper::formatMemory(memory_get_usage(false));
}
);
- $progress = new \Symfony\Component\Console\Helper\ProgressBar($output, $howManyJobs);
+ $progress = new ProgressBar($output, $howManyJobs);
$progress->setFormat($format);
return $progress;