domain-expiration/src/Deblan/Command/CheckDomainsCommand.php
2019-12-10 13:49:25 +01:00

120 lines
3 KiB
PHP

<?php
namespace Deblan\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Process\Process;
use Deblan\Parser\WhoisParser as Parser;
/**
* class CheckDomainsCommand.
*
* @author Simon Vieille <simon@deblan.fr>
*/
class CheckDomainsCommand extends CheckCommand
{
/**
* {@inheritdoc}
*/
protected function configure()
{
parent::configure();
$this
->setName('domains')
->setHelp(<<<'EOF'
The <info>%command.name%</info> retrieves the expiration dates of the given domains.
Example: %command.full_name% example.com other-example.com
EOF
);
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->input = $input;
$this->output = $output;
$wait = (int) $this->input->getOption('wait');
$this->checkDomains($wait);
$short = $this->input->getOption('short');
$json = $this->input->getOption('json');
$table = $this->input->getOption('table') || !$json;
$noHeaders = $this->input->getOption('no-headers');
$successes = $this->sort($this->successes);
$fails = $this->sort($this->fails);
if ($json) {
return $this->output->write(json_encode(array_merge($successes, $fails)));
}
if ($table) {
$this->renderTable($successes, $fails, $short, $noHeaders);
}
}
/**
* Checks domains.
*
* @param int $wait
*/
protected function checkDomains(int $wait):void
{
$domains = $this->getDomains();
$count = count($domains);
foreach ($domains as $key => $domain) {
$data = $this->checkDomain($domain);
if ($data['expiryDate'] === null) {
$this->fails[] = $data;
} else {
$this->successes[] = $data;
}
if ($wait > 0 && $key !== $count - 1) {
sleep($wait);
}
}
}
/**
* Checks domain.
*
* @param mixed $domain
*
* @return array
*/
protected function checkDomain($domain):array
{
$process = new Process(['whois', $domain]);
$process->run();
$whois = $process->getOutput();
$parser = new Parser($whois);
$expiryDate = $parser->getExpiryDate();
if ($expiryDate) {
$comparison = $expiryDate->getTimestamp();
$dayUntilExpiry = floor(($expiryDate->getTimestamp() - time()) / 3600 / 24);
} else {
$comparison = 'FAIL';
$dayUntilExpiry = null;
}
return [
'domain' => $domain,
'expiryDate' => $expiryDate,
'dayUntilExpiry' => $dayUntilExpiry,
'comparison' => $expiryDate ? $expiryDate->getTimestamp() : 'FAIL',
];
}
}