PSR12 code standard.
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful

This commit is contained in:
Jens True 2023-06-08 12:44:59 +00:00
parent afc4a1e3ce
commit d0270b00ca
8 changed files with 108 additions and 116 deletions

@ -1,12 +1,14 @@
analyze-all: analyze: analyze-phpmd analyze-phpstan analyze-psalm analyze-phpcs
@echo PHPMessDetector
analyze-phpmd:
-./vendor/bin/phpmd src text cleancode,codesize,controversial,design,naming,unusedcode -./vendor/bin/phpmd src text cleancode,codesize,controversial,design,naming,unusedcode
@echo PHPStan analyze-phpstan:
-./vendor/bin/phpstan analyze --level=7 src/ backup -./vendor/bin/phpstan analyze --level=7 --error-format=raw src/ backup
@echo Psalm analyze-psalm:
-./vendor/bin/psalm -./vendor/bin/psalm
@echo PHP_CodeSniffer analyze-phpcs:
-./vendor/bin/phpcs src -./vendor/bin/phpcs src backup --report=emacs --standard=PSR12
install: install:
php composer.phar install --no-dev php composer.phar install --no-dev
install-dev: install-dev:

10
composer.lock generated

@ -2922,16 +2922,16 @@
}, },
{ {
"name": "phpstan/phpstan", "name": "phpstan/phpstan",
"version": "1.10.16", "version": "1.10.18",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/phpstan/phpstan.git", "url": "https://github.com/phpstan/phpstan.git",
"reference": "352bdbb960bb523e3d71b834862589f910921c23" "reference": "52b6416c579663eebdd2f1d97df21971daf3b43f"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/352bdbb960bb523e3d71b834862589f910921c23", "url": "https://api.github.com/repos/phpstan/phpstan/zipball/52b6416c579663eebdd2f1d97df21971daf3b43f",
"reference": "352bdbb960bb523e3d71b834862589f910921c23", "reference": "52b6416c579663eebdd2f1d97df21971daf3b43f",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -2980,7 +2980,7 @@
"type": "tidelift" "type": "tidelift"
} }
], ],
"time": "2023-06-05T08:21:46+00:00" "time": "2023-06-07T22:00:43+00:00"
}, },
{ {
"name": "phpunit/php-code-coverage", "name": "phpunit/php-code-coverage",

@ -6,6 +6,7 @@
xmlns="https://getpsalm.org/schema/config" xmlns="https://getpsalm.org/schema/config"
xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd" xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd"
findUnusedBaselineEntry="true" findUnusedBaselineEntry="true"
findUnusedCode="true"
> >
<projectFiles> <projectFiles>
<directory name="src/" /> <directory name="src/" />

@ -1,9 +1,9 @@
<?php <?php
namespace App; namespace App;
use Symfony\Component\Yaml\Yaml; use Symfony\Component\Yaml\Yaml;
use Symfony\Component\Yaml\Exception\ParseException; use Symfony\Component\Yaml\Exception\ParseException;
use Monolog\Logger; use Monolog\Logger;
use Monolog\Handler\StreamHandler; use Monolog\Handler\StreamHandler;
use Psr\Log\NullLogger; use Psr\Log\NullLogger;
@ -20,32 +20,32 @@ use Psr\Log\NullLogger;
class App class App
{ {
protected Logger $logger; protected Logger $logger;
protected array $config; protected mixed $config;
/** /**
* Create a new instance providing a config file * Create a new instance providing a config file
* *
* @param string $configFile Relative or full path to YML config. * @param string $configFile Relative or full path to YML config.
*/ */
function __construct(string $configFile) public function __construct(string $configFile)
{ {
$this->config = Yaml::parseFile($configFile); $parser = new Yaml();
$this->config = $parser->parseFile($configFile);
$logger = new Logger('app'); $logger = new Logger('app');
if (isset($this->config['log'])) { if (isset($this->config['log'])) {
$logger->pushHandler(new StreamHandler($this->getConfig()['log'])); $logger->pushHandler(new StreamHandler($this->getConfig()['log']));
} }
$logger->info("Initialization complete"); $logger->info("Initialization complete");
$this->logger = $logger; $this->logger = $logger;
} }
/** /**
* Get the full configuration * Get the full configuration
* *
* @return array Full configuration structure * @return mixed Full configuration structure
*/ */
function getConfig() : array public function getConfig(): mixed
{ {
return $this->config; return $this->config;
} }
@ -55,7 +55,7 @@ class App
* *
* @return Logger Instance of logger * @return Logger Instance of logger
*/ */
function getLogger() : Logger public function getLogger(): Logger
{ {
return $this->logger; return $this->logger;
} }

@ -1,52 +1,46 @@
<?php <?php
namespace App; namespace App;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle; use Symfony\Component\Console\Style\SymfonyStyle;
use Twig\Environment; use Twig\Environment;
use Twig\Loader\ArrayLoader; use Twig\Loader\ArrayLoader;
use DateTime; use DateTime;
use Ntfy\Server; use Ntfy\Server;
use Ntfy\Message; use Ntfy\Message;
use Ntfy\Client; use Ntfy\Client;
#[AsCommand(
name: 'backup',
description: 'Start backup to assigned buckets.',
hidden: false,
)]
class CommandBackup extends Command class CommandBackup extends Command
{ {
static $defaultName = "backup"; public static $defaultName = "backup";
static $defaultDescription = "Start backup to assigned buckets"; public static $defaultDescription = "Start backup to assigned buckets";
protected function configure(): void protected function configure(): void
{ {
$this->addArgument('config', InputArgument::OPTIONAL, 'Configuration file', "config.yml"); $this->addArgument(
'config',
InputArgument::OPTIONAL,
'Configuration file',
"config.yml"
);
} }
protected function execute(InputInterface $input, OutputInterface $output): int protected function execute(InputInterface $input, OutputInterface $output): int
{ {
$io = new SymfonyStyle($input, $output); $sio = new SymfonyStyle($input, $output);
$io->title('Start backup process'); $sio->title('Start backup process');
try { try {
$app = new App($input->getArgument('config')); $app = new App($input->getArgument('config'));
} } catch (\Throwable $e) {
catch (\Throwable $e) { $sio->error('Configuration error:' . $e->getMessage());
$io->error('Unable to parse the YAML string: '. $e->getMessage());
return Command::FAILURE; return Command::FAILURE;
} }
$rclone = new Rclone\Rclone(); $rclone = new Rclone\Rclone();
$rclone->setLogger($app->getLogger()->withName('rclone')); $rclone->setLogger($app->getLogger()->withName('rclone'));
@ -57,7 +51,7 @@ class CommandBackup extends Command
$twig = new Environment($loader); $twig = new Environment($loader);
$twig->addExtension(new Twig\AppExtension()); $twig->addExtension(new Twig\AppExtension());
foreach ($io->progressIterate($app->getConfig()['backup']) as $conf) { foreach ($sio->progressIterate($app->getConfig()['backup']) as $conf) {
$message = new Message(); $message = new Message();
$message->topic($app->getConfig()['notification']['topic']); $message->topic($app->getConfig()['notification']['topic']);
$message->title($conf['title']); $message->title($conf['title']);
@ -82,7 +76,7 @@ class CommandBackup extends Command
$client->send($message); $client->send($message);
} }
$io->success("Complete"); $sio->success("Complete");
return Command::SUCCESS; return Command::SUCCESS;
} }
} }

@ -1,45 +1,46 @@
<?php <?php
namespace App; namespace App;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle; use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(
name: 'show',
description: 'Show all backup entries.',
hidden: false,
)]
class CommandShow extends Command class CommandShow extends Command
{ {
static $defaultName = "show"; public static $defaultName = "show";
static $defaultDescription = "Show all backup entries"; public static $defaultDescription = "Show all backup entries";
protected function configure(): void protected function configure(): void
{ {
$this->addArgument('config', InputArgument::OPTIONAL, 'Configuration file', "config.yml"); $this->addArgument(
'config',
InputArgument::OPTIONAL,
'Configuration file',
"config.yml"
);
} }
protected function execute(InputInterface $input, OutputInterface $output): int protected function execute(InputInterface $input, OutputInterface $output): int
{ {
$io = new SymfonyStyle($input, $output); $sio = new SymfonyStyle($input, $output);
$io->title('List backup entities'); $sio->title('List backup entities');
try { try {
$app = new App($input->getArgument('config')); $app = new App($input->getArgument('config'));
} } catch (\Throwable $e) {
catch (\Throwable $e) { $sio->error('Configuration error: ' . $e->getMessage());
$io->error('Unable to parse the YAML string: '. $e->getMessage());
return Command::FAILURE; return Command::FAILURE;
} }
$io->table(['Description', 'Source', 'Destination'], $app->getConfig()['backup']); $sio->table(
['Description', 'Source', 'Destination'],
$app->getConfig()['backup']
);
$io->success("Done"); $sio->success("Done");
return Command::SUCCESS; return Command::SUCCESS;
} }
} }

@ -1,15 +1,14 @@
<?php <?php
namespace App\Rclone; namespace App\Rclone;
use Psr\Log\LoggerAwareTrait; use Psr\Log\LoggerAwareTrait;
use Psr\Log\NullLogger; use Psr\Log\NullLogger;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Symfony\Component\Process\Process; use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException; use Symfony\Component\Process\Exception\ProcessFailedException;
use Exception; use Exception;
/** /**
* Wrapper for the rclone command line utility * Wrapper for the rclone command line utility
* *
@ -32,59 +31,55 @@ class Rclone
protected string $version = ""; protected string $version = "";
/** /**
* Create a new instance * Create a new instance.
* *
* Default it looks for "rclone" on the path. * Default it looks for "rclone" on the path.
* But the path can be configured to be absolute. * But the path can be configured to be absolute.
* *
* @param string $rclonePath Relative or absolute path * @param string $rclonePath Relative or absolute path
*/ */
function __construct(string $rclonePath = "rclone") public function __construct(string $rclonePath = "rclone")
{ {
$this->rclonePath = $rclonePath; $this->rclonePath = $rclonePath;
$this->setLogger(new NullLogger); $this->setLogger(new NullLogger());
try
{ try {
$version = $this->exec('--version'); $version = $this->exec('--version');
$this->version = explode("\n", $version)[0]; $this->version = explode("\n", $version)[0];
} } catch (ProcessFailedException $e) {
catch(ProcessFailedException $e)
{
throw new Exception("Check installation of rclone"); throw new Exception("Check installation of rclone");
} }
if (!\str_contains($this->version, 'rclone')) { if (!\str_contains($this->version, 'rclone')) {
throw new Exception("Rclone not recognized"); throw new Exception("Rclone not recognized");
} }
} }
/** /**
* Get the rclone version * Get the rclone version.
* *
* @return string Version string * @return string Version string
*/ */
function getVersion(): string public function getVersion(): string
{ {
return $this->version; return $this->version;
} }
/** /**
* Calculate the size of a mount/path * Calculate the size of a mount/path.
* *
* @param string $path mount/path. * @param string $path mount/path.
* *
* @return int Size in bytes * @return int Size in bytes
*/ */
function getSize(string $path): int public function getSize(string $path): int
{ {
$output = $this->exec('size', ['--json', $path]); $output = $this->exec('size', ['--json', $path]);
return (int)json_decode($output)->bytes; return (int)json_decode($output)->bytes;
} }
/** /**
* Copy from src to dest * Copy from source to destination.
* *
* @param $src Source mount and path * @param $src Source mount and path
* @param $dest Destination mount and path * @param $dest Destination mount and path
@ -92,7 +87,7 @@ class Rclone
* *
* @return string Stdout from command * @return string Stdout from command
*/ */
function copy(string $src, string $dest, string $bandwidth = null): string public function copy(string $src, string $dest, string $bandwidth = null): string
{ {
$options = array(); $options = array();
@ -107,14 +102,14 @@ class Rclone
} }
/** /**
* Execute a command on the rclone binary * Execute a command on the rclone binary.
* *
* @param string $command Top level Rclone command * @param string $command Top level Rclone command
* @param array<String> $options Array of additional options * @param array<String> $options Array of additional options
* *
* @return string stdout data. * @return string stdout data.
*/ */
protected function exec(string $command, array $options = array()) : string protected function exec(string $command, array $options = array()): string
{ {
$process = new Process( $process = new Process(
array_merge( array_merge(
@ -128,7 +123,7 @@ class Rclone
$this->logger->info("Execute command", [$process->getCommandLine()]); $this->logger->info("Execute command", [$process->getCommandLine()]);
} }
$process->setTimeout(4*3600); $process->setTimeout(4 * 3600);
$process->run(); $process->run();
// executes after the command finishes // executes after the command finishes

@ -20,9 +20,9 @@ class AppExtension extends AbstractExtension
/** /**
* Extend the filters * Extend the filters
* *
* * @return TwigFilter[]
*/ */
public function getFilters() : array public function getFilters(): array
{ {
return array( return array(
new TwigFilter('formatBytes', array($this, 'formatBytes')), new TwigFilter('formatBytes', array($this, 'formatBytes')),
@ -43,5 +43,4 @@ class AppExtension extends AbstractExtension
$fact = (int)(floor((strlen((string)$bytes) - 1) / 3)); $fact = (int)(floor((strlen((string)$bytes) - 1) / 3));
return sprintf("%.{$precision}f", $bytes / pow(1024, $fact)) . $size[$fact]; return sprintf("%.{$precision}f", $bytes / pow(1024, $fact)) . $size[$fact];
} }
} }