Fix code style

This commit is contained in:
Niklas Keller
2017-12-29 19:23:48 +01:00
parent d8a93a273c
commit e04a6c0c9b
19 changed files with 100 additions and 99 deletions

3
.gitignore vendored
View File

@@ -2,4 +2,5 @@
/data/ /data/
/info/ /info/
/vendor/ /vendor/
/config.test.yml /config.test.yml
/.php_cs.cache

View File

@@ -10,4 +10,4 @@ class AcmeFactory {
public function build(string $directory, PrivateKey $keyPair): AcmeService { public function build(string $directory, PrivateKey $keyPair): AcmeService {
return new AcmeService(new AcmeClient($directory, $keyPair)); return new AcmeService(new AcmeClient($directory, $keyPair));
} }
} }

View File

@@ -51,13 +51,13 @@ class Auto implements Command {
if ($args->defined('server')) { if ($args->defined('server')) {
$config['server'] = $args->get('server'); $config['server'] = $args->get('server');
} else if (!isset($config['server']) && $args->exists('server')) { } elseif (!isset($config['server']) && $args->exists('server')) {
$config['server'] = $args->get('server'); $config['server'] = $args->get('server');
} }
if ($args->defined('storage')) { if ($args->defined('storage')) {
$config['storage'] = $args->get('storage'); $config['storage'] = $args->get('storage');
} else if (!isset($config['storage']) && $args->exists('storage')) { } elseif (!isset($config['storage']) && $args->exists('storage')) {
$config['storage'] = $args->get('storage'); $config['storage'] = $args->get('storage');
} }
@@ -81,7 +81,7 @@ class Auto implements Command {
return self::EXIT_CONFIG_ERROR; return self::EXIT_CONFIG_ERROR;
} }
if (isset($config['challenge-concurrency']) && !is_numeric($config['challenge-concurrency'])) { if (isset($config['challenge-concurrency']) && !\is_numeric($config['challenge-concurrency'])) {
$this->climate->error("Config file ({$configPath}) defines an invalid 'challenge-concurrency' value."); $this->climate->error("Config file ({$configPath}) defines an invalid 'challenge-concurrency' value.");
return self::EXIT_CONFIG_ERROR; return self::EXIT_CONFIG_ERROR;
} }
@@ -140,7 +140,7 @@ class Auto implements Command {
foreach ($values as $i => $value) { foreach ($values as $i => $value) {
if ($value === self::STATUS_RENEWED) { if ($value === self::STATUS_RENEWED) {
$certificate = $config['certificates'][$i]; $certificate = $config['certificates'][$i];
$this->climate->info('Certificate for ' . implode(', ', array_keys($this->toDomainPathMap($certificate['paths']))) . ' successfully renewed.'); $this->climate->info('Certificate for ' . \implode(', ', \array_keys($this->toDomainPathMap($certificate['paths']))) . ' successfully renewed.');
} }
} }
} }
@@ -148,7 +148,7 @@ class Auto implements Command {
if ($status['failure'] > 0) { if ($status['failure'] > 0) {
foreach ($errors as $i => $error) { foreach ($errors as $i => $error) {
$certificate = $config['certificates'][$i]; $certificate = $config['certificates'][$i];
$this->climate->error('Issuance for the following domains failed: ' . implode(', ', array_keys($this->toDomainPathMap($certificate['paths'])))); $this->climate->error('Issuance for the following domains failed: ' . \implode(', ', \array_keys($this->toDomainPathMap($certificate['paths']))));
$this->climate->error("Reason: {$error}"); $this->climate->error("Reason: {$error}");
} }
@@ -177,8 +177,8 @@ class Auto implements Command {
*/ */
private function checkAndIssue(array $certificate, string $server, string $storage, int $concurrency = null): \Generator { private function checkAndIssue(array $certificate, string $server, string $storage, int $concurrency = null): \Generator {
$domainPathMap = $this->toDomainPathMap($certificate['paths']); $domainPathMap = $this->toDomainPathMap($certificate['paths']);
$domains = array_keys($domainPathMap); $domains = \array_keys($domainPathMap);
$commonName = reset($domains); $commonName = \reset($domains);
$process = new Process([ $process = new Process([
PHP_BINARY, PHP_BINARY,
@@ -191,7 +191,7 @@ class Auto implements Command {
'--name', '--name',
$commonName, $commonName,
'--names', '--names',
implode(',', $domains), \implode(',', $domains),
]); ]);
$process->start(); $process->start();
@@ -213,9 +213,9 @@ class Auto implements Command {
'--storage', '--storage',
$storage, $storage,
'--domains', '--domains',
implode(',', $domains), \implode(',', $domains),
'--path', '--path',
implode(PATH_SEPARATOR, array_values($domainPathMap)), \implode(PATH_SEPARATOR, \array_values($domainPathMap)),
]; ];
if (isset($certificate['user'])) { if (isset($certificate['user'])) {
@@ -253,7 +253,7 @@ class Auto implements Command {
$result = []; $result = [];
foreach ($paths as $path => $domains) { foreach ($paths as $path => $domains) {
if (is_numeric($path)) { if (\is_numeric($path)) {
$message = <<<MESSAGE $message = <<<MESSAGE
Your configuration has the wrong format. Received a numeric value as path name. Your configuration has the wrong format. Received a numeric value as path name.
@@ -330,4 +330,4 @@ MESSAGE;
return $args; return $args;
} }
} }

View File

@@ -37,20 +37,20 @@ class Check implements Command {
$cert = new Certificate($pem); $cert = new Certificate($pem);
$this->climate->br(); $this->climate->br();
$this->climate->whisper(' Certificate is valid until ' . date('d.m.Y', $cert->getValidTo()))->br(); $this->climate->whisper(' Certificate is valid until ' . \date('d.m.Y', $cert->getValidTo()))->br();
if ($args->defined('names')) { if ($args->defined('names')) {
$names = array_map('trim', explode(',', $args->get('names'))); $names = \array_map('trim', \explode(',', $args->get('names')));
$missingNames = array_diff($names, $cert->getNames()); $missingNames = \array_diff($names, $cert->getNames());
if ($missingNames) { if ($missingNames) {
$this->climate->comment(' The following names are not covered: ' . implode(', ', $missingNames))->br(); $this->climate->comment(' The following names are not covered: ' . \implode(', ', $missingNames))->br();
return 1; return 1;
} }
} }
if ($cert->getValidTo() > time() + $args->get('ttl') * 24 * 60 * 60) { if ($cert->getValidTo() > \time() + $args->get('ttl') * 24 * 60 * 60) {
return 0; return 0;
} }
@@ -82,4 +82,4 @@ class Check implements Command {
], ],
]; ];
} }
} }

View File

@@ -9,4 +9,4 @@ interface Command {
public function execute(Manager $args): Promise; public function execute(Manager $args): Promise;
public static function getDefinition(): array; public static function getDefinition(): array;
} }

View File

@@ -34,9 +34,9 @@ class Issue implements Command {
return call(function () use ($args) { return call(function () use ($args) {
$user = null; $user = null;
if (0 !== stripos(PHP_OS, 'WIN')) { if (0 !== \stripos(PHP_OS, 'WIN')) {
if (posix_geteuid() !== 0) { if (\posix_geteuid() !== 0) {
$processUser = posix_getpwnam(posix_geteuid()); $processUser = \posix_getpwnam(\posix_geteuid());
$currentUsername = $processUser['name']; $currentUsername = $processUser['name'];
$user = $args->get('user') ?: $currentUsername; $user = $args->get('user') ?: $currentUsername;
@@ -48,12 +48,12 @@ class Issue implements Command {
} }
} }
$domains = array_map('trim', explode(':', str_replace([',', ';'], ':', $args->get('domains')))); $domains = \array_map('trim', \explode(':', \str_replace([',', ';'], ':', $args->get('domains'))));
yield from $this->checkDnsRecords($domains); yield from $this->checkDnsRecords($domains);
$docRoots = explode(PATH_SEPARATOR, str_replace("\\", '/', $args->get('path'))); $docRoots = \explode(PATH_SEPARATOR, \str_replace("\\", '/', $args->get('path')));
$docRoots = array_map(function ($root) { $docRoots = \array_map(function ($root) {
return rtrim($root, '/'); return \rtrim($root, '/');
}, $docRoots); }, $docRoots);
if (\count($domains) < \count($docRoots)) { if (\count($domains) < \count($docRoots)) {
@@ -61,9 +61,9 @@ class Issue implements Command {
} }
if (\count($domains) > \count($docRoots)) { if (\count($domains) > \count($docRoots)) {
$docRoots = array_merge( $docRoots = \array_merge(
$docRoots, $docRoots,
array_fill(\count($docRoots), \count($domains) - \count($docRoots), end($docRoots)) \array_fill(\count($docRoots), \count($domains) - \count($docRoots), \end($docRoots))
); );
} }
@@ -96,7 +96,7 @@ class Issue implements Command {
throw new AcmeException('Issuance failed, not all challenges could be solved.'); throw new AcmeException('Issuance failed, not all challenges could be solved.');
} }
$path = 'certs/' . $keyFile . '/' . reset($domains) . '/key.pem'; $path = 'certs/' . $keyFile . '/' . \reset($domains) . '/key.pem';
$bits = $args->get('bits'); $bits = $args->get('bits');
try { try {
@@ -119,7 +119,7 @@ class Issue implements Command {
yield $certificateStore->put($certificates); yield $certificateStore->put($certificates);
$this->climate->info(' Successfully issued certificate.'); $this->climate->info(' Successfully issued certificate.');
$this->climate->info(" See {$path}/" . reset($domains)); $this->climate->info(" See {$path}/" . \reset($domains));
$this->climate->br(); $this->climate->br();
return 0; return 0;
@@ -134,10 +134,10 @@ class Issue implements Command {
throw new AcmeException("Couldn't find any combination of challenges which this client can solve!"); throw new AcmeException("Couldn't find any combination of challenges which this client can solve!");
} }
$challenge = $challenges->challenges[reset($goodChallenges)]; $challenge = $challenges->challenges[\reset($goodChallenges)];
$token = $challenge->token; $token = $challenge->token;
if (!preg_match('#^[a-zA-Z0-9-_]+$#', $token)) { if (!\preg_match('#^[a-zA-Z0-9-_]+$#', $token)) {
throw new AcmeException('Protocol violation: Invalid Token!'); throw new AcmeException('Protocol violation: Invalid Token!');
} }
@@ -165,8 +165,8 @@ class Issue implements Command {
list($errors) = yield Promise\any($promises); list($errors) = yield Promise\any($promises);
if ($errors) { if ($errors) {
$failedDomains = implode(', ', array_keys($errors)); $failedDomains = \implode(', ', \array_keys($errors));
$reasons = implode("\n\n", array_map(function ($exception) { $reasons = \implode("\n\n", \array_map(function ($exception) {
/** @var \Throwable $exception */ /** @var \Throwable $exception */
return \get_class($exception) . ': ' . $exception->getMessage(); return \get_class($exception) . ': ' . $exception->getMessage();
}, $errors)); }, $errors));

View File

@@ -45,13 +45,13 @@ class Revoke implements Command {
throw new \RuntimeException("There's no such certificate (" . $path . ')'); throw new \RuntimeException("There's no such certificate (" . $path . ')');
} }
if ($cert->getValidTo() < time()) { if ($cert->getValidTo() < \time()) {
$this->climate->comment(' Certificate did already expire, no need to revoke it.'); $this->climate->comment(' Certificate did already expire, no need to revoke it.');
} }
$names = $cert->getNames(); $names = $cert->getNames();
$this->climate->whisper(' Certificate was valid for ' . \count($names) . ' domains.'); $this->climate->whisper(' Certificate was valid for ' . \count($names) . ' domains.');
$this->climate->whisper(' - ' . implode(PHP_EOL . ' - ', $names) . PHP_EOL); $this->climate->whisper(' - ' . \implode(PHP_EOL . ' - ', $names) . PHP_EOL);
yield $acme->revokeCertificate($pem); yield $acme->revokeCertificate($pem);
@@ -75,4 +75,4 @@ class Revoke implements Command {
], ],
]; ];
} }
} }

View File

@@ -57,11 +57,11 @@ class Setup implements Command {
$acme = $this->acmeFactory->build($server, $keyPair); $acme = $this->acmeFactory->build($server, $keyPair);
$this->climate->whisper(' Registering with ' . substr($server, 8) . ' ...'); $this->climate->whisper(' Registering with ' . \substr($server, 8) . ' ...');
/** @var Registration $registration */ /** @var Registration $registration */
$registration = yield $acme->register($email); $registration = yield $acme->register($email);
$this->climate->info(' Registration successful. Contacts: ' . implode(', ', $registration->getContact())); $this->climate->info(' Registration successful. Contacts: ' . \implode(', ', $registration->getContact()));
$this->climate->br(); $this->climate->br();
return 0; return 0;
@@ -69,7 +69,7 @@ class Setup implements Command {
} }
private function checkEmail(string $email) { private function checkEmail(string $email) {
$host = substr($email, strrpos($email, '@') + 1); $host = \substr($email, \strrpos($email, '@') + 1);
if (!$host) { if (!$host) {
throw new AcmeException("Invalid contact email: '{$email}'"); throw new AcmeException("Invalid contact email: '{$email}'");
@@ -98,7 +98,7 @@ class Setup implements Command {
$configPath = AcmeClient\getConfigPath(); $configPath = AcmeClient\getConfigPath();
if ($configPath) { if ($configPath) {
$config = Yaml::parse(file_get_contents($configPath)); $config = Yaml::parse(\file_get_contents($configPath));
if (isset($config['email']) && \is_string($config['email'])) { if (isset($config['email']) && \is_string($config['email'])) {
$args['email']['required'] = false; $args['email']['required'] = false;
@@ -108,4 +108,4 @@ class Setup implements Command {
return $args; return $args;
} }
} }

View File

@@ -50,13 +50,13 @@ class Status {
$pem = yield $certificateStore->get($domain); $pem = yield $certificateStore->get($domain);
$cert = new Certificate($pem); $cert = new Certificate($pem);
$symbol = time() > $cert->getValidTo() ? '<red> ✗ </red>' : '<green> ✓ </green>'; $symbol = \time() > $cert->getValidTo() ? '<red> ✗ </red>' : '<green> ✓ </green>';
if (time() < $cert->getValidTo() && time() + $args->get('ttl') * 24 * 60 * 60 > $cert->getValidTo()) { if (\time() < $cert->getValidTo() && \time() + $args->get('ttl') * 24 * 60 * 60 > $cert->getValidTo()) {
$symbol = '<yellow> ⭮ </yellow>'; $symbol = '<yellow> ⭮ </yellow>';
} }
$this->climate->out(' [' . $symbol . '] ' . implode(', ', $cert->getNames())); $this->climate->out(' [' . $symbol . '] ' . \implode(', ', $cert->getNames()));
} }
$this->climate->br(); $this->climate->br();
@@ -76,4 +76,4 @@ class Status {
], ],
]; ];
} }
} }

View File

@@ -17,16 +17,16 @@ class Version implements Command {
public function execute(Manager $args): Promise { public function execute(Manager $args): Promise {
$version = $this->getVersion(); $version = $this->getVersion();
$buildTime = $this->readFileOr('info/build.time', time()); $buildTime = $this->readFileOr('info/build.time', \time());
$buildDate = date('M jS Y H:i:s T', (int) trim($buildTime)); $buildDate = \date('M jS Y H:i:s T', (int) \trim($buildTime));
$package = json_decode($this->readFileOr('composer.json', new \Exception('No composer.json found.'))); $package = \json_decode($this->readFileOr('composer.json', new \Exception('No composer.json found.')));
$this->climate->out("┌ <green>kelunik/acme-client</green> @ <yellow>{$version}</yellow> (built: {$buildDate})"); $this->climate->out("┌ <green>kelunik/acme-client</green> @ <yellow>{$version}</yellow> (built: {$buildDate})");
$this->climate->out(($args->defined('deps') ? '│' : '└') . ' ' . $this->getDescription($package)); $this->climate->out(($args->defined('deps') ? '│' : '└') . ' ' . $this->getDescription($package));
if ($args->defined('deps')) { if ($args->defined('deps')) {
$lockFile = json_decode($this->readFileOr('composer.lock', new \Exception('No composer.lock found.'))); $lockFile = \json_decode($this->readFileOr('composer.lock', new \Exception('No composer.lock found.')));
$packages = $lockFile->packages; $packages = $lockFile->packages;
for ($i = 0, $count = \count($packages); $i < $count; $i++) { for ($i = 0, $count = \count($packages); $i < $count; $i++) {
@@ -46,18 +46,18 @@ class Version implements Command {
} }
private function getVersion() { private function getVersion() {
if (file_exists(__DIR__ . '/../../.git')) { if (\file_exists(__DIR__ . '/../../.git')) {
$version = `git describe --tags`; $version = `git describe --tags`;
} else { } else {
$version = $this->readFileOr('info/build.version', '-unknown'); $version = $this->readFileOr('info/build.version', '-unknown');
} }
return substr(trim($version), 1); return \substr(\trim($version), 1);
} }
private function readFileOr($file, $default = '') { private function readFileOr($file, $default = '') {
if (file_exists(__DIR__ . '/../../' . $file)) { if (\file_exists(__DIR__ . '/../../' . $file)) {
return file_get_contents(__DIR__ . '/../../' . $file); return \file_get_contents(__DIR__ . '/../../' . $file);
} }
if ($default instanceof \Throwable) { if ($default instanceof \Throwable) {
@@ -76,4 +76,4 @@ class Version implements Command {
], ],
]; ];
} }
} }

View File

@@ -3,4 +3,4 @@
namespace Kelunik\AcmeClient; namespace Kelunik\AcmeClient;
class ConfigException extends \Exception { class ConfigException extends \Exception {
} }

View File

@@ -13,7 +13,7 @@ class CertificateStore {
private $root; private $root;
public function __construct(string $root) { public function __construct(string $root) {
$this->root = rtrim(str_replace("\\", '/', $root), '/'); $this->root = \rtrim(\str_replace("\\", '/', $root), '/');
} }
public function get(string $name): Promise { public function get(string $name): Promise {
@@ -54,10 +54,10 @@ class CertificateStore {
yield File\put($path . '/cert.pem', $certificates[0]); yield File\put($path . '/cert.pem', $certificates[0]);
yield File\chmod($path . '/cert.pem', 0644); yield File\chmod($path . '/cert.pem', 0644);
yield File\put($path . '/fullchain.pem', implode("\n", $certificates)); yield File\put($path . '/fullchain.pem', \implode("\n", $certificates));
yield File\chmod($path . '/fullchain.pem', 0644); yield File\chmod($path . '/fullchain.pem', 0644);
yield File\put($path . '/chain.pem', implode("\n", $chain)); yield File\put($path . '/chain.pem', \implode("\n", $chain));
yield File\chmod($path . '/chain.pem', 0644); yield File\chmod($path . '/chain.pem', 0644);
} catch (FilesystemException $e) { } catch (FilesystemException $e) {
throw new CertificateStoreException("Couldn't save certificates for '{$commonName}'", 0, $e); throw new CertificateStoreException("Couldn't save certificates for '{$commonName}'", 0, $e);

View File

@@ -3,4 +3,4 @@
namespace Kelunik\AcmeClient\Stores; namespace Kelunik\AcmeClient\Stores;
class CertificateStoreException extends \Exception { class CertificateStoreException extends \Exception {
} }

View File

@@ -10,7 +10,7 @@ class ChallengeStore {
private $docroot; private $docroot;
public function __construct(string $docroot) { public function __construct(string $docroot) {
$this->docroot = rtrim(str_replace("\\", '/', $docroot), '/'); $this->docroot = \rtrim(\str_replace("\\", '/', $docroot), '/');
} }
public function put(string $token, string $payload, string $user = null): Promise { public function put(string $token, string $payload, string $user = null): Promise {
@@ -26,7 +26,7 @@ class ChallengeStore {
throw new ChallengeStoreException("Couldn't create key directory: '{$path}'"); throw new ChallengeStoreException("Couldn't create key directory: '{$path}'");
} }
if ($user && !$userInfo = posix_getpwnam($user)) { if ($user && !$userInfo = \posix_getpwnam($user)) {
throw new ChallengeStoreException("Unknown user: '{$user}'"); throw new ChallengeStoreException("Unknown user: '{$user}'");
} }
@@ -54,4 +54,4 @@ class ChallengeStore {
} }
}); });
} }
} }

View File

@@ -3,4 +3,4 @@
namespace Kelunik\AcmeClient\Stores; namespace Kelunik\AcmeClient\Stores;
class ChallengeStoreException extends \Exception { class ChallengeStoreException extends \Exception {
} }

View File

@@ -12,7 +12,7 @@ class KeyStore {
private $root; private $root;
public function __construct(string $root = '') { public function __construct(string $root = '') {
$this->root = rtrim(str_replace("\\", '/', $root), '/'); $this->root = \rtrim(\str_replace("\\", '/', $root), '/');
} }
public function get(string $path): Promise { public function get(string $path): Promise {
@@ -21,7 +21,7 @@ class KeyStore {
$privateKey = yield File\get($file); $privateKey = yield File\get($file);
// Check key here to be valid, PrivateKey doesn't do that, we fail early here // Check key here to be valid, PrivateKey doesn't do that, we fail early here
$res = openssl_pkey_get_private($privateKey); $res = \openssl_pkey_get_private($privateKey);
if ($res === false) { if ($res === false) {
throw new KeyStoreException("Invalid private key: '{$file}'"); throw new KeyStoreException("Invalid private key: '{$file}'");
@@ -51,4 +51,4 @@ class KeyStore {
return $key; return $key;
}); });
} }
} }

View File

@@ -3,4 +3,4 @@
namespace Kelunik\AcmeClient\Stores; namespace Kelunik\AcmeClient\Stores;
class KeyStoreException extends \Exception { class KeyStoreException extends \Exception {
} }

View File

@@ -24,7 +24,7 @@ function concurrentMap(int $concurrency, array $values, callable $functor): arra
} finally { } finally {
$lock->release(); $lock->release();
} }
}), $values, array_keys($values)); }), $values, \array_keys($values));
} }
/** /**
@@ -37,14 +37,14 @@ function concurrentMap(int $concurrency, array $values, callable $functor): arra
* @return string suggestion or empty string if no command is similar enough * @return string suggestion or empty string if no command is similar enough
*/ */
function suggestCommand(string $badCommand, array $commands, int $suggestThreshold = 70): string { function suggestCommand(string $badCommand, array $commands, int $suggestThreshold = 70): string {
$badCommand = strtolower($badCommand); $badCommand = \strtolower($badCommand);
$bestMatch = ''; $bestMatch = '';
$bestMatchPercentage = 0; $bestMatchPercentage = 0;
$byRefPercentage = 0; $byRefPercentage = 0;
foreach ($commands as $command) { foreach ($commands as $command) {
\similar_text($badCommand, strtolower($command), $byRefPercentage); \similar_text($badCommand, \strtolower($command), $byRefPercentage);
if ($byRefPercentage > $bestMatchPercentage) { if ($byRefPercentage > $bestMatchPercentage) {
$bestMatchPercentage = $byRefPercentage; $bestMatchPercentage = $byRefPercentage;
@@ -74,11 +74,11 @@ function resolveServer(string $uri): string {
return $shortcuts[$uri]; return $shortcuts[$uri];
} }
if (strpos($uri, '/') === false) { if (\strpos($uri, '/') === false) {
throw new InvalidArgumentException('Invalid server URI: ' . $uri); throw new InvalidArgumentException('Invalid server URI: ' . $uri);
} }
$protocol = substr($uri, 0, strpos($uri, '://')); $protocol = \substr($uri, 0, \strpos($uri, '://'));
if (!$protocol || $protocol === $uri) { if (!$protocol || $protocol === $uri) {
return "https://{$uri}"; return "https://{$uri}";
@@ -95,11 +95,11 @@ function resolveServer(string $uri): string {
* @return string identifier usable as file name * @return string identifier usable as file name
*/ */
function serverToKeyname(string $server): string { function serverToKeyname(string $server): string {
$server = substr($server, strpos($server, '://') + 3); $server = \substr($server, \strpos($server, '://') + 3);
$keyFile = str_replace('/', '.', $server); $keyFile = \str_replace('/', '.', $server);
$keyFile = preg_replace('@[^a-z0-9._-]@', '', $keyFile); $keyFile = \preg_replace('@[^a-z0-9._-]@', '', $keyFile);
$keyFile = preg_replace("@\\.+@", '.', $keyFile); $keyFile = \preg_replace("@\\.+@", '.', $keyFile);
return $keyFile; return $keyFile;
} }
@@ -110,7 +110,7 @@ function serverToKeyname(string $server): string {
* @return bool {@code true} if running as Phar, {@code false} otherwise * @return bool {@code true} if running as Phar, {@code false} otherwise
*/ */
function isPhar(): bool { function isPhar(): bool {
if (!class_exists('Phar')) { if (!\class_exists('Phar')) {
return false; return false;
} }
@@ -125,7 +125,7 @@ function isPhar(): bool {
* @return string normalized path * @return string normalized path
*/ */
function normalizePath(string $path): string { function normalizePath(string $path): string {
return rtrim(str_replace("\\", '/', $path), '/'); return \rtrim(\str_replace("\\", '/', $path), '/');
} }
/** /**
@@ -136,8 +136,8 @@ function normalizePath(string $path): string {
function getConfigPath() { function getConfigPath() {
$paths = isPhar() ? [\substr(\dirname(Phar::running()), \strlen('phar://')) . '/acme-client.yml'] : []; $paths = isPhar() ? [\substr(\dirname(Phar::running()), \strlen('phar://')) . '/acme-client.yml'] : [];
if (0 !== stripos(PHP_OS, 'WIN')) { if (0 !== \stripos(PHP_OS, 'WIN')) {
if ($home = getenv('HOME')) { if ($home = \getenv('HOME')) {
$paths[] = $home . '/.acme-client.yml'; $paths[] = $home . '/.acme-client.yml';
} }
@@ -145,9 +145,9 @@ function getConfigPath() {
} }
do { do {
$path = array_shift($paths); $path = \array_shift($paths);
if (file_exists($path)) { if (\file_exists($path)) {
return $path; return $path;
} }
} while (\count($paths)); } while (\count($paths));
@@ -168,7 +168,7 @@ function getArgumentDescription($argument): array {
$config = []; $config = [];
if ($configPath = getConfigPath()) { if ($configPath = getConfigPath()) {
$configContent = file_get_contents($configPath); $configContent = \file_get_contents($configPath);
try { try {
$config = Yaml::parse($configContent); $config = Yaml::parse($configContent);
@@ -212,7 +212,7 @@ function getArgumentDescription($argument): array {
if (!$isPhar) { if (!$isPhar) {
$desc['defaultValue'] = \dirname(__DIR__) . '/data'; $desc['defaultValue'] = \dirname(__DIR__) . '/data';
} else if (isset($config['storage'])) { } elseif (isset($config['storage'])) {
$desc['required'] = false; $desc['required'] = false;
$desc['defaultValue'] = $config['storage']; $desc['defaultValue'] = $config['storage'];
} }
@@ -233,23 +233,23 @@ function getBinary(): string {
$binary = 'bin/acme'; $binary = 'bin/acme';
if (isPhar()) { if (isPhar()) {
$binary = substr(Phar::running(), \strlen('phar://')); $binary = \substr(Phar::running(), \strlen('phar://'));
$path = getenv('PATH'); $path = \getenv('PATH');
$locations = explode(PATH_SEPARATOR, $path); $locations = \explode(PATH_SEPARATOR, $path);
$binaryPath = \dirname($binary); $binaryPath = \dirname($binary);
foreach ($locations as $location) { foreach ($locations as $location) {
if ($location === $binaryPath) { if ($location === $binaryPath) {
return substr($binary, \strlen($binaryPath) + 1); return \substr($binary, \strlen($binaryPath) + 1);
} }
} }
$cwd = getcwd(); $cwd = \getcwd();
if ($cwd && strpos($binary, $cwd) === 0) { if ($cwd && \strpos($binary, $cwd) === 0) {
$binary = '.' . substr($binary, \strlen($cwd)); $binary = '.' . \substr($binary, \strlen($cwd));
} }
} }
@@ -270,11 +270,11 @@ function ellipsis($text, $max = 70, $append = '…'): string {
return $text; return $text;
} }
$out = substr($text, 0, $max); $out = \substr($text, 0, $max);
if (strpos($text, ' ') === false) { if (\strpos($text, ' ') === false) {
return $out . $append; return $out . $append;
} }
return preg_replace("/\\w+$/", '', $out) . $append; return \preg_replace("/\\w+$/", '', $out) . $append;
} }

View File

@@ -28,4 +28,4 @@ class FunctionsTest extends TestCase {
$this->assertSame('/etc/foobar', normalizePath('/etc/foobar/')); $this->assertSame('/etc/foobar', normalizePath('/etc/foobar/'));
$this->assertSame('C:/etc/foobar', normalizePath("C:\\etc\\foobar\\")); $this->assertSame('C:/etc/foobar', normalizePath("C:\\etc\\foobar\\"));
} }
} }