From 997212b3ab543eecdf87b7fc02d7edb793318fb7 Mon Sep 17 00:00:00 2001 From: Markus Blaschke Date: Fri, 24 Jul 2015 10:36:33 +0200 Subject: [PATCH 1/8] Added mysql command builder with auto configuration Fixed #51 --- .../Console/Command/Mysql/BackupCommand.php | 12 ++----- .../Console/Command/Mysql/RestoreCommand.php | 12 ++----- .../CommandBuilder/MysqlCommandBuilder.php | 36 +++++++++++++++++++ 3 files changed, 40 insertions(+), 20 deletions(-) create mode 100644 src/app/CliTools/Shell/CommandBuilder/MysqlCommandBuilder.php diff --git a/src/app/CliTools/Console/Command/Mysql/BackupCommand.php b/src/app/CliTools/Console/Command/Mysql/BackupCommand.php index 91bae94..29f624d 100644 --- a/src/app/CliTools/Console/Command/Mysql/BackupCommand.php +++ b/src/app/CliTools/Console/Command/Mysql/BackupCommand.php @@ -22,6 +22,7 @@ use CliTools\Database\DatabaseConnection; use CliTools\Shell\CommandBuilder\CommandBuilder; +use CliTools\Shell\CommandBuilder\MysqlCommandBuilder; use CliTools\Shell\CommandBuilder\CommandBuilderInterface; use CliTools\Utility\FilterUtility; use Symfony\Component\Console\Input\InputArgument; @@ -111,16 +112,7 @@ public function execute(InputInterface $input, OutputInterface $output) { break; } - $command = new CommandBuilder('mysqldump','--user=%s %s --single-transaction', array(DatabaseConnection::getDbUsername(), $database)); - - // Set server connection details - if ($input->getOption('host')) { - $command->addArgumentTemplate('-h %s', $input->getOption('host')); - } - - if ($input->getOption('port')) { - $command->addArgumentTemplate('-P %s', $input->getOption('port')); - } + $command = new MysqlCommandBuilder('mysqldump', '--single-transaction %s', array($database)); if (!empty($filter)) { $command = $this->addFilterArguments($command, $database, $filter); diff --git a/src/app/CliTools/Console/Command/Mysql/RestoreCommand.php b/src/app/CliTools/Console/Command/Mysql/RestoreCommand.php index 6758226..9cba7fe 100644 --- a/src/app/CliTools/Console/Command/Mysql/RestoreCommand.php +++ b/src/app/CliTools/Console/Command/Mysql/RestoreCommand.php @@ -26,6 +26,7 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use CliTools\Shell\CommandBuilder\CommandBuilder; +use CliTools\Shell\CommandBuilder\MysqlCommandBuilder; class RestoreCommand extends AbstractCommand { @@ -89,16 +90,7 @@ public function execute(InputInterface $input, OutputInterface $output) { putenv('MYSQL_PWD=' . DatabaseConnection::getDbPassword()); - $commandMysql = new CommandBuilder('mysql','--user=%s %s --one-database', array(DatabaseConnection::getDbUsername(), $database)); - - // Set server connection details - if ($input->getOption('host')) { - $commandMysql->addArgumentTemplate('-h %s', $input->getOption('host')); - } - - if ($input->getOption('port')) { - $commandMysql->addArgumentTemplate('-P %s', $input->getOption('port')); - } + $commandMysql = new MysqlCommandBuilder('mysql', '%s --one-database', array($database)); $commandFile = new CommandBuilder(); $commandFile->addArgument($dumpFile); diff --git a/src/app/CliTools/Shell/CommandBuilder/MysqlCommandBuilder.php b/src/app/CliTools/Shell/CommandBuilder/MysqlCommandBuilder.php new file mode 100644 index 0000000..5495199 --- /dev/null +++ b/src/app/CliTools/Shell/CommandBuilder/MysqlCommandBuilder.php @@ -0,0 +1,36 @@ + + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +class MysqlCommandBuilder extends CommandBuilder { + + /** + * Initalized command + */ + protected function initialize() { + $this + ->addArgumentTemplate('--user=%s', DatabaseConnection::getDbUsername()) + ->addArgumentTemplate('--password=%s', DatabaseConnection::getDbPassword()) + ->addArgumentTemplate('--host=%s', DatabaseConnection::getDbHostname()) + ->addArgumentTemplate('--port=%s', DatabaseConnection::getDbPort()); + } + +} From e9afc6c3930e12a62e4ca5f4a597500268115ce8 Mon Sep 17 00:00:00 2001 From: Markus Blaschke Date: Fri, 24 Jul 2015 10:43:17 +0200 Subject: [PATCH 2/8] Fixed coding style (PSR2) --- src/app/CliTools/Console/Application.php | 81 +++-- .../Console/Command/AbstractCommand.php | 48 ++- .../Console/Command/AbstractTraceCommand.php | 34 +- .../Console/Command/Apache/RestartCommand.php | 16 +- .../Console/Command/Apache/TraceCommand.php | 11 +- .../Command/Common/FixRightsCommand.php | 33 +- .../Console/Command/Common/MakeCommand.php | 21 +- .../Command/Common/SelfUpdateCommand.php | 62 ++-- .../Command/Docker/AbstractCommand.php | 42 ++- .../Console/Command/Docker/CliCommand.php | 29 +- .../Console/Command/Docker/ComposeCommand.php | 16 +- .../Console/Command/Docker/CreateCommand.php | 136 ++++---- .../Console/Command/Docker/ExecCommand.php | 19 +- .../Console/Command/Docker/IftopCommand.php | 19 +- .../Console/Command/Docker/MysqlCommand.php | 19 +- .../Console/Command/Docker/RootCommand.php | 31 +- .../Console/Command/Docker/ShellCommand.php | 43 +-- .../Console/Command/Docker/SniffCommand.php | 59 ++-- .../Console/Command/Docker/UpCommand.php | 34 +- .../Console/Command/Log/ApacheCommand.php | 28 +- .../Console/Command/Log/DebugCommand.php | 26 +- .../Console/Command/Log/MailCommand.php | 24 +- .../Console/Command/Log/PhpCommand.php | 26 +- .../Console/Command/Mysql/AbstractCommand.php | 60 ++-- .../Console/Command/Mysql/BackupCommand.php | 51 +-- .../Console/Command/Mysql/ClearCommand.php | 28 +- .../Command/Mysql/ConnectionsCommand.php | 14 +- .../Console/Command/Mysql/ConvertCommand.php | 64 ++-- .../Console/Command/Mysql/DebugCommand.php | 34 +- .../Console/Command/Mysql/DropCommand.php | 24 +- .../Console/Command/Mysql/ListCommand.php | 106 +++--- .../Console/Command/Mysql/RestartCommand.php | 16 +- .../Console/Command/Mysql/RestoreCommand.php | 40 +-- .../Console/Command/Mysql/SlowLogCommand.php | 58 ++-- .../Console/Command/Php/ComposerCommand.php | 29 +- .../Console/Command/Php/RestartCommand.php | 16 +- .../Console/Command/Php/TraceCommand.php | 11 +- .../Console/Command/Samba/RestartCommand.php | 16 +- .../Console/Command/Sync/AbstractCommand.php | 318 ++++++++++-------- .../Sync/AbstractRemoteSyncCommand.php | 6 +- .../Command/Sync/AbstractShareCommand.php | 13 +- .../Console/Command/Sync/BackupCommand.php | 36 +- .../Console/Command/Sync/DeployCommand.php | 20 +- .../Console/Command/Sync/InitCommand.php | 26 +- .../Console/Command/Sync/RestoreCommand.php | 30 +- .../Console/Command/Sync/ServerCommand.php | 35 +- .../Console/Command/System/BannerCommand.php | 21 +- .../Command/System/CrontaskCommand.php | 60 ++-- .../Console/Command/System/EnvCommand.php | 14 +- .../Command/System/OpenFilesCommand.php | 33 +- .../Console/Command/System/RebootCommand.php | 18 +- .../Command/System/ShutdownCommand.php | 18 +- .../Console/Command/System/StartupCommand.php | 34 +- .../Console/Command/System/SwapCommand.php | 26 +- .../Console/Command/System/UpdateCommand.php | 36 +- .../Console/Command/System/VersionCommand.php | 21 +- .../Console/Command/TYPO3/BeUserCommand.php | 61 ++-- .../Console/Command/TYPO3/CleanupCommand.php | 27 +- .../Command/TYPO3/ClearCacheCommand.php | 33 +- .../Console/Command/TYPO3/DomainCommand.php | 110 +++--- .../Command/TYPO3/InstallerCommand.php | 40 ++- .../Console/Command/TYPO3/ListCommand.php | 29 +- .../Command/TYPO3/SchedulerCommand.php | 35 +- .../Command/User/RebuildSshConfigCommand.php | 17 +- .../Console/Command/Vagrant/ShareCommand.php | 139 ++++---- .../Filter/AnyParameterFilterInterface.php | 3 +- .../Filter/OnlyRootFilterInterface.php | 3 +- .../Formatter/OutputFormatterStyle.php | 62 ++-- .../CliTools/Database/DatabaseConnection.php | 142 +++++--- .../Exception/CommandExecutionException.php | 15 +- src/app/CliTools/Exception/StopException.php | 3 +- .../Iterator/Filter/DirectoryFilter.php | 6 +- .../Filter/ProcProcessDirectoryFilter.php | 6 +- .../Filter/RecursiveDirectoryFilter.php | 6 +- .../Filter/Typo3RecursiveDirectoryFilter.php | 6 +- src/app/CliTools/Reader/ConfigReader.php | 51 ++- .../CliTools/Service/SelfUpdateService.php | 82 +++-- src/app/CliTools/Service/SettingsService.php | 24 +- .../CommandBuilder/AbstractCommandBuilder.php | 197 +++++++---- .../Shell/CommandBuilder/CommandBuilder.php | 3 +- .../CommandBuilderInterface.php | 5 +- .../CommandBuilder/EditorCommandBuilder.php | 6 +- .../CommandBuilder/FullSelfCommandBuilder.php | 6 +- .../CommandBuilder/MysqlCommandBuilder.php | 21 +- .../OutputCombineCommandBuilder.php | 18 +- .../CommandBuilder/RemoteCommandBuilder.php | 3 +- .../CommandBuilder/SelfCommandBuilder.php | 6 +- src/app/CliTools/Shell/Executor.php | 76 +++-- src/app/CliTools/Utility/ConsoleUtility.php | 28 +- src/app/CliTools/Utility/DockerUtility.php | 18 +- src/app/CliTools/Utility/FilterUtility.php | 9 +- src/app/CliTools/Utility/FormatUtility.php | 9 +- src/app/CliTools/Utility/PhpUtility.php | 52 ++- src/app/CliTools/Utility/Typo3Utility.php | 12 +- src/app/CliTools/Utility/UnixUtility.php | 105 +++--- 95 files changed, 2185 insertions(+), 1478 deletions(-) diff --git a/src/app/CliTools/Console/Application.php b/src/app/CliTools/Console/Application.php index e1e8920..03acfc2 100644 --- a/src/app/CliTools/Console/Application.php +++ b/src/app/CliTools/Console/Application.php @@ -20,14 +20,15 @@ * along with this program. If not, see . */ +use CliTools\Console\Formatter\OutputFormatterStyle; use CliTools\Database\DatabaseConnection; use CliTools\Service\SettingsService; -use CliTools\Console\Formatter\OutputFormatterStyle; +use Symfony\Component\Console\Input\ArgvInput; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Input\ArgvInput; -class Application extends \Symfony\Component\Console\Application { +class Application extends \Symfony\Component\Console\Application +{ /** * Configuration @@ -40,7 +41,7 @@ class Application extends \Symfony\Component\Console\Application { 'class' => array(), 'ignore' => array(), ), - '_files' => array(), + '_files' => array(), ); /** @@ -67,7 +68,8 @@ class Application extends \Symfony\Component\Console\Application { * * @param string $file Config file (.ini) */ - public function loadConfig($file) { + public function loadConfig($file) + { if (is_readable($file)) { $parsedConfig = parse_ini_file($file, true); $this->config = array_replace_recursive($this->config, $parsedConfig); @@ -85,7 +87,8 @@ public function loadConfig($file) { * * @return null */ - public function getConfigValue($area, $confKey, $defaultValue = null) { + public function getConfigValue($area, $confKey, $defaultValue = null) + { $ret = $defaultValue; if (isset($this->config[$area][$confKey])) { @@ -98,7 +101,8 @@ public function getConfigValue($area, $confKey, $defaultValue = null) { /** * Initialize */ - public function initialize() { + public function initialize() + { $this->initializeErrorHandler(); $this->initializeChecks(); $this->initializeConfiguration(); @@ -110,14 +114,16 @@ public function initialize() { * * @param callable $func */ - public function registerTearDown(callable $func) { + public function registerTearDown(callable $func) + { $this->tearDownFuncList[] = $func; } /** * Call teardown callbacks */ - public function callTearDown() { + public function callTearDown() + { foreach ($this->tearDownFuncList as $func) { call_user_func($func); } @@ -137,7 +143,8 @@ public function callTearDown() { * @return int 0 if everything went fine, or an error code * @throws \Exception */ - public function doRun(InputInterface $input, OutputInterface $output) { + public function doRun(InputInterface $input, OutputInterface $output) + { $ret = 0; try { @@ -151,7 +158,8 @@ public function doRun(InputInterface $input, OutputInterface $output) { if (!empty($command) && $command instanceof \CliTools\Console\Filter\AnyParameterFilterInterface) { // Remove all paramters and fake input without any paramters // prevent eg. --help message - $argCount = $command->getDefinition()->getArgumentRequiredCount(); + $argCount = $command->getDefinition() + ->getArgumentRequiredCount(); $argvFiltered = array_splice($_SERVER['argv'], 0, 2 + $argCount); @@ -162,7 +170,7 @@ public function doRun(InputInterface $input, OutputInterface $output) { } else { $ret = parent::doRun($input, $output); } - } catch(\CliTools\Exception\StopException $e) { + } catch (\CliTools\Exception\StopException $e) { $this->callTearDown(); $ret = (int)$e->getMessage(); } catch (\Exception $e) { @@ -182,36 +190,42 @@ public function doRun(InputInterface $input, OutputInterface $output) { * @param InputInterface $input An InputInterface instance * @param OutputInterface $output An OutputInterface instance */ - protected function configureIO(InputInterface $input, OutputInterface $output) { + protected function configureIO(InputInterface $input, OutputInterface $output) + { parent::configureIO($input, $output); $style = new OutputFormatterStyle(); $style->setApplication($this); $style->setWrap('-', '-'); - $output->getFormatter()->setStyle('h1', $style); + $output->getFormatter() + ->setStyle('h1', $style); $style = new OutputFormatterStyle(); $style->setPaddingOutside(' ===> '); - $output->getFormatter()->setStyle('h2', $style); + $output->getFormatter() + ->setStyle('h2', $style); $style = new OutputFormatterStyle(); $style->setPaddingOutside(' - '); - $output->getFormatter()->setStyle('p', $style); + $output->getFormatter() + ->setStyle('p', $style); $style = new OutputFormatterStyle('white', 'red'); $style->setPadding(' [EE] '); - $output->getFormatter()->setStyle('p-error', $style); + $output->getFormatter() + ->setStyle('p-error', $style); } /** * Initialize POSIX trap */ - protected function initializePosixTrap() { + protected function initializePosixTrap() + { declare(ticks = 1); $me = $this; - $signalHandler = function ($signal) use($me) { + $signalHandler = function ($signal) use ($me) { $me->callTearDown(); // Prevent terminal messup @@ -225,7 +239,8 @@ protected function initializePosixTrap() { /** * Init error handler */ - protected function initializeErrorHandler() { + protected function initializeErrorHandler() + { $errorHandler = function ($errno, $errstr, $errfile, $errline) { $msg = array( 'Message: ' . $errstr, @@ -244,7 +259,8 @@ protected function initializeErrorHandler() { /** * PHP Checks */ - protected function initializeChecks() { + protected function initializeChecks() + { if (!function_exists('pcntl_signal')) { echo ' [ERROR] PHP-Module pcnt not loaded'; exit(1); @@ -254,7 +270,8 @@ protected function initializeChecks() { /** * Initialize configuration */ - protected function initializeConfiguration() { + protected function initializeConfiguration() + { $isRunningAsRoot = $this->isRunningAsRoot(); //######################### @@ -289,7 +306,10 @@ protected function initializeConfiguration() { foreach ($this->config['commands']['class'] as $class) { if ($this->checkCommandClass($class)) { // check OnlyRoot filter - if (!$isRunningAsRoot && is_subclass_of($class, '\CliTools\Console\Filter\OnlyRootFilterInterface') + if (!$isRunningAsRoot && is_subclass_of( + $class, + '\CliTools\Console\Filter\OnlyRootFilterInterface' + ) ) { // class only useable for root continue; @@ -308,7 +328,8 @@ protected function initializeConfiguration() { * * @return bool */ - protected function checkCommandClass($class) { + protected function checkCommandClass($class) + { // Ignores (deprecated) foreach ($this->config['commands']['ignore'] as $exclude) { @@ -320,7 +341,6 @@ protected function checkCommandClass($class) { if (preg_match($regExp, $class)) { return false; } - } elseif ($class === $exclude) { // direct ignore return false; @@ -338,7 +358,6 @@ protected function checkCommandClass($class) { if (preg_match($regExp, $class)) { return false; } - } elseif ($class === $exclude) { // direct ignore return false; @@ -358,7 +377,8 @@ protected function checkCommandClass($class) { * * @return bool */ - public function isRunningAsRoot() { + public function isRunningAsRoot() + { $currentUid = (int)posix_getuid(); return $currentUid === 0; @@ -369,10 +389,12 @@ public function isRunningAsRoot() { * * @return SettingsService */ - public function getSettingsService() { + public function getSettingsService() + { if ($this->settingsService === null) { $this->settingsService = new SettingsService(); } + return $this->settingsService; } @@ -381,7 +403,8 @@ public function getSettingsService() { * * @param string $title Title */ - public function setTerminalTitle($title) { + public function setTerminalTitle($title) + { // DECSLPP. echo "\033]0;" . 'ct: ' . $title . "\033\\"; } diff --git a/src/app/CliTools/Console/Command/AbstractCommand.php b/src/app/CliTools/Console/Command/AbstractCommand.php index a286a91..18d6989 100644 --- a/src/app/CliTools/Console/Command/AbstractCommand.php +++ b/src/app/CliTools/Console/Command/AbstractCommand.php @@ -20,14 +20,15 @@ * along with this program. If not, see . */ +use CliTools\Shell\CommandBuilder\CommandBuilder; +use CliTools\Shell\CommandBuilder\FullSelfCommandBuilder; use CliTools\Utility\ConsoleUtility; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use CliTools\Shell\CommandBuilder\FullSelfCommandBuilder; -use CliTools\Shell\CommandBuilder\CommandBuilder; -abstract class AbstractCommand extends Command { +abstract class AbstractCommand extends Command +{ /** * Message list (will be shown at the end) @@ -66,7 +67,8 @@ abstract class AbstractCommand extends Command { * @param InputInterface $input An InputInterface instance * @param OutputInterface $output An OutputInterface instance */ - protected function initialize(InputInterface $input, OutputInterface $output) { + protected function initialize(InputInterface $input, OutputInterface $output) + { $this->input = $input; $this->output = $output; @@ -97,7 +99,8 @@ protected function initialize(InputInterface $input, OutputInterface $output) { * * @api */ - public function run(InputInterface $input, OutputInterface $output) { + public function run(InputInterface $input, OutputInterface $output) + { try { $ret = parent::run($input, $output); @@ -114,11 +117,12 @@ public function run(InputInterface $input, OutputInterface $output) { /** * Get full parameter list * - * @param integer $offset Parameter offset + * @param integer $offset Parameter offset * * @return mixed */ - protected function getFullParameterList($offset = null) { + protected function getFullParameterList($offset = null) + { $ret = $_SERVER['argv']; // remove requested offset @@ -137,8 +141,11 @@ protected function getFullParameterList($offset = null) { * * @return int|null|void */ - protected function elevateProcess(InputInterface $input, OutputInterface $output) { - if (!$this->getApplication()->isRunningAsRoot()) { + protected function elevateProcess(InputInterface $input, OutputInterface $output) + { + if (!$this->getApplication() + ->isRunningAsRoot() + ) { // Process is not running as root, trying to elevate to root $output->writeln('Elevating process using sudo...'); @@ -169,7 +176,8 @@ protected function elevateProcess(InputInterface $input, OutputInterface $output * @return int|null|void * @throws \Exception */ - protected function showLog($logList, $input, $output, $grep = null, $optionList = null) { + protected function showLog($logList, $input, $output, $grep = null, $optionList = null) + { $this->elevateProcess($input, $output); // check if logfiles are accessable @@ -202,7 +210,8 @@ protected function showLog($logList, $input, $output, $grep = null, $optionList * * @param string $message Message */ - protected function addFinishMessage($message) { + protected function addFinishMessage($message) + { $this->output->writeln($message); $this->finishMessageList[] = $message; } @@ -210,7 +219,8 @@ protected function addFinishMessage($message) { /** * Show all finish messages */ - protected function showFinishMessages() { + protected function showFinishMessages() + { if (!empty($this->finishMessageList)) { $this->output->writeln(''); @@ -231,7 +241,8 @@ protected function showFinishMessages() { * * @api */ - public function getApplication() { + public function getApplication() + { return parent::getApplication(); } @@ -247,13 +258,14 @@ public function getApplication() { * * @return Command The current instance */ - public function setTerminalTitle($title) { + public function setTerminalTitle($title) + { $args = func_get_args(); $titleList = array(); - foreach($args as $value) { + foreach ($args as $value) { if (is_array($value)) { - $value = implode(' ', $value); + $value = implode(' ', $value); } $titleList[] = trim($value); @@ -262,7 +274,9 @@ public function setTerminalTitle($title) { $title = implode(' ', $titleList); $title = trim($title); - $this->getApplication()->setTerminalTitle($title); + $this->getApplication() + ->setTerminalTitle($title); + return $this; } } diff --git a/src/app/CliTools/Console/Command/AbstractTraceCommand.php b/src/app/CliTools/Console/Command/AbstractTraceCommand.php index 13162f4..6d4d025 100644 --- a/src/app/CliTools/Console/Command/AbstractTraceCommand.php +++ b/src/app/CliTools/Console/Command/AbstractTraceCommand.php @@ -28,7 +28,8 @@ use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Question\ChoiceQuestion; -abstract class AbstractTraceCommand extends AbstractCommand { +abstract class AbstractTraceCommand extends AbstractCommand +{ /** * Process names for strace'ing @@ -40,12 +41,13 @@ abstract class AbstractTraceCommand extends AbstractCommand { /** * Configure command */ - protected function configure() { + protected function configure() + { $this->addArgument( - 'grep', - InputArgument::OPTIONAL, - 'Grep' - ) + 'grep', + InputArgument::OPTIONAL, + 'Grep' + ) ->addOption( 'all', null, @@ -80,11 +82,12 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $this->elevateProcess($input, $output); - $pid = null; - $grep = $input->getArgument('grep'); + $pid = null; + $grep = $input->getArgument('grep'); $command = new CommandBuilder('strace', '-f'); $command->setOutputRedirect(CommandBuilder::OUTPUT_REDIRECT_ALL_STDOUT); @@ -105,7 +108,7 @@ public function execute(InputInterface $input, OutputInterface $output) { $questionDialog = new QuestionHelper(); $pid = $questionDialog->ask($input, $output, $question); - } catch(\InvalidArgumentException $e) { + } catch (\InvalidArgumentException $e) { // Invalid value, just stop here throw new \CliTools\Exception\StopException(1); } @@ -160,7 +163,8 @@ public function execute(InputInterface $input, OutputInterface $output) { * * @return array */ - protected function buildProcessList() { + protected function buildProcessList() + { $currentPid = posix_getpid(); $processList = array( @@ -169,8 +173,12 @@ protected function buildProcessList() { $command = new CommandBuilder('ps'); $command->addArgumentRaw('h -o pid,comm,args') - ->addArgumentTemplate('-C %s', implode(',', $this->traceProcessNameList)); - $cmdOutput = $command->execute()->getOutput(); + ->addArgumentTemplate( + '-C %s', + implode(',', $this->traceProcessNameList) + ); + $cmdOutput = $command->execute() + ->getOutput(); $pidList = array(); foreach ($cmdOutput as $outputLine) { diff --git a/src/app/CliTools/Console/Command/Apache/RestartCommand.php b/src/app/CliTools/Console/Command/Apache/RestartCommand.php index 4dd389c..6509319 100644 --- a/src/app/CliTools/Console/Command/Apache/RestartCommand.php +++ b/src/app/CliTools/Console/Command/Apache/RestartCommand.php @@ -20,19 +20,20 @@ * along with this program. If not, see . */ +use CliTools\Shell\CommandBuilder\CommandBuilder; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use CliTools\Shell\CommandBuilder\CommandBuilder; -class RestartCommand extends \CliTools\Console\Command\AbstractCommand { +class RestartCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('apache:restart') - ->setDescription('Restart Apache'); + protected function configure() + { + $this->setName('apache:restart') + ->setDescription('Restart Apache'); } /** @@ -43,7 +44,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $this->elevateProcess($input, $output); $command = new CommandBuilder('service', 'apache2 restart'); diff --git a/src/app/CliTools/Console/Command/Apache/TraceCommand.php b/src/app/CliTools/Console/Command/Apache/TraceCommand.php index 2330425..d9659e7 100644 --- a/src/app/CliTools/Console/Command/Apache/TraceCommand.php +++ b/src/app/CliTools/Console/Command/Apache/TraceCommand.php @@ -20,7 +20,8 @@ * along with this program. If not, see . */ -class TraceCommand extends \CliTools\Console\Command\AbstractTraceCommand { +class TraceCommand extends \CliTools\Console\Command\AbstractTraceCommand +{ /** * Process names for strace'ing @@ -32,10 +33,10 @@ class TraceCommand extends \CliTools\Console\Command\AbstractTraceCommand { /** * Configure command */ - protected function configure() { - $this - ->setName('apache:trace') - ->setDescription('Debug Apache processes with strace'); + protected function configure() + { + $this->setName('apache:trace') + ->setDescription('Debug Apache processes with strace'); parent::configure(); } diff --git a/src/app/CliTools/Console/Command/Common/FixRightsCommand.php b/src/app/CliTools/Console/Command/Common/FixRightsCommand.php index a0bf82e..26645f3 100644 --- a/src/app/CliTools/Console/Command/Common/FixRightsCommand.php +++ b/src/app/CliTools/Console/Command/Common/FixRightsCommand.php @@ -20,24 +20,25 @@ * along with this program. If not, see . */ -use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class FixRightsCommand extends \CliTools\Console\Command\AbstractCommand { +class FixRightsCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('fix-rights') - ->setDescription('Fix rights of multiple directories and files') - ->addArgument( - 'path', - InputArgument::REQUIRED | InputArgument::IS_ARRAY, - 'Path (multiple)' - ); + protected function configure() + { + $this->setName('fix-rights') + ->setDescription('Fix rights of multiple directories and files') + ->addArgument( + 'path', + InputArgument::REQUIRED | InputArgument::IS_ARRAY, + 'Path (multiple)' + ); } /** @@ -48,7 +49,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $pathList = $this->input->getArgument('path'); $this->checkPathList($pathList); @@ -75,7 +77,8 @@ public function execute(InputInterface $input, OutputInterface $output) { * * @param \SplFileInfo $file */ - protected function setRights(\SplFileInfo $file) { + protected function setRights(\SplFileInfo $file) + { $isDir = false; if ($file->isDir()) { @@ -113,9 +116,11 @@ protected function setRights(\SplFileInfo $file) { * Check path list * * @param $pathList + * * @throws \RuntimeException */ - protected function checkPathList($pathList) { + protected function checkPathList($pathList) + { foreach ($pathList as $path) { if (!file_exists($path)) { throw new \RuntimeException('Path "' . $path . '" does not exists or is not writeable'); diff --git a/src/app/CliTools/Console/Command/Common/MakeCommand.php b/src/app/CliTools/Console/Command/Common/MakeCommand.php index c21c5fd..ad855d2 100644 --- a/src/app/CliTools/Console/Command/Common/MakeCommand.php +++ b/src/app/CliTools/Console/Command/Common/MakeCommand.php @@ -20,21 +20,23 @@ * along with this program. If not, see . */ -use CliTools\Utility\UnixUtility; -use CliTools\Utility\PhpUtility; use CliTools\Shell\CommandBuilder\CommandBuilder; +use CliTools\Utility\PhpUtility; +use CliTools\Utility\UnixUtility; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class MakeCommand extends \CliTools\Console\Command\AbstractCommand implements \CliTools\Console\Filter\AnyParameterFilterInterface { +class MakeCommand extends \CliTools\Console\Command\AbstractCommand implements + \CliTools\Console\Filter\AnyParameterFilterInterface +{ /** * Configure command */ - protected function configure() { - $this - ->setName('make') - ->setDescription('Search Makefile updir and start makefile'); + protected function configure() + { + $this->setName('make') + ->setDescription('Search Makefile updir and start makefile'); } /** @@ -45,9 +47,10 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $paramList = $this->getFullParameterList(); - $path = UnixUtility::findFileInDirectortyTree('Makefile'); + $path = UnixUtility::findFileInDirectortyTree('Makefile'); if (!empty($path)) { $path = dirname($path); diff --git a/src/app/CliTools/Console/Command/Common/SelfUpdateCommand.php b/src/app/CliTools/Console/Command/Common/SelfUpdateCommand.php index 8daf646..e8e3545 100644 --- a/src/app/CliTools/Console/Command/Common/SelfUpdateCommand.php +++ b/src/app/CliTools/Console/Command/Common/SelfUpdateCommand.php @@ -21,38 +21,41 @@ */ use CliTools\Service\SelfUpdateService; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -class SelfUpdateCommand extends \CliTools\Console\Command\AbstractCommand { +class SelfUpdateCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('self-update') - ->setAliases(array('selfupdate')) - ->setDescription('Self update of CliTools Command') - ->addOption( - 'force', - 'f', - InputOption::VALUE_NONE, - 'Force update' - ) - ->addOption( - 'beta', - null, - InputOption::VALUE_NONE, - 'Allow update to beta releases' - ) - ->addOption( - 'fallback', - null, - InputOption::VALUE_NONE, - 'Fallback to old update url' - ); + protected function configure() + { + $this->setName('self-update') + ->setAliases(array('selfupdate')) + ->setDescription( + 'Self update of CliTools Command' + ) + ->addOption( + 'force', + 'f', + InputOption::VALUE_NONE, + 'Force update' + ) + ->addOption( + 'beta', + null, + InputOption::VALUE_NONE, + 'Allow update to beta releases' + ) + ->addOption( + 'fallback', + null, + InputOption::VALUE_NONE, + 'Fallback to old update url' + ); } /** @@ -63,7 +66,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $force = (bool)$input->getOption('force'); $updateService = new SelfUpdateService($this->getApplication(), $output); @@ -77,9 +81,9 @@ public function execute(InputInterface $input, OutputInterface $output) { } // Check if we need root rights - if (!$this->getApplication()->isRunningAsRoot() - && $updateService->isElevationNeeded()) - { + if (!$this->getApplication() + ->isRunningAsRoot() && $updateService->isElevationNeeded() + ) { $this->elevateProcess($input, $output); } diff --git a/src/app/CliTools/Console/Command/Docker/AbstractCommand.php b/src/app/CliTools/Console/Command/Docker/AbstractCommand.php index 1cf5d23..13c6db5 100644 --- a/src/app/CliTools/Console/Command/Docker/AbstractCommand.php +++ b/src/app/CliTools/Console/Command/Docker/AbstractCommand.php @@ -24,7 +24,8 @@ use CliTools\Shell\CommandBuilder\CommandBuilderInterface; use CliTools\Utility\PhpUtility; -abstract class AbstractCommand extends \CliTools\Console\Command\AbstractCommand { +abstract class AbstractCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Docker path @@ -38,7 +39,8 @@ abstract class AbstractCommand extends \CliTools\Console\Command\AbstractCommand * * @return bool|null|string */ - protected function getDockerPath() { + protected function getDockerPath() + { if ($this->dockerPath === null) { $composePath = \CliTools\Utility\DockerUtility::searchDockerDirectoryRecursive(); @@ -59,16 +61,19 @@ protected function getDockerPath() { * * @return string|bool|null */ - protected function getDockerEnv($containerName, $envName) { + protected function getDockerEnv($containerName, $envName) + { $ret = null; if (empty($containerName)) { $this->output->writeln('No container specified'); + return false; } if (empty($envName)) { $this->output->writeln('No environment name specified'); + return false; } @@ -86,7 +91,9 @@ protected function getDockerEnv($containerName, $envName) { $conf = \CliTools\Utility\DockerUtility::getDockerConfiguration($dockerContainerName); if (empty($conf)) { - throw new \RuntimeException('Could not read docker configuration from container "' . $dockerContainerName . '"'); + throw new \RuntimeException( + 'Could not read docker configuration from container "' . $dockerContainerName . '"' + ); } if (!empty($conf->Config->Env[$envName])) { @@ -105,14 +112,17 @@ protected function getDockerEnv($containerName, $envName) { * * @return int|null|void */ - protected function executeDockerExec($containerName, CommandBuilderInterface $command) { + protected function executeDockerExec($containerName, CommandBuilderInterface $command) + { if (empty($containerName)) { $this->output->writeln('No container specified'); + return 1; } if (!$command->isExecuteable()) { $this->output->writeln('No command specified or not executeable'); + return 1; } @@ -126,7 +136,10 @@ protected function executeDockerExec($containerName, CommandBuilderInterface $co // Switch to directory of docker-compose.yml PhpUtility::chdir($path); - $this->output->writeln('Executing "' . $command->getCommand() . '" in docker container "' . $dockerContainerName . '" ...'); + $this->output->writeln( + 'Executing "' . $command->getCommand( + ) . '" in docker container "' . $dockerContainerName . '" ...' + ); $dockerCommand = new CommandBuilder('docker', 'exec -ti %s', array($dockerContainerName)); $dockerCommand->append($command, false); @@ -143,11 +156,12 @@ protected function executeDockerExec($containerName, CommandBuilderInterface $co /** * Execute docker compose run * - * @param null|CommandBuilderInterface $command Command + * @param null|CommandBuilderInterface $command Command * * @return int|null|void */ - protected function executeDockerCompose(CommandBuilderInterface $command = null) { + protected function executeDockerCompose(CommandBuilderInterface $command = null) + { // Search updir for docker-compose.yml $path = \CliTools\Utility\DockerUtility::searchDockerDirectoryRecursive(); @@ -172,12 +186,13 @@ protected function executeDockerCompose(CommandBuilderInterface $command = null) /** * Execute docker compose run * - * @param string $containerName Container name - * @param CommandBuilderInterface $command Command + * @param string $containerName Container name + * @param CommandBuilderInterface $command Command * * @return int|null|void */ - protected function executeDockerComposeRun($containerName, CommandBuilderInterface $command) { + protected function executeDockerComposeRun($containerName, CommandBuilderInterface $command) + { // Search updir for docker-compose.yml $path = $this->getDockerPath(); @@ -185,7 +200,10 @@ protected function executeDockerComposeRun($containerName, CommandBuilderInterfa // Switch to directory of docker-compose.yml PhpUtility::chdir($path); - $this->output->writeln('Executing "' . $command->getCommand() . '" in docker container "' . $containerName . '" ...'); + $this->output->writeln( + 'Executing "' . $command->getCommand( + ) . '" in docker container "' . $containerName . '" ...' + ); $dockerCommand = new CommandBuilder('docker-compose', 'run --rm %s', array($containerName)); $dockerCommand->append($command, false); diff --git a/src/app/CliTools/Console/Command/Docker/CliCommand.php b/src/app/CliTools/Console/Command/Docker/CliCommand.php index 38f1844..14cc03b 100644 --- a/src/app/CliTools/Console/Command/Docker/CliCommand.php +++ b/src/app/CliTools/Console/Command/Docker/CliCommand.php @@ -24,15 +24,18 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class CliCommand extends AbstractCommand implements \CliTools\Console\Filter\AnyParameterFilterInterface { +class CliCommand extends AbstractCommand implements \CliTools\Console\Filter\AnyParameterFilterInterface +{ /** * Configure command */ - protected function configure() { - $this - ->setName('docker:cli') - ->setDescription('Run cli command in docker container (defined by CLI_SCRIPT and CLI_USER as docker environment variable)'); + protected function configure() + { + $this->setName('docker:cli') + ->setDescription( + 'Run cli command in docker container (defined by CLI_SCRIPT and CLI_USER as docker environment variable)' + ); } /** @@ -43,12 +46,15 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $ret = 0; $paramList = $this->getFullParameterList(); - $container = $this->getApplication()->getConfigValue('docker', 'container'); - $cliMethod = $this->getApplication()->getConfigValue('docker', 'climethod'); + $container = $this->getApplication() + ->getConfigValue('docker', 'container'); + $cliMethod = $this->getApplication() + ->getConfigValue('docker', 'climethod'); switch ($cliMethod) { ########################### @@ -59,7 +65,10 @@ public function execute(InputInterface $input, OutputInterface $output) { $cliUser = $this->getDockerEnv($container, 'CLI_USER'); if (empty($cliScript)) { - $output->writeln('Docker container "' . $container . '" doesn\'t have environment variable "CLI_SCRIPT"'); + $output->writeln( + 'Docker container "' . $container . '" doesn\'t have environment variable "CLI_SCRIPT"' + ); + return 1; } @@ -89,7 +98,7 @@ public function execute(InputInterface $input, OutputInterface $output) { break; default: - $output->writeln('CliMethod "' . $cliMethod .'" not defined'); + $output->writeln('CliMethod "' . $cliMethod . '" not defined'); $ret = 1; break; } diff --git a/src/app/CliTools/Console/Command/Docker/ComposeCommand.php b/src/app/CliTools/Console/Command/Docker/ComposeCommand.php index 9d1d716..18fe29d 100644 --- a/src/app/CliTools/Console/Command/Docker/ComposeCommand.php +++ b/src/app/CliTools/Console/Command/Docker/ComposeCommand.php @@ -20,19 +20,20 @@ * along with this program. If not, see . */ +use CliTools\Shell\CommandBuilder\CommandBuilder; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use CliTools\Shell\CommandBuilder\CommandBuilder; -class ComposeCommand extends AbstractCommand implements \CliTools\Console\Filter\AnyParameterFilterInterface { +class ComposeCommand extends AbstractCommand implements \CliTools\Console\Filter\AnyParameterFilterInterface +{ /** * Configure command */ - protected function configure() { - $this - ->setName('docker:compose') - ->setDescription('Run general docker-compose command in docker container'); + protected function configure() + { + $this->setName('docker:compose') + ->setDescription('Run general docker-compose command in docker container'); } /** @@ -43,7 +44,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $paramList = $this->getFullParameterList(); $command = new CommandBuilder(); diff --git a/src/app/CliTools/Console/Command/Docker/CreateCommand.php b/src/app/CliTools/Console/Command/Docker/CreateCommand.php index 5cc1986..d6ba659 100644 --- a/src/app/CliTools/Console/Command/Docker/CreateCommand.php +++ b/src/app/CliTools/Console/Command/Docker/CreateCommand.php @@ -20,53 +20,54 @@ * along with this program. If not, see . */ -use CliTools\Utility\PhpUtility; use CliTools\Shell\CommandBuilder\CommandBuilder; -use CliTools\Shell\CommandBuilder\SelfCommandBuilder; use CliTools\Shell\CommandBuilder\EditorCommandBuilder; +use CliTools\Shell\CommandBuilder\SelfCommandBuilder; +use CliTools\Utility\PhpUtility; use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -class CreateCommand extends AbstractCommand { +class CreateCommand extends AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('docker:create') - ->setDescription('Create new docker boilerplate') - ->addArgument( - 'path', - InputArgument::REQUIRED, - 'Directory for new docker boilerplate instance' - ) - ->addOption( - 'docker', - 'd', - InputOption::VALUE_REQUIRED, - 'Docker Boilerplate repository' - ) - ->addOption( - 'code', - 'c', - InputOption::VALUE_REQUIRED, - 'Code repository' - ) - ->addOption( - 'make', - 'm', - InputOption::VALUE_REQUIRED, - 'Makefile command' - ) - ->addOption( - 'up', - null, - InputOption::VALUE_NONE, - 'Build and start docker containers' - ); + protected function configure() + { + $this->setName('docker:create') + ->setDescription('Create new docker boilerplate') + ->addArgument( + 'path', + InputArgument::REQUIRED, + 'Directory for new docker boilerplate instance' + ) + ->addOption( + 'docker', + 'd', + InputOption::VALUE_REQUIRED, + 'Docker Boilerplate repository' + ) + ->addOption( + 'code', + 'c', + InputOption::VALUE_REQUIRED, + 'Code repository' + ) + ->addOption( + 'make', + 'm', + InputOption::VALUE_REQUIRED, + 'Makefile command' + ) + ->addOption( + 'up', + null, + InputOption::VALUE_NONE, + 'Build and start docker containers' + ); } /** @@ -77,7 +78,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $currDir = getcwd(); $path = $input->getArgument('path'); @@ -87,7 +89,8 @@ public function execute(InputInterface $input, OutputInterface $output) { $boilerplateRepo = $this->input->getOption('docker'); } else { // Boilerplate from config - $boilerplateRepo = $this->getApplication()->getConfigValue('docker', 'boilerplate'); + $boilerplateRepo = $this->getApplication() + ->getConfigValue('docker', 'boilerplate'); } $output->writeln('

Creating new docker boilerplate instance in "' . $path . '"

'); @@ -139,7 +142,8 @@ public function execute(InputInterface $input, OutputInterface $output) { * * @param string $path Path to file */ - protected function startInteractiveEditor($path) { + protected function startInteractiveEditor($path) + { if (file_exists($path)) { // Start editor with file (if $EDITOR is set) try { @@ -147,12 +151,11 @@ protected function startInteractiveEditor($path) { $this->setTerminalTitle('Edit', basename($path)); - $this->output->writeln('

Starting interactive EDITOR for file ' .$path . '

'); + $this->output->writeln('

Starting interactive EDITOR for file ' . $path . '

'); sleep(1); - $editor - ->addArgument($path) - ->executeInteractive(); + $editor->addArgument($path) + ->executeInteractive(); } catch (\Exception $e) { $this->addFinishMessage('' . $e->getMessage() . ''); } @@ -165,10 +168,11 @@ protected function startInteractiveEditor($path) { * @param string $path Path * @param string $repo Repository */ - protected function createDockerInstance($path, $repo) { + protected function createDockerInstance($path, $repo) + { $this->setTerminalTitle('Cloning docker'); - $command = new CommandBuilder('git','clone --branch=master --recursive %s %s', array($repo, $path)); + $command = new CommandBuilder('git', 'clone --branch=master --recursive %s %s', array($repo, $path)); $command->executeInteractive(); } @@ -178,7 +182,8 @@ protected function createDockerInstance($path, $repo) { * @param string $path Path * @param string $repo Repository */ - protected function initCode($path, $repo) { + protected function initCode($path, $repo) + { $this->setTerminalTitle('Cloning code'); $path .= '/code'; @@ -193,13 +198,12 @@ protected function initCode($path, $repo) { // Remove code directory $command = new CommandBuilder('rmdir'); - $command - ->addArgumentSeparator() - ->addArgument($path) - ->executeInteractive(); + $command->addArgumentSeparator() + ->addArgument($path) + ->executeInteractive(); } - $command = new CommandBuilder('git','clone --branch=master --recursive %s %s', array($repo, $path)); + $command = new CommandBuilder('git', 'clone --branch=master --recursive %s %s', array($repo, $path)); $command->executeInteractive(); } @@ -209,7 +213,8 @@ protected function initCode($path, $repo) { * * @param string $path Path */ - protected function initDocumentRoot($path) { + protected function initDocumentRoot($path) + { $codePath = $path . '/code'; $dockerEnvFile = $path . '/docker-env.yml'; @@ -226,12 +231,16 @@ protected function initDocumentRoot($path) { $documentRoot = 'code/web'; } - if ($documentRoot && is_file($dockerEnvFile) ) { + if ($documentRoot && is_file($dockerEnvFile)) { $dockerEnv = PhpUtility::fileGetContentsArray($dockerEnvFile); unset($line); foreach ($dockerEnv as &$line) { - $line = preg_replace('/^[\s]*DOCUMENT_ROOT[\s]*=code\/?[\s]*$/ms', 'DOCUMENT_ROOT=' . $documentRoot, $line); + $line = preg_replace( + '/^[\s]*DOCUMENT_ROOT[\s]*=code\/?[\s]*$/ms', + 'DOCUMENT_ROOT=' . $documentRoot, + $line + ); } unset($line); @@ -247,20 +256,20 @@ protected function initDocumentRoot($path) { * @param string $path Path of code * @param string $makeCommand Makefile command */ - protected function runMakefile($path, $makeCommand) { + protected function runMakefile($path, $makeCommand) + { $this->setTerminalTitle('Run make'); $path .= '/code'; $this->output->writeln('Running make with command "' . $makeCommand . '"'); try { - PhpUtility::chdir($path); + PhpUtility::chdir($path); - // Remove code directory - $command = new CommandBuilder('make'); - $command - ->addArgument($makeCommand) - ->executeInteractive(); + // Remove code directory + $command = new CommandBuilder('make'); + $command->addArgument($makeCommand) + ->executeInteractive(); } catch (\Exception $e) { $this->addFinishMessage('Make command failed: ' . $e->getMessage() . ''); } @@ -271,7 +280,8 @@ protected function runMakefile($path, $makeCommand) { * * @param string $path Path */ - protected function startDockerInstance($path) { + protected function startDockerInstance($path) + { $this->setTerminalTitle('Start docker'); $this->output->writeln('Building docker containers "' . $path . '"'); diff --git a/src/app/CliTools/Console/Command/Docker/ExecCommand.php b/src/app/CliTools/Console/Command/Docker/ExecCommand.php index 19a7a1f..7d06fc8 100644 --- a/src/app/CliTools/Console/Command/Docker/ExecCommand.php +++ b/src/app/CliTools/Console/Command/Docker/ExecCommand.php @@ -20,19 +20,20 @@ * along with this program. If not, see . */ +use CliTools\Shell\CommandBuilder\RemoteCommandBuilder; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use CliTools\Shell\CommandBuilder\RemoteCommandBuilder; -class ExecCommand extends AbstractCommand implements \CliTools\Console\Filter\AnyParameterFilterInterface { +class ExecCommand extends AbstractCommand implements \CliTools\Console\Filter\AnyParameterFilterInterface +{ /** * Configure command */ - protected function configure() { - $this - ->setName('docker:exec') - ->setDescription('Run defined command in docker container'); + protected function configure() + { + $this->setName('docker:exec') + ->setDescription('Run defined command in docker container'); } /** @@ -43,9 +44,11 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $paramList = $this->getFullParameterList(); - $container = $this->getApplication()->getConfigValue('docker', 'container'); + $container = $this->getApplication() + ->getConfigValue('docker', 'container'); if (!empty($paramList)) { diff --git a/src/app/CliTools/Console/Command/Docker/IftopCommand.php b/src/app/CliTools/Console/Command/Docker/IftopCommand.php index 6c9da42..2505528 100644 --- a/src/app/CliTools/Console/Command/Docker/IftopCommand.php +++ b/src/app/CliTools/Console/Command/Docker/IftopCommand.php @@ -20,19 +20,20 @@ * along with this program. If not, see . */ +use CliTools\Shell\CommandBuilder\CommandBuilder; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use CliTools\Shell\CommandBuilder\CommandBuilder; -class IftopCommand extends \CliTools\Console\Command\AbstractCommand { +class IftopCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('docker:iftop') - ->setDescription('Exec iftop for Docker'); + protected function configure() + { + $this->setName('docker:iftop') + ->setDescription('Exec iftop for Docker'); } /** @@ -43,10 +44,12 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $this->elevateProcess($input, $output); - $dockerInterface = $this->getApplication()->getConfigValue('docker', 'interface'); + $dockerInterface = $this->getApplication() + ->getConfigValue('docker', 'interface'); $command = new CommandBuilder('iftop', '-i %s', array($dockerInterface)); $command->executeInteractive(); diff --git a/src/app/CliTools/Console/Command/Docker/MysqlCommand.php b/src/app/CliTools/Console/Command/Docker/MysqlCommand.php index 85fe6e0..f094fc0 100644 --- a/src/app/CliTools/Console/Command/Docker/MysqlCommand.php +++ b/src/app/CliTools/Console/Command/Docker/MysqlCommand.php @@ -20,19 +20,20 @@ * along with this program. If not, see . */ +use CliTools\Shell\CommandBuilder\RemoteCommandBuilder; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use CliTools\Shell\CommandBuilder\RemoteCommandBuilder; -class MysqlCommand extends AbstractCommand { +class MysqlCommand extends AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('docker:mysql') - ->setDescription('Enter mysql in docker container'); + protected function configure() + { + $this->setName('docker:mysql') + ->setDescription('Enter mysql in docker container'); } /** @@ -43,8 +44,10 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { - $container = $this->getApplication()->getConfigValue('docker', 'container'); + public function execute(InputInterface $input, OutputInterface $output) + { + $container = $this->getApplication() + ->getConfigValue('docker', 'container'); $command = new RemoteCommandBuilder('mysql'); diff --git a/src/app/CliTools/Console/Command/Docker/RootCommand.php b/src/app/CliTools/Console/Command/Docker/RootCommand.php index de8fdf8..8ac1e19 100644 --- a/src/app/CliTools/Console/Command/Docker/RootCommand.php +++ b/src/app/CliTools/Console/Command/Docker/RootCommand.php @@ -20,25 +20,26 @@ * along with this program. If not, see . */ +use CliTools\Shell\CommandBuilder\RemoteCommandBuilder; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use CliTools\Shell\CommandBuilder\RemoteCommandBuilder; -class RootCommand extends AbstractCommand { +class RootCommand extends AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('docker:root') - ->setDescription('Enter shell as root in docker container') - ->addArgument( - 'container', - InputArgument::OPTIONAL, - 'Container' - ); + protected function configure() + { + $this->setName('docker:root') + ->setDescription('Enter shell as root in docker container') + ->addArgument( + 'container', + InputArgument::OPTIONAL, + 'Container' + ); } /** @@ -49,8 +50,10 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { - $container = $this->getApplication()->getConfigValue('docker', 'container'); + public function execute(InputInterface $input, OutputInterface $output) + { + $container = $this->getApplication() + ->getConfigValue('docker', 'container'); if ($input->getArgument('container')) { $container = $input->getArgument('container'); @@ -59,7 +62,7 @@ public function execute(InputInterface $input, OutputInterface $output) { $this->setTerminalTitle('docker', 'root', $container); $command = new RemoteCommandBuilder('bash'); - $ret = $this->executeDockerExec($container, $command); + $ret = $this->executeDockerExec($container, $command); return $ret; } diff --git a/src/app/CliTools/Console/Command/Docker/ShellCommand.php b/src/app/CliTools/Console/Command/Docker/ShellCommand.php index 575285c..364d5de 100644 --- a/src/app/CliTools/Console/Command/Docker/ShellCommand.php +++ b/src/app/CliTools/Console/Command/Docker/ShellCommand.php @@ -20,32 +20,33 @@ * along with this program. If not, see . */ +use CliTools\Shell\CommandBuilder\RemoteCommandBuilder; use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use CliTools\Shell\CommandBuilder\RemoteCommandBuilder; -class ShellCommand extends AbstractCommand { +class ShellCommand extends AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('docker:shell') - ->setDescription('Enter shell in docker container') - ->addArgument( - 'container', - InputArgument::OPTIONAL, - 'Container' - ) - ->addOption( - 'user', - 'u', - InputOption::VALUE_REQUIRED, - 'User for sudo' - ); + protected function configure() + { + $this->setName('docker:shell') + ->setDescription('Enter shell in docker container') + ->addArgument( + 'container', + InputArgument::OPTIONAL, + 'Container' + ) + ->addOption( + 'user', + 'u', + InputOption::VALUE_REQUIRED, + 'User for sudo' + ); } /** @@ -56,8 +57,10 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { - $container = $this->getApplication()->getConfigValue('docker', 'container'); + public function execute(InputInterface $input, OutputInterface $output) + { + $container = $this->getApplication() + ->getConfigValue('docker', 'container'); if ($input->getArgument('container')) { $container = $input->getArgument('container'); diff --git a/src/app/CliTools/Console/Command/Docker/SniffCommand.php b/src/app/CliTools/Console/Command/Docker/SniffCommand.php index 81129c4..4c2e969 100644 --- a/src/app/CliTools/Console/Command/Docker/SniffCommand.php +++ b/src/app/CliTools/Console/Command/Docker/SniffCommand.php @@ -20,27 +20,28 @@ * along with this program. If not, see . */ +use CliTools\Shell\CommandBuilder\CommandBuilder; +use Symfony\Component\Console\Helper\QuestionHelper; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Helper\QuestionHelper; -use Symfony\Component\Console\Question\ChoiceQuestion; use Symfony\Component\Console\Output\OutputInterface; -use CliTools\Shell\CommandBuilder\CommandBuilder; +use Symfony\Component\Console\Question\ChoiceQuestion; -class SniffCommand extends AbstractCommand { +class SniffCommand extends AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('docker:sniff') - ->setDescription('Start network sniffing with docker') - ->addArgument( - 'protocol', - InputArgument::OPTIONAL, - 'Protocol' - ); + protected function configure() + { + $this->setName('docker:sniff') + ->setDescription('Start network sniffing with docker') + ->addArgument( + 'protocol', + InputArgument::OPTIONAL, + 'Protocol' + ); } /** @@ -51,14 +52,16 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $this->elevateProcess($input, $output); - $dockerInterface = $this->getApplication()->getConfigValue('docker', 'interface'); + $dockerInterface = $this->getApplication() + ->getConfigValue('docker', 'interface'); $output->writeln('

Starting network sniffing

'); - $protocol = $this->getProtocol(); + $protocol = $this->getProtocol(); $command = new CommandBuilder(); @@ -113,7 +116,9 @@ public function execute(InputInterface $input, OutputInterface $output) { case 'http': $output->writeln('

Using protocol "http"

'); $command->setCommand('tshark'); - $command->addArgumentRaw('tcp port 80 or tcp port 443 -2 -V -R "http.request" -Tfields -e ip.dst -e http.request.method -e http.request.full_uri'); + $command->addArgumentRaw( + 'tcp port 80 or tcp port 443 -2 -V -R "http.request" -Tfields -e ip.dst -e http.request.method -e http.request.full_uri' + ); break; // ############## @@ -144,7 +149,9 @@ public function execute(InputInterface $input, OutputInterface $output) { case 'elasticsearch': $output->writeln('

Using protocol "elasticsearch"

'); $command->setCommand('tcpdump'); - $command->addArgumentRaw('-A -nn -s 0 \'tcp dst port 9200 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)\''); + $command->addArgumentRaw( + '-A -nn -s 0 \'tcp dst port 9200 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)\'' + ); break; // ############## @@ -199,10 +206,13 @@ public function execute(InputInterface $input, OutputInterface $output) { // ############## default: $output->writeln('Protocol not supported:'); - $output->writeln(' OSI layer 7: http, solr, elasticsearch, memcache, redis, smtp, mysql, dns'); + $output->writeln( + ' OSI layer 7: http, solr, elasticsearch, memcache, redis, smtp, mysql, dns' + ); $output->writeln(' OSI layer 4: tcp'); $output->writeln(' OSI layer 3: icmp'); $output->writeln(' OSI layer 2: arp'); + return 1; break; } @@ -224,7 +234,7 @@ public function execute(InputInterface $input, OutputInterface $output) { break; } - $this->setTerminalTitle('sniffer', $protocol, '(' . $command->getCommand() .')'); + $this->setTerminalTitle('sniffer', $protocol, '(' . $command->getCommand() . ')'); $command->executeInteractive(); @@ -237,10 +247,11 @@ public function execute(InputInterface $input, OutputInterface $output) { * * @return string */ - protected function getProtocol() { + protected function getProtocol() + { $ret = null; - if(!$this->input->getArgument('protocol')) { + if (!$this->input->getArgument('protocol')) { $protocolList = array( 'http' => 'HTTP (requests only)', 'http-full' => 'HTTP (full)', @@ -253,7 +264,7 @@ protected function getProtocol() { 'dns' => 'DNS', 'tcp' => 'TCP', 'icmp' => 'ICMP', - 'arp' => 'ARP', + 'arp' => 'ARP', ); try { @@ -263,7 +274,7 @@ protected function getProtocol() { $questionDialog = new QuestionHelper(); $ret = $questionDialog->ask($this->input, $this->output, $question); - } catch(\InvalidArgumentException $e) { + } catch (\InvalidArgumentException $e) { // Invalid server context, just stop here throw new \CliTools\Exception\StopException(1); } diff --git a/src/app/CliTools/Console/Command/Docker/UpCommand.php b/src/app/CliTools/Console/Command/Docker/UpCommand.php index b558adb..d8e3822 100644 --- a/src/app/CliTools/Console/Command/Docker/UpCommand.php +++ b/src/app/CliTools/Console/Command/Docker/UpCommand.php @@ -20,19 +20,20 @@ * along with this program. If not, see . */ +use CliTools\Shell\CommandBuilder\CommandBuilder; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use CliTools\Shell\CommandBuilder\CommandBuilder; -class UpCommand extends AbstractCommand { +class UpCommand extends AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('docker:up') - ->setDescription('Start docker container (with fast switching)'); + protected function configure() + { + $this->setName('docker:up') + ->setDescription('Start docker container (with fast switching)'); } /** @@ -43,10 +44,13 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $dockerPath = \CliTools\Utility\DockerUtility::searchDockerDirectoryRecursive(); - $lastDockerPath = $this->getApplication()->getSettingsService()->get('docker.up.last'); + $lastDockerPath = $this->getApplication() + ->getSettingsService() + ->get('docker.up.last'); if (!empty($dockerPath)) { $dockerPath = dirname($dockerPath); @@ -57,7 +61,7 @@ public function execute(InputInterface $input, OutputInterface $output) { // Stop last docker instance if ($dockerPath && $lastDockerPath) { // Only stop if instance is another one - if($dockerPath !== $lastDockerPath) { + if ($dockerPath !== $lastDockerPath) { $this->stopContainersFromPrevRun($lastDockerPath); } } @@ -65,11 +69,13 @@ public function execute(InputInterface $input, OutputInterface $output) { // Start current docker containers $this->output->writeln('

Start docker containers in "' . $dockerPath . '"

'); $command = new CommandBuilder(null, 'up -d'); - $ret = $this->executeDockerCompose($command); + $ret = $this->executeDockerCompose($command); // Store docker path in settings (last docker startup) if ($dockerPath) { - $this->getApplication()->getSettingsService()->set('docker.up.last', $dockerPath); + $this->getApplication() + ->getSettingsService() + ->set('docker.up.last', $dockerPath); } return $ret; @@ -80,7 +86,8 @@ public function execute(InputInterface $input, OutputInterface $output) { * * @param string $path Path */ - protected function stopContainersFromPrevRun($path) { + protected function stopContainersFromPrevRun($path) + { $currentPath = getcwd(); try { @@ -95,6 +102,7 @@ protected function stopContainersFromPrevRun($path) { // Jump back \CliTools\Utility\PhpUtility::chdir($currentPath); - } catch (\Exception $e) {} + } catch (\Exception $e) { + } } } diff --git a/src/app/CliTools/Console/Command/Log/ApacheCommand.php b/src/app/CliTools/Console/Command/Log/ApacheCommand.php index 55aba20..e08a8dd 100644 --- a/src/app/CliTools/Console/Command/Log/ApacheCommand.php +++ b/src/app/CliTools/Console/Command/Log/ApacheCommand.php @@ -24,21 +24,24 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class ApacheCommand extends \CliTools\Console\Command\AbstractCommand { +class ApacheCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('log:apache') - ->setAliases(array('apache:log')) - ->setDescription('Show up apache log') - ->addArgument( - 'grep', - InputArgument::OPTIONAL, - 'Grep' - ); + protected function configure() + { + $this->setName('log:apache') + ->setAliases(array('apache:log')) + ->setDescription( + 'Show up apache log' + ) + ->addArgument( + 'grep', + InputArgument::OPTIONAL, + 'Grep' + ); } /** @@ -49,7 +52,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { // Read grep value $grep = null; if ($input->hasArgument('grep')) { diff --git a/src/app/CliTools/Console/Command/Log/DebugCommand.php b/src/app/CliTools/Console/Command/Log/DebugCommand.php index 67ed98a..183bc17 100644 --- a/src/app/CliTools/Console/Command/Log/DebugCommand.php +++ b/src/app/CliTools/Console/Command/Log/DebugCommand.php @@ -24,21 +24,22 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class DebugCommand extends \CliTools\Console\Command\AbstractCommand { +class DebugCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('log:debug') - ->setAliases(array('debug')) - ->setDescription('Show up debugging log') - ->addArgument( - 'grep', - InputArgument::OPTIONAL, - 'Grep' - ); + protected function configure() + { + $this->setName('log:debug') + ->setAliases(array('debug')) + ->setDescription('Show up debugging log') + ->addArgument( + 'grep', + InputArgument::OPTIONAL, + 'Grep' + ); } /** @@ -49,7 +50,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { // Read grep value $grep = null; if ($input->hasArgument('grep')) { diff --git a/src/app/CliTools/Console/Command/Log/MailCommand.php b/src/app/CliTools/Console/Command/Log/MailCommand.php index 778c8d8..2231a30 100644 --- a/src/app/CliTools/Console/Command/Log/MailCommand.php +++ b/src/app/CliTools/Console/Command/Log/MailCommand.php @@ -24,20 +24,21 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class MailCommand extends \CliTools\Console\Command\AbstractCommand { +class MailCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('log:mail') - ->setDescription('Show up mail log') - ->addArgument( - 'grep', - InputArgument::OPTIONAL, - 'Grep' - ); + protected function configure() + { + $this->setName('log:mail') + ->setDescription('Show up mail log') + ->addArgument( + 'grep', + InputArgument::OPTIONAL, + 'Grep' + ); } /** @@ -48,7 +49,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { // Read grep value $grep = null; if ($input->hasArgument('grep')) { diff --git a/src/app/CliTools/Console/Command/Log/PhpCommand.php b/src/app/CliTools/Console/Command/Log/PhpCommand.php index 425d233..a78609d 100644 --- a/src/app/CliTools/Console/Command/Log/PhpCommand.php +++ b/src/app/CliTools/Console/Command/Log/PhpCommand.php @@ -24,21 +24,22 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class PhpCommand extends \CliTools\Console\Command\AbstractCommand { +class PhpCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('log:php') - ->setAliases(array('php:log')) - ->setDescription('Show up php log') - ->addArgument( - 'grep', - InputArgument::OPTIONAL, - 'Grep' - ); + protected function configure() + { + $this->setName('log:php') + ->setAliases(array('php:log')) + ->setDescription('Show up php log') + ->addArgument( + 'grep', + InputArgument::OPTIONAL, + 'Grep' + ); } /** @@ -49,7 +50,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { // Read grep value $grep = null; if ($input->hasArgument('grep')) { diff --git a/src/app/CliTools/Console/Command/Mysql/AbstractCommand.php b/src/app/CliTools/Console/Command/Mysql/AbstractCommand.php index 04dcbfe..4fd16bd 100644 --- a/src/app/CliTools/Console/Command/Mysql/AbstractCommand.php +++ b/src/app/CliTools/Console/Command/Mysql/AbstractCommand.php @@ -25,37 +25,38 @@ use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -abstract class AbstractCommand extends \CliTools\Console\Command\AbstractCommand { +abstract class AbstractCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->addOption( - 'host', - null, - InputOption::VALUE_REQUIRED, - 'MySQL host' - ) - ->addOption( - 'port', - null, - InputOption::VALUE_REQUIRED, - 'MySQL port' - ) - ->addOption( - 'user', - 'u', - InputOption::VALUE_REQUIRED, - 'MySQL user' - ) - ->addOption( - 'password', - 'p', - InputOption::VALUE_REQUIRED, - 'MySQL host' - ); + protected function configure() + { + $this->addOption( + 'host', + null, + InputOption::VALUE_REQUIRED, + 'MySQL host' + ) + ->addOption( + 'port', + null, + InputOption::VALUE_REQUIRED, + 'MySQL port' + ) + ->addOption( + 'user', + 'u', + InputOption::VALUE_REQUIRED, + 'MySQL user' + ) + ->addOption( + 'password', + 'p', + InputOption::VALUE_REQUIRED, + 'MySQL host' + ); } /** @@ -67,7 +68,8 @@ protected function configure() { * @param InputInterface $input An InputInterface instance * @param OutputInterface $output An OutputInterface instance */ - protected function initialize(InputInterface $input, OutputInterface $output) { + protected function initialize(InputInterface $input, OutputInterface $output) + { parent::initialize($input, $output); $dsn = null; @@ -103,7 +105,7 @@ protected function initialize(InputInterface $input, OutputInterface $output) { $password = $this->input->getOption('password'); } - if ($dsn !== null || $user !== null || $password !== null) { + if ($dsn !== null || $user !== null || $password !== null) { DatabaseConnection::setDsn($dsn, $user, $password); } } diff --git a/src/app/CliTools/Console/Command/Mysql/BackupCommand.php b/src/app/CliTools/Console/Command/Mysql/BackupCommand.php index 29f624d..65d3e93 100644 --- a/src/app/CliTools/Console/Command/Mysql/BackupCommand.php +++ b/src/app/CliTools/Console/Command/Mysql/BackupCommand.php @@ -22,41 +22,42 @@ use CliTools\Database\DatabaseConnection; use CliTools\Shell\CommandBuilder\CommandBuilder; -use CliTools\Shell\CommandBuilder\MysqlCommandBuilder; use CliTools\Shell\CommandBuilder\CommandBuilderInterface; +use CliTools\Shell\CommandBuilder\MysqlCommandBuilder; use CliTools\Utility\FilterUtility; use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -class BackupCommand extends AbstractCommand { +class BackupCommand extends AbstractCommand +{ /** * Configure command */ - protected function configure() { + protected function configure() + { parent::configure(); - $this - ->setName('mysql:backup') - ->setDescription('Backup database') - ->addArgument( + $this->setName('mysql:backup') + ->setDescription('Backup database') + ->addArgument( 'db', InputArgument::REQUIRED, 'Database name' - ) - ->addArgument( + ) + ->addArgument( 'file', InputArgument::REQUIRED, 'File (mysql dump)' - ) - ->addOption( - 'filter', - 'f', - InputOption::VALUE_REQUIRED, - 'Filter (eg. typo3)' - ); + ) + ->addOption( + 'filter', + 'f', + InputOption::VALUE_REQUIRED, + 'Filter (eg. typo3)' + ); } /** @@ -67,7 +68,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $database = $input->getArgument('db'); $dumpFile = $input->getArgument('file'); $filter = $input->getOption('filter'); @@ -108,7 +110,7 @@ public function execute(InputInterface $input, OutputInterface $output) { $output->writeln('

Using LZMA compression

'); $commandCompressor = new CommandBuilder('xz'); $commandCompressor->addArgument('--compress') - ->addArgument('--stdout'); + ->addArgument('--stdout'); break; } @@ -140,11 +142,13 @@ public function execute(InputInterface $input, OutputInterface $output) { * * @return CommandBuilderInterface */ - protected function addFilterArguments(CommandBuilderInterface $commandDump, $database, $filter) { + protected function addFilterArguments(CommandBuilderInterface $commandDump, $database, $filter) + { $command = $commandDump; // get filter - $filterList = $this->getApplication()->getConfigValue('mysql-backup-filter', $filter); + $filterList = $this->getApplication() + ->getConfigValue('mysql-backup-filter', $filter); if (empty($filterList)) { throw new \RuntimeException('MySQL dump filters "' . $filter . '" not available"'); @@ -170,9 +174,8 @@ protected function addFilterArguments(CommandBuilderInterface $commandDump, $dat // Combine both commands to one $command = new \CliTools\Shell\CommandBuilder\OutputCombineCommandBuilder(); - $command - ->addCommandForCombinedOutput($commandStructure) - ->addCommandForCombinedOutput($commandData); + $command->addCommandForCombinedOutput($commandStructure) + ->addCommandForCombinedOutput($commandData); return $command; } diff --git a/src/app/CliTools/Console/Command/Mysql/ClearCommand.php b/src/app/CliTools/Console/Command/Mysql/ClearCommand.php index c4db1c2..a1dde42 100644 --- a/src/app/CliTools/Console/Command/Mysql/ClearCommand.php +++ b/src/app/CliTools/Console/Command/Mysql/ClearCommand.php @@ -25,23 +25,26 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class ClearCommand extends AbstractCommand { +class ClearCommand extends AbstractCommand +{ /** * Configure command */ - protected function configure() { + protected function configure() + { parent::configure(); - $this - ->setName('mysql:clear') - ->setAliases(array('mysql:create')) - ->setDescription('Clear (recreate) database') - ->addArgument( - 'db', - InputArgument::REQUIRED, - 'Database name' - ); + $this->setName('mysql:clear') + ->setAliases(array('mysql:create')) + ->setDescription( + 'Clear (recreate) database' + ) + ->addArgument( + 'db', + InputArgument::REQUIRED, + 'Database name' + ); } /** @@ -52,7 +55,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $database = $input->getArgument('db'); $output->writeln('

Clearing database "' . $database . '"

'); diff --git a/src/app/CliTools/Console/Command/Mysql/ConnectionsCommand.php b/src/app/CliTools/Console/Command/Mysql/ConnectionsCommand.php index 318f241..6f121c3 100644 --- a/src/app/CliTools/Console/Command/Mysql/ConnectionsCommand.php +++ b/src/app/CliTools/Console/Command/Mysql/ConnectionsCommand.php @@ -25,17 +25,18 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class ConnectionsCommand extends AbstractCommand { +class ConnectionsCommand extends AbstractCommand +{ /** * Configure command */ - protected function configure() { + protected function configure() + { parent::configure(); - $this - ->setName('mysql:connections') - ->setDescription('List current connections'); + $this->setName('mysql:connections') + ->setDescription('List current connections'); } /** @@ -46,7 +47,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { // Get current connection id $query = 'SELECT CONNECTION_ID()'; $conId = DatabaseConnection::getOne($query); diff --git a/src/app/CliTools/Console/Command/Mysql/ConvertCommand.php b/src/app/CliTools/Console/Command/Mysql/ConvertCommand.php index 9594872..2164262 100644 --- a/src/app/CliTools/Console/Command/Mysql/ConvertCommand.php +++ b/src/app/CliTools/Console/Command/Mysql/ConvertCommand.php @@ -22,44 +22,45 @@ use CliTools\Database\DatabaseConnection; use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -class ConvertCommand extends AbstractCommand { +class ConvertCommand extends AbstractCommand +{ /** * Configure command */ - protected function configure() { + protected function configure() + { parent::configure(); - $this - ->setName('mysql:convert') - ->setDescription('Convert charset/collation of a database') - ->addArgument( - 'database', - InputArgument::REQUIRED, - 'Database name' - ) + $this->setName('mysql:convert') + ->setDescription('Convert charset/collation of a database') + ->addArgument( + 'database', + InputArgument::REQUIRED, + 'Database name' + ) ->addOption( - 'charset', - null, - InputOption::VALUE_REQUIRED, - 'Charset (default: utf8)' + 'charset', + null, + InputOption::VALUE_REQUIRED, + 'Charset (default: utf8)' ) - ->addOption( - 'collation', - null, - InputOption::VALUE_REQUIRED, - 'Collation (default: utf8_general_ci)' - ) - ->addOption( - 'stdout', - null, - InputOption::VALUE_NONE, - 'Only print sql statements, do not execute it' - ); + ->addOption( + 'collation', + null, + InputOption::VALUE_REQUIRED, + 'Collation (default: utf8_general_ci)' + ) + ->addOption( + 'stdout', + null, + InputOption::VALUE_NONE, + 'Only print sql statements, do not execute it' + ); } /** @@ -70,7 +71,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $charset = 'utf8'; $collation = 'utf8_general_ci'; $stdout = false; @@ -94,7 +96,8 @@ public function execute(InputInterface $input, OutputInterface $output) { // ################## $query = 'ALTER DATABASE %s CHARACTER SET %s COLLATE %s'; - $query = sprintf($query, + $query = sprintf( + $query, DatabaseConnection::sanitizeSqlDatabase($database), DatabaseConnection::quote($charset), DatabaseConnection::quote($collation) @@ -117,7 +120,8 @@ public function execute(InputInterface $input, OutputInterface $output) { foreach ($tableList as $table) { // Build statement $query = 'ALTER TABLE %s.%s CONVERT TO CHARACTER SET %s COLLATE %s'; - $query = sprintf($query, + $query = sprintf( + $query, DatabaseConnection::sanitizeSqlDatabase($database), DatabaseConnection::sanitizeSqlTable($table), DatabaseConnection::quote($charset), diff --git a/src/app/CliTools/Console/Command/Mysql/DebugCommand.php b/src/app/CliTools/Console/Command/Mysql/DebugCommand.php index e72f217..98d3a41 100644 --- a/src/app/CliTools/Console/Command/Mysql/DebugCommand.php +++ b/src/app/CliTools/Console/Command/Mysql/DebugCommand.php @@ -25,21 +25,24 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class DebugCommand extends AbstractCommand { +class DebugCommand extends AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('mysql:debug') - ->setAliases(array('mysql:querylog')) - ->setDescription('Debug mysql connections') - ->addArgument( - 'grep', - InputArgument::OPTIONAL, - 'Grep' - ); + protected function configure() + { + $this->setName('mysql:debug') + ->setAliases(array('mysql:querylog')) + ->setDescription( + 'Debug mysql connections' + ) + ->addArgument( + 'grep', + InputArgument::OPTIONAL, + 'Grep' + ); } /** @@ -50,10 +53,12 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $this->elevateProcess($input, $output); - $debugLogLocation = $this->getApplication()->getConfigValue('db', 'debug_log_dir'); + $debugLogLocation = $this->getApplication() + ->getConfigValue('db', 'debug_log_dir'); $debugLogDir = dirname($debugLogLocation); $output->writeln('

Starting MySQL general query log

'); @@ -91,7 +96,8 @@ public function execute(InputInterface $input, OutputInterface $output) { $query = 'SET GLOBAL general_log = \'OFF\''; DatabaseConnection::exec($query); }; - $this->getApplication()->registerTearDown($tearDownFunc); + $this->getApplication() + ->registerTearDown($tearDownFunc); // Read grep value $grep = null; diff --git a/src/app/CliTools/Console/Command/Mysql/DropCommand.php b/src/app/CliTools/Console/Command/Mysql/DropCommand.php index e2a7015..9ef9417 100644 --- a/src/app/CliTools/Console/Command/Mysql/DropCommand.php +++ b/src/app/CliTools/Console/Command/Mysql/DropCommand.php @@ -25,22 +25,23 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class DropCommand extends AbstractCommand { +class DropCommand extends AbstractCommand +{ /** * Configure command */ - protected function configure() { + protected function configure() + { parent::configure(); - $this - ->setName('mysql:drop') - ->setDescription('Drop database') - ->addArgument( - 'db', - InputArgument::REQUIRED, - 'Database name' - ); + $this->setName('mysql:drop') + ->setDescription('Drop database') + ->addArgument( + 'db', + InputArgument::REQUIRED, + 'Database name' + ); } /** @@ -51,7 +52,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $database = $input->getArgument('db'); $output->writeln('

Dropping Database "' . $database . '"...

'); diff --git a/src/app/CliTools/Console/Command/Mysql/ListCommand.php b/src/app/CliTools/Console/Command/Mysql/ListCommand.php index 3971b0d..eaf62b0 100644 --- a/src/app/CliTools/Console/Command/Mysql/ListCommand.php +++ b/src/app/CliTools/Console/Command/Mysql/ListCommand.php @@ -28,40 +28,42 @@ use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -class ListCommand extends AbstractCommand { +class ListCommand extends AbstractCommand +{ /** * Configure command */ - protected function configure() { + protected function configure() + { parent::configure(); - $this - ->setName('mysql:list') - ->setDescription('List all databases') - ->addOption( - 'sort-name', null, - InputOption::VALUE_NONE, - 'Sort output by table count' - ) - ->addOption( - 'sort-data', - null, - InputOption::VALUE_NONE, - 'Sort output by data size' - ) - ->addOption( - 'sort-index', - null, - InputOption::VALUE_NONE, - 'Sort output by index size' - ) - ->addOption( - 'sort-total', - null, - InputOption::VALUE_NONE, - 'Sort output by total size' - ); + $this->setName('mysql:list') + ->setDescription('List all databases') + ->addOption( + 'sort-name', + null, + InputOption::VALUE_NONE, + 'Sort output by table count' + ) + ->addOption( + 'sort-data', + null, + InputOption::VALUE_NONE, + 'Sort output by data size' + ) + ->addOption( + 'sort-index', + null, + InputOption::VALUE_NONE, + 'Sort output by index size' + ) + ->addOption( + 'sort-total', + null, + InputOption::VALUE_NONE, + 'Sort output by total size' + ); } /** @@ -72,7 +74,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { // Get list of databases $databaseList = DatabaseConnection::databaseList(); @@ -123,36 +126,51 @@ public function execute(InputInterface $input, OutputInterface $output) { // ######################## // Sort: default by name (natural sort) - uasort($databaseRowList, function ($a, $b) { - return strnatcmp($a['name'], $b['name']); - }); + uasort( + $databaseRowList, + function ($a, $b) { + return strnatcmp($a['name'], $b['name']); + } + ); // Sort: by table names if ($input->getOption('sort-name')) { - uasort($databaseRowList, function ($a, $b) { - return $a['table_count'] < $b['table_count']; - }); + uasort( + $databaseRowList, + function ($a, $b) { + return $a['table_count'] < $b['table_count']; + } + ); } // Sort: by data size if ($input->getOption('sort-data')) { - uasort($databaseRowList, function ($a, $b) { - return $a['data_size'] < $b['data_size']; - }); + uasort( + $databaseRowList, + function ($a, $b) { + return $a['data_size'] < $b['data_size']; + } + ); } // Sort: by index size if ($input->getOption('sort-index')) { - uasort($databaseRowList, function ($a, $b) { - return $a['index_size'] < $b['index_size']; - }); + uasort( + $databaseRowList, + function ($a, $b) { + return $a['index_size'] < $b['index_size']; + } + ); } // Sort: by total size if ($input->getOption('sort-total')) { - uasort($databaseRowList, function ($a, $b) { - return $a['total_size'] < $b['total_size']; - }); + uasort( + $databaseRowList, + function ($a, $b) { + return $a['total_size'] < $b['total_size']; + } + ); } // ######################## diff --git a/src/app/CliTools/Console/Command/Mysql/RestartCommand.php b/src/app/CliTools/Console/Command/Mysql/RestartCommand.php index fa012bc..3ac9520 100644 --- a/src/app/CliTools/Console/Command/Mysql/RestartCommand.php +++ b/src/app/CliTools/Console/Command/Mysql/RestartCommand.php @@ -20,19 +20,20 @@ * along with this program. If not, see . */ +use CliTools\Shell\CommandBuilder\CommandBuilder; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use CliTools\Shell\CommandBuilder\CommandBuilder; -class RestartCommand extends AbstractCommand { +class RestartCommand extends AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('mysql:restart') - ->setDescription('Restart MySQL'); + protected function configure() + { + $this->setName('mysql:restart') + ->setDescription('Restart MySQL'); } /** @@ -43,7 +44,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $this->elevateProcess($input, $output); $command = new CommandBuilder('service', 'mysql restart'); diff --git a/src/app/CliTools/Console/Command/Mysql/RestoreCommand.php b/src/app/CliTools/Console/Command/Mysql/RestoreCommand.php index 9cba7fe..73d9386 100644 --- a/src/app/CliTools/Console/Command/Mysql/RestoreCommand.php +++ b/src/app/CliTools/Console/Command/Mysql/RestoreCommand.php @@ -21,34 +21,35 @@ */ use CliTools\Database\DatabaseConnection; +use CliTools\Shell\CommandBuilder\CommandBuilder; +use CliTools\Shell\CommandBuilder\MysqlCommandBuilder; use CliTools\Utility\PhpUtility; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use CliTools\Shell\CommandBuilder\CommandBuilder; -use CliTools\Shell\CommandBuilder\MysqlCommandBuilder; -class RestoreCommand extends AbstractCommand { +class RestoreCommand extends AbstractCommand +{ /** * Configure command */ - protected function configure() { + protected function configure() + { parent::configure(); - $this - ->setName('mysql:restore') - ->setDescription('Restore database') - ->addArgument( - 'db', - InputArgument::REQUIRED, - 'Database name' - ) - ->addArgument( - 'file', - InputArgument::REQUIRED, - 'File (mysql dump)' - ); + $this->setName('mysql:restore') + ->setDescription('Restore database') + ->addArgument( + 'db', + InputArgument::REQUIRED, + 'Database name' + ) + ->addArgument( + 'file', + InputArgument::REQUIRED, + 'File (mysql dump)' + ); } /** @@ -59,7 +60,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $database = $input->getArgument('db'); $dumpFile = $input->getArgument('file'); @@ -110,7 +112,7 @@ public function execute(InputInterface $input, OutputInterface $output) { case 'application/x-lzma': case 'application/x-xz': - $output->writeln('

Using LZMA decompression

'); + $output->writeln('

Using LZMA decompression

'); $commandFile->setCommand('xzcat'); break; diff --git a/src/app/CliTools/Console/Command/Mysql/SlowLogCommand.php b/src/app/CliTools/Console/Command/Mysql/SlowLogCommand.php index 7b09cd1..99e449e 100644 --- a/src/app/CliTools/Console/Command/Mysql/SlowLogCommand.php +++ b/src/app/CliTools/Console/Command/Mysql/SlowLogCommand.php @@ -22,36 +22,37 @@ use CliTools\Database\DatabaseConnection; use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -class SlowLogCommand extends AbstractCommand { +class SlowLogCommand extends AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('mysql:slowlog') - ->setDescription('Enable and show slow query log') - ->addArgument( - 'grep', - InputArgument::OPTIONAL, - 'Grep' - ) - ->addOption( - 'time', - 't', - InputOption::VALUE_REQUIRED, - 'Slow query time (default 1 second)' - ) - ->addOption( - 'no-index', - 'i', - InputOption::VALUE_NONE, - 'Enable log queries without indexes log' - ); + protected function configure() + { + $this->setName('mysql:slowlog') + ->setDescription('Enable and show slow query log') + ->addArgument( + 'grep', + InputArgument::OPTIONAL, + 'Grep' + ) + ->addOption( + 'time', + 't', + InputOption::VALUE_REQUIRED, + 'Slow query time (default 1 second)' + ) + ->addOption( + 'no-index', + 'i', + InputOption::VALUE_NONE, + 'Enable log queries without indexes log' + ); } /** @@ -62,10 +63,11 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $this->elevateProcess($input, $output); - $slowLogQueryTime = 1; + $slowLogQueryTime = 1; $logNonIndexedQueries = false; // Slow log threshold @@ -78,7 +80,8 @@ public function execute(InputInterface $input, OutputInterface $output) { $logNonIndexedQueries = true; } - $debugLogLocation = $this->getApplication()->getConfigValue('db', 'debug_log_dir'); + $debugLogLocation = $this->getApplication() + ->getConfigValue('db', 'debug_log_dir'); $debugLogDir = dirname($debugLogLocation); $output->writeln('

Starting MySQL slow query log

'); @@ -136,7 +139,8 @@ public function execute(InputInterface $input, OutputInterface $output) { DatabaseConnection::exec($query); } }; - $this->getApplication()->registerTearDown($tearDownFunc); + $this->getApplication() + ->registerTearDown($tearDownFunc); // Read grep value $grep = null; diff --git a/src/app/CliTools/Console/Command/Php/ComposerCommand.php b/src/app/CliTools/Console/Command/Php/ComposerCommand.php index bb2f82b..123657e 100644 --- a/src/app/CliTools/Console/Command/Php/ComposerCommand.php +++ b/src/app/CliTools/Console/Command/Php/ComposerCommand.php @@ -20,21 +20,23 @@ * along with this program. If not, see . */ -use CliTools\Utility\UnixUtility; -use CliTools\Utility\PhpUtility; use CliTools\Shell\CommandBuilder\CommandBuilder; +use CliTools\Utility\PhpUtility; +use CliTools\Utility\UnixUtility; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class ComposerCommand extends \CliTools\Console\Command\AbstractCommand implements \CliTools\Console\Filter\AnyParameterFilterInterface { +class ComposerCommand extends \CliTools\Console\Command\AbstractCommand implements + \CliTools\Console\Filter\AnyParameterFilterInterface +{ /** * Configure command */ - protected function configure() { - $this - ->setName('php:composer') - ->setDescription('Search composer.json updir and start composer'); + protected function configure() + { + $this->setName('php:composer') + ->setDescription('Search composer.json updir and start composer'); } /** @@ -45,7 +47,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $paramList = $this->getFullParameterList(); if ($this->checkIfComposerJsonIsNeeded($paramList)) { @@ -60,6 +63,7 @@ public function execute(InputInterface $input, OutputInterface $output) { return $this->runComposer($paramList); } else { $this->output->writeln('No composer.json found in tree'); + return 1; } } else { @@ -74,7 +78,8 @@ public function execute(InputInterface $input, OutputInterface $output) { * * @return int|null|void */ - protected function checkIfComposerJsonIsNeeded(array $paramList) { + protected function checkIfComposerJsonIsNeeded(array $paramList) + { if (empty($paramList)) { // no params -> show help return false; @@ -111,8 +116,10 @@ protected function checkIfComposerJsonIsNeeded(array $paramList) { * * @return int|null|void */ - protected function runComposer(array $paramList) { - $composerCmd = $this->getApplication()->getConfigValue('bin', 'composer'); + protected function runComposer(array $paramList) + { + $composerCmd = $this->getApplication() + ->getConfigValue('bin', 'composer'); $command = new CommandBuilder(); $command->parse($composerCmd); diff --git a/src/app/CliTools/Console/Command/Php/RestartCommand.php b/src/app/CliTools/Console/Command/Php/RestartCommand.php index 86fca58..5ae7585 100644 --- a/src/app/CliTools/Console/Command/Php/RestartCommand.php +++ b/src/app/CliTools/Console/Command/Php/RestartCommand.php @@ -20,19 +20,20 @@ * along with this program. If not, see . */ +use CliTools\Shell\CommandBuilder\CommandBuilder; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use CliTools\Shell\CommandBuilder\CommandBuilder; -class RestartCommand extends \CliTools\Console\Command\AbstractCommand { +class RestartCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('php:restart') - ->setDescription('Restart PHP FPM'); + protected function configure() + { + $this->setName('php:restart') + ->setDescription('Restart PHP FPM'); } /** @@ -43,7 +44,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $this->elevateProcess($input, $output); $command = new CommandBuilder('service', 'php5-fpm restart'); diff --git a/src/app/CliTools/Console/Command/Php/TraceCommand.php b/src/app/CliTools/Console/Command/Php/TraceCommand.php index e5b0b92..723d90e 100644 --- a/src/app/CliTools/Console/Command/Php/TraceCommand.php +++ b/src/app/CliTools/Console/Command/Php/TraceCommand.php @@ -20,7 +20,8 @@ * along with this program. If not, see . */ -class TraceCommand extends \CliTools\Console\Command\AbstractTraceCommand { +class TraceCommand extends \CliTools\Console\Command\AbstractTraceCommand +{ /** * Process names for strace'ing @@ -32,10 +33,10 @@ class TraceCommand extends \CliTools\Console\Command\AbstractTraceCommand { /** * Configure command */ - protected function configure() { - $this - ->setName('php:trace') - ->setDescription('Debug PHP processes with strace'); + protected function configure() + { + $this->setName('php:trace') + ->setDescription('Debug PHP processes with strace'); parent::configure(); } diff --git a/src/app/CliTools/Console/Command/Samba/RestartCommand.php b/src/app/CliTools/Console/Command/Samba/RestartCommand.php index 349be43..069ef72 100644 --- a/src/app/CliTools/Console/Command/Samba/RestartCommand.php +++ b/src/app/CliTools/Console/Command/Samba/RestartCommand.php @@ -20,19 +20,20 @@ * along with this program. If not, see . */ +use CliTools\Shell\CommandBuilder\CommandBuilder; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use CliTools\Shell\CommandBuilder\CommandBuilder; -class RestartCommand extends \CliTools\Console\Command\AbstractCommand { +class RestartCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('samba:restart') - ->setDescription('Restart Samba SMB daemon'); + protected function configure() + { + $this->setName('samba:restart') + ->setDescription('Restart Samba SMB daemon'); } /** @@ -43,7 +44,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $this->elevateProcess($input, $output); $commandSmbd = new CommandBuilder('service', 'smbd restart'); diff --git a/src/app/CliTools/Console/Command/Sync/AbstractCommand.php b/src/app/CliTools/Console/Command/Sync/AbstractCommand.php index 8d07784..af5851c 100644 --- a/src/app/CliTools/Console/Command/Sync/AbstractCommand.php +++ b/src/app/CliTools/Console/Command/Sync/AbstractCommand.php @@ -20,26 +20,27 @@ * along with this program. If not, see . */ -use CliTools\Utility\PhpUtility; -use CliTools\Utility\UnixUtility; -use CliTools\Utility\ConsoleUtility; -use CliTools\Utility\FilterUtility; +use CliTools\Database\DatabaseConnection; +use CliTools\Reader\ConfigReader; use CliTools\Shell\CommandBuilder\CommandBuilder; -use CliTools\Shell\CommandBuilder\RemoteCommandBuilder; -use CliTools\Shell\CommandBuilder\SelfCommandBuilder; use CliTools\Shell\CommandBuilder\CommandBuilderInterface; use CliTools\Shell\CommandBuilder\OutputCombineCommandBuilder; -use CliTools\Reader\ConfigReader; -use CliTools\Database\DatabaseConnection; -use Symfony\Component\Console\Input\InputOption; +use CliTools\Shell\CommandBuilder\RemoteCommandBuilder; +use CliTools\Shell\CommandBuilder\SelfCommandBuilder; +use CliTools\Utility\ConsoleUtility; +use CliTools\Utility\FilterUtility; +use CliTools\Utility\PhpUtility; +use CliTools\Utility\UnixUtility; +use Symfony\Component\Console\Helper\QuestionHelper; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Yaml\Yaml; -use Symfony\Component\Console\Helper\QuestionHelper; use Symfony\Component\Console\Question\ChoiceQuestion; +use Symfony\Component\Yaml\Yaml; -abstract class AbstractCommand extends \CliTools\Console\Command\AbstractCommand { +abstract class AbstractCommand extends \CliTools\Console\Command\AbstractCommand +{ const CONFIG_FILE = 'clisync.yml'; const GLOBAL_KEY = 'GLOBAL'; @@ -89,32 +90,32 @@ abstract class AbstractCommand extends \CliTools\Console\Command\AbstractCommand /** * Configure command */ - protected function configure() { - $this - ->setDescription('Sync files and database from server') - ->addArgument( - 'context', - InputArgument::OPTIONAL, - 'Configuration name for server' - ) - ->addOption( - 'mysql', - null, - InputOption::VALUE_NONE, - 'Run only mysql' - ) - ->addOption( - 'rsync', - null, - InputOption::VALUE_NONE, - 'Run only rsync' - ) - ->addOption( - 'config', - null, - InputOption::VALUE_NONE, - 'Show generated config' - ); + protected function configure() + { + $this->setDescription('Sync files and database from server') + ->addArgument( + 'context', + InputArgument::OPTIONAL, + 'Configuration name for server' + ) + ->addOption( + 'mysql', + null, + InputOption::VALUE_NONE, + 'Run only mysql' + ) + ->addOption( + 'rsync', + null, + InputOption::VALUE_NONE, + 'Run only rsync' + ) + ->addOption( + 'config', + null, + InputOption::VALUE_NONE, + 'Show generated config' + ); } /** @@ -125,9 +126,11 @@ protected function configure() { * * @param InputInterface $input An InputInterface instance * @param OutputInterface $output An OutputInterface instance + * * @throws \RuntimeException */ - protected function initialize(InputInterface $input, OutputInterface $output) { + protected function initialize(InputInterface $input, OutputInterface $output) + { parent::initialize($input, $output); $this->initializeConfiguration(); @@ -136,7 +139,8 @@ protected function initialize(InputInterface $input, OutputInterface $output) { /** * Init configuration */ - protected function initializeConfiguration() { + protected function initializeConfiguration() + { // Search for configuration in path $this->findConfigurationInPath(); @@ -149,7 +153,8 @@ protected function initializeConfiguration() { * * @return boolean */ - protected function validateConfiguration() { + protected function validateConfiguration() + { $ret = true; // Rsync (optional) @@ -175,7 +180,8 @@ protected function validateConfiguration() { /** * Find configuration file in current path */ - protected function findConfigurationInPath() { + protected function findConfigurationInPath() + { $confFileList = array( self::CONFIG_FILE, '.' . self::CONFIG_FILE, @@ -190,13 +196,16 @@ protected function findConfigurationInPath() { $this->workingPath = dirname($this->confFilePath); - $this->output->writeln('Found ' . self::CONFIG_FILE . ' directory: ' . $this->workingPath . ''); + $this->output->writeln( + 'Found ' . self::CONFIG_FILE . ' directory: ' . $this->workingPath . '' + ); } /** * Read and validate configuration */ - protected function readConfiguration() { + protected function readConfiguration() + { $this->config = new ConfigReader(); if (empty($this->confArea)) { @@ -222,7 +231,8 @@ protected function readConfiguration() { * * @return array|null */ - protected function getContextListFromConfiguration() { + protected function getContextListFromConfiguration() + { return $this->config->getArray($this->confArea); } @@ -230,9 +240,11 @@ protected function getContextListFromConfiguration() { * Get command list from current configuration * * @param string $section Section name for commands (startup, final) + * * @return array */ - protected function getCommandList($section) { + protected function getCommandList($section) + { $ret = array(); if ($this->contextConfig->exists('command.' . $section)) { @@ -247,7 +259,8 @@ protected function getCommandList($section) { * * @param $context */ - protected function buildContextConfiguration($context) { + protected function buildContextConfiguration($context) + { $this->contextConfig = new ConfigReader(); // Fetch global conf @@ -273,13 +286,13 @@ protected function buildContextConfiguration($context) { $contextConf = $areaConf[$context]; - $arrayFilterRecursive = function($input, $callback) use (&$arrayFilterRecursive) { + $arrayFilterRecursive = function ($input, $callback) use (&$arrayFilterRecursive) { $ret = array(); foreach ($input as $key => $value) { if (is_array($value)) { $value = $arrayFilterRecursive($value, $callback); } else { - if (strlen($value)==0) { + if (strlen($value) == 0) { $value = null; } } @@ -293,9 +306,9 @@ protected function buildContextConfiguration($context) { }; // Merge - $globalConf = $arrayFilterRecursive( $globalConf, 'strlen' ); - $areaGlobalConf = $arrayFilterRecursive( $areaGlobalConf, 'strlen' ); - $contextConf = $arrayFilterRecursive( $contextConf, 'strlen' ); + $globalConf = $arrayFilterRecursive($globalConf, 'strlen'); + $areaGlobalConf = $arrayFilterRecursive($areaGlobalConf, 'strlen'); + $contextConf = $arrayFilterRecursive($contextConf, 'strlen'); $conf = array_replace_recursive($globalConf, $areaGlobalConf, $contextConf); @@ -312,7 +325,8 @@ protected function buildContextConfiguration($context) { * @return int|null|void * @throws \Exception */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { try { // Get context selection $this->initContext(); @@ -329,7 +343,6 @@ public function execute(InputInterface $input, OutputInterface $output) { $this->runMain(); $this->runCommands('finalize'); } - } catch (\Exception $e) { $this->cleanup(); throw $e; @@ -341,7 +354,8 @@ public function execute(InputInterface $input, OutputInterface $output) { /** * Init context */ - protected function initContext() { + protected function initContext() + { $context = $this->getContextFromUser(); $this->buildContextConfiguration($context); @@ -355,7 +369,8 @@ protected function initContext() { /** * Get context from user */ - protected function getContextFromUser() { + protected function getContextFromUser() + { $ret = null; if (!$this->input->getArgument('context')) { @@ -396,7 +411,7 @@ protected function getContextFromUser() { foreach ($dbList as $databaseConf) { if (strpos($databaseConf, ':') !== false) { // local and foreign database in one string - $databaseConf = explode(':', $databaseConf, 2); + $databaseConf = explode(':', $databaseConf, 2); $foreignDbList[] = $databaseConf[1]; } else { // database equal @@ -426,7 +441,7 @@ protected function getContextFromUser() { $questionDialog = new QuestionHelper(); $ret = $questionDialog->ask($this->input, $this->output, $question); - } catch(\InvalidArgumentException $e) { + } catch (\InvalidArgumentException $e) { // Invalid server context, just stop here throw new \CliTools\Exception\StopException(1); } @@ -440,7 +455,8 @@ protected function getContextFromUser() { /** * Show context configuration */ - protected function showContextConfig() { + protected function showContextConfig() + { print_r($this->contextConfig->get()); } @@ -449,8 +465,9 @@ protected function showContextConfig() { * * @return boolean */ - protected function validateConfigurationRsync() { - $ret = true; + protected function validateConfigurationRsync() + { + $ret = true; // Check if rsync target exists if (!$this->getRsyncPathFromConfig()) { @@ -473,7 +490,8 @@ protected function validateConfigurationRsync() { * * @return boolean */ - protected function validateConfigurationMysql() { + protected function validateConfigurationMysql() + { $ret = true; // Check if one database is configured @@ -488,8 +506,9 @@ protected function validateConfigurationMysql() { /** * Startup task */ - protected function startup() { - $this->tempDir = '/tmp/.clisync-'.getmypid(); + protected function startup() + { + $this->tempDir = '/tmp/.clisync-' . getmypid(); $this->clearTempDir(); PhpUtility::mkdir($this->tempDir, 0777, true); PhpUtility::mkdir($this->tempDir . '/mysql/', 0777, true); @@ -500,14 +519,16 @@ protected function startup() { /** * Cleanup task */ - protected function cleanup() { + protected function cleanup() + { $this->clearTempDir(); } /** * Clear temp. storage directory if exists */ - protected function clearTempDir() { + protected function clearTempDir() + { // Remove storage dir if (!empty($this->tempDir) && is_dir($this->tempDir)) { $command = new CommandBuilder('rm', '-rf'); @@ -522,7 +543,8 @@ protected function clearTempDir() { * * @throws \CliTools\Exception\StopException */ - protected function checkIfDockerExists() { + protected function checkIfDockerExists() + { $dockerPath = \CliTools\Utility\DockerUtility::searchDockerDirectoryRecursive(); if (!empty($dockerPath)) { @@ -543,7 +565,8 @@ protected function checkIfDockerExists() { /** * Run defined commands */ - protected function runCommands($area) { + protected function runCommands($area) + { $commandList = $this->getCommandList($area); if (!empty($commandList)) { @@ -555,7 +578,7 @@ protected function runCommands($area) { // Simple, local task $command = new CommandBuilder(); $command->parse($commandRow); - } elseif(is_array($commandRow)) { + } elseif (is_array($commandRow)) { // Complex task $command = $this->buildComplexTask($commandRow); } @@ -574,7 +597,8 @@ protected function runCommands($area) { * * @return CommandBuilder|CommandBuilderInterface */ - protected function buildComplexTask(array $task) { + protected function buildComplexTask(array $task) + { if (empty($task['type'])) { $task['type'] = 'local'; } @@ -609,13 +633,14 @@ protected function buildComplexTask(array $task) { /** * Create rsync command for sync * - * @param string $source Source directory - * @param string $target Target directory - * @param string $confKey List of files (patterns) + * @param string $source Source directory + * @param string $target Target directory + * @param string $confKey List of files (patterns) * * @return CommandBuilder */ - protected function createRsyncCommandWithConfiguration($source, $target, $confKey) { + protected function createRsyncCommandWithConfiguration($source, $target, $confKey) + { $options = array(); // ############# @@ -640,7 +665,7 @@ protected function createRsyncCommandWithConfiguration($source, $target, $confKe if ($this->contextConfig->exists($confKey . '.conf.maxSize')) { $options['max-size'] = array( 'template' => '--max-size=%s', - 'params' => array( + 'params' => array( $this->contextConfig->get($confKey . '.conf.maxSize') ), ); @@ -652,7 +677,7 @@ protected function createRsyncCommandWithConfiguration($source, $target, $confKe if ($this->contextConfig->exists($confKey . '.conf.minSize')) { $options['min-size'] = array( 'template' => '--min-size=%s', - 'params' => array( + 'params' => array( $this->contextConfig->get($confKey . '.conf.minSize') ), ); @@ -664,15 +689,21 @@ protected function createRsyncCommandWithConfiguration($source, $target, $confKe /** * Create rsync command for sync * - * @param string $source Source directory - * @param string $target Target directory - * @param array|null $filelist List of files (patterns) - * @param array|null $exclude List of excludes (patterns) - * @param array|null $options Custom rsync options + * @param string $source Source directory + * @param string $target Target directory + * @param array|null $filelist List of files (patterns) + * @param array|null $exclude List of excludes (patterns) + * @param array|null $options Custom rsync options * * @return CommandBuilder */ - protected function createRsyncCommand($source, $target, array $filelist = null, array $exclude = null, array $options = null) { + protected function createRsyncCommand( + $source, + $target, + array $filelist = null, + array $exclude = null, + array $options = null + ) { $this->output->writeln('Rsync from ' . $source . ' to ' . $target . ''); $command = new CommandBuilder('rsync', '-rlptD --delete-after --progress --human-readable'); @@ -694,7 +725,6 @@ protected function createRsyncCommand($source, $target, array $filelist = null, } else { $command->addArgument($optionValue); } - } } @@ -714,12 +744,13 @@ protected function createRsyncCommand($source, $target, array $filelist = null, * * @return boolean|string */ - protected function getRsyncPathFromConfig() { + protected function getRsyncPathFromConfig() + { $ret = false; if ($this->contextConfig->exists('rsync.path')) { // Use path from rsync $ret = $this->contextConfig->get('rsync.path'); - } elseif($this->contextConfig->exists('ssh.hostname') && $this->contextConfig->exists('ssh.path')) { + } elseif ($this->contextConfig->exists('ssh.hostname') && $this->contextConfig->exists('ssh.path')) { // Build path from ssh configuration $ret = $this->contextConfig->get('ssh.hostname') . ':' . $this->contextConfig->get('ssh.path'); } @@ -733,7 +764,8 @@ protected function getRsyncPathFromConfig() { * * @return boolean|string */ - protected function getRsyncWorkingPath() { + protected function getRsyncWorkingPath() + { $ret = $this->workingPath; // remove right / @@ -752,7 +784,8 @@ protected function getRsyncWorkingPath() { * @param CommandBuilder $command Rsync Command * @param array $list List of files */ - protected function rsyncAddFileList(CommandBuilder $command, array $list) { + protected function rsyncAddFileList(CommandBuilder $command, array $list) + { $rsyncFilter = $this->tempDir . '/.rsync-filelist'; PhpUtility::filePutContents($rsyncFilter, implode("\n", $list)); @@ -760,19 +793,22 @@ protected function rsyncAddFileList(CommandBuilder $command, array $list) { $command->addArgumentTemplate('--files-from=%s', $rsyncFilter); // cleanup rsync file - $command->getExecutor()->addFinisherCallback(function () use ($rsyncFilter) { - unlink($rsyncFilter); - }); - + $command->getExecutor() + ->addFinisherCallback( + function () use ($rsyncFilter) { + unlink($rsyncFilter); + } + ); } /** * Add exclude (pattern) list to rsync command * - * @param CommandBuilder $command Rsync Command - * @param array $list List of excludes + * @param CommandBuilder $command Rsync Command + * @param array $list List of excludes */ - protected function rsyncAddExcludeList(CommandBuilder $command, $list) { + protected function rsyncAddExcludeList(CommandBuilder $command, $list) + { $rsyncFilter = $this->tempDir . '/.rsync-exclude'; PhpUtility::filePutContents($rsyncFilter, implode("\n", $list)); @@ -780,22 +816,27 @@ protected function rsyncAddExcludeList(CommandBuilder $command, $list) { $command->addArgumentTemplate('--exclude-from=%s', $rsyncFilter); // cleanup rsync file - $command->getExecutor()->addFinisherCallback(function () use ($rsyncFilter) { - unlink($rsyncFilter); - }); + $command->getExecutor() + ->addFinisherCallback( + function () use ($rsyncFilter) { + unlink($rsyncFilter); + } + ); } /** * Create mysql backup command * - * @param string $database Database name - * @param string $dumpFile MySQL dump file + * @param string $database Database name + * @param string $dumpFile MySQL dump file * * @return SelfCommandBuilder */ - protected function createMysqlRestoreCommand($database, $dumpFile) { + protected function createMysqlRestoreCommand($database, $dumpFile) + { $command = new SelfCommandBuilder(); $command->addArgumentTemplate('mysql:restore %s %s', $database, $dumpFile); + return $command; } @@ -808,7 +849,8 @@ protected function createMysqlRestoreCommand($database, $dumpFile) { * * @return SelfCommandBuilder */ - protected function createMysqlBackupCommand($database, $dumpFile, $filter = null) { + protected function createMysqlBackupCommand($database, $dumpFile, $filter = null) + { $command = new SelfCommandBuilder(); $command->addArgumentTemplate('mysql:backup %s %s', $database, $dumpFile); @@ -823,9 +865,11 @@ protected function createMysqlBackupCommand($database, $dumpFile, $filter = null * Wrap command with ssh if needed * * @param CommandBuilderInterface $command + * * @return CommandBuilderInterface */ - protected function wrapRemoteCommand(CommandBuilderInterface $command) { + protected function wrapRemoteCommand(CommandBuilderInterface $command) + { // Wrap in ssh if needed if ($this->contextConfig->exists('ssh.hostname')) { $sshCommand = new CommandBuilder('ssh', '-o BatchMode=yes'); @@ -845,13 +889,12 @@ protected function wrapRemoteCommand(CommandBuilderInterface $command) { * * @return RemoteCommandBuilder */ - protected function createRemoteMySqlCommand($database = null) { + protected function createRemoteMySqlCommand($database = null) + { $command = new RemoteCommandBuilder('mysql'); - $command - // batch mode - ->addArgument('-B') - // skip column names - ->addArgument('-N'); + $command// batch mode + ->addArgument('-B')// skip column names + ->addArgument('-N'); // Add username if ($this->contextConfig->exists('mysql.username')) { @@ -883,13 +926,12 @@ protected function createRemoteMySqlCommand($database = null) { * * @return RemoteCommandBuilder */ - protected function createLocalMySqlCommand($database = null) { + protected function createLocalMySqlCommand($database = null) + { $command = new RemoteCommandBuilder('mysql'); - $command - // batch mode - ->addArgument('-B') - // skip column names - ->addArgument('-N'); + $command// batch mode + ->addArgument('-B')// skip column names + ->addArgument('-N'); // Add username if (DatabaseConnection::getDbUsername()) { @@ -925,7 +967,8 @@ protected function createLocalMySqlCommand($database = null) { * * @return RemoteCommandBuilder */ - protected function createRemoteMySqlDumpCommand($database = null) { + protected function createRemoteMySqlDumpCommand($database = null) + { $command = new RemoteCommandBuilder('mysqldump'); // Add username @@ -949,15 +992,15 @@ protected function createRemoteMySqlDumpCommand($database = null) { } // Transfer compression - switch($this->contextConfig->get('mysql.compression')) { + switch ($this->contextConfig->get('mysql.compression')) { case 'bzip2': // Add pipe compressor (bzip2 compressed transfer via ssh) - $command->addPipeCommand( new CommandBuilder('bzip2', '--compress --stdout') ); + $command->addPipeCommand(new CommandBuilder('bzip2', '--compress --stdout')); break; case 'gzip': // Add pipe compressor (gzip compressed transfer via ssh) - $command->addPipeCommand( new CommandBuilder('gzip', '--stdout') ); + $command->addPipeCommand(new CommandBuilder('gzip', '--stdout')); break; } @@ -975,7 +1018,8 @@ protected function createRemoteMySqlDumpCommand($database = null) { * * @return RemoteCommandBuilder */ - protected function createLocalMySqlDumpCommand($database = null) { + protected function createLocalMySqlDumpCommand($database = null) + { $command = new RemoteCommandBuilder('mysqldump'); // Add username @@ -1008,15 +1052,15 @@ protected function createLocalMySqlDumpCommand($database = null) { } // Transfer compression - switch($this->contextConfig->get('mysql.compression')) { + switch ($this->contextConfig->get('mysql.compression')) { case 'bzip2': // Add pipe compressor (bzip2 compressed transfer via ssh) - $command->addPipeCommand( new CommandBuilder('bzip2', '--compress --stdout') ); + $command->addPipeCommand(new CommandBuilder('bzip2', '--compress --stdout')); break; case 'gzip': // Add pipe compressor (gzip compressed transfer via ssh) - $command->addPipeCommand( new CommandBuilder('gzip', '--stdout') ); + $command->addPipeCommand(new CommandBuilder('gzip', '--stdout')); break; } @@ -1027,13 +1071,14 @@ protected function createLocalMySqlDumpCommand($database = null) { /** * Add mysqldump filter to command * - * @param CommandBuilderInterface $commandDump Command - * @param string $database Database - * @param boolean $isRemote Remote filter + * @param CommandBuilderInterface $commandDump Command + * @param string $database Database + * @param boolean $isRemote Remote filter * * @return CommandBuilderInterface */ - protected function addMysqlDumpFilterArguments(CommandBuilderInterface $commandDump, $database, $isRemote = true) { + protected function addMysqlDumpFilterArguments(CommandBuilderInterface $commandDump, $database, $isRemote = true) + { $command = $commandDump; $filter = $this->contextConfig->get('mysql.filter'); @@ -1043,7 +1088,8 @@ protected function addMysqlDumpFilterArguments(CommandBuilderInterface $commandD $filterList = (array)$filter; $filter = 'custom table filter'; } else { - $filterList = $this->getApplication()->getConfigValue('mysql-backup-filter', $filter); + $filterList = $this->getApplication() + ->getConfigValue('mysql-backup-filter', $filter); } if (empty($filterList)) { @@ -1066,22 +1112,21 @@ protected function addMysqlDumpFilterArguments(CommandBuilderInterface $commandD $tableListDumper = $this->wrapRemoteCommand($tableListDumper); } - $tableList = $tableListDumper->execute()->getOutput(); + $tableList = $tableListDumper->execute() + ->getOutput(); // Filter table list $ignoredTableList = FilterUtility::mysqlIgnoredTableFilter($tableList, $filterList, $database); // Dump only structure $commandStructure = clone $command; - $commandStructure - ->addArgument('--no-data') - ->clearPipes(); + $commandStructure->addArgument('--no-data') + ->clearPipes(); // Dump only data (only filtered tables) $commandData = clone $command; - $commandData - ->addArgument('--no-create-info') - ->clearPipes(); + $commandData->addArgument('--no-create-info') + ->clearPipes(); if (!empty($ignoredTableList)) { $commandData->addArgumentTemplateMultiple('--ignore-table=%s', $ignoredTableList); @@ -1091,9 +1136,8 @@ protected function addMysqlDumpFilterArguments(CommandBuilderInterface $commandD // Combine both commands to one $command = new OutputCombineCommandBuilder(); - $command - ->addCommandForCombinedOutput($commandStructure) - ->addCommandForCombinedOutput($commandData); + $command->addCommandForCombinedOutput($commandStructure) + ->addCommandForCombinedOutput($commandData); // Read compression pipe if (!empty($commandPipeList)) { diff --git a/src/app/CliTools/Console/Command/Sync/AbstractRemoteSyncCommand.php b/src/app/CliTools/Console/Command/Sync/AbstractRemoteSyncCommand.php index f26efa2..fe16d51 100644 --- a/src/app/CliTools/Console/Command/Sync/AbstractRemoteSyncCommand.php +++ b/src/app/CliTools/Console/Command/Sync/AbstractRemoteSyncCommand.php @@ -20,14 +20,16 @@ * along with this program. If not, see . */ -abstract class AbstractRemoteSyncCommand extends AbstractCommand { +abstract class AbstractRemoteSyncCommand extends AbstractCommand +{ /** * Validate configuration * * @return boolean */ - protected function validateConfiguration() { + protected function validateConfiguration() + { $ret = parent::validateConfiguration(); $output = $this->output; diff --git a/src/app/CliTools/Console/Command/Sync/AbstractShareCommand.php b/src/app/CliTools/Console/Command/Sync/AbstractShareCommand.php index ddc04cb..b2e05ae 100644 --- a/src/app/CliTools/Console/Command/Sync/AbstractShareCommand.php +++ b/src/app/CliTools/Console/Command/Sync/AbstractShareCommand.php @@ -20,15 +20,17 @@ * along with this program. If not, see . */ -abstract class AbstractShareCommand extends AbstractCommand { +abstract class AbstractShareCommand extends AbstractCommand +{ - const PATH_DUMP = '/dump/'; - const PATH_DATA = '/data/'; + const PATH_DUMP = '/dump/'; + const PATH_DATA = '/data/'; /** * Configure command */ - protected function configure() { + protected function configure() + { parent::configure(); $this->confArea = 'share'; @@ -39,7 +41,8 @@ protected function configure() { * * @return boolean */ - protected function validateConfiguration() { + protected function validateConfiguration() + { $ret = parent::validateConfiguration(); // Rsync required for share diff --git a/src/app/CliTools/Console/Command/Sync/BackupCommand.php b/src/app/CliTools/Console/Command/Sync/BackupCommand.php index 5c261a2..9a4e551 100644 --- a/src/app/CliTools/Console/Command/Sync/BackupCommand.php +++ b/src/app/CliTools/Console/Command/Sync/BackupCommand.php @@ -22,23 +22,25 @@ use CliTools\Shell\CommandBuilder\OutputCombineCommandBuilder; -class BackupCommand extends AbstractShareCommand { +class BackupCommand extends AbstractShareCommand +{ /** * Configure command */ - protected function configure() { + protected function configure() + { parent::configure(); - $this - ->setName('sync:backup') - ->setDescription('Backup files and database from share'); + $this->setName('sync:backup') + ->setDescription('Backup files and database from share'); } /** * Startup task */ - protected function startup() { + protected function startup() + { $this->output->writeln('

Starting share backup

'); parent::startup(); } @@ -46,7 +48,8 @@ protected function startup() { /** * Backup task */ - protected function runMain() { + protected function runMain() + { // ################## // Option specific runners // ################## @@ -79,9 +82,10 @@ protected function runMain() { /** * Sync files with rsync */ - protected function runTaskRsync() { - $source = $this->getRsyncWorkingPath(); - $target = $this->getRsyncPathFromConfig() . self::PATH_DATA; + protected function runTaskRsync() + { + $source = $this->getRsyncWorkingPath(); + $target = $this->getRsyncPathFromConfig() . self::PATH_DATA; $command = $this->createRsyncCommandWithConfiguration($source, $target, 'rsync'); $command->executeInteractive(); @@ -90,7 +94,8 @@ protected function runTaskRsync() { /** * Sync database */ - protected function runTaskMysql() { + protected function runTaskMysql() + { // ################## // Sync databases // ################## @@ -115,16 +120,15 @@ protected function runTaskMysql() { $command = new OutputCombineCommandBuilder(); $command->addCommandForCombinedOutput($mysqldump); - $command - ->setOutputRedirectToFile($dumpFile) - ->executeInteractive(); + $command->setOutputRedirectToFile($dumpFile) + ->executeInteractive(); } // ################## // Backup mysql dump // ################## - $source = $this->tempDir; - $target = $this->getRsyncPathFromConfig() . self::PATH_DUMP; + $source = $this->tempDir; + $target = $this->getRsyncPathFromConfig() . self::PATH_DUMP; $command = $this->createRsyncCommand($source, $target); $command->executeInteractive(); } diff --git a/src/app/CliTools/Console/Command/Sync/DeployCommand.php b/src/app/CliTools/Console/Command/Sync/DeployCommand.php index 12fff68..637c3a7 100644 --- a/src/app/CliTools/Console/Command/Sync/DeployCommand.php +++ b/src/app/CliTools/Console/Command/Sync/DeployCommand.php @@ -22,25 +22,27 @@ use CliTools\Database\DatabaseConnection; -class DeployCommand extends AbstractRemoteSyncCommand { +class DeployCommand extends AbstractRemoteSyncCommand +{ /** * Configure command */ - protected function configure() { + protected function configure() + { parent::configure(); $this->confArea = 'deploy'; - $this - ->setName('sync:deploy') - ->setDescription('Deploy files and database to server'); + $this->setName('sync:deploy') + ->setDescription('Deploy files and database to server'); } /** * Startup task */ - protected function startup() { + protected function startup() + { $this->output->writeln('

Starting server deployment

'); parent::startup(); } @@ -48,7 +50,8 @@ protected function startup() { /** * Backup task */ - protected function runMain() { + protected function runMain() + { // ################## // Option specific runners // ################## @@ -88,7 +91,8 @@ protected function runMain() { /** * Sync files with rsync */ - protected function runTaskRsync() { + protected function runTaskRsync() + { // ################## // Deploy dirs // ################## diff --git a/src/app/CliTools/Console/Command/Sync/InitCommand.php b/src/app/CliTools/Console/Command/Sync/InitCommand.php index 31cbf99..09ecfb3 100644 --- a/src/app/CliTools/Console/Command/Sync/InitCommand.php +++ b/src/app/CliTools/Console/Command/Sync/InitCommand.php @@ -20,20 +20,21 @@ * along with this program. If not, see . */ -use CliTools\Utility\PhpUtility; use CliTools\Shell\CommandBuilder\EditorCommandBuilder; +use CliTools\Utility\PhpUtility; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class InitCommand extends \CliTools\Console\Command\AbstractCommand { +class InitCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('sync:init') - ->setDescription('Create example clisync.yml'); + protected function configure() + { + $this->setName('sync:init') + ->setDescription('Create example clisync.yml'); } /** @@ -45,11 +46,15 @@ protected function configure() { * @return int|null|void * @throws \Exception */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $cliSyncFilePath = getcwd() . '/' . AbstractCommand::CONFIG_FILE; if (file_exists($cliSyncFilePath)) { - $this->output->writeln('Configuration file ' . AbstractCommand::CONFIG_FILE . ' already exists'); + $this->output->writeln( + 'Configuration file ' . AbstractCommand::CONFIG_FILE . ' already exists' + ); + return 1; } @@ -62,9 +67,8 @@ public function execute(InputInterface $input, OutputInterface $output) { // Start editor with file (if $EDITOR is set) try { $editor = new EditorCommandBuilder(); - $editor - ->addArgument($cliSyncFilePath) - ->executeInteractive(); + $editor->addArgument($cliSyncFilePath) + ->executeInteractive(); } catch (\Exception $e) { $this->output->writeln('' . $e->getMessage() . ''); } diff --git a/src/app/CliTools/Console/Command/Sync/RestoreCommand.php b/src/app/CliTools/Console/Command/Sync/RestoreCommand.php index c2699c6..3601733 100644 --- a/src/app/CliTools/Console/Command/Sync/RestoreCommand.php +++ b/src/app/CliTools/Console/Command/Sync/RestoreCommand.php @@ -20,23 +20,25 @@ * along with this program. If not, see . */ -class RestoreCommand extends AbstractShareCommand { +class RestoreCommand extends AbstractShareCommand +{ /** * Configure command */ - protected function configure() { + protected function configure() + { parent::configure(); - $this - ->setName('sync:restore') - ->setDescription('Restore files and database from share'); + $this->setName('sync:restore') + ->setDescription('Restore files and database from share'); } /** * Startup task */ - protected function startup() { + protected function startup() + { $this->output->writeln('

Starting share restore

'); parent::startup(); } @@ -44,7 +46,8 @@ protected function startup() { /** * Restore task */ - protected function runMain() { + protected function runMain() + { // ################## // Option specific runners // ################## @@ -77,9 +80,10 @@ protected function runMain() { /** * Sync files with rsync */ - protected function runTaskRsync() { - $source = $this->getRsyncPathFromConfig() . self::PATH_DATA; - $target = $this->getRsyncWorkingPath(); + protected function runTaskRsync() + { + $source = $this->getRsyncPathFromConfig() . self::PATH_DATA; + $target = $this->getRsyncWorkingPath(); $command = $this->createRsyncCommandWithConfiguration($source, $target, 'rsync'); $command->executeInteractive(); @@ -88,7 +92,8 @@ protected function runTaskRsync() { /** * Sync files with mysql */ - protected function runTaskMysql() { + protected function runTaskMysql() + { $source = $this->getRsyncPathFromConfig() . self::PATH_DUMP; $target = $this->tempDir; $command = $this->createRsyncCommand($source, $target); @@ -106,7 +111,8 @@ protected function runTaskMysql() { if (!empty($database)) { $this->output->writeln('

Restoring database ' . $database . '

'); - $this->createMysqlRestoreCommand($database, $item->getPathname())->executeInteractive(); + $this->createMysqlRestoreCommand($database, $item->getPathname()) + ->executeInteractive(); } } } diff --git a/src/app/CliTools/Console/Command/Sync/ServerCommand.php b/src/app/CliTools/Console/Command/Sync/ServerCommand.php index 27a0988..51cbbc2 100644 --- a/src/app/CliTools/Console/Command/Sync/ServerCommand.php +++ b/src/app/CliTools/Console/Command/Sync/ServerCommand.php @@ -22,25 +22,27 @@ use CliTools\Database\DatabaseConnection; -class ServerCommand extends AbstractRemoteSyncCommand { +class ServerCommand extends AbstractRemoteSyncCommand +{ /** * Configure command */ - protected function configure() { + protected function configure() + { parent::configure(); $this->confArea = 'sync'; - $this - ->setName('sync:server') - ->setDescription('Sync files and database from server'); + $this->setName('sync:server') + ->setDescription('Sync files and database from server'); } /** * Startup task */ - protected function startup() { + protected function startup() + { $this->output->writeln('

Starting server synchronization

'); parent::startup(); } @@ -50,7 +52,8 @@ protected function startup() { * * @return boolean */ - protected function validateConfiguration() { + protected function validateConfiguration() + { $ret = parent::validateConfiguration(); $output = $this->output; @@ -73,7 +76,8 @@ protected function validateConfiguration() { /** * Backup task */ - protected function runMain() { + protected function runMain() + { // ################## // Option specific runners // ################## @@ -113,7 +117,8 @@ protected function runMain() { /** * Sync files with rsync */ - protected function runTaskRsync() { + protected function runTaskRsync() + { // ################## // Restore dirs // ################## @@ -127,7 +132,8 @@ protected function runTaskRsync() { /** * Sync database */ - protected function runTaskDatabase() { + protected function runTaskDatabase() + { // ################## // Sync databases // ################## @@ -155,7 +161,11 @@ protected function runTaskDatabase() { $mysqldump = $this->createRemoteMySqlDumpCommand($foreignDatabase); if ($this->contextConfig->exists('mysql.filter')) { - $mysqldump = $this->addMysqlDumpFilterArguments($mysqldump, $foreignDatabase, $this->contextConfig->get('mysql.filter')); + $mysqldump = $this->addMysqlDumpFilterArguments( + $mysqldump, + $foreignDatabase, + $this->contextConfig->get('mysql.filter') + ); } $command = $this->wrapRemoteCommand($mysqldump); @@ -168,7 +178,8 @@ protected function runTaskDatabase() { // ########## $this->output->writeln('

Restoring database "' . $localDatabase . '"

'); - $this->createMysqlRestoreCommand($localDatabase, $dumpFile)->executeInteractive(); + $this->createMysqlRestoreCommand($localDatabase, $dumpFile) + ->executeInteractive(); } } diff --git a/src/app/CliTools/Console/Command/System/BannerCommand.php b/src/app/CliTools/Console/Command/System/BannerCommand.php index 01b6b20..bc4f6a7 100644 --- a/src/app/CliTools/Console/Command/System/BannerCommand.php +++ b/src/app/CliTools/Console/Command/System/BannerCommand.php @@ -25,7 +25,9 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class BannerCommand extends \CliTools\Console\Command\AbstractCommand implements \CliTools\Console\Filter\OnlyRootFilterInterface { +class BannerCommand extends \CliTools\Console\Command\AbstractCommand implements + \CliTools\Console\Filter\OnlyRootFilterInterface +{ /** * Enable automatic terminal title @@ -37,10 +39,10 @@ class BannerCommand extends \CliTools\Console\Command\AbstractCommand implements /** * Configure command */ - protected function configure() { - $this - ->setName('system:banner') - ->setDescription('Banner generator for /etc/issue'); + protected function configure() + { + $this->setName('system:banner') + ->setDescription('Banner generator for /etc/issue'); } /** @@ -51,7 +53,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $clearScreen = "\033[H" . "\033[2J"; $normalFont = "\033[0m"; @@ -73,7 +76,8 @@ public function execute(InputInterface $input, OutputInterface $output) { * * @return string */ - protected function generateBannerHeader() { + protected function generateBannerHeader() + { // INFO: you can use figlet command for generating ascii-art-text $logo = ' @@ -104,7 +108,8 @@ protected function generateBannerHeader() { * * @return string */ - protected function generateSystemInfo() { + protected function generateSystemInfo() + { $ret = array(); $leftCol = array(); diff --git a/src/app/CliTools/Console/Command/System/CrontaskCommand.php b/src/app/CliTools/Console/Command/System/CrontaskCommand.php index df3671c..736e590 100644 --- a/src/app/CliTools/Console/Command/System/CrontaskCommand.php +++ b/src/app/CliTools/Console/Command/System/CrontaskCommand.php @@ -20,12 +20,14 @@ * along with this program. If not, see . */ -use CliTools\Utility\UnixUtility; use CliTools\Shell\CommandBuilder\SelfCommandBuilder; +use CliTools\Utility\UnixUtility; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class CrontaskCommand extends \CliTools\Console\Command\AbstractCommand implements \CliTools\Console\Filter\OnlyRootFilterInterface { +class CrontaskCommand extends \CliTools\Console\Command\AbstractCommand implements + \CliTools\Console\Filter\OnlyRootFilterInterface +{ /** * List of warning messages @@ -37,10 +39,10 @@ class CrontaskCommand extends \CliTools\Console\Command\AbstractCommand implemen /** * Configure command */ - protected function configure() { - $this - ->setName('system:crontask') - ->setDescription('System cron task'); + protected function configure() + { + $this->setName('system:crontask') + ->setDescription('System cron task'); } /** @@ -51,10 +53,13 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $this->setupBanner(); - if ($this->getApplication()->getConfigValue('syscheck', 'enabled', true)) { + if ($this->getApplication() + ->getConfigValue('syscheck', 'enabled', true) + ) { $this->systemCheck(); } @@ -64,10 +69,12 @@ public function execute(InputInterface $input, OutputInterface $output) { /** * Setup banner */ - protected function setupBanner() { + protected function setupBanner() + { $command = new SelfCommandBuilder(); $command->addArgument('system:banner'); - $output = $command->execute()->getOutputString(); + $output = $command->execute() + ->getOutputString(); // escape special chars for /etc/issue $outputIssue = addcslashes($output, '\\'); @@ -81,17 +88,22 @@ protected function setupBanner() { /** * Check system health */ - protected function systemCheck() { + protected function systemCheck() + { $this->systemCheckDiskUsage(); if (!empty($this->sysCheckMessageList)) { - if ($this->getApplication()->getConfigValue('syscheck', 'growl', 0)) { + if ($this->getApplication() + ->getConfigValue('syscheck', 'growl', 0) + ) { // Growl notification $message = 'WARNING:' . "\n\n" . implode("\n", $this->sysCheckMessageList); $this->sendGrowlMessage('CliTools :: System Check Warnings', $message); } - if ($this->getApplication()->getConfigValue('syscheck', 'wall', 0)) { + if ($this->getApplication() + ->getConfigValue('syscheck', 'wall', 0) + ) { // Local wall message $msgPrefix = ' - '; $message = ' -- CliTools :: System Check Warnings --' . "\n\n"; @@ -108,11 +120,14 @@ protected function systemCheck() { * @param string $title Notification title * @param string $message Notification message */ - protected function sendGrowlMessage($title, $message) { + protected function sendGrowlMessage($title, $message) + { require CLITOOLS_ROOT_FS . '/vendor/jamiebicknell/Growl-GNTP/growl.gntp.php'; - $growlServer = (string)$this->getApplication()->getConfigValue('growl', 'server', null); - $growlPassword = (string)$this->getApplication()->getConfigValue('growl', 'password', null); + $growlServer = (string)$this->getApplication() + ->getConfigValue('growl', 'server', null); + $growlPassword = (string)$this->getApplication() + ->getConfigValue('growl', 'password', null); if (!empty($growlServer)) { $growl = new \Growl($growlServer, $growlPassword); @@ -129,8 +144,12 @@ protected function sendGrowlMessage($title, $message) { /** * Check system disk usage */ - protected function systemCheckDiskUsage() { - $diskUsageLimit = abs($this->getApplication()->getConfigValue('syscheck', 'diskusage', 0)); + protected function systemCheckDiskUsage() + { + $diskUsageLimit = abs( + $this->getApplication() + ->getConfigValue('syscheck', 'diskusage', 0) + ); if (!empty($diskUsageLimit)) { $mountInfoList = UnixUtility::mountInfoList(); @@ -143,7 +162,10 @@ protected function systemCheckDiskUsage() { ); if ($usageInt >= $diskUsageLimit) { - $this->sysCheckMessageList[] = 'Mount "' . $mount . '" exceeds limit of ' . $diskUsageLimit . '% (' . implode(', ', $statsLine) . ')'; + $this->sysCheckMessageList[] = 'Mount "' . $mount . '" exceeds limit of ' . $diskUsageLimit . '% (' . implode( + ', ', + $statsLine + ) . ')'; } } } diff --git a/src/app/CliTools/Console/Command/System/EnvCommand.php b/src/app/CliTools/Console/Command/System/EnvCommand.php index af76e5b..1c16417 100644 --- a/src/app/CliTools/Console/Command/System/EnvCommand.php +++ b/src/app/CliTools/Console/Command/System/EnvCommand.php @@ -24,15 +24,16 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class EnvCommand extends \CliTools\Console\Command\AbstractCommand { +class EnvCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('system:env') - ->setDescription('List environment variables'); + protected function configure() + { + $this->setName('system:env') + ->setDescription('List environment variables'); } /** @@ -43,7 +44,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $envNameList = array( 'USER', diff --git a/src/app/CliTools/Console/Command/System/OpenFilesCommand.php b/src/app/CliTools/Console/Command/System/OpenFilesCommand.php index 5979602..0e6666d 100644 --- a/src/app/CliTools/Console/Command/System/OpenFilesCommand.php +++ b/src/app/CliTools/Console/Command/System/OpenFilesCommand.php @@ -20,22 +20,23 @@ * along with this program. If not, see . */ -use CliTools\Utility\FormatUtility; use CliTools\Shell\CommandBuilder\CommandBuilder; +use CliTools\Utility\FormatUtility; use Symfony\Component\Console\Helper\Table; use Symfony\Component\Console\Helper\TableSeparator; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class OpenFilesCommand extends \CliTools\Console\Command\AbstractCommand { +class OpenFilesCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('system:openfiles') - ->setDescription('List swap usage'); + protected function configure() + { + $this->setName('system:openfiles') + ->setDescription('List swap usage'); } /** @@ -46,19 +47,25 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $this->elevateProcess($input, $output); $procList = array(); $openFilesTotal = 0; $command = new CommandBuilder('lsof', '-n'); - $command->addPipeCommand( new CommandBuilder('grep', '-oE \'^[a-z]+\'') ) - ->addPipeCommand( new CommandBuilder('sort') ) - ->addPipeCommand( new CommandBuilder('uniq', '-c') ) - ->addPipeCommand( new CommandBuilder('sort', '-n')) - ->setOutputRedirect(CommandBuilder::OUTPUT_REDIRECT_NO_STDERR); - $execOutput = $command->execute()->getOutput(); + $command->addPipeCommand(new CommandBuilder('grep', '-oE \'^[a-z]+\'')) + ->addPipeCommand( + new CommandBuilder('sort') + ) + ->addPipeCommand(new CommandBuilder('uniq', '-c')) + ->addPipeCommand( + new CommandBuilder('sort', '-n') + ) + ->setOutputRedirect(CommandBuilder::OUTPUT_REDIRECT_NO_STDERR); + $execOutput = $command->execute() + ->getOutput(); foreach ($execOutput as $execOutputLine) { // get open files and proc name from output diff --git a/src/app/CliTools/Console/Command/System/RebootCommand.php b/src/app/CliTools/Console/Command/System/RebootCommand.php index 36bbc0c..1bebe11 100644 --- a/src/app/CliTools/Console/Command/System/RebootCommand.php +++ b/src/app/CliTools/Console/Command/System/RebootCommand.php @@ -20,20 +20,21 @@ * along with this program. If not, see . */ +use CliTools\Shell\CommandBuilder\CommandBuilder; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use CliTools\Shell\CommandBuilder\CommandBuilder; -class RebootCommand extends \CliTools\Console\Command\AbstractCommand { +class RebootCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('system:reboot') - ->setAliases(array('reboot')) - ->setDescription('Reboot system'); + protected function configure() + { + $this->setName('system:reboot') + ->setAliases(array('reboot')) + ->setDescription('Reboot system'); } /** @@ -44,7 +45,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $this->elevateProcess($input, $output); $command = new CommandBuilder('reboot'); diff --git a/src/app/CliTools/Console/Command/System/ShutdownCommand.php b/src/app/CliTools/Console/Command/System/ShutdownCommand.php index 317ca11..24c341e 100644 --- a/src/app/CliTools/Console/Command/System/ShutdownCommand.php +++ b/src/app/CliTools/Console/Command/System/ShutdownCommand.php @@ -20,20 +20,21 @@ * along with this program. If not, see . */ +use CliTools\Shell\CommandBuilder\CommandBuilder; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use CliTools\Shell\CommandBuilder\CommandBuilder; -class ShutdownCommand extends \CliTools\Console\Command\AbstractCommand { +class ShutdownCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('system:shutdown') - ->setAliases(array('shutdown')) - ->setDescription('Shutdown system'); + protected function configure() + { + $this->setName('system:shutdown') + ->setAliases(array('shutdown')) + ->setDescription('Shutdown system'); } /** @@ -44,7 +45,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $this->elevateProcess($input, $output); $command = new CommandBuilder('shutdown', '-h now'); diff --git a/src/app/CliTools/Console/Command/System/StartupCommand.php b/src/app/CliTools/Console/Command/System/StartupCommand.php index f6dcaaa..839b937 100644 --- a/src/app/CliTools/Console/Command/System/StartupCommand.php +++ b/src/app/CliTools/Console/Command/System/StartupCommand.php @@ -20,22 +20,24 @@ * along with this program. If not, see . */ -use CliTools\Utility\UnixUtility; use CliTools\Database\DatabaseConnection; use CliTools\Shell\CommandBuilder\CommandBuilder; use CliTools\Shell\CommandBuilder\SelfCommandBuilder; +use CliTools\Utility\UnixUtility; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class StartupCommand extends \CliTools\Console\Command\AbstractCommand implements \CliTools\Console\Filter\OnlyRootFilterInterface { +class StartupCommand extends \CliTools\Console\Command\AbstractCommand implements + \CliTools\Console\Filter\OnlyRootFilterInterface +{ /** * Configure command */ - protected function configure() { - $this - ->setName('system:startup') - ->setDescription('System startup task'); + protected function configure() + { + $this->setName('system:startup') + ->setDescription('System startup task'); } /** @@ -46,7 +48,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $this->setupBanner(); $this->cleanupMysql(); @@ -56,10 +59,12 @@ public function execute(InputInterface $input, OutputInterface $output) { /** * Setup banner */ - protected function setupBanner() { + protected function setupBanner() + { $command = new SelfCommandBuilder(); $command->addArgument('system:banner'); - $output = $command->execute()->getOutputString(); + $output = $command->execute() + ->getOutputString(); // escape special chars for /etc/issue $outputIssue = addcslashes($output, '\\'); @@ -75,7 +80,8 @@ protected function setupBanner() { * * @return string */ - protected function cleanupMysql() { + protected function cleanupMysql() + { try { // ############################ // Clear general log @@ -92,9 +98,11 @@ protected function cleanupMysql() { if (!empty($logFileRow['Value'])) { $command = new CommandBuilder('rm'); $command->addArgument('-f') - ->addArgumentSeparator() - ->addArgument($logFileRow['Value']) - ->executeInteractive(); + ->addArgumentSeparator() + ->addArgument( + $logFileRow['Value'] + ) + ->executeInteractive(); } } catch (\Exception $e) { // do nothing if no mysql is running diff --git a/src/app/CliTools/Console/Command/System/SwapCommand.php b/src/app/CliTools/Console/Command/System/SwapCommand.php index d0db100..e7f27ac 100644 --- a/src/app/CliTools/Console/Command/System/SwapCommand.php +++ b/src/app/CliTools/Console/Command/System/SwapCommand.php @@ -27,15 +27,16 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class SwapCommand extends \CliTools\Console\Command\AbstractCommand { +class SwapCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('system:swap') - ->setDescription('List swap usage'); + protected function configure() + { + $this->setName('system:swap') + ->setDescription('List swap usage'); } /** @@ -46,7 +47,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $this->elevateProcess($input, $output); $dirIterator = new \DirectoryIterator('/proc'); @@ -83,9 +85,12 @@ public function execute(InputInterface $input, OutputInterface $output) { // Sort // ######################## - uasort($procList, function ($a, $b) { - return $a['swap'] > $b['swap']; - }); + uasort( + $procList, + function ($a, $b) { + return $a['swap'] > $b['swap']; + } + ); // ######################## // Output @@ -122,7 +127,8 @@ public function execute(InputInterface $input, OutputInterface $output) { * * @return int|null */ - protected function getProcessSwap($processStatsPath) { + protected function getProcessSwap($processStatsPath) + { $ret = 0; $smapsFile = $processStatsPath . '/smaps'; diff --git a/src/app/CliTools/Console/Command/System/UpdateCommand.php b/src/app/CliTools/Console/Command/System/UpdateCommand.php index c39bcb3..53dc31b 100644 --- a/src/app/CliTools/Console/Command/System/UpdateCommand.php +++ b/src/app/CliTools/Console/Command/System/UpdateCommand.php @@ -22,20 +22,20 @@ use CliTools\Service\SelfUpdateService; use CliTools\Shell\CommandBuilder\CommandBuilder; -use CliTools\Shell\CommandBuilder\SelfCommandBuilder; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class UpdateCommand extends \CliTools\Console\Command\AbstractCommand { +class UpdateCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('system:update') - ->setAliases(array('update')) - ->setDescription('Update system'); + protected function configure() + { + $this->setName('system:update') + ->setAliases(array('update')) + ->setDescription('Update system'); } /** @@ -46,8 +46,11 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { - if (!$this->getApplication()->isRunningAsRoot()) { + public function execute(InputInterface $input, OutputInterface $output) + { + if (!$this->getApplication() + ->isRunningAsRoot() + ) { $this->userUpdate($input, $output); } @@ -66,13 +69,15 @@ public function execute(InputInterface $input, OutputInterface $output) { * * @return int|null|void */ - protected function userUpdate(InputInterface $input, OutputInterface $output) { + protected function userUpdate(InputInterface $input, OutputInterface $output) + { // GIT pulls and other stuff // ################## // SSH Git repo update // ################## - $reposDirectory = $this->getApplication()->getConfigValue('config', 'ssh_conf_path', '/opt/conf/ssh'); + $reposDirectory = $this->getApplication() + ->getConfigValue('config', 'ssh_conf_path', '/opt/conf/ssh'); if (is_dir($reposDirectory) && is_dir($reposDirectory . '/.git')) { // SSH Git repo exists, update now @@ -107,7 +112,8 @@ protected function userUpdate(InputInterface $input, OutputInterface $output) { * * @return int|null|void */ - protected function systemUpdate(InputInterface $input, OutputInterface $output) { + protected function systemUpdate(InputInterface $input, OutputInterface $output) + { $errorMsgList = array(); // ################## @@ -204,8 +210,10 @@ protected function systemUpdate(InputInterface $input, OutputInterface $output) * @param OutputInterface $output Output * @param string $msg Message */ - protected function outputBlock($output, $msg) { - list($termWidth) = $this->getApplication()->getTerminalDimensions(); + protected function outputBlock($output, $msg) + { + list($termWidth) = $this->getApplication() + ->getTerminalDimensions(); $separator = '' . str_repeat('-', $termWidth) . ''; $msg = str_repeat(' ', $termWidth - strlen($msg) - 10) . $msg; diff --git a/src/app/CliTools/Console/Command/System/VersionCommand.php b/src/app/CliTools/Console/Command/System/VersionCommand.php index c0205b4..28ccc2d 100644 --- a/src/app/CliTools/Console/Command/System/VersionCommand.php +++ b/src/app/CliTools/Console/Command/System/VersionCommand.php @@ -27,15 +27,16 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class VersionCommand extends \CliTools\Console\Command\AbstractCommand { +class VersionCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('system:version') - ->setDescription('List common version'); + protected function configure() + { + $this->setName('system:version') + ->setDescription('List common version'); } /** @@ -46,14 +47,15 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $versionList = array(); // ############################ // System (LSB Version) // ############################ - $versionRow = array( + $versionRow = array( 'system' => 'System', 'version' => UnixUtility::lsbSystemDescription(), ); @@ -88,7 +90,8 @@ public function execute(InputInterface $input, OutputInterface $output) { $command = new CommandBuilder('apache2ctl', '-v'); $command->setOutputRedirect(CommandBuilder::OUTPUT_REDIRECT_NO_STDERR); - $execOutput = $command->execute()->getOutput(); + $execOutput = $command->execute() + ->getOutput(); foreach ($execOutput as $execOutputLine) { if (strpos($execOutputLine, ':') !== false) { @@ -107,7 +110,7 @@ public function execute(InputInterface $input, OutputInterface $output) { // ############################ // Docker // ############################ - $versionRow = array( + $versionRow = array( 'system' => 'Docker', 'version' => \CliTools\Utility\UnixUtility::dockerVersion(), ); diff --git a/src/app/CliTools/Console/Command/TYPO3/BeUserCommand.php b/src/app/CliTools/Console/Command/TYPO3/BeUserCommand.php index 631c29b..8d8dd84 100644 --- a/src/app/CliTools/Console/Command/TYPO3/BeUserCommand.php +++ b/src/app/CliTools/Console/Command/TYPO3/BeUserCommand.php @@ -27,36 +27,37 @@ use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -class BeUserCommand extends \CliTools\Console\Command\AbstractCommand { +class BeUserCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('typo3:beuser') - ->setDescription('Add backend admin user to database') - ->addArgument( - 'database', - InputArgument::OPTIONAL, - 'Database name' - ) - ->addArgument( - 'user', - InputArgument::OPTIONAL, - 'Username' - ) - ->addArgument( - 'password', - InputArgument::OPTIONAL, - 'Password' - ) - ->addOption( - 'plain', - null, - InputOption::VALUE_NONE, - 'Do not crypt password (non salted password)' - ); + protected function configure() + { + $this->setName('typo3:beuser') + ->setDescription('Add backend admin user to database') + ->addArgument( + 'database', + InputArgument::OPTIONAL, + 'Database name' + ) + ->addArgument( + 'user', + InputArgument::OPTIONAL, + 'Username' + ) + ->addArgument( + 'password', + InputArgument::OPTIONAL, + 'Password' + ) + ->addOption( + 'plain', + null, + InputOption::VALUE_NONE, + 'Do not crypt password (non salted password)' + ); } /** @@ -67,7 +68,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { // ################## // Init // ################## @@ -125,7 +127,7 @@ public function execute(InputInterface $input, OutputInterface $output) { $dbFound = false; foreach ($databaseList as $dbName) { // Check if database is TYPO3 instance - $query = 'SELECT COUNT(*) as count + $query = 'SELECT COUNT(*) as count FROM information_schema.tables WHERE table_schema = ' . DatabaseConnection::quote($dbName) . ' AND table_name = \'be_users\''; @@ -157,7 +159,8 @@ public function execute(InputInterface $input, OutputInterface $output) { * @param string $username Username * @param string $password Password (salted/hashed) */ - protected function setTypo3UserForDatabase($database, $username, $password) { + protected function setTypo3UserForDatabase($database, $username, $password) + { // ################## // Update/insert user // ################## diff --git a/src/app/CliTools/Console/Command/TYPO3/CleanupCommand.php b/src/app/CliTools/Console/Command/TYPO3/CleanupCommand.php index a8bbdb6..1a6529e 100644 --- a/src/app/CliTools/Console/Command/TYPO3/CleanupCommand.php +++ b/src/app/CliTools/Console/Command/TYPO3/CleanupCommand.php @@ -25,20 +25,21 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class CleanupCommand extends \CliTools\Console\Command\AbstractCommand { +class CleanupCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('typo3:cleanup') - ->setDescription('Cleanup caches, logs and indexed search') - ->addArgument( - 'db', - InputArgument::REQUIRED, - 'Database name' - ); + protected function configure() + { + $this->setName('typo3:cleanup') + ->setDescription('Cleanup caches, logs and indexed search') + ->addArgument( + 'db', + InputArgument::REQUIRED, + 'Database name' + ); } /** @@ -49,7 +50,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { // ################## // Init // ################## @@ -103,7 +105,8 @@ public function execute(InputInterface $input, OutputInterface $output) { * * @param string $database Database */ - protected function cleanupTypo3Database($database) { + protected function cleanupTypo3Database($database) + { $cleanupTableList = array(); // Check if database is TYPO3 instance diff --git a/src/app/CliTools/Console/Command/TYPO3/ClearCacheCommand.php b/src/app/CliTools/Console/Command/TYPO3/ClearCacheCommand.php index f5c161c..de82287 100644 --- a/src/app/CliTools/Console/Command/TYPO3/ClearCacheCommand.php +++ b/src/app/CliTools/Console/Command/TYPO3/ClearCacheCommand.php @@ -20,26 +20,29 @@ * along with this program. If not, see . */ -use CliTools\Utility\Typo3Utility; use CliTools\Shell\CommandBuilder\CommandBuilder; +use CliTools\Utility\Typo3Utility; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class ClearCacheCommand extends \CliTools\Console\Command\AbstractCommand { +class ClearCacheCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('typo3:clearcache') - ->setDescription('Clear cache on all (or one specific) TYPO3 instances') - ->addArgument( - 'path', - InputArgument::OPTIONAL, - 'Path to TYPO3 instance' - ); + protected function configure() + { + $this->setName('typo3:clearcache') + ->setDescription( + 'Clear cache on all (or one specific) TYPO3 instances' + ) + ->addArgument( + 'path', + InputArgument::OPTIONAL, + 'Path to TYPO3 instance' + ); } /** @@ -50,11 +53,13 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { // #################### // Init // #################### - $basePath = $this->getApplication()->getConfigValue('config', 'www_base_path', '/var/www/'); + $basePath = $this->getApplication() + ->getConfigValue('config', 'www_base_path', '/var/www/'); $maxDepth = 3; $output->writeln('

Clear TYPO3 cache

'); @@ -85,7 +90,7 @@ public function execute(InputInterface $input, OutputInterface $output) { $command = new CommandBuilder('php'); $command->setArgumentList($params) - ->executeInteractive(); + ->executeInteractive(); } catch (\Exception $e) { $output->writeln(' Failed with exception: ' . $e->getMessage() . ''); } diff --git a/src/app/CliTools/Console/Command/TYPO3/DomainCommand.php b/src/app/CliTools/Console/Command/TYPO3/DomainCommand.php index 321423e..763a00f 100644 --- a/src/app/CliTools/Console/Command/TYPO3/DomainCommand.php +++ b/src/app/CliTools/Console/Command/TYPO3/DomainCommand.php @@ -21,49 +21,50 @@ */ use CliTools\Database\DatabaseConnection; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -class DomainCommand extends \CliTools\Console\Command\AbstractCommand { +class DomainCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('typo3:domain') - ->setDescription('Add common development domains to database') - ->addArgument( - 'db', - InputArgument::OPTIONAL, - 'Database name' - ) - ->addOption( - 'baseurl', - null, - InputOption::VALUE_NONE, - 'Also set config.baseURL setting' - ) - ->addOption( - 'list', - null, - InputOption::VALUE_NONE, - 'List only databases' - ) - ->addOption( - 'remove', - null, - InputOption::VALUE_REQUIRED, - 'Remove domain (with wildcard support)' - ) - ->addOption( - 'duplicate', - null, - InputOption::VALUE_REQUIRED, - 'Add duplication domains (will duplicate all domains in system, eg. for vagrant share)' - ); + protected function configure() + { + $this->setName('typo3:domain') + ->setDescription('Add common development domains to database') + ->addArgument( + 'db', + InputArgument::OPTIONAL, + 'Database name' + ) + ->addOption( + 'baseurl', + null, + InputOption::VALUE_NONE, + 'Also set config.baseURL setting' + ) + ->addOption( + 'list', + null, + InputOption::VALUE_NONE, + 'List only databases' + ) + ->addOption( + 'remove', + null, + InputOption::VALUE_REQUIRED, + 'Remove domain (with wildcard support)' + ) + ->addOption( + 'duplicate', + null, + InputOption::VALUE_REQUIRED, + 'Add duplication domains (will duplicate all domains in system, eg. for vagrant share)' + ); } /** @@ -74,7 +75,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { // ################## // Init // ################## @@ -94,7 +96,7 @@ public function execute(InputInterface $input, OutputInterface $output) { foreach ($databaseList as $dbName) { // Check if database is TYPO3 instance - $query = 'SELECT COUNT(*) as count + $query = 'SELECT COUNT(*) as count FROM information_schema.tables WHERE table_schema = ' . DatabaseConnection::quote($dbName) . ' AND table_name = \'sys_domain\''; @@ -115,7 +117,8 @@ public function execute(InputInterface $input, OutputInterface $output) { /** * Run tasks for one domain */ - protected function runTaskForDomain($dbName) { + protected function runTaskForDomain($dbName) + { DatabaseConnection::switchDatabase($dbName); if ($this->input->getOption('list')) { @@ -148,7 +151,8 @@ protected function runTaskForDomain($dbName) { /** * Remove domains */ - protected function removeDomains($pattern) { + protected function removeDomains($pattern) + { $pattern = str_replace('*', '%', $pattern); $query = 'DELETE FROM sys_domain WHERE domainName LIKE %s'; @@ -159,8 +163,9 @@ protected function removeDomains($pattern) { /** * Update baseURL config */ - protected function updateBaseUrlConfig() { - $query = 'SELECT st.uid as template_id, + protected function updateBaseUrlConfig() + { + $query = 'SELECT st.uid as template_id, st.config as template_config, (SELECT sd.domainName FROM sys_domain sd @@ -184,7 +189,7 @@ protected function updateBaseUrlConfig() { $templateConf = trim($templateConf); // Add new baseURL - $templateConf .= "\n" . 'config.baseURL = http://' . $domainName .'/'; + $templateConf .= "\n" . 'config.baseURL = http://' . $domainName . '/'; $query = 'UPDATE sys_template SET config = %s WHERE uid = %s'; $query = sprintf($query, DatabaseConnection::quote($templateConf), (int)$templateId); @@ -197,10 +202,12 @@ protected function updateBaseUrlConfig() { * * @param string $suffix Domain suffix */ - protected function addDuplicateDomains($suffix) { - $devDomain = '.' . $this->getApplication()->getConfigValue('config', 'domain_dev'); + protected function addDuplicateDomains($suffix) + { + $devDomain = '.' . $this->getApplication() + ->getConfigValue('config', 'domain_dev'); - $query = 'SELECT * FROM sys_domain'; + $query = 'SELECT * FROM sys_domain'; $domainList = DatabaseConnection::getAll($query); foreach ($domainList as $domain) { @@ -209,7 +216,7 @@ protected function addDuplicateDomains($suffix) { $domainName = $domain['domainName']; // remove development suffix - $domainName = preg_replace('/' . preg_quote($devDomain). '$/', '', $domainName); + $domainName = preg_replace('/' . preg_quote($devDomain) . '$/', '', $domainName); // add share domain $domainName .= '.' . ltrim($suffix, '.'); @@ -225,8 +232,9 @@ protected function addDuplicateDomains($suffix) { * * @param string $dbName Domain name */ - protected function showDomainList($dbName) { - $query = 'SELECT domainName FROM sys_domain ORDER BY domainName ASC'; + protected function showDomainList($dbName) + { + $query = 'SELECT domainName FROM sys_domain ORDER BY domainName ASC'; $domainList = DatabaseConnection::getCol($query); $this->output->writeln('

Domain list of "' . $dbName . '":

'); @@ -242,8 +250,10 @@ protected function showDomainList($dbName) { * * @return void */ - protected function manipulateDomains() { - $devDomain = '.' . $this->getApplication()->getConfigValue('config', 'domain_dev'); + protected function manipulateDomains() + { + $devDomain = '.' . $this->getApplication() + ->getConfigValue('config', 'domain_dev'); $domainLength = strlen($devDomain); // ################## diff --git a/src/app/CliTools/Console/Command/TYPO3/InstallerCommand.php b/src/app/CliTools/Console/Command/TYPO3/InstallerCommand.php index c827bfd..bd17d9d 100644 --- a/src/app/CliTools/Console/Command/TYPO3/InstallerCommand.php +++ b/src/app/CliTools/Console/Command/TYPO3/InstallerCommand.php @@ -26,25 +26,29 @@ use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -class InstallerCommand extends \CliTools\Console\Command\AbstractCommand { +class InstallerCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('typo3:installer') - ->setDescription('Enable installer on all (or one specific) TYPO3 instances') - ->addArgument( - 'path', - InputArgument::OPTIONAL, - 'Path to TYPO3 instance' - )->addOption( - 'remove', - 'r', - InputOption::VALUE_NONE, - 'Remove installer file' - ); + protected function configure() + { + $this->setName('typo3:installer') + ->setDescription( + 'Enable installer on all (or one specific) TYPO3 instances' + ) + ->addArgument( + 'path', + InputArgument::OPTIONAL, + 'Path to TYPO3 instance' + ) + ->addOption( + 'remove', + 'r', + InputOption::VALUE_NONE, + 'Remove installer file' + ); } /** @@ -55,11 +59,13 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { // #################### // Init // #################### - $basePath = $this->getApplication()->getConfigValue('config', 'www_base_path', '/var/www/'); + $basePath = $this->getApplication() + ->getConfigValue('config', 'www_base_path', '/var/www/'); $maxDepth = 3; $enableInstaller = true; diff --git a/src/app/CliTools/Console/Command/TYPO3/ListCommand.php b/src/app/CliTools/Console/Command/TYPO3/ListCommand.php index 9b141aa..2839068 100644 --- a/src/app/CliTools/Console/Command/TYPO3/ListCommand.php +++ b/src/app/CliTools/Console/Command/TYPO3/ListCommand.php @@ -26,20 +26,21 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class ListCommand extends \CliTools\Console\Command\AbstractCommand { +class ListCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('typo3:list') - ->setDescription('List all TYPO3 instances') - ->addArgument( - 'path', - InputArgument::OPTIONAL, - 'Path to TYPO3 instance' - ); + protected function configure() + { + $this->setName('typo3:list') + ->setDescription('List all TYPO3 instances') + ->addArgument( + 'path', + InputArgument::OPTIONAL, + 'Path to TYPO3 instance' + ); } /** @@ -50,12 +51,14 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { // #################### // Init // #################### - $basePath = $this->getApplication()->getConfigValue('config', 'www_base_path', '/var/www/'); - $maxDepth = 3; + $basePath = $this->getApplication() + ->getConfigValue('config', 'www_base_path', '/var/www/'); + $maxDepth = 3; $basePath = Typo3Utility::guessBestTypo3BasePath($basePath, $input, 'path'); diff --git a/src/app/CliTools/Console/Command/TYPO3/SchedulerCommand.php b/src/app/CliTools/Console/Command/TYPO3/SchedulerCommand.php index 83f5d66..46b5c74 100644 --- a/src/app/CliTools/Console/Command/TYPO3/SchedulerCommand.php +++ b/src/app/CliTools/Console/Command/TYPO3/SchedulerCommand.php @@ -20,26 +20,29 @@ * along with this program. If not, see . */ -use CliTools\Utility\Typo3Utility; use CliTools\Shell\CommandBuilder\CommandBuilder; +use CliTools\Utility\Typo3Utility; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class SchedulerCommand extends \CliTools\Console\Command\AbstractCommand { +class SchedulerCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('typo3:scheduler') - ->setDescription('Run scheduler on all (or one specific) TYPO3 instances') - ->addArgument( - 'path', - InputArgument::OPTIONAL, - 'Path to TYPO3 instance' -); + protected function configure() + { + $this->setName('typo3:scheduler') + ->setDescription( + 'Run scheduler on all (or one specific) TYPO3 instances' + ) + ->addArgument( + 'path', + InputArgument::OPTIONAL, + 'Path to TYPO3 instance' + ); } /** @@ -50,11 +53,13 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { // #################### // Init // #################### - $basePath = $this->getApplication()->getConfigValue('config', 'www_base_path', '/var/www/'); + $basePath = $this->getApplication() + ->getConfigValue('config', 'www_base_path', '/var/www/'); $maxDepth = 3; $basePath = Typo3Utility::guessBestTypo3BasePath($basePath, $input, 'path'); @@ -69,8 +74,8 @@ public function execute(InputInterface $input, OutputInterface $output) { try { $command = new CommandBuilder('php'); $command->addArgument('/typo3/cli_dispatch.phpsh') - ->addArgument('scheduler') - ->executeInteractive(); + ->addArgument('scheduler') + ->executeInteractive(); } catch (\Exception $e) { $output->writeln('Failed TYPO3 scheduler on ' . $dirPath . ''); } diff --git a/src/app/CliTools/Console/Command/User/RebuildSshConfigCommand.php b/src/app/CliTools/Console/Command/User/RebuildSshConfigCommand.php index 8adcf21..b140e67 100644 --- a/src/app/CliTools/Console/Command/User/RebuildSshConfigCommand.php +++ b/src/app/CliTools/Console/Command/User/RebuildSshConfigCommand.php @@ -23,15 +23,16 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class RebuildSshConfigCommand extends \CliTools\Console\Command\AbstractCommand { +class RebuildSshConfigCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('user:rebuildsshconfig') - ->setDescription('Rebuild SSH Config for current user'); + protected function configure() + { + $this->setName('user:rebuildsshconfig') + ->setDescription('Rebuild SSH Config for current user'); } /** @@ -42,7 +43,8 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { $userHome = getenv('HOME'); $userName = getenv('USER'); @@ -50,7 +52,8 @@ public function execute(InputInterface $input, OutputInterface $output) { $targetConfFile = $userHome . '/.ssh/config'; $userConfFile = $userHome . '/.ssh/config.user'; - $reposDirectory = $this->getApplication()->getConfigValue('config', 'ssh_conf_path', '/opt/conf/ssh'); + $reposDirectory = $this->getApplication() + ->getConfigValue('config', 'ssh_conf_path', '/opt/conf/ssh'); $defaultFile = $reposDirectory . '/default.conf'; $defaultUserFile = $userHome . '/.ssh/config.default'; diff --git a/src/app/CliTools/Console/Command/Vagrant/ShareCommand.php b/src/app/CliTools/Console/Command/Vagrant/ShareCommand.php index 2c97fa3..7daa36c 100644 --- a/src/app/CliTools/Console/Command/Vagrant/ShareCommand.php +++ b/src/app/CliTools/Console/Command/Vagrant/ShareCommand.php @@ -22,67 +22,68 @@ use CliTools\Shell\CommandBuilder\CommandBuilder; use CliTools\Shell\CommandBuilder\SelfCommandBuilder; +use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; -use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Output\OutputInterface; -class ShareCommand extends \CliTools\Console\Command\AbstractCommand { +class ShareCommand extends \CliTools\Console\Command\AbstractCommand +{ /** * Configure command */ - protected function configure() { - $this - ->setName('vagrant:share') - ->setDescription('Start share for vagrant') - ->addArgument( - 'name', - InputArgument::OPTIONAL, - 'Specific name for the share' - ) - ->addOption( - 'http', - null, - InputOption::VALUE_REQUIRED, - 'Local HTTP port to forward to' - ) - ->addOption( - 'https', - null, - InputOption::VALUE_REQUIRED, - 'Local HTTPS port to forward to' - ) - ->addOption( - 'name', - null, - InputOption::VALUE_REQUIRED, - 'Specific name for the share' - ) - ->addOption( - 'ssh', - null, - InputOption::VALUE_NONE, - 'Allow \'vagrant connect --ssh\' access' - ) - ->addOption( - 'ssh-no-password', - null, - InputOption::VALUE_NONE, - 'Key won\'t be encrypted with --ssh' - ) - ->addOption( - 'ssh-port', - null, - InputOption::VALUE_REQUIRED, - 'Specific port for SSH when using --ssh' - ) - ->addOption( - '--ssh-once', - null, - InputOption::VALUE_NONE, - 'Allow \'vagrant connect --ssh\' only one time' - ); + protected function configure() + { + $this->setName('vagrant:share') + ->setDescription('Start share for vagrant') + ->addArgument( + 'name', + InputArgument::OPTIONAL, + 'Specific name for the share' + ) + ->addOption( + 'http', + null, + InputOption::VALUE_REQUIRED, + 'Local HTTP port to forward to' + ) + ->addOption( + 'https', + null, + InputOption::VALUE_REQUIRED, + 'Local HTTPS port to forward to' + ) + ->addOption( + 'name', + null, + InputOption::VALUE_REQUIRED, + 'Specific name for the share' + ) + ->addOption( + 'ssh', + null, + InputOption::VALUE_NONE, + 'Allow \'vagrant connect --ssh\' access' + ) + ->addOption( + 'ssh-no-password', + null, + InputOption::VALUE_NONE, + 'Key won\'t be encrypted with --ssh' + ) + ->addOption( + 'ssh-port', + null, + InputOption::VALUE_REQUIRED, + 'Specific port for SSH when using --ssh' + ) + ->addOption( + '--ssh-once', + null, + InputOption::VALUE_NONE, + 'Allow \'vagrant connect --ssh\' only one time' + ); } /** @@ -93,9 +94,10 @@ protected function configure() { * * @return int|null|void */ - public function execute(InputInterface $input, OutputInterface $output) { + public function execute(InputInterface $input, OutputInterface $output) + { - $runningCallback = function($process, $status) { + $runningCallback = function ($process, $status) { static $domainFound = false; if ($domainFound) { return; @@ -113,11 +115,13 @@ public function execute(InputInterface $input, OutputInterface $output) { $domainName = $matches[1]; $typo3Domain = new SelfCommandBuilder(); - $typo3Domain - ->addArgument('typo3:domain') - ->addArgumentTemplate('--remove=%s', '*.vagrantshare.com') - ->addArgumentTemplate('--duplicate=%s', $domainName . '.vagrantshare.com') - ->execute(); + $typo3Domain->addArgument('typo3:domain') + ->addArgumentTemplate( + '--remove=%s', + '*.vagrantshare.com' + ) + ->addArgumentTemplate('--duplicate=%s', $domainName . '.vagrantshare.com') + ->execute(); $domainFound = true; } @@ -126,14 +130,17 @@ public function execute(InputInterface $input, OutputInterface $output) { } }; - $cleanupCallback = function() { + $cleanupCallback = function () { $typo3Domain = new SelfCommandBuilder(); - $typo3Domain - ->addArgument('typo3:domain') - ->addArgumentTemplate('--remove=%s', '*.vagrantshare.com') - ->execute(); + $typo3Domain->addArgument('typo3:domain') + ->addArgumentTemplate( + '--remove=%s', + '*.vagrantshare.com' + ) + ->execute(); }; - $this->getApplication()->registerTearDown($cleanupCallback); + $this->getApplication() + ->registerTearDown($cleanupCallback); $opts = array( 'runningCallback' => $runningCallback, diff --git a/src/app/CliTools/Console/Filter/AnyParameterFilterInterface.php b/src/app/CliTools/Console/Filter/AnyParameterFilterInterface.php index cb8c804..5febac6 100644 --- a/src/app/CliTools/Console/Filter/AnyParameterFilterInterface.php +++ b/src/app/CliTools/Console/Filter/AnyParameterFilterInterface.php @@ -20,6 +20,7 @@ * along with this program. If not, see . */ -interface AnyParameterFilterInterface { +interface AnyParameterFilterInterface +{ } diff --git a/src/app/CliTools/Console/Filter/OnlyRootFilterInterface.php b/src/app/CliTools/Console/Filter/OnlyRootFilterInterface.php index a272ff3..fccd1f0 100644 --- a/src/app/CliTools/Console/Filter/OnlyRootFilterInterface.php +++ b/src/app/CliTools/Console/Filter/OnlyRootFilterInterface.php @@ -20,6 +20,7 @@ * along with this program. If not, see . */ -interface OnlyRootFilterInterface { +interface OnlyRootFilterInterface +{ } diff --git a/src/app/CliTools/Console/Formatter/OutputFormatterStyle.php b/src/app/CliTools/Console/Formatter/OutputFormatterStyle.php index 17024a2..0c4c0b0 100644 --- a/src/app/CliTools/Console/Formatter/OutputFormatterStyle.php +++ b/src/app/CliTools/Console/Formatter/OutputFormatterStyle.php @@ -20,34 +20,35 @@ * along with this program. If not, see . */ -class OutputFormatterStyle extends \Symfony\Component\Console\Formatter\OutputFormatterStyle { +class OutputFormatterStyle extends \Symfony\Component\Console\Formatter\OutputFormatterStyle +{ protected static $availableForegroundColors = array( - 'black' => array('set' => 30, 'unset' => 39), - 'red' => array('set' => 31, 'unset' => 39), - 'green' => array('set' => 32, 'unset' => 39), - 'yellow' => array('set' => 33, 'unset' => 39), - 'blue' => array('set' => 34, 'unset' => 39), + 'black' => array('set' => 30, 'unset' => 39), + 'red' => array('set' => 31, 'unset' => 39), + 'green' => array('set' => 32, 'unset' => 39), + 'yellow' => array('set' => 33, 'unset' => 39), + 'blue' => array('set' => 34, 'unset' => 39), 'magenta' => array('set' => 35, 'unset' => 39), - 'cyan' => array('set' => 36, 'unset' => 39), - 'white' => array('set' => 37, 'unset' => 39), + 'cyan' => array('set' => 36, 'unset' => 39), + 'white' => array('set' => 37, 'unset' => 39), ); protected static $availableBackgroundColors = array( - 'black' => array('set' => 40, 'unset' => 49), - 'red' => array('set' => 41, 'unset' => 49), - 'green' => array('set' => 42, 'unset' => 49), - 'yellow' => array('set' => 43, 'unset' => 49), - 'blue' => array('set' => 44, 'unset' => 49), + 'black' => array('set' => 40, 'unset' => 49), + 'red' => array('set' => 41, 'unset' => 49), + 'green' => array('set' => 42, 'unset' => 49), + 'yellow' => array('set' => 43, 'unset' => 49), + 'blue' => array('set' => 44, 'unset' => 49), 'magenta' => array('set' => 45, 'unset' => 49), - 'cyan' => array('set' => 46, 'unset' => 49), - 'white' => array('set' => 47, 'unset' => 49), + 'cyan' => array('set' => 46, 'unset' => 49), + 'white' => array('set' => 47, 'unset' => 49), ); - protected static $availableOptions = array( - 'bold' => array('set' => 1, 'unset' => 22), + protected static $availableOptions = array( + 'bold' => array('set' => 1, 'unset' => 22), 'underscore' => array('set' => 4, 'unset' => 24), - 'blink' => array('set' => 5, 'unset' => 25), - 'reverse' => array('set' => 7, 'unset' => 27), - 'conceal' => array('set' => 8, 'unset' => 28), + 'blink' => array('set' => 5, 'unset' => 25), + 'reverse' => array('set' => 7, 'unset' => 27), + 'conceal' => array('set' => 8, 'unset' => 28), ); /** @@ -83,7 +84,8 @@ class OutputFormatterStyle extends \Symfony\Component\Console\Formatter\OutputFo * * @param integer|string $padding Padding */ - public function setPadding($padding) { + public function setPadding($padding) + { $this->padding = $padding; } @@ -92,7 +94,8 @@ public function setPadding($padding) { * * @param integer|string $padding Padding */ - public function setPaddingOutside($padding) { + public function setPaddingOutside($padding) + { $this->paddingOutside = $padding; } @@ -101,7 +104,8 @@ public function setPaddingOutside($padding) { * * @param \CliTools\Console\Application $app Application */ - public function setApplication(\CliTools\Console\Application $app) { + public function setApplication(\CliTools\Console\Application $app) + { $this->application = $app; } @@ -110,7 +114,8 @@ public function setApplication(\CliTools\Console\Application $app) { * * @param string $wrap Wrap value */ - public function setWrap($wrap) { + public function setWrap($wrap) + { $this->wrap = $wrap; } @@ -121,7 +126,8 @@ public function setWrap($wrap) { * * @return string */ - public function apply($text) { + public function apply($text) + { $ret = $text; @@ -141,11 +147,11 @@ public function apply($text) { if (!empty($this->wrap)) { list($width) = $this->application->getTerminalDimensions(); - $length = strlen($text); - $wrapLength = (int)($width - $length - 2)/2 * 0.5; + $length = strlen($text); + $wrapLength = (int)($width - $length - 2) / 2 * 0.5; if ($wrapLength >= 1) { - $ret = str_repeat($this->wrap, $wrapLength) . ' '. $ret . ' ' . str_repeat($this->wrap, $wrapLength); + $ret = str_repeat($this->wrap, $wrapLength) . ' ' . $ret . ' ' . str_repeat($this->wrap, $wrapLength); } } diff --git a/src/app/CliTools/Database/DatabaseConnection.php b/src/app/CliTools/Database/DatabaseConnection.php index 900b0e2..3780889 100644 --- a/src/app/CliTools/Database/DatabaseConnection.php +++ b/src/app/CliTools/Database/DatabaseConnection.php @@ -22,7 +22,8 @@ use CliTools\Utility\ConsoleUtility; -class DatabaseConnection { +class DatabaseConnection +{ /** * Database connectiond dsn @@ -59,7 +60,8 @@ class DatabaseConnection { * @param string|null $username Username * @param string|null $password Password */ - public static function setDsn($dsn, $username = null, $password = null) { + public static function setDsn($dsn, $username = null, $password = null) + { if ($dsn !== null) { self::$dbDsn = $dsn; @@ -81,7 +83,8 @@ public static function setDsn($dsn, $username = null, $password = null) { * * @return string */ - public static function getDsn() { + public static function getDsn() + { return self::$dbDsn; } @@ -90,7 +93,8 @@ public static function getDsn() { * * @return string */ - public static function getDbUsername() { + public static function getDbUsername() + { return self::$dbUsername; } @@ -99,7 +103,8 @@ public static function getDbUsername() { * * @return string */ - public static function getDbPassword() { + public static function getDbPassword() + { return self::$dbPassword; } @@ -108,7 +113,8 @@ public static function getDbPassword() { * * @return string */ - public static function getDbHostname() { + public static function getDbHostname() + { return self::parseDsnValue('host'); } @@ -117,7 +123,8 @@ public static function getDbHostname() { * * @return string */ - public static function getDbPort() { + public static function getDbPort() + { return self::parseDsnValue('port'); } @@ -128,7 +135,8 @@ public static function getDbPort() { * @return \PDO * @throws \PDOException */ - public static function getConnection() { + public static function getConnection() + { if (self::$connection === null) { try { @@ -138,11 +146,16 @@ public static function getConnection() { $con->exec('SET NAMES utf8'); $con->exec('SET CHARACTER SET utf8'); // SET SESSION sql_mode = 'STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE' - $con->exec('SET SESSION sql_mode = \'ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE\''); + $con->exec( + 'SET SESSION sql_mode = \'ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE\'' + ); self::$connection = $con; } catch (\Exception $e) { - throw new \PDOException('Cannot connect to "' . self::$dbDsn . '" with user "' . self::$dbUsername . '" and password "' . self::$dbPassword . '", error was:' . $e->getMessage()); + throw new \PDOException( + 'Cannot connect to "' . self::$dbDsn . '" with user "' . self::$dbUsername . '" and password "' . self::$dbPassword . '", error was:' . $e->getMessage( + ) + ); } } @@ -155,10 +168,12 @@ public static function getConnection() { * * @return bool */ - public static function ping() { + public static function ping() + { ConsoleUtility::verboseWriteln('DB::PING', null); try { - self::getConnection()->query('SELECT 1'); + self::getConnection() + ->query('SELECT 1'); } catch (\PDOException $e) { ConsoleUtility::verboseWriteln('DB::QUERY::EXCEPTION', $e); throw $e; @@ -175,11 +190,13 @@ public static function ping() { * @return \PDOStatement * @throws \PDOException */ - public static function query($query) { + public static function query($query) + { ConsoleUtility::verboseWriteln('DB::QUERY', $query); try { - $ret = self::getConnection()->query($query); + $ret = self::getConnection() + ->query($query); } catch (\PDOException $e) { ConsoleUtility::verboseWriteln('DB::QUERY::EXCEPTION', $e); throw $e; @@ -195,7 +212,8 @@ public static function query($query) { * * @throws \PDOException */ - public static function switchDatabase($database) { + public static function switchDatabase($database) + { self::exec('USE ' . self::sanitizeSqlDatabase($database)); } @@ -207,11 +225,13 @@ public static function switchDatabase($database) { * @return int * @throws \PDOException */ - public static function exec($query) { + public static function exec($query) + { ConsoleUtility::verboseWriteln('DB::EXEC', $query); try { - $ret = self::getConnection()->exec($query); + $ret = self::getConnection() + ->exec($query); } catch (\PDOException $e) { ConsoleUtility::verboseWriteln('DB::EXEC::EXCEPTION', $e); throw $e; @@ -230,7 +250,8 @@ public static function exec($query) { * @return int * @throws \PDOException */ - public static function insert($table, $values) { + public static function insert($table, $values) + { $fieldList = array_keys($values); $valueList = array(); @@ -239,7 +260,7 @@ public static function insert($table, $values) { } $query = 'INSERT INTO %s (%s) VALUES (%s)'; - $query = sprintf($query, $table, implode(',',$fieldList), implode(',',$valueList)); + $query = sprintf($query, $table, implode(',', $fieldList), implode(',', $valueList)); self::exec($query); } @@ -251,8 +272,10 @@ public static function insert($table, $values) { * @return string * @throws \PDOException */ - public static function quote($value) { - return self::getConnection()->quote($value); + public static function quote($value) + { + return self::getConnection() + ->quote($value); } @@ -263,7 +286,8 @@ public static function quote($value) { * * @return array */ - public static function quoteArray($valueList) { + public static function quoteArray($valueList) + { $ret = array(); foreach ($valueList as $k => $v) { $ret[$k] = self::quote($v); @@ -279,7 +303,8 @@ public static function quoteArray($valueList) { * * @return mixed|null */ - public static function getOne($query) { + public static function getOne($query) + { $ret = null; $res = self::query($query); @@ -299,7 +324,8 @@ public static function getOne($query) { * @return mixed|null * @throws \PDOException */ - public static function getRow($query) { + public static function getRow($query) + { $ret = null; $res = self::query($query); @@ -319,7 +345,8 @@ public static function getRow($query) { * @return array * @throws \PDOException */ - public static function getAll($query) { + public static function getAll($query) + { $ret = array(); $res = self::query($query); @@ -341,7 +368,8 @@ public static function getAll($query) { * @return array * @throws \PDOException */ - public static function getAllWithIndex($query, $indexCol = null) { + public static function getAllWithIndex($query, $indexCol = null) + { $ret = array(); $res = self::query($query); @@ -369,7 +397,8 @@ public static function getAllWithIndex($query, $indexCol = null) { * @return array * @throws \PDOException */ - public static function getCol($query) { + public static function getCol($query) + { $ret = array(); $res = self::query($query); @@ -389,7 +418,8 @@ public static function getCol($query) { * @return array * @throws \PDOException */ - public static function getColWithIndex($query) { + public static function getColWithIndex($query) + { $ret = array(); $res = self::query($query); @@ -410,7 +440,8 @@ public static function getColWithIndex($query) { * @return array * @throws \PDOException */ - public static function getList($query) { + public static function getList($query) + { $ret = array(); $res = self::query($query); @@ -428,14 +459,16 @@ public static function getList($query) { * Check if database exists * * @param string $database Database name + * * @return boolean */ - public static function databaseExists($database) { + public static function databaseExists($database) + { $query = 'SELECT COUNT(*) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = %s'; $query = sprintf($query, self::quote($database)); $ret = (int)self::getOne($query); - return ($ret === 1 ); + return ($ret === 1); } /** @@ -443,7 +476,8 @@ public static function databaseExists($database) { * * @return array */ - public static function databaseList() { + public static function databaseList() + { // Get list of databases $query = 'SELECT SCHEMA_NAME FROM information_schema.SCHEMATA'; $ret = DatabaseConnection::getCol($query); @@ -458,9 +492,11 @@ public static function databaseList() { * Return list of tables of one database * * @param string $database Database name + * * @return array */ - public static function tableList($database) { + public static function tableList($database) + { $query = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = %s'; $query = sprintf($query, self::quote($database)); $ret = self::getCol($query); @@ -474,11 +510,13 @@ public static function tableList($database) { * * @param string $database Database name * @param string $table Table name + * * @return boolean */ - public static function tableExists($database, $table) { + public static function tableExists($database, $table) + { $query = 'SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s'; - $query = sprintf($query, self::quote($database), self::quote($table) ); + $query = sprintf($query, self::quote($database), self::quote($table)); $ret = (bool)self::getOne($query); return $ret; @@ -487,21 +525,24 @@ public static function tableExists($database, $table) { /** * Begin transaction */ - public static function beginTransaction() { + public static function beginTransaction() + { self::exec('BEGIN TRANSACTION'); } /** * Commit transaction */ - public static function commit() { + public static function commit() + { self::exec('COMMIT'); } /** * Rollback transaction */ - public static function rollback() { + public static function rollback() + { self::exec('ROLLBACK'); } @@ -516,7 +557,8 @@ public static function rollback() { * * @return string */ - public static function addCondition($condition) { + public static function addCondition($condition) + { $ret = ' '; if (!empty($condition)) { @@ -539,7 +581,8 @@ public static function addCondition($condition) { * * @return string */ - public static function conditionIn($field, $values, $required = true) { + public static function conditionIn($field, $values, $required = true) + { if (!empty($values)) { $quotedValues = self::quoteArray($values); @@ -564,7 +607,8 @@ public static function conditionIn($field, $values, $required = true) { * * @return string */ - public static function conditionNotIn($field, $values, $required = true) { + public static function conditionNotIn($field, $values, $required = true) + { if (!empty($values)) { $quotedValues = self::quoteArray($values); @@ -587,7 +631,8 @@ public static function conditionNotIn($field, $values, $required = true) { * * @return string */ - public static function sanitizeSqlField($field) { + public static function sanitizeSqlField($field) + { $field = preg_replace('/[\0\\\\\/]/', '', $field); // Rule: Database, table, and column names cannot end with space characters. @@ -603,7 +648,8 @@ public static function sanitizeSqlField($field) { * * @return string */ - public static function sanitizeSqlTable($table) { + public static function sanitizeSqlTable($table) + { return '`' . self::sanitizeSqlIdentifier($table) . '`'; } @@ -614,7 +660,8 @@ public static function sanitizeSqlTable($table) { * * @return string */ - public static function sanitizeSqlDatabase($database) { + public static function sanitizeSqlDatabase($database) + { return '`' . self::sanitizeSqlIdentifier($database) . '`'; } @@ -625,7 +672,8 @@ public static function sanitizeSqlDatabase($database) { * * @return string */ - public static function sanitizeSqlIdentifier($value) { + public static function sanitizeSqlIdentifier($value) + { $ret = preg_replace('/[\0\\\\\/\.]/', '', $value); // Rule: Database, table, and column names cannot end with space characters. @@ -639,9 +687,11 @@ public static function sanitizeSqlIdentifier($value) { * * @param string $key DSN Key * @param string|null $default Default value + * * @return string|null */ - protected static function parseDsnValue($key, $default = NULL) { + protected static function parseDsnValue($key, $default = null) + { $ret = $default; $pattern = sprintf('~%s=([^;]*)(?:;|$)~', preg_quote($key, '~')); diff --git a/src/app/CliTools/Exception/CommandExecutionException.php b/src/app/CliTools/Exception/CommandExecutionException.php index 9fa52d5..abbba22 100644 --- a/src/app/CliTools/Exception/CommandExecutionException.php +++ b/src/app/CliTools/Exception/CommandExecutionException.php @@ -22,7 +22,8 @@ use CliTools\Shell\CommandBuilder\CommandBuilderInterface; -class CommandExecutionException extends \RuntimeException { +class CommandExecutionException extends \RuntimeException +{ /** * Return code from cli command @@ -43,7 +44,8 @@ class CommandExecutionException extends \RuntimeException { * * @return integer */ - public function getReturnCode() { + public function getReturnCode() + { return $this->returnCode; } @@ -52,7 +54,8 @@ public function getReturnCode() { * * @param integer $returnCode */ - public function setReturnCode($returnCode) { + public function setReturnCode($returnCode) + { $this->returnCode = $returnCode; } @@ -61,7 +64,8 @@ public function setReturnCode($returnCode) { * * @return CommandBuilderInterface|null */ - public function getCommand() { + public function getCommand() + { return $this->command; } @@ -70,7 +74,8 @@ public function getCommand() { * * @param CommandBuilderInterface $command */ - public function setCommand(CommandBuilderInterface $command) { + public function setCommand(CommandBuilderInterface $command) + { $this->command = $command; } diff --git a/src/app/CliTools/Exception/StopException.php b/src/app/CliTools/Exception/StopException.php index 0d565b8..92f6cd3 100644 --- a/src/app/CliTools/Exception/StopException.php +++ b/src/app/CliTools/Exception/StopException.php @@ -20,6 +20,7 @@ * along with this program. If not, see . */ -class StopException extends \RuntimeException { +class StopException extends \RuntimeException +{ } diff --git a/src/app/CliTools/Iterator/Filter/DirectoryFilter.php b/src/app/CliTools/Iterator/Filter/DirectoryFilter.php index 45e0936..6b32218 100644 --- a/src/app/CliTools/Iterator/Filter/DirectoryFilter.php +++ b/src/app/CliTools/Iterator/Filter/DirectoryFilter.php @@ -20,14 +20,16 @@ * along with this program. If not, see . */ -class DirectoryFilter extends \FilterIterator { +class DirectoryFilter extends \FilterIterator +{ /** * Filter for directories * * @return bool */ - public function accept() { + public function accept() + { /** @var \DirectoryIterator $dirEntry */ $dirEntry = $this->current(); diff --git a/src/app/CliTools/Iterator/Filter/ProcProcessDirectoryFilter.php b/src/app/CliTools/Iterator/Filter/ProcProcessDirectoryFilter.php index 2e2db72..c1c614e 100644 --- a/src/app/CliTools/Iterator/Filter/ProcProcessDirectoryFilter.php +++ b/src/app/CliTools/Iterator/Filter/ProcProcessDirectoryFilter.php @@ -20,14 +20,16 @@ * along with this program. If not, see . */ -class ProcProcessDirectoryFilter extends DirectoryFilter { +class ProcProcessDirectoryFilter extends DirectoryFilter +{ /** * Filter process directories in /proc/ * * @return bool */ - public function accept() { + public function accept() + { if (!parent::accept()) { return false; } diff --git a/src/app/CliTools/Iterator/Filter/RecursiveDirectoryFilter.php b/src/app/CliTools/Iterator/Filter/RecursiveDirectoryFilter.php index e8f729d..465a4f1 100644 --- a/src/app/CliTools/Iterator/Filter/RecursiveDirectoryFilter.php +++ b/src/app/CliTools/Iterator/Filter/RecursiveDirectoryFilter.php @@ -20,14 +20,16 @@ * along with this program. If not, see . */ -class RecursiveDirectoryFilter extends \RecursiveFilterIterator { +class RecursiveDirectoryFilter extends \RecursiveFilterIterator +{ /** * Filter for directories * * @return bool */ - public function accept() { + public function accept() + { /** @var \DirectoryIterator $dirEntry */ $dirEntry = $this->current(); diff --git a/src/app/CliTools/Iterator/Filter/Typo3RecursiveDirectoryFilter.php b/src/app/CliTools/Iterator/Filter/Typo3RecursiveDirectoryFilter.php index 1beae1c..e3ca107 100644 --- a/src/app/CliTools/Iterator/Filter/Typo3RecursiveDirectoryFilter.php +++ b/src/app/CliTools/Iterator/Filter/Typo3RecursiveDirectoryFilter.php @@ -20,7 +20,8 @@ * along with this program. If not, see . */ -class Typo3RecursiveDirectoryFilter extends \CliTools\Iterator\Filter\RecursiveDirectoryFilter { +class Typo3RecursiveDirectoryFilter extends \CliTools\Iterator\Filter\RecursiveDirectoryFilter +{ /** * List of directories which will be ignored (for sub search) @@ -50,7 +51,8 @@ class Typo3RecursiveDirectoryFilter extends \CliTools\Iterator\Filter\RecursiveD * * @return bool */ - public function accept() { + public function accept() + { if (!parent::accept()) { return false; } diff --git a/src/app/CliTools/Reader/ConfigReader.php b/src/app/CliTools/Reader/ConfigReader.php index fa4ce16..52c4826 100644 --- a/src/app/CliTools/Reader/ConfigReader.php +++ b/src/app/CliTools/Reader/ConfigReader.php @@ -20,7 +20,8 @@ * along with this program. If not, see . */ -class ConfigReader implements \ArrayAccess { +class ConfigReader implements \ArrayAccess +{ /** * Data storage @@ -34,7 +35,8 @@ class ConfigReader implements \ArrayAccess { * * @param array $data Data configuration */ - public function __construct(array $data = null) { + public function __construct(array $data = null) + { if ($data !== null) { $this->setData($data); } @@ -45,7 +47,8 @@ public function __construct(array $data = null) { * * @param array $data Data configuration */ - public function setData(array $data) { + public function setData(array $data) + { $this->data = $data; } @@ -53,9 +56,11 @@ public function setData(array $data) { * Get value from specific node (dotted array notation) * * @param string|null $path Path to node (eg. foo.bar.baz) + * * @return mixed|null */ - public function get($path = null) { + public function get($path = null) + { return $this->getNode($path); } @@ -63,9 +68,11 @@ public function get($path = null) { * Get array value from specific node (dotted array notation) * * @param string|null $path Path to node (eg. foo.bar.baz) + * * @return array|null */ - public function getArray($path = null) { + public function getArray($path = null) + { $ret = $this->getNode($path); if (!is_array($ret)) { @@ -79,9 +86,11 @@ public function getArray($path = null) { * Get list of keys from specific node (dotted array notation) * * @param string|null $path Path to node (eg. foo.bar.baz) + * * @return array|null */ - public function getList($path = null) { + public function getList($path = null) + { $ret = $this->getNode($path); if (is_array($ret)) { @@ -99,7 +108,8 @@ public function getList($path = null) { * @param string $path Path to node (eg. foo.bar.baz) * @param mixed $value Value to set */ - public function set($path, $value) { + public function set($path, $value) + { $node =& $this->getNode($path); $node = $value; } @@ -107,9 +117,10 @@ public function set($path, $value) { /** * Clear value at specific node (dotted array notation) * - * @param null|string $path Path to node (eg. foo.bar.baz) + * @param null|string $path Path to node (eg. foo.bar.baz) */ - public function clear($path = null) { + public function clear($path = null) + { $node =& $this->getNode($path); $node = null; } @@ -118,9 +129,11 @@ public function clear($path = null) { * Check if specific node exists * * @param null|string $path Path to node (eg. foo.bar.baz) + * * @return bool */ - public function exists($path = null) { + public function exists($path = null) + { return ($this->getNode($path) !== null); } @@ -128,9 +141,11 @@ public function exists($path = null) { * Get node by reference * * @param string|null $path Path to node (eg. foo.bar.baz) + * * @return mixed|null */ - protected function &getNode($path) { + protected function &getNode($path) + { $data = &$this->data; if ($path !== null) { @@ -159,7 +174,8 @@ protected function &getNode($path) { * @param string $offset Array key * @param mixed $value Value */ - public function offsetSet($offset, $value) { + public function offsetSet($offset, $value) + { if ($offset === null) { $this->data[] = $value; } else { @@ -171,9 +187,11 @@ public function offsetSet($offset, $value) { * Array accessor: Check if offset exists * * @param string $offset Array key + * * @return boolean */ - public function offsetExists($offset) { + public function offsetExists($offset) + { return isset($this->data[$offset]); } @@ -182,7 +200,8 @@ public function offsetExists($offset) { * * @param string $offset Array key */ - public function offsetUnset($offset) { + public function offsetUnset($offset) + { unset($this->data[$offset]); } @@ -190,9 +209,11 @@ public function offsetUnset($offset) { * Array accessor: Get value at offset * * @param string $offset Array key + * * @return mixed */ - public function offsetGet($offset) { + public function offsetGet($offset) + { return isset($this->data[$offset]) ? $this->data[$offset] : null; } diff --git a/src/app/CliTools/Service/SelfUpdateService.php b/src/app/CliTools/Service/SelfUpdateService.php index 89a34c4..8b899fb 100644 --- a/src/app/CliTools/Service/SelfUpdateService.php +++ b/src/app/CliTools/Service/SelfUpdateService.php @@ -22,7 +22,8 @@ * along with this program. If not, see . */ -class SelfUpdateService { +class SelfUpdateService +{ /** * Github repo url * @@ -102,7 +103,8 @@ class SelfUpdateService { * @param $app * @param $output */ - public function __construct($app, $output) { + public function __construct($app, $output) + { $this->application = $app; $this->output = $output; @@ -114,8 +116,10 @@ public function __construct($app, $output) { * * @return $this */ - public function enablePreVersions() { + public function enablePreVersions() + { $this->updateAllowPreRelease = true; + return $this; } @@ -124,9 +128,11 @@ public function enablePreVersions() { * * @return $this */ - public function enableUpdateFallback() { + public function enableUpdateFallback() + { $this->updateUrl = $this->application->getConfigValue('config', 'update_fallback_url', null); $this->updateVersion = 'fallback'; + return $this; } @@ -135,7 +141,8 @@ public function enableUpdateFallback() { * * @return boolean */ - public function isElevationNeeded() { + public function isElevationNeeded() + { $ret = false; if (posix_getuid() !== $this->cliToolsCommandPerms['owner']) { @@ -150,7 +157,8 @@ public function isElevationNeeded() { * * @param boolean $force Force update */ - public function update($force = false) { + public function update($force = false) + { // Only ask for github if update url is not set if (!$this->updateUrl) { @@ -174,7 +182,8 @@ public function update($force = false) { * * @return bool */ - protected function checkIfUpdateNeeded($force) { + protected function checkIfUpdateNeeded($force) + { $ret = false; $this->output->write('Checking version... '); @@ -201,7 +210,8 @@ protected function checkIfUpdateNeeded($force) { /** * Do update */ - protected function doUpdate() { + protected function doUpdate() + { if (empty($this->updateUrl)) { throw new \RuntimeException('Self-Update url is not found'); } @@ -234,7 +244,9 @@ protected function doUpdate() { // Version $this->output->writeln(''); - $this->output->writeln('Updated from Version ' . CLITOOLS_COMMAND_VERSION . ' to ' . $this->updateVersion . ''); + $this->output->writeln( + 'Updated from Version ' . CLITOOLS_COMMAND_VERSION . ' to ' . $this->updateVersion . '' + ); $this->output->writeln(''); // Changelog @@ -251,7 +263,8 @@ protected function doUpdate() { /** * Fetch latest release from github api */ - protected function fetchLatestReleaseFromGithub() { + protected function fetchLatestReleaseFromGithub() + { $this->output->write('Getting informations from GitHub... '); $releaseList = \CliTools\Utility\PhpUtility::curlFetch($this->githubReleaseUrl); @@ -298,22 +311,28 @@ protected function fetchLatestReleaseFromGithub() { $this->output->writeln('done'); } else { $this->output->writeln('failed'); - throw new \RuntimeException('Could not fetch new version - maybe GitHub API is down or other error occurred'); + throw new \RuntimeException( + 'Could not fetch new version - maybe GitHub API is down or other error occurred' + ); } } /** * Show changelog */ - protected function showChangelog() { + protected function showChangelog() + { $message = $this->updateChangelog; // Pad lines $message = explode("\n", $message); - $message = array_map(function($line) { - return ' ' . $line; - }, $message); + $message = array_map( + function ($line) { + return ' ' . $line; + }, + $message + ); $message = implode("\n", $message); $message = preg_replace('/`([^`]+)`/', '\1', $message); @@ -326,7 +345,8 @@ protected function showChangelog() { /** * Get current file informations= */ - protected function collectInformations() { + protected function collectInformations() + { $this->output->writeln('Collecting informations...'); // ################## @@ -351,21 +371,22 @@ protected function collectInformations() { // ################## // Set github defaults // ################## - $this->githubRepo = $this->application->getConfigValue('config', 'github_repo', null); + $this->githubRepo = $this->application->getConfigValue('config', 'github_repo', null); $this->githubReleaseUrl = 'https://api.github.com/repos/' . $this->githubRepo . '/releases'; } /** * Download file */ - protected function downloadUpdate() { + protected function downloadUpdate() + { $output = $this->output; // Progress counter - $progress = function($downloadTotal, $downoadProgress) use ($output) { + $progress = function ($downloadTotal, $downoadProgress) use ($output) { static $counter = 0; - if($counter % 30 === 0) { + if ($counter % 30 === 0) { $output->write('.'); } @@ -383,7 +404,8 @@ protected function downloadUpdate() { /** * Deploy update */ - protected function deployUpdate() { + protected function deployUpdate() + { // ################## // Backup @@ -422,19 +444,25 @@ protected function deployUpdate() { * * @return string */ - protected function testUpdate() { + protected function testUpdate() + { $command = new CommandBuilder('php'); - $ret = $command->addArgument($this->cliToolsUpdatePath) - ->addArgument('--version') - ->addArgument('--no-ansi') - ->execute()->getOutputString(); + $ret = $command->addArgument($this->cliToolsUpdatePath) + ->addArgument('--version') + ->addArgument( + '--no-ansi' + ) + ->execute() + ->getOutputString(); + return $ret; } /** * Cleanup */ - protected function cleanup() { + protected function cleanup() + { // Remove old update file if set and exists if ($this->cliToolsUpdatePath && file_exists($this->cliToolsUpdatePath)) { unlink($this->cliToolsUpdatePath); diff --git a/src/app/CliTools/Service/SettingsService.php b/src/app/CliTools/Service/SettingsService.php index 6993e1a..6bb847d 100644 --- a/src/app/CliTools/Service/SettingsService.php +++ b/src/app/CliTools/Service/SettingsService.php @@ -20,7 +20,8 @@ * along with this program. If not, see . */ -class SettingsService { +class SettingsService +{ /** * Path to settings file @@ -39,7 +40,8 @@ class SettingsService { /** * Constructor */ - public function __construct() { + public function __construct() + { $this->settingsPath = getenv('HOME') . '/.clitools.state'; $this->load(); } @@ -47,10 +49,11 @@ public function __construct() { /** * Set value * - * @param string $key Setting key - * @param mixed $value Value + * @param string $key Setting key + * @param mixed $value Value */ - public function set($key, $value) { + public function set($key, $value) + { $this->values[$key] = $value; } @@ -61,7 +64,8 @@ public function set($key, $value) { * * @return null|mixed */ - public function get($key) { + public function get($key) + { $ret = null; if (array_key_exists($key, $this->values)) { @@ -74,9 +78,10 @@ public function get($key) { /** * Load settings from .clitool.state file */ - public function load() { + public function load() + { if (file_exists($this->settingsPath)) { - $content = file_get_contents($this->settingsPath); + $content = file_get_contents($this->settingsPath); $this->values = json_decode($content, true); } } @@ -84,7 +89,8 @@ public function load() { /** * Store settings to .clitool.state file */ - public function store() { + public function store() + { file_put_contents($this->settingsPath, json_encode($this->values)); } } diff --git a/src/app/CliTools/Shell/CommandBuilder/AbstractCommandBuilder.php b/src/app/CliTools/Shell/CommandBuilder/AbstractCommandBuilder.php index 8bc47ad..15da88e 100644 --- a/src/app/CliTools/Shell/CommandBuilder/AbstractCommandBuilder.php +++ b/src/app/CliTools/Shell/CommandBuilder/AbstractCommandBuilder.php @@ -22,7 +22,8 @@ use CliTools\Shell\Executor; -class AbstractCommandBuilder implements CommandBuilderInterface { +class AbstractCommandBuilder implements CommandBuilderInterface +{ // ########################################## // Constants @@ -31,7 +32,7 @@ class AbstractCommandBuilder implements CommandBuilderInterface { /** * Redirect STDOUT and STDERR to /dev/null (no output) */ - const OUTPUT_REDIRECT_NULL = ' &> /dev/null'; + const OUTPUT_REDIRECT_NULL = ' &> /dev/null'; /** * Redirect STDERR to STDOUT @@ -41,7 +42,7 @@ class AbstractCommandBuilder implements CommandBuilderInterface { /** * Redirect STDERR to /dev/null (no error output) */ - const OUTPUT_REDIRECT_NO_STDERR = ' 2> /dev/null'; + const OUTPUT_REDIRECT_NO_STDERR = ' 2> /dev/null'; // ########################################## // Attributs @@ -89,11 +90,12 @@ class AbstractCommandBuilder implements CommandBuilderInterface { /** * Constructor * - * @param null|string $command Command - * @param null|string|array $args Arguments - * @param null|array $argParams Argument params (sprintf) + * @param null|string $command Command + * @param null|string|array $args Arguments + * @param null|array $argParams Argument params (sprintf) */ - public function __construct($command = null, $args = null, $argParams = null) { + public function __construct($command = null, $args = null, $argParams = null) + { $this->initialize(); if ($command !== null) { @@ -123,14 +125,15 @@ public function __construct($command = null, $args = null, $argParams = null) { /** * Initalized command */ - protected function initialize() { - + protected function initialize() + { } /** * @return string */ - public function getCommand() { + public function getCommand() + { return $this->command; } @@ -138,10 +141,13 @@ public function getCommand() { * Set command * * @param string $command + * * @return $this */ - public function setCommand($command) { + public function setCommand($command) + { $this->command = $command; + return $this; } @@ -150,11 +156,13 @@ public function setCommand($command) { * * @return $this */ - public function clear() { + public function clear() + { $this->command = null; $this->argumentList = array(); $this->outputRedirect = null; $this->pipeList = array(); + return $this; } @@ -163,8 +171,10 @@ public function clear() { * * @return $this */ - public function clearArguments() { + public function clearArguments() + { $this->argumentList = array(); + return $this; } @@ -173,8 +183,10 @@ public function clearArguments() { * * @return $this */ - public function addArgumentSeparator() { + public function addArgumentSeparator() + { $this->argumentList[] = '--'; + return $this; } @@ -182,53 +194,63 @@ public function addArgumentSeparator() { * Set argument from list * * @param array $args Arguments + * * @return $this */ - public function setArgumentList(array $args) { + public function setArgumentList(array $args) + { $this->clearArguments(); $this->appendArgumentsToList($args); + return $this; } /** * Set arguments raw (unescaped) * - * @param string $arg... Argument + * @param string $arg ... Argument + * * @return $this */ - public function addArgumentRaw($arg) { + public function addArgumentRaw($arg) + { return $this->addArgumentList(func_get_args(), false); } /** * Set arguments list raw (unescaped) * - * @param array $arg... Argument + * @param array $arg ... Argument + * * @return $this */ - public function addArgumentListRaw($arg) { + public function addArgumentListRaw($arg) + { return $this->addArgumentList($arg, false); } /** * Set arguments * - * @param string $arg... Argument + * @param string $arg ... Argument + * * @return $this */ - public function addArgument($arg) { + public function addArgument($arg) + { return $this->addArgumentList(func_get_args()); } /** * Add argument with template * - * @param string $arg Argument sprintf - * @param string $params... Argument parameters + * @param string $arg Argument sprintf + * @param string $params ... Argument parameters * * @return $this */ - public function addArgumentTemplate($arg, $params) { + public function addArgumentTemplate($arg, $params) + { $funcArgs = func_get_args(); array_shift($funcArgs); @@ -238,12 +260,13 @@ public function addArgumentTemplate($arg, $params) { /** * Add argument with template multiple times * - * @param string $arg Argument sprintf - * @param array $paramList Argument parameters + * @param string $arg Argument sprintf + * @param array $paramList Argument parameters * * @return $this */ - public function addArgumentTemplateMultiple($arg, $paramList) { + public function addArgumentTemplateMultiple($arg, $paramList) + { foreach ($paramList as $param) { $this->addArgumentTemplate($arg, $param); } @@ -254,28 +277,33 @@ public function addArgumentTemplateMultiple($arg, $paramList) { /** * Set argument with template * - * @param string $arg Argument sprintf - * @param array $params Argument parameters + * @param string $arg Argument sprintf + * @param array $params Argument parameters * * @return $this */ - public function addArgumentTemplateList($arg, array $params) { + public function addArgumentTemplateList($arg, array $params) + { $this->validateArgumentValue($arg); - $params = array_map('escapeshellarg', $params); + $params = array_map('escapeshellarg', $params); $this->argumentList[] = vsprintf($arg, $params); + return $this; } /** * Add arguments list * - * @param array $arg Argument + * @param array $arg Argument * @param boolean $escape Escape shell arguments + * * @return $this */ - public function addArgumentList(array $arg, $escape = true) { + public function addArgumentList(array $arg, $escape = true) + { $this->appendArgumentsToList($arg, $escape); + return $this; } @@ -287,7 +315,8 @@ public function addArgumentList(array $arg, $escape = true) { * * @return $this */ - protected function appendArgumentToList($arg, $escape = true) { + protected function appendArgumentToList($arg, $escape = true) + { $this->validateArgumentValue($arg); if ($escape) { @@ -300,12 +329,13 @@ protected function appendArgumentToList($arg, $escape = true) { /** * Append multiple arguments to list * - * @param array $args Arguments + * @param array $args Arguments * @param boolean $escape Enable argument escaping * * @return $this */ - protected function appendArgumentsToList($args, $escape = true) { + protected function appendArgumentsToList($args, $escape = true) + { // Validate each argument value array_walk($args, array($this, 'validateArgumentValue')); @@ -321,7 +351,8 @@ protected function appendArgumentsToList($args, $escape = true) { * * @return array */ - public function getArgumentList() { + public function getArgumentList() + { return $this->argumentList; } @@ -330,7 +361,8 @@ public function getArgumentList() { * * @return null|string */ - public function getOutputRedirect() { + public function getOutputRedirect() + { return $this->outputRedirect; } @@ -338,10 +370,13 @@ public function getOutputRedirect() { * Set output (stdout and/or stderr) redirection * * @param null|string $outputRedirect + * * @return $this */ - public function setOutputRedirect($outputRedirect = null) { + public function setOutputRedirect($outputRedirect = null) + { $this->outputRedirect = $outputRedirect; + return $this; } @@ -350,10 +385,13 @@ public function setOutputRedirect($outputRedirect = null) { * Redirect command stdout output to file * * @param string $filename Filename + * * @return $this */ - public function setOutputRedirectToFile($filename) { + public function setOutputRedirectToFile($filename) + { $this->outputRedirect = '> ' . escapeshellarg($filename); + return $this; } @@ -362,8 +400,10 @@ public function setOutputRedirectToFile($filename) { * * @return $this */ - public function clearOutputRedirect() { + public function clearOutputRedirect() + { $this->outputRedirect = null; + return $this; } @@ -373,9 +413,11 @@ public function clearOutputRedirect() { * WARNING: Not safe! * * @param string $str Command string + * * @return $this */ - public function parse($str) { + public function parse($str) + { $parsedCmd = explode(' ', $str, 2); // Check required command @@ -390,6 +432,7 @@ public function parse($str) { if (!empty($parsedCmd[1])) { $this->addArgumentRaw($parsedCmd[1]); } + return $this; } @@ -397,12 +440,13 @@ public function parse($str) { /** * Append another command builder * - * @param CommandBuilderInterface $command Command builder - * @param boolean $inline Add command as inline string (one big parameter) + * @param CommandBuilderInterface $command Command builder + * @param boolean $inline Add command as inline string (one big parameter) * * @return $this */ - public function append(CommandBuilderInterface $command, $inline = true) { + public function append(CommandBuilderInterface $command, $inline = true) + { // Check if sub command is executeable if (!$command->isExecuteable()) { @@ -414,7 +458,7 @@ public function append(CommandBuilderInterface $command, $inline = true) { $this->addArgument($command->build()); } else { // Append each as own argument - $this->addArgument( $command->command ); + $this->addArgument($command->command); $this->argumentList = array_merge($this->argumentList, $command->argumentList); } @@ -426,14 +470,18 @@ public function append(CommandBuilderInterface $command, $inline = true) { * * @return bool */ - public function isExecuteable() { + public function isExecuteable() + { // Command must be set if (empty($this->command)) { return false; } // Only check command paths for local commands - if (!($this instanceof RemoteCommandBuilder) && !\CliTools\Utility\UnixUtility::checkExecutable($this->command)) { + if (!($this instanceof RemoteCommandBuilder) && !\CliTools\Utility\UnixUtility::checkExecutable( + $this->command + ) + ) { return false; } @@ -446,7 +494,8 @@ public function isExecuteable() { * * @return array */ - public function getPipeList() { + public function getPipeList() + { return $this->pipeList; } @@ -454,10 +503,13 @@ public function getPipeList() { * Set pipe list * * @param array $pipeList + * * @return $this */ - public function setPipeList(array $pipeList) { + public function setPipeList(array $pipeList) + { $this->pipeList = $pipeList; + return $this; } @@ -466,8 +518,10 @@ public function setPipeList(array $pipeList) { * * @return $this */ - public function clearPipes() { + public function clearPipes() + { $this->pipeList = array(); + return $this; } @@ -475,10 +529,13 @@ public function clearPipes() { * Add pipe command * * @param CommandBuilderInterface $command + * * @return $this */ - public function addPipeCommand(CommandBuilderInterface $command) { + public function addPipeCommand(CommandBuilderInterface $command) + { $this->pipeList[] = $command; + return $this; } @@ -488,11 +545,14 @@ public function addPipeCommand(CommandBuilderInterface $command) { * @return string * @throws \Exception */ - public function build() { + public function build() + { $ret = array(); if (!$this->isExecuteable()) { - throw new \RuntimeException('Command "' . $this->getCommand() . '" is not executable or available, please install it'); + throw new \RuntimeException( + 'Command "' . $this->getCommand() . '" is not executable or available, please install it' + ); } // Add command @@ -523,7 +583,8 @@ public function build() { * * @return Executor */ - public function getExecutor() { + public function getExecutor() + { if ($this->executor === null) { $this->executor = new Executor($this); } @@ -536,7 +597,8 @@ public function getExecutor() { * * @param Executor $executor */ - public function setExecutor(Executor $executor) { + public function setExecutor(Executor $executor) + { $this->executor = $executor; } @@ -545,27 +607,34 @@ public function setExecutor(Executor $executor) { * * @return Executor */ - public function execute() { - return $this->getExecutor()->execute(); + public function execute() + { + return $this->getExecutor() + ->execute(); } /** * Execute command * * @param array $opts Option array + * * @return Executor */ - public function executeInteractive(array $opts = null) { - return $this->getExecutor()->execInteractive($opts); + public function executeInteractive(array $opts = null) + { + return $this->getExecutor() + ->execInteractive($opts); } /** * Validate argument value * * @param mixed $value Value + * * @throws \RuntimeException */ - protected function validateArgumentValue($value) { + protected function validateArgumentValue($value) + { if (strlen($value) === 0) { throw new \RuntimeException('Argument value cannot be empty'); } @@ -578,7 +647,8 @@ protected function validateArgumentValue($value) { /** * Clone command */ - public function __clone() { + public function __clone() + { if (!empty($this->executor)) { $this->executor = clone $this->executor; } @@ -589,7 +659,8 @@ public function __clone() { * * @return string */ - public function __toString() { + public function __toString() + { return $this->build(); } diff --git a/src/app/CliTools/Shell/CommandBuilder/CommandBuilder.php b/src/app/CliTools/Shell/CommandBuilder/CommandBuilder.php index 2757325..40b7275 100644 --- a/src/app/CliTools/Shell/CommandBuilder/CommandBuilder.php +++ b/src/app/CliTools/Shell/CommandBuilder/CommandBuilder.php @@ -20,6 +20,7 @@ * along with this program. If not, see . */ -class CommandBuilder extends AbstractCommandBuilder { +class CommandBuilder extends AbstractCommandBuilder +{ } diff --git a/src/app/CliTools/Shell/CommandBuilder/CommandBuilderInterface.php b/src/app/CliTools/Shell/CommandBuilder/CommandBuilderInterface.php index cfa3b59..ba72be8 100644 --- a/src/app/CliTools/Shell/CommandBuilder/CommandBuilderInterface.php +++ b/src/app/CliTools/Shell/CommandBuilder/CommandBuilderInterface.php @@ -20,9 +20,8 @@ * along with this program. If not, see . */ -use CliTools\Shell\Executor; - -interface CommandBuilderInterface { +interface CommandBuilderInterface +{ /** * @return string */ diff --git a/src/app/CliTools/Shell/CommandBuilder/EditorCommandBuilder.php b/src/app/CliTools/Shell/CommandBuilder/EditorCommandBuilder.php index 53a9b1f..16a3dc6 100644 --- a/src/app/CliTools/Shell/CommandBuilder/EditorCommandBuilder.php +++ b/src/app/CliTools/Shell/CommandBuilder/EditorCommandBuilder.php @@ -20,14 +20,16 @@ * along with this program. If not, see . */ -class EditorCommandBuilder extends CommandBuilder { +class EditorCommandBuilder extends CommandBuilder +{ /** * Initalized command * * @throws \RuntimeException */ - protected function initialize() { + protected function initialize() + { parent::initialize(); $editorCmd = getenv('EDITOR'); diff --git a/src/app/CliTools/Shell/CommandBuilder/FullSelfCommandBuilder.php b/src/app/CliTools/Shell/CommandBuilder/FullSelfCommandBuilder.php index 5b1e384..8292b5c 100644 --- a/src/app/CliTools/Shell/CommandBuilder/FullSelfCommandBuilder.php +++ b/src/app/CliTools/Shell/CommandBuilder/FullSelfCommandBuilder.php @@ -20,13 +20,15 @@ * along with this program. If not, see . */ -class FullSelfCommandBuilder extends CommandBuilder { +class FullSelfCommandBuilder extends CommandBuilder +{ /** * Initalized command */ - protected function initialize() { + protected function initialize() + { parent::initialize(); $arguments = $_SERVER['argv']; diff --git a/src/app/CliTools/Shell/CommandBuilder/MysqlCommandBuilder.php b/src/app/CliTools/Shell/CommandBuilder/MysqlCommandBuilder.php index 5495199..d1e0da1 100644 --- a/src/app/CliTools/Shell/CommandBuilder/MysqlCommandBuilder.php +++ b/src/app/CliTools/Shell/CommandBuilder/MysqlCommandBuilder.php @@ -20,17 +20,24 @@ * along with this program. If not, see . */ -class MysqlCommandBuilder extends CommandBuilder { +class MysqlCommandBuilder extends CommandBuilder +{ /** * Initalized command */ - protected function initialize() { - $this - ->addArgumentTemplate('--user=%s', DatabaseConnection::getDbUsername()) - ->addArgumentTemplate('--password=%s', DatabaseConnection::getDbPassword()) - ->addArgumentTemplate('--host=%s', DatabaseConnection::getDbHostname()) - ->addArgumentTemplate('--port=%s', DatabaseConnection::getDbPort()); + protected function initialize() + { + $this->addArgumentTemplate('--user=%s', DatabaseConnection::getDbUsername()) + ->addArgumentTemplate( + '--password=%s', + DatabaseConnection::getDbPassword() + ) + ->addArgumentTemplate('--host=%s', DatabaseConnection::getDbHostname()) + ->addArgumentTemplate( + '--port=%s', + DatabaseConnection::getDbPort() + ); } } diff --git a/src/app/CliTools/Shell/CommandBuilder/OutputCombineCommandBuilder.php b/src/app/CliTools/Shell/CommandBuilder/OutputCombineCommandBuilder.php index 417e131..873116b 100644 --- a/src/app/CliTools/Shell/CommandBuilder/OutputCombineCommandBuilder.php +++ b/src/app/CliTools/Shell/CommandBuilder/OutputCombineCommandBuilder.php @@ -20,7 +20,8 @@ * along with this program. If not, see . */ -class OutputCombineCommandBuilder extends AbstractCommandBuilder { +class OutputCombineCommandBuilder extends AbstractCommandBuilder +{ /** * Command list which should be combined @@ -36,7 +37,8 @@ class OutputCombineCommandBuilder extends AbstractCommandBuilder { * * @return $this */ - public function addCommandForCombinedOutput(CommandBuilderInterface $command) { + public function addCommandForCombinedOutput(CommandBuilderInterface $command) + { if ($command->isExecuteable()) { $this->commandList[] = $command; } else { @@ -51,7 +53,8 @@ public function addCommandForCombinedOutput(CommandBuilderInterface $command) { * * @return bool */ - public function isExecuteable() { + public function isExecuteable() + { $ret = true; if (empty($this->commandList)) { @@ -66,7 +69,8 @@ public function isExecuteable() { * * @return $this */ - public function clear() { + public function clear() + { $ret = parent::__clone(); $this->commandList = array(); @@ -81,7 +85,8 @@ public function clear() { * @return string * @throws \Exception */ - public function build() { + public function build() + { $ret = array(); if (!$this->isExecuteable()) { @@ -113,7 +118,8 @@ public function build() { /** * Clone command */ - public function __clone() { + public function __clone() + { parent::__clone(); $commandList = array(); diff --git a/src/app/CliTools/Shell/CommandBuilder/RemoteCommandBuilder.php b/src/app/CliTools/Shell/CommandBuilder/RemoteCommandBuilder.php index a52ed2d..892a188 100644 --- a/src/app/CliTools/Shell/CommandBuilder/RemoteCommandBuilder.php +++ b/src/app/CliTools/Shell/CommandBuilder/RemoteCommandBuilder.php @@ -20,6 +20,7 @@ * along with this program. If not, see . */ -class RemoteCommandBuilder extends CommandBuilder { +class RemoteCommandBuilder extends CommandBuilder +{ } diff --git a/src/app/CliTools/Shell/CommandBuilder/SelfCommandBuilder.php b/src/app/CliTools/Shell/CommandBuilder/SelfCommandBuilder.php index fd25d2c..d2e29fc 100644 --- a/src/app/CliTools/Shell/CommandBuilder/SelfCommandBuilder.php +++ b/src/app/CliTools/Shell/CommandBuilder/SelfCommandBuilder.php @@ -20,12 +20,14 @@ * along with this program. If not, see . */ -class SelfCommandBuilder extends CommandBuilder { +class SelfCommandBuilder extends CommandBuilder +{ /** * Initalized command */ - protected function initialize() { + protected function initialize() + { parent::initialize(); $arguments = $_SERVER['argv']; diff --git a/src/app/CliTools/Shell/Executor.php b/src/app/CliTools/Shell/Executor.php index 34a6814..754a80f 100644 --- a/src/app/CliTools/Shell/Executor.php +++ b/src/app/CliTools/Shell/Executor.php @@ -24,7 +24,8 @@ use CliTools\Shell\CommandBuilder\CommandBuilderInterface; use CliTools\Utility\ConsoleUtility; -class Executor { +class Executor +{ // ########################################## // Constants @@ -77,9 +78,10 @@ class Executor { /** * Constructor * - * @param null|CommandBuilderInterface $command Command for execution + * @param null|CommandBuilderInterface $command Command for execution */ - public function __construct(CommandBuilderInterface $command = null) { + public function __construct(CommandBuilderInterface $command = null) + { if ($command !== null) { $this->command = $command; } @@ -90,7 +92,8 @@ public function __construct(CommandBuilderInterface $command = null) { * * @return CommandBuilderInterface */ - public function getCommand() { + public function getCommand() + { return $this->command; } @@ -98,10 +101,13 @@ public function getCommand() { * Set command * * @param CommandBuilderInterface $command + * * @return $this */ - public function setCommand(CommandBuilderInterface $command) { + public function setCommand(CommandBuilderInterface $command) + { $this->command = $command; + return $this; } @@ -110,7 +116,8 @@ public function setCommand(CommandBuilderInterface $command) { * * @return int|null */ - public function getReturnCode() { + public function getReturnCode() + { return $this->returnCode; } @@ -119,7 +126,8 @@ public function getReturnCode() { * * @return array|null */ - public function getOutput() { + public function getOutput() + { return $this->output; } @@ -128,7 +136,8 @@ public function getOutput() { * * @return string|null */ - public function getOutputString() { + public function getOutputString() + { $ret = null; if ($this->output !== null) { @@ -143,7 +152,8 @@ public function getOutputString() { * * @return boolean */ - public function isStrictMode() { + public function isStrictMode() + { return (bool)$this->strictMode; } @@ -151,20 +161,24 @@ public function isStrictMode() { * Set strict mode * * @return $this + * * @param boolean $strictMode */ - public function setStrictMode($strictMode) { + public function setStrictMode($strictMode) + { $this->strictMode = (bool)$strictMode; + return $this; } /** * Clear state */ - public function clear() { - $this->output = null; + public function clear() + { + $this->output = null; $this->returnCode = null; - $this->finishers = array(); + $this->finishers = array(); } @@ -174,7 +188,8 @@ public function clear() { * @return $this * @throws \Exception */ - public function execute() { + public function execute() + { $this->checkCommand(); ConsoleUtility::verboseWriteln('EXEC::STD', $this->command->build()); @@ -184,7 +199,9 @@ public function execute() { $this->runFinishers(); if ($this->strictMode && $this->returnCode !== 0) { - throw $this->generateException('Process ' . $this->command->getCommand() . ' did not finished successfully'); + throw $this->generateException( + 'Process ' . $this->command->getCommand() . ' did not finished successfully' + ); } return $this; @@ -194,16 +211,18 @@ public function execute() { * Execute interactive * * @param array $opts Option array + * * @return $this * @throws \Exception */ - public function execInteractive(array $opts = null) { + public function execInteractive(array $opts = null) + { $this->checkCommand(); ConsoleUtility::verboseWriteln('EXEC::INTERACTIVE', $this->command->build()); $descriptorSpec = array( - 0 => array('file', 'php://stdin', 'r'), // stdin is a file that the child will read from + 0 => array('file', 'php://stdin', 'r'), // stdin is a file that the child will read from 1 => array('file', 'php://stdout', 'w'), // stdout is a file that the child will write to 2 => array('file', 'php://stderr', 'w') // stderr is a file that the child will write to ); @@ -237,9 +256,12 @@ public function execInteractive(array $opts = null) { if ($status['signaled'] === true && $status['exitcode'] === -1) { // user may hit CTRL+C - ConsoleUtility::getOutput()->writeln('Processed stopped by signal'); + ConsoleUtility::getOutput() + ->writeln('Processed stopped by signal'); } elseif ($this->strictMode && $this->returnCode !== 0) { - throw $this->generateException('Process ' . $this->command->getCommand() . ' did not finished successfully'); + throw $this->generateException( + 'Process ' . $this->command->getCommand() . ' did not finished successfully' + ); } } else { throw $this->generateException('Process ' . $this->command->getCommand() . ' could not be started'); @@ -254,13 +276,16 @@ public function execInteractive(array $opts = null) { * @return $this * @throws CommandExecutionException */ - protected function checkCommand() { + protected function checkCommand() + { if ($this->command === null) { throw $this->generateException('Commmand is not set'); } if (!$this->command->isExecuteable()) { - throw $this->generateException('Commmand "' . $this->command->getCommand() . '" is not executable or available'); + throw $this->generateException( + 'Commmand "' . $this->command->getCommand() . '" is not executable or available' + ); } return $this; @@ -273,7 +298,8 @@ protected function checkCommand() { * * @return CommandExecutionException */ - protected function generateException($msg) { + protected function generateException($msg) + { $e = new CommandExecutionException($msg); if ($this->returnCode !== null) { @@ -292,14 +318,16 @@ protected function generateException($msg) { * * @param callable $callback */ - public function addFinisherCallback(callable $callback) { + public function addFinisherCallback(callable $callback) + { $this->finishers[] = $callback; } /** * Run finisher commands */ - public function runFinishers() { + public function runFinishers() + { foreach ($this->finishers as $call) { if (is_callable($call)) { $call($this); diff --git a/src/app/CliTools/Utility/ConsoleUtility.php b/src/app/CliTools/Utility/ConsoleUtility.php index 1dad09e..7d0319b 100644 --- a/src/app/CliTools/Utility/ConsoleUtility.php +++ b/src/app/CliTools/Utility/ConsoleUtility.php @@ -20,12 +20,13 @@ * along with this program. If not, see . */ -use Symfony\Component\Console\Question\Question; use Symfony\Component\Console\Helper\QuestionHelper; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Question\Question; -abstract class ConsoleUtility { +abstract class ConsoleUtility +{ /** * Input @@ -50,7 +51,8 @@ abstract class ConsoleUtility { * @param InputInterface $input An InputInterface instance * @param OutputInterface $output An OutputInterface instance */ - public static function initialize(InputInterface $input, OutputInterface $output) { + public static function initialize(InputInterface $input, OutputInterface $output) + { self::$input = $input; self::$output = $output; } @@ -60,7 +62,8 @@ public static function initialize(InputInterface $input, OutputInterface $output * * @return InputInterface */ - public static function input() { + public static function input() + { return self::$input; } @@ -69,7 +72,8 @@ public static function input() { * * @return OutputInterface */ - public static function getOutput() { + public static function getOutput() + { return self::$output; } @@ -79,7 +83,8 @@ public static function getOutput() { * @param string $area Area * @param string $line Line */ - public static function verboseWriteln($area, $line) { + public static function verboseWriteln($area, $line) + { if (self::$output->isVerbose()) { // Special stuff if line is exception @@ -114,18 +119,19 @@ public static function verboseWriteln($area, $line) { /** * Ask question with yes/no detection * - * @param string $question Question - * @param string $default Default + * @param string $question Question + * @param string $default Default * * @return bool */ - public static function questionYesNo($message, $default) { + public static function questionYesNo($message, $default) + { $ret = false; while (1) { - $question = new Question(' >>> ' . $message . ' [yes/no] ', $default); + $question = new Question(' >>> ' . $message . ' [yes/no] ', $default); $questionDialog = new QuestionHelper(); - $answer = $questionDialog->ask(self::$input, self::$output, $question); + $answer = $questionDialog->ask(self::$input, self::$output, $question); if (stripos($answer, 'n') === 0) { $ret = false; diff --git a/src/app/CliTools/Utility/DockerUtility.php b/src/app/CliTools/Utility/DockerUtility.php index 74c0a3f..83b180e 100644 --- a/src/app/CliTools/Utility/DockerUtility.php +++ b/src/app/CliTools/Utility/DockerUtility.php @@ -23,7 +23,8 @@ use CliTools\Shell\CommandBuilder\CommandBuilder; use CliTools\Shell\Executor; -class DockerUtility { +class DockerUtility +{ /** * Parse docker configuration (from docker inspect) @@ -32,7 +33,8 @@ class DockerUtility { * * @return stdClass|null */ - public static function getDockerConfiguration($container) { + public static function getDockerConfiguration($container) + { // Build command $command = new CommandBuilder('docker', 'inspect %s', array($container)); @@ -72,7 +74,8 @@ public static function getDockerConfiguration($container) { * * @return bool|string */ - public static function searchDockerDirectoryRecursive($path = null) { + public static function searchDockerDirectoryRecursive($path = null) + { return UnixUtility::findFileInDirectortyTree('docker-compose.yml', $path); } @@ -83,7 +86,8 @@ public static function searchDockerDirectoryRecursive($path = null) { * * @return bool */ - public static function isDockerDirectory($path = null) { + public static function isDockerDirectory($path = null) + { if ($path === null) { $path = getcwd(); } @@ -110,7 +114,8 @@ public static function isDockerDirectory($path = null) { * * @return mixed|string */ - public static function getDockerInstancePrefix($path = null) { + public static function getDockerInstancePrefix($path = null) + { if ($path === null) { $path = getcwd(); } @@ -131,7 +136,8 @@ public static function getDockerInstancePrefix($path = null) { * * @return string */ - public static function getDockerInstanceName($containerName, $containerNumber = 1, $path = null) { + public static function getDockerInstanceName($containerName, $containerNumber = 1, $path = null) + { $dockerName = array( \CliTools\Utility\DockerUtility::getDockerInstancePrefix($path), (string)$containerName, diff --git a/src/app/CliTools/Utility/FilterUtility.php b/src/app/CliTools/Utility/FilterUtility.php index 09d169e..eb8d915 100644 --- a/src/app/CliTools/Utility/FilterUtility.php +++ b/src/app/CliTools/Utility/FilterUtility.php @@ -20,7 +20,8 @@ * along with this program. If not, see . */ -class FilterUtility { +class FilterUtility +{ /** * Filter mysql table list by filter @@ -30,7 +31,8 @@ class FilterUtility { * * @return array */ - public static function mysqlTableFilter(array $tables, array $filters) { + public static function mysqlTableFilter(array $tables, array $filters) + { $ret = array(); foreach ($tables as $table) { @@ -54,7 +56,8 @@ public static function mysqlTableFilter(array $tables, array $filters) { * * @return array */ - public static function mysqlIgnoredTableFilter(array $tables, array $filters, $database = null) { + public static function mysqlIgnoredTableFilter(array $tables, array $filters, $database = null) + { $ret = array(); foreach ($tables as $table) { diff --git a/src/app/CliTools/Utility/FormatUtility.php b/src/app/CliTools/Utility/FormatUtility.php index f55ba73..da381af 100644 --- a/src/app/CliTools/Utility/FormatUtility.php +++ b/src/app/CliTools/Utility/FormatUtility.php @@ -20,7 +20,8 @@ * along with this program. If not, see . */ -class FormatUtility { +class FormatUtility +{ /** * Format number in human readable format @@ -30,7 +31,8 @@ class FormatUtility { * * @return string */ - public static function number($number, $precision = 0) { + public static function number($number, $precision = 0) + { $ret = number_format($number, $precision); return $ret; @@ -44,7 +46,8 @@ public static function number($number, $precision = 0) { * * @return string */ - public static function bytes($bytes, $precision = 2) { + public static function bytes($bytes, $precision = 2) + { $units = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB'); $bytes = max($bytes, 0); diff --git a/src/app/CliTools/Utility/PhpUtility.php b/src/app/CliTools/Utility/PhpUtility.php index e5656c8..473512e 100644 --- a/src/app/CliTools/Utility/PhpUtility.php +++ b/src/app/CliTools/Utility/PhpUtility.php @@ -20,15 +20,18 @@ * along with this program. If not, see . */ -class PhpUtility { +class PhpUtility +{ /** * Get content of file * * @param string $file Filename + * * @return string */ - public static function fileGetContents($file) { + public static function fileGetContents($file) + { if (!is_file($file) || !is_readable($file)) { throw new \RuntimeException('Could not read "' . $file . '"'); } @@ -40,9 +43,11 @@ public static function fileGetContents($file) { * Get content of file (array) * * @param string $file Filename + * * @return array */ - public static function fileGetContentsArray($file) { + public static function fileGetContentsArray($file) + { $content = self::fileGetContents($file); $content = str_replace("/r/n", "/n", $content); @@ -57,7 +62,8 @@ public static function fileGetContentsArray($file) { * @param string $file Filename * @param string $content Content */ - public static function filePutContents($file, $content) { + public static function filePutContents($file, $content) + { if (file_put_contents($file, $content) === false) { throw new \RuntimeException('Could not write "' . $file . '"'); } @@ -67,9 +73,11 @@ public static function filePutContents($file, $content) { * Change current working directory * * @param string $path Target path + * * @throws \RuntimeException */ - public static function chdir($path) { + public static function chdir($path) + { if (!is_dir($path) || !chdir($path)) { throw new \RuntimeException('Could not change working directory to "' . $path . '"'); } @@ -78,13 +86,15 @@ public static function chdir($path) { /** * Create new directory * - * @param string $path Directory - * @param integer $mode Perms - * @param boolean $recursive Creation of nested directories - * @param resource $context Context + * @param string $path Directory + * @param integer $mode Perms + * @param boolean $recursive Creation of nested directories + * @param resource $context Context + * * @throws \RuntimeException */ - public static function mkdir($path, $mode = 0777, $recursive = false, $context = null) { + public static function mkdir($path, $mode = 0777, $recursive = false, $context = null) + { if ($context !== null) { $res = mkdir($path, $mode, $recursive, $context); } else { @@ -100,9 +110,11 @@ public static function mkdir($path, $mode = 0777, $recursive = false, $context = * Remove file * * @param string $path Path to file + * * @throws \RuntimeException */ - public static function unlink($path) { + public static function unlink($path) + { if (!unlink($path)) { throw new \RuntimeException('Could not change working directory to "' . $path . '"'); } @@ -116,7 +128,8 @@ public static function unlink($path) { * * @return mixed */ - public static function curlFetch($url, callable $progress = null) { + public static function curlFetch($url, callable $progress = null) + { $curlHandle = curl_init(); curl_setopt($curlHandle, CURLOPT_URL, $url); curl_setopt($curlHandle, CURLOPT_VERBOSE, 0); @@ -125,9 +138,13 @@ public static function curlFetch($url, callable $progress = null) { curl_setopt($curlHandle, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curlHandle, CURLOPT_FOLLOWLOCATION, 1); - curl_setopt($curlHandle, CURLOPT_USERAGENT, 'CliTools ' . CLITOOLS_COMMAND_VERSION . '(https://github.com/mblaschke/vagrant-clitools)'); + curl_setopt( + $curlHandle, + CURLOPT_USERAGENT, + 'CliTools ' . CLITOOLS_COMMAND_VERSION . '(https://github.com/mblaschke/vagrant-clitools)' + ); - if($progress) { + if ($progress) { curl_setopt($curlHandle, CURLOPT_NOPROGRESS, false); curl_setopt($curlHandle, CURLOPT_PROGRESSFUNCTION, $progress); } @@ -149,10 +166,11 @@ public static function curlFetch($url, callable $progress = null) { * * @return string */ - public static function getMimeType($file) { + public static function getMimeType($file) + { // Get mime type from file - $finfo = finfo_open(FILEINFO_MIME_TYPE); - $ret = finfo_file($finfo, $file); + $finfo = finfo_open(FILEINFO_MIME_TYPE); + $ret = finfo_file($finfo, $file); finfo_close($finfo); if ($ret === 'application/octet-stream') { diff --git a/src/app/CliTools/Utility/Typo3Utility.php b/src/app/CliTools/Utility/Typo3Utility.php index e9c0687..f695e87 100644 --- a/src/app/CliTools/Utility/Typo3Utility.php +++ b/src/app/CliTools/Utility/Typo3Utility.php @@ -23,7 +23,8 @@ use CliTools\Iterator\Filter\Typo3RecursiveDirectoryFilter; use Symfony\Component\Console\Input\InputInterface; -class Typo3Utility { +class Typo3Utility +{ const PASSWORD_TYPE_MD5_SALTED = 'md5_salted'; const PASSWORD_TYPE_MD5 = 'md5'; @@ -36,7 +37,8 @@ class Typo3Utility { * * @return null|string */ - public static function generatePassword($password, $type = null) { + public static function generatePassword($password, $type = null) + { $ret = null; if ($type === null) { @@ -77,7 +79,8 @@ public static function generatePassword($password, $type = null) { * @return null|string * @throws \RuntimeException */ - public static function guessBestTypo3BasePath($basePath, $input = null, $inputArgName = null) { + public static function guessBestTypo3BasePath($basePath, $input = null, $inputArgName = null) + { $ret = null; $userPath = null; @@ -121,7 +124,8 @@ public static function guessBestTypo3BasePath($basePath, $input = null, $inputAr * * @return array */ - public static function getTypo3InstancePathList($basePath, $maxDepth = 3) { + public static function getTypo3InstancePathList($basePath, $maxDepth = 3) + { $ret = array(); // #################### diff --git a/src/app/CliTools/Utility/UnixUtility.php b/src/app/CliTools/Utility/UnixUtility.php index 135f059..a28476d 100644 --- a/src/app/CliTools/Utility/UnixUtility.php +++ b/src/app/CliTools/Utility/UnixUtility.php @@ -22,7 +22,8 @@ use CliTools\Shell\CommandBuilder\CommandBuilder; -abstract class UnixUtility { +abstract class UnixUtility +{ /** * Path list @@ -36,10 +37,12 @@ abstract class UnixUtility { * * @return string */ - public static function lsbSystemDescription() { + public static function lsbSystemDescription() + { $command = new CommandBuilder('lsb_release', '-d'); - $command->addPipeCommand( new CommandBuilder('cut', '-f 2 -d ":"') ); - $ret = $command->execute()->getOutputString(); + $command->addPipeCommand(new CommandBuilder('cut', '-f 2 -d ":"')); + $ret = $command->execute() + ->getOutputString(); $ret = trim($ret); @@ -51,9 +54,11 @@ public static function lsbSystemDescription() { * * @return integer */ - public static function cpuCount() { + public static function cpuCount() + { $command = new CommandBuilder('nproc'); - $ret = $command->execute()->getOutputString(); + $ret = $command->execute() + ->getOutputString(); $ret = (int)trim($ret); @@ -65,10 +70,12 @@ public static function cpuCount() { * * @return integer */ - public static function memorySize() { + public static function memorySize() + { $command = new CommandBuilder('cat', '/proc/meminfo'); - $command->addPipeCommand( new CommandBuilder('awk', '\'match($1,"MemTotal") == 1 {print $2}\'') ); - $ret = $command->execute()->getOutputString(); + $command->addPipeCommand(new CommandBuilder('awk', '\'match($1,"MemTotal") == 1 {print $2}\'')); + $ret = $command->execute() + ->getOutputString(); // in bytes $ret = (int)trim($ret) * 1024; @@ -81,9 +88,11 @@ public static function memorySize() { * * @return string */ - public static function kernelVersion() { + public static function kernelVersion() + { $command = new CommandBuilder('uname', '-r'); - $ret = $command->execute()->getOutputString(); + $ret = $command->execute() + ->getOutputString(); $ret = trim($ret); @@ -95,11 +104,13 @@ public static function kernelVersion() { * * @return string */ - public static function dockerVersion() { + public static function dockerVersion() + { $ret = ''; try { $command = new CommandBuilder('docker', '--version'); - $ret = $command->execute()->getOutputString(); + $ret = $command->execute() + ->getOutputString(); $ret = trim($ret); } catch (\Exception $e) { @@ -114,11 +125,15 @@ public static function dockerVersion() { * * @return array */ - public static function mountInfoList() { + public static function mountInfoList() + { $command = new CommandBuilder('df', '-a --type=ext3 --type=ext4 --type vmhgfs --type vboxsf --portability'); - $command->addPipeCommand( new CommandBuilder('tail', '--lines=+2') ) - ->addPipeCommand( new CommandBuilder('awk', '\'{ print $6 " " $3 " " $4 " " $5 }\'') ); - $execOutput = $command->execute()->getOutput(); + $command->addPipeCommand(new CommandBuilder('tail', '--lines=+2')) + ->addPipeCommand( + new CommandBuilder('awk', '\'{ print $6 " " $3 " " $4 " " $5 }\'') + ); + $execOutput = $command->execute() + ->getOutput(); $ret = array(); foreach ($execOutput as $line) { @@ -139,7 +154,8 @@ public static function mountInfoList() { * * @return array */ - public static function networkInterfaceList($regExp) { + public static function networkInterfaceList($regExp) + { $sysDir = '/sys/class/net/'; $netInterfaceList = array(); @@ -175,8 +191,11 @@ public static function networkInterfaceList($regExp) { unset($netInterfaceList['lo']); foreach ($netInterfaceList as $netName => &$netConf) { - $command = new CommandBuilder('ifdata', '-pa %s', array($netName)); - $netConf['ipaddress'] = trim($command->execute()->getOutputString()); + $command = new CommandBuilder('ifdata', '-pa %s', array($netName)); + $netConf['ipaddress'] = trim( + $command->execute() + ->getOutputString() + ); } unset($netConf); @@ -188,11 +207,15 @@ public static function networkInterfaceList($regExp) { * * @return null */ - public static function defaultGateway() { + public static function defaultGateway() + { $command = new CommandBuilder('ip', 'route show'); - $command->addPipeCommand( new CommandBuilder('grep', '\'default\'') ) - ->addPipeCommand( new CommandBuilder('awk', '\'{print $3}\'') ); - $ret = $command->execute()->getOutputString(); + $command->addPipeCommand(new CommandBuilder('grep', '\'default\'')) + ->addPipeCommand( + new CommandBuilder('awk', '\'{print $3}\'') + ); + $ret = $command->execute() + ->getOutputString(); $ret = trim($ret); @@ -204,7 +227,8 @@ public static function defaultGateway() { * * @param string $message Message */ - public static function sendWallMessage($message) { + public static function sendWallMessage($message) + { $wall = new CommandBuilder('wall'); $wall->setOutputRedirect(CommandBuilder::OUTPUT_REDIRECT_NULL); @@ -219,10 +243,11 @@ public static function sendWallMessage($message) { * * @return array */ - public static function pathList() { + public static function pathList() + { if (self::$pathList === null) { - $pathList = explode(':', getenv('PATH')); + $pathList = explode(':', getenv('PATH')); self::$pathList = array_map('trim', $pathList); } @@ -236,9 +261,10 @@ public static function pathList() { * * @return bool */ - public static function checkExecutable($command) { + public static function checkExecutable($command) + { - if (strpos($command,'/') !== false) { + if (strpos($command, '/') !== false) { // command with path if (file_exists($command) && is_executable($command)) { return true; @@ -262,9 +288,11 @@ public static function checkExecutable($command) { * * @param string|array $file Filename * @param string $path Path + * * @return boolean|string */ - public static function findFileInDirectortyTree($file, $path = null) { + public static function findFileInDirectortyTree($file, $path = null) + { $ret = false; $fileList = (array)$file; @@ -298,31 +326,32 @@ public static function findFileInDirectortyTree($file, $path = null) { /** * Reload tty */ - public static function reloadTtyBanner($ttyName) { + public static function reloadTtyBanner($ttyName) + { // Check if we can reload tty try { $who = new CommandBuilder('who'); - $who->addPipeCommand( new CommandBuilder('grep', '%s', array($ttyName))); + $who->addPipeCommand(new CommandBuilder('grep', '%s', array($ttyName))); $who->execute(); - // if there is no exception -> there is a logged in user } catch (\Exception $e) { // if there is an exception -> there is NO logged in user try { $ps = new CommandBuilder('ps', 'h -o pid,comm,args -C getty'); - $ps->addPipeCommand( new CommandBuilder('grep', '%s', array($ttyName))); - $output = $ps->execute()->getOutput(); + $ps->addPipeCommand(new CommandBuilder('grep', '%s', array($ttyName))); + $output = $ps->execute() + ->getOutput(); if (!empty($output)) { $outputLine = trim(reset($output)); $outputLineParts = preg_split('/[\s]+/', $outputLine); - list($pid) = $outputLineParts; + list($pid) = $outputLineParts; posix_kill($pid, SIGHUP); } - - } catch (\Exception $e) {} + } catch (\Exception $e) { + } } } } From 2ee3adffb687c4e43d2a700bb0ba22e81f10c323 Mon Sep 17 00:00:00 2001 From: Markus Blaschke Date: Fri, 24 Jul 2015 10:57:06 +0200 Subject: [PATCH 3/8] Replaced --files-from with --include-from for rsync Fixes #52 --- src/app/CliTools/Console/Command/Sync/AbstractCommand.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/CliTools/Console/Command/Sync/AbstractCommand.php b/src/app/CliTools/Console/Command/Sync/AbstractCommand.php index af5851c..d360be3 100644 --- a/src/app/CliTools/Console/Command/Sync/AbstractCommand.php +++ b/src/app/CliTools/Console/Command/Sync/AbstractCommand.php @@ -790,7 +790,7 @@ protected function rsyncAddFileList(CommandBuilder $command, array $list) PhpUtility::filePutContents($rsyncFilter, implode("\n", $list)); - $command->addArgumentTemplate('--files-from=%s', $rsyncFilter); + $command->addArgumentTemplate('--include-from=%s', $rsyncFilter); // cleanup rsync file $command->getExecutor() From f99e88a8ea1e70c5a6ae4acddeb06dbdfc306848 Mon Sep 17 00:00:00 2001 From: Markus Blaschke Date: Fri, 24 Jul 2015 10:58:58 +0200 Subject: [PATCH 4/8] Added example clitools.ini for docker for macos Fixes #50 --- Documentation/Examples/macos-docker-clitools.ini | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 Documentation/Examples/macos-docker-clitools.ini diff --git a/Documentation/Examples/macos-docker-clitools.ini b/Documentation/Examples/macos-docker-clitools.ini new file mode 100644 index 0000000..4b14dd0 --- /dev/null +++ b/Documentation/Examples/macos-docker-clitools.ini @@ -0,0 +1,4 @@ +[db] +dsn = "mysql:host=192.168.56.2;port=13306" +username = "root" +password = "dev" From 089f6c90d28b89f4dd5e615bb62044827bf52835 Mon Sep 17 00:00:00 2001 From: Markus Blaschke Date: Fri, 24 Jul 2015 11:15:38 +0200 Subject: [PATCH 5/8] Fixed coding style --- src/app/CliTools/Console/Command/Sync/AbstractCommand.php | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/app/CliTools/Console/Command/Sync/AbstractCommand.php b/src/app/CliTools/Console/Command/Sync/AbstractCommand.php index d360be3..5f0f1b3 100644 --- a/src/app/CliTools/Console/Command/Sync/AbstractCommand.php +++ b/src/app/CliTools/Console/Command/Sync/AbstractCommand.php @@ -929,9 +929,11 @@ protected function createRemoteMySqlCommand($database = null) protected function createLocalMySqlCommand($database = null) { $command = new RemoteCommandBuilder('mysql'); - $command// batch mode - ->addArgument('-B')// skip column names - ->addArgument('-N'); + $command + // batch mode + ->addArgument('-B') + // skip column names + ->addArgument('-N'); // Add username if (DatabaseConnection::getDbUsername()) { From ef8382e582093e64bc694475debfe12db3a92a92 Mon Sep 17 00:00:00 2001 From: Markus Blaschke Date: Fri, 24 Jul 2015 12:17:53 +0200 Subject: [PATCH 6/8] Fixed coding style --- src/app/CliTools/Console/Command/Sync/AbstractCommand.php | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/app/CliTools/Console/Command/Sync/AbstractCommand.php b/src/app/CliTools/Console/Command/Sync/AbstractCommand.php index 5f0f1b3..2b1f2af 100644 --- a/src/app/CliTools/Console/Command/Sync/AbstractCommand.php +++ b/src/app/CliTools/Console/Command/Sync/AbstractCommand.php @@ -892,9 +892,11 @@ protected function wrapRemoteCommand(CommandBuilderInterface $command) protected function createRemoteMySqlCommand($database = null) { $command = new RemoteCommandBuilder('mysql'); - $command// batch mode - ->addArgument('-B')// skip column names - ->addArgument('-N'); + $command + // batch mode + ->addArgument('-B') + // skip column names + ->addArgument('-N'); // Add username if ($this->contextConfig->exists('mysql.username')) { From 096fb426e497c5c2e8024186be1bbffefc2731ab Mon Sep 17 00:00:00 2001 From: Markus Blaschke Date: Thu, 30 Jul 2015 23:16:51 +0200 Subject: [PATCH 7/8] Switched to webdevops repositories --- src/app/CliTools/Utility/PhpUtility.php | 2 +- src/config.ini | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/app/CliTools/Utility/PhpUtility.php b/src/app/CliTools/Utility/PhpUtility.php index 473512e..6d72c28 100644 --- a/src/app/CliTools/Utility/PhpUtility.php +++ b/src/app/CliTools/Utility/PhpUtility.php @@ -141,7 +141,7 @@ public static function curlFetch($url, callable $progress = null) curl_setopt( $curlHandle, CURLOPT_USERAGENT, - 'CliTools ' . CLITOOLS_COMMAND_VERSION . '(https://github.com/mblaschke/vagrant-clitools)' + 'CliTools ' . CLITOOLS_COMMAND_VERSION . '(https://github.com/webdevops/clitools)' ); if ($progress) { diff --git a/src/config.ini b/src/config.ini index dd808c0..0e90a71 100644 --- a/src/config.ini +++ b/src/config.ini @@ -2,7 +2,7 @@ ssh_conf_path = "/opt/conf/ssh" www_base_path = "/var/www" domain_dev = "vm" -github_repo = "mblaschke/clitools" +github_repo = "webdevops/clitools" update_fallback_url = "https://www.achenar.net/clicommand/clitools.phar" [db] @@ -23,7 +23,7 @@ diskusage = 90 [docker] container = main interface = docker0 -boilerplate = https://github.com/mblaschke/TYPO3-docker-boilerplate.git +boilerplate = https://github.com/webdevops/php-docker-boilerplate.git climethod = docker-exec ; climethod = dockercompose-run From 6b193716cb24508f88d7e524db852a15fc5acc26 Mon Sep 17 00:00:00 2001 From: Markus Blaschke Date: Thu, 30 Jul 2015 23:18:26 +0200 Subject: [PATCH 8/8] Version bump 2.1.3 --- README.md | 2 +- src/command.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 348c21c..9ec007e 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # CliTools for Docker, PHP und MySQL development -[![latest v2.1.1](https://img.shields.io/badge/latest-v2.1.1-green.svg?style=flat)](https://github.com/mblaschke/clitools/releases/tag/2.1.1) +[![latest v2.1.3](https://img.shields.io/badge/latest-v2.1.3-green.svg?style=flat)](https://github.com/mblaschke/clitools/releases/tag/2.1.3) [![License GPL3](https://img.shields.io/badge/license-GPL3-blue.svg?style=flat)](/LICENSE) [![Average time to resolve an issue](http://isitmaintained.com/badge/resolution/mblaschke/clitools.svg)](http://isitmaintained.com/project/mblaschke/clitools "Average time to resolve an issue") [![Percentage of issues still open](http://isitmaintained.com/badge/open/mblaschke/clitools.svg)](http://isitmaintained.com/project/mblaschke/clitools "Percentage of issues still open") diff --git a/src/command.php b/src/command.php index 06e4226..612c747 100644 --- a/src/command.php +++ b/src/command.php @@ -20,7 +20,7 @@ */ error_reporting(E_ALL); -define('CLITOOLS_COMMAND_VERSION', '2.1.2'); +define('CLITOOLS_COMMAND_VERSION', '2.1.3'); define('CLITOOLS_ROOT_FS', __DIR__); require __DIR__ . '/vendor/autoload.php';