Exemplo n.º 1
0
 public function testClean()
 {
     // Initialize
     $aInput = ['key1' => 'value1', 'key2' => ' ', 'key3' => 'value3'];
     // Assert
     $this->assertEquals(2, count(ExtendedArray::clean($aInput)));
 }
Exemplo n.º 2
0
 public static function askBinaryPath(Event $oEvent, $sLabel, $sBinaryName, $sCheckCommand, $sDefault = null, $bGetRealDefaultValue = true, $bMandatory = false)
 {
     // Get real default value
     $aOutput = [];
     if ($bGetRealDefaultValue) {
         try {
             ExtendedShell::exec(sprintf('which %s', $sBinaryName), $aOutput);
         } catch (Exception $oException) {
             $aOutput = [];
         }
     }
     $sDefault = isset($aOutput[0]) ? trim($aOutput[0]) : $sDefault;
     // Return
     return self::ask($oEvent, self::formatQuestion($sLabel, $sDefault), $sDefault, $bMandatory, function ($sValue) use($sCheckCommand) {
         // Initialize
         $aOutput = [];
         // Update check command
         $sCheckCommand = sprintf($sCheckCommand, $sValue);
         // Exec
         try {
             ExtendedShell::exec($sCheckCommand, $aOutput);
         } catch (\Exception $oException) {
             throw new RuntimeException(sprintf("Invalid path %s with error %s", $sValue, implode(', ', ExtendedArray::clean($aOutput))));
         }
         // Return
         return $sValue;
     });
 }
 public function __construct(array $aRepository)
 {
     // Check required keys
     ExtendedArray::checkRequiredKeys($aRepository, ['name']);
     // Initialize
     $this->sName = $aRepository['name'];
 }
 public function __construct(array $aConfig = [])
 {
     // Parent construct
     parent::__construct($aConfig);
     // Extend config
     $aConfig = ExtendedArray::extendWithDefaultValues($aConfig, ['connection_timeout' => 10, 'server_failure_limit' => 5, 'remove_failed_servers' => true, 'retry_timeout' => 1]);
     // Check Memcached is loaded
     if (!extension_loaded('memcached')) {
         throw new RuntimeException('Memcached extension is not loaded');
     }
     // Create client
     $this->oClient = new Memcached();
     $this->oClient->setOption(Memcached::OPT_CONNECT_TIMEOUT, $aConfig['connection_timeout']);
     $this->oClient->setOption(Memcached::OPT_DISTRIBUTION, Memcached::DISTRIBUTION_CONSISTENT);
     $this->oClient->setOption(Memcached::OPT_SERVER_FAILURE_LIMIT, $aConfig['server_failure_limit']);
     $this->oClient->setOption(Memcached::OPT_REMOVE_FAILED_SERVERS, $aConfig['remove_failed_servers']);
     $this->oClient->setOption(Memcached::OPT_RETRY_TIMEOUT, $aConfig['retry_timeout']);
     // Add servers
     if (array_key_exists('servers', $aConfig)) {
         $aServers = array_filter(explode(',', $aConfig['servers']));
         foreach ($aServers as $sAddress) {
             // Parse address
             list($sHost, $sPort) = array_pad(explode(':', $sAddress), 2, '');
             // Add server
             $this->oClient->addServer($sHost, intval($sPort));
         }
     }
 }
 protected function __construct(array $aConfig)
 {
     // Extend config
     $aConfig = ExtendedArray::extendWithDefaultValues($aConfig, ['prefix' => '', 'ttl' => 0]);
     // Set attributes
     $this->sPrefix = $aConfig['prefix'];
     $this->iTTL = intval($aConfig['ttl']);
 }
Exemplo n.º 6
0
 /**
  * @param $sPath
  * @return array
  */
 public function parsePath($sPath)
 {
     // Parse path
     if (preg_match('/^([a-z_]+)\\:\\/(.+)/i', $sPath, $aMatches) > 0) {
         return [$aMatches[1], $aMatches[2]];
     } else {
         return [$this->sDefaultHandlerName !== '' ? $this->sDefaultHandlerName : ExtendedArray::getFirstKey($this->aHandlers), $sPath];
     }
 }
Exemplo n.º 7
0
 public function __construct(array $aConfig)
 {
     // Initialize
     $this->aConfig = $aConfig;
     // Default values
     $this->aConfig = ExtendedArray::extendWithDefaultValues($this->aConfig, ['timeout' => 0]);
     // Check config required attributes
     ExtendedArray::checkRequiredKeys($this->aConfig, ['timeout']);
 }
Exemplo n.º 8
0
 public function __construct(array $aCommit)
 {
     // Check required keys
     ExtendedArray::checkRequiredKeys($aCommit, ['branch', 'author', 'raw_node', 'message']);
     // Initialize
     $this->sBranch = $aCommit['branch'];
     $this->sAuthor = $aCommit['author'];
     $this->sNode = $aCommit['raw_node'];
     $this->sMessage = $aCommit['message'];
 }
Exemplo n.º 9
0
 public function __construct(array $aPayload)
 {
     // Check required keys
     ExtendedArray::checkRequiredKeys($aPayload, ['repository', 'commits']);
     // Initialize
     $this->oRepository = new Repository($aPayload['repository']);
     foreach ($aPayload['commits'] as $aCommit) {
         $this->aCommits[] = new Commit($aCommit);
     }
 }
Exemplo n.º 10
0
 public static function decode($sInput, $sKey, array $aRequiredKeys = [], $iValidityDuration = 0)
 {
     // Split input
     $aExplodedInput = explode('.', $sInput);
     // Invalid input
     if (count($aExplodedInput) !== 2) {
         throw new InvalidInputException(sprintf('Invalid members count %s', count($aExplodedInput)));
     }
     // Get members
     $sPayload = base64_decode($aExplodedInput[0]);
     $sSignature = base64_decode($aExplodedInput[1]);
     // Check signature
     if ($sSignature !== static::signPayload($sPayload, $sKey)) {
         throw new InvalidSignatureException(sprintf('Invalid signature %s', $sSignature));
     }
     // Unbuild payload
     $aPayload = static::unbuildPayload($sPayload);
     // Invalid payload
     if (is_null($aPayload)) {
         throw new InvalidPayloadException(sprintf('Payload <%s> is a malformed JSON', $sPayload));
     }
     // Check required keys
     $aRequiredKeys = array_merge($aRequiredKeys, ['timestamp', 'nonce']);
     try {
         ExtendedArray::checkRequiredKeys($aPayload, $aRequiredKeys);
     } catch (\Exception $oException) {
         throw new InvalidPayloadException($oException->getMessage());
     }
     // Check time validity
     $iTimestamp = intval($aPayload['timestamp']);
     if ($iValidityDuration > 0 && time() > $iTimestamp + $iValidityDuration) {
         throw new InvalidPayloadException(sprintf('Timestamp <%s> has expired', $iTimestamp));
     } elseif ($iTimestamp > time()) {
         throw new InvalidPayloadException(sprintf('Timestamp <%s> is in the future', $iTimestamp));
     }
     // Return
     unset($aPayload['timestamp']);
     unset($aPayload['nonce']);
     return $aPayload;
 }
Exemplo n.º 11
0
 public function __construct(array $aConfig = [])
 {
     // Parent construct
     parent::__construct($aConfig);
     // Extend config
     $aConfig = ExtendedArray::extendWithDefaultValues($aConfig, ['timeout' => 0.0]);
     // Check Redis is loaded
     if (!extension_loaded('redis')) {
         throw new RuntimeException('Redis extension is not loaded');
     }
     // Create client
     $this->oClient = new Redis();
     // Add servers
     if (array_key_exists('servers', $aConfig)) {
         $aServers = array_filter(explode(',', $aConfig['servers']));
         foreach ($aServers as $sAddress) {
             // Parse address
             list($sHost, $sPort) = array_pad(explode(':', $sAddress), 2, '');
             // Connect
             $this->oClient->connect($sHost, intval($sPort), $aConfig['timeout']);
         }
     }
 }
Exemplo n.º 12
0
 public static function getExtension($sPath)
 {
     $aExplodedBasename = explode('.', self::getBasename($sPath));
     return count($aExplodedBasename) > 1 ? ExtendedArray::getLastValue($aExplodedBasename) : '';
 }
Exemplo n.º 13
0
use Asticode\FileManager\FileManager;
use Asticode\Toolbox\ExtendedArray;
use Aura\Sql\ExtendedPdo;
use Aura\Sql\ConnectionLocator;
use Asticode\DataMapper\DataMapper;
use Asticode\DeploymentManager\Service;
// Set options
set_time_limit(0);
date_default_timezone_set('UTC');
// Include Composer autoload
require_once __DIR__ . '/../vendor/autoload.php';
// Get config
$aConfig = call_user_func(function () {
    $aGlobalConfig = (require __DIR__ . '/../app/config/global.php');
    $aLocalConfig = file_exists(__DIR__ . '/../app/config/local.php') ? require __DIR__ . '/../app/config/local.php' : [];
    return ExtendedArray::extendWithDefaultValues($aLocalConfig, $aGlobalConfig);
});
// Get inputs
$oInput = new ArgvInput();
// Build logger
/** @var \Psr\Log\LoggerInterface $oLogger */
$oLogger = call_user_func(function () use($aConfig, $oInput) {
    // Get min level message
    if ($oInput->hasParameterOption(['-v', '-vv', '-vvv', '--verbose'])) {
        $iMinMsgLevel = LogLevel::DEBUG;
    } else {
        $iMinMsgLevel = LogLevel::INFO;
    }
    // Build handlers
    $oHandler = new StreamHandler('php://stdout', $iMinMsgLevel);
    $oSyslogHandler = new SyslogHandler($aConfig['logger']['syslog']['ident'], $aConfig['logger']['syslog']['facility'], $aConfig['logger']['syslog']['level']);
Exemplo n.º 14
0
 public static function postInstall(Event $oEvent)
 {
     // Initialize
     $sAppDirPath = __DIR__ . '/../../../app';
     $sLocalDistConfigPath = sprintf('%s/%s', $sAppDirPath, 'install/local.php.dist');
     $sLocalConfigPath = sprintf('%s/%s', $sAppDirPath, 'config/local.php');
     // Create file manager
     $oFileManager = new FileManager([]);
     $oFileManager->addHandler('local', 'PHP', []);
     // Make sure console is executable
     $sOutput = 'Make sure the deployment manager console is executable';
     $sErrorMessage = '';
     try {
         ExtendedShell::exec(sprintf('chmod +x %s', sprintf('%s/%s', $sAppDirPath, 'console')));
     } catch (Exception $oException) {
         // Update error message
         $sErrorMessage = $oException->getMessage();
     }
     // No error
     if ($sErrorMessage === '') {
         $sResult = 'OK';
     } else {
         $sResult = 'KO';
     }
     // Output
     $oEvent->getIO()->write(sprintf("\n%s: %s", $sOutput, $sResult));
     // Copy dist config
     $sOutput = 'Copy the local dist config';
     $sErrorMessage = '';
     try {
         $oFileManager->copy($sLocalDistConfigPath, $sLocalConfigPath);
     } catch (Exception $oException) {
         // Update error message
         $sErrorMessage = $oException->getMessage();
     }
     // Error
     if ($sErrorMessage === '') {
         // Output
         $oEvent->getIO()->write(sprintf("\n%s: OK", $sOutput));
         // Explain
         $oEvent->getIO()->write("\nTo install the manager, you need a valid UTF-8 database as well as a user with " . "read/write privileges on it. Once you have it, please fill in the information below:\n");
         // Set ouput
         $sOutput = 'Update local config parameters';
         // Get local config content
         $sLocalConfigContent = $oFileManager->read($sLocalConfigPath);
         // Get values to ask
         $aValuesToAsk = ['%DATASOURCE_HOSTNAME%' => ['label' => 'database host', 'default' => 'localhost', 'mandatory' => true], '%DATASOURCE_DATABASE%' => ['label' => 'database name', 'default' => 'deployment', 'mandatory' => true], '%DATASOURCE_USERNAME%' => ['label' => 'database user name', 'mandatory' => true], '%DATASOURCE_PASSWORD%' => ['label' => 'database user password', 'mandatory' => false], '%BUILD_nb_backups_per_project%' => ['label' => 'number of backups kept per project', 'default' => '2', 'mandatory' => true], '%BUILD_BIN_COMPOSER%' => ['label' => 'full path to composer binary', 'default' => '/usr/bin/composer', 'mandatory' => true, 'binary' => ['check_command' => '%s -v', 'name' => 'composer']], '%BUILD_BIN_GIT%' => ['label' => 'full path to git binary', 'default' => '/usr/local/bin/git', 'mandatory' => true, 'binary' => ['check_command' => '%s --version', 'name' => 'git']], '%BUILD_BIN_PHP%' => ['label' => 'full path to php binary', 'default' => '/usr/bin/php', 'mandatory' => true, 'binary' => ['check_command' => '%s -v', 'name' => 'php']]];
         // Loop through values to ask
         foreach ($aValuesToAsk as $sKeyToReplace => $aValueToAsk) {
             // Initialize
             $sDefault = isset($aValueToAsk['default']) ? $aValueToAsk['default'] : null;
             // Binary path
             if (isset($aValueToAsk['binary'])) {
                 // Get value
                 $sValue = ExtendedComposer::askBinaryPath($oEvent, $aValueToAsk['label'], $aValueToAsk['binary']['name'], $aValueToAsk['binary']['check_command'], $sDefault, true, $aValueToAsk['mandatory']);
             } else {
                 // Get value
                 $sValue = ExtendedComposer::askString($oEvent, $aValueToAsk['label'], $sDefault, $aValueToAsk['mandatory']);
             }
             // Replace config
             $sLocalConfigContent = preg_replace(sprintf('/%s/', ExtendedString::pregQuote($sKeyToReplace)), $sValue, $sLocalConfigContent);
         }
         // Put local config content
         $oFileManager->write($sLocalConfigContent, $sLocalConfigPath, WriteMethod::OVERWRITE);
         // Output
         $oEvent->getIO()->write(sprintf("\n%s: OK", $sOutput));
         // Get config
         $aConfig = ExtendedArray::extendWithDefaultValues(require __DIR__ . '/../../../app/config/local.php', require __DIR__ . '/../../../app/config/global.php');
         // Build extended PDO
         $aDatasourceConfig = $aConfig['datasources']['write']['deployment'];
         $oExtendedPDO = new ExtendedPdo("mysql:host={$aDatasourceConfig['hostname']};" . "dbname={$aDatasourceConfig['database']};", $aDatasourceConfig['username'], $aDatasourceConfig['password'], $aConfig['pdo_options']);
         // Execute SQL commands
         $sOutput = 'Execute SQL commands';
         $sErrorMessage = '';
         try {
             // Get SQL files
             $aSQLFiles = $oFileManager->explore(__DIR__ . '/../../../sql', OrderField::BASENAME);
             // Loop through SQL files
             /** @var $oSQLFile \Asticode\FileManager\Entity\File */
             foreach ($aSQLFiles as $oSQLFile) {
                 // Split statements
                 $aStatements = explode(';', $oFileManager->read($oSQLFile->getPath()));
                 // Loop through statements
                 foreach ($aStatements as $sStatement) {
                     if ($sStatement !== '') {
                         $oExtendedPDO->exec($sStatement);
                     }
                 }
             }
         } catch (Exception $oException) {
             // Get error message
             $sErrorMessage = $oException->getMessage();
         }
         // Error
         if ($sErrorMessage === '') {
             // Output
             $oEvent->getIO()->write(sprintf("\n%s: OK", $sOutput));
             // Create dirs
             $sOutput = 'Create directories';
             $aDirsToCreate = ['backups', 'gits', 'tmp'];
             // Check keys exist
             ExtendedArray::checkRequiredKeys($aConfig['build']['dirs'], $aDirsToCreate);
             // Loop through dirs to create
             foreach ($aDirsToCreate as $sDirToCreate) {
                 // Create dir
                 $oFileManager->createDir($aConfig['build']['dirs'][$sDirToCreate]);
             }
             // Output
             $oEvent->getIO()->write(sprintf("\n%s: OK", $sOutput));
             // Conclude
             $oEvent->getIO()->write("\n\nInstallation successful!\n\n\nYou can now add a new project with\n\n" . "    \$ <your path>/app/console project:add\n\nOr remove a project with\n\n" . "    \$ <your path>/app/console project:remove\n");
         } else {
             // Output
             $oEvent->getIO()->write(sprintf("\n%s: KO\n", $sOutput));
             // Throw exception
             throw new RuntimeException($sErrorMessage);
         }
     } else {
         // Output
         $oEvent->getIO()->write(sprintf("\n%s: KO\n", $sOutput));
         // Throw exception
         throw new RuntimeException($sErrorMessage);
     }
 }