Skip to content

Instantly share code, notes, and snippets.

@alfonsodev
Created January 14, 2019 11:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alfonsodev/040591491f3510d333be285ef96f687a to your computer and use it in GitHub Desktop.
Save alfonsodev/040591491f3510d333be285ef96f687a to your computer and use it in GitHub Desktop.
Wait for is useful for docker images
<?php
namespace App\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use App\Service\CacheService;
class WaitForCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('tools:wait-for')
->setDescription('Waits dependent services, db, redis, elastic-search ...')
->setHelp('This command allows you to create a user...')
->addArgument('thing', InputArgument::OPTIONAL, 'what to wait for [db, redis, getslug]');
}
private function waitForDatabase(OutputInterface $output)
{
sleep(3);
try {
$entityManager = $this->getContainer()->get('doctrine');
$output->writeln('ping connection');
$ping = $entityManager->getConnection()->ping();
if ($ping) {
$output->writeln('db ping ready 🚀');
return;
}
$output->writeln('Waiting for database connection');
$this->waitForDatabase($output);
return;
} catch (\Exception $e) {
if (strpos($e->getMessage(), 'database "azp" does not exist') !== false) {
$output->writeln('db missing, so ready to go 🚀');
return;
}
$output->writeln('>>> ' . $e->getMessage());
$this->waitForDatabase($output);
return;
}
}
private function waitForGetSlug(OutputInterface $output)
{
$entityManager = $this->getContainer()->get('doctrine');
$queryExtension = 'CREATE EXTENSION IF NOT EXISTS "uuid-ossp";';
$statement = $entityManager->getConnection()->prepare($queryExtension);
$statement->execute();
return;
}
private function waitForRedis(OutputInterface $output)
{
try {
$cacheService = $this->getContainer()->get('app.cache');
$cache = $cacheService->getInstance();
$item = $cache->getItem('wait-for-redis');
$item->set(true);
$cache->save($item);
if ($item->isHit()) {
$output->writeln('Redis service is ready 🚀');
return true;
}
$output->writeln('waiting for redis to start ...');
sleep(1);
$this->waitForRedis($output);
return;
} catch (\Exception $e) {
$output->writeln('Waiting for redis ...');
sleep(1);
$this->waitForRedis($output);
}
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$argument = $input->getArgument('thing');
if ($argument === 'db') {
$this->waitForDatabase($output);
} elseif ($argument === 'db') {
$this->waitForRedis($output);
} elseif ($argument === 'getslug') {
$this->waitForGetSlug($output);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment