domain-expiration/src/Deblan/Command/CheckHttpsCertificatesCommand.php
2023-11-03 13:40:53 +01:00

127 lines
3.3 KiB
PHP

<?php
namespace Deblan\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Command\Command as BaseCommand;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Process\Process;
use Deblan\Parser\SslCertParser as Parser;
use Symfony\Component\Console\Input\InputOption;
/**
* class CheckHttpsCertificatesCommand.
*
* @author Simon Vieille <simon@deblan.fr>
*/
class CheckHttpsCertificatesCommand extends CheckCommand
{
/**
* {@inheritdoc}
*/
protected function configure()
{
parent::configure();
$this
->setName('https-certificates')
->setHelp(<<<'EOF'
The <info>%command.name%</info> retrieves the expiration dates of the HTTPS certificates of 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->checkHttpsCertificates($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);
}
}
/**
* Check HTTPS Certificates.
*
* @param int $wait
*/
protected function checkHttpsCertificates(int $wait):void
{
$domains = $this->getDomains();
$count = count($domains);
foreach ($domains as $key => $domain) {
$data = $this->checkHttpsCertificate($domain);
if ($data['expiryDate'] === null) {
$this->fails[] = $data;
} else {
$this->successes[] = $data;
}
if ($wait > 0 && $key !== $count - 1) {
sleep($wait);
}
}
}
/**
* Check HTTPS Certificate using a domain.
*
* @param mixed $domain
*
* @return array
*/
protected function checkHttpsCertificate($domain):array
{
$process = new Process([
'lib/check_ssl_cert/check_ssl_cert',
'-H',
$domain,
]);
$process->run();
$content = $process->getOutput();
$parser = new Parser($content);
$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',
];
}
}