PHPStorm refactoring.

This commit is contained in:
Andrés Montañez 2014-08-06 14:01:39 -03:00
parent 4c584b2634
commit fddeebe59a
48 changed files with 2011 additions and 1996 deletions

View file

@ -17,21 +17,20 @@ namespace Mage;
*/
class Autoload
{
/**
* Autoload a Class by it's Class Name
* @param string $className
/**
* Autoload a Class by it's Class Name
* @param string $className
* @return boolean
*/
*/
public function autoLoad($className)
{
$className = ltrim($className, '/');
$postfix = '/' . str_replace(array('_', '\\'), '/', $className . '.php');
$postfix = '/' . str_replace(array('_', '\\'), '/', $className . '.php');
//Try to load a normal Mage class (or Task). Think that Mage component is compiled to .phar
$baseDir = dirname(dirname(__FILE__));
$classFileWithinPhar = $baseDir . $postfix;
if($this->isReadable($classFileWithinPhar))
{
if ($this->isReadable($classFileWithinPhar)) {
/** @noinspection PhpIncludeInspection */
require_once $classFileWithinPhar;
return true;
@ -39,7 +38,7 @@ class Autoload
//Try to load a custom Task or Class. Notice that the path is absolute to CWD
$classFileOutsidePhar = getcwd() . '/.mage/tasks' . $postfix;
if($this->isReadable($classFileOutsidePhar)){
if ($this->isReadable($classFileOutsidePhar)) {
/** @noinspection PhpIncludeInspection */
require_once $classFileOutsidePhar;
return true;

View file

@ -19,11 +19,11 @@ use Mage\Config;
*/
abstract class AbstractCommand
{
/**
* Instance of the loaded Configuration.
*
* @var \Mage\Config
*/
/**
* Instance of the loaded Configuration.
*
* @var \Mage\Config
*/
protected $config = null;
/**

View file

@ -24,11 +24,11 @@ use Exception;
*/
class AddCommand extends AbstractCommand
{
/**
* Adds new Configuration Elements
* @see \Mage\Command\AbstractCommand::run()
* @throws Exception
*/
/**
* Adds new Configuration Elements
* @see \Mage\Command\AbstractCommand::run()
* @throws Exception
*/
public function run()
{
$subCommand = $this->getConfig()->getArgument(1);
@ -71,24 +71,24 @@ class AddCommand extends AbstractCommand
Console::output('Adding new environment: <dark_gray>' . $environmentName . '</dark_gray>');
$releasesConfig = 'releases:' . PHP_EOL
. ' enabled: true' . PHP_EOL
. ' max: 10' . PHP_EOL
. ' symlink: current' . PHP_EOL
. ' directory: releases' . PHP_EOL;
. ' enabled: true' . PHP_EOL
. ' max: 10' . PHP_EOL
. ' symlink: current' . PHP_EOL
. ' directory: releases' . PHP_EOL;
$baseConfig = '#' . $environmentName . PHP_EOL
. 'deployment:' . PHP_EOL
. ' user: dummy' . PHP_EOL
. ' from: ./' . PHP_EOL
. ' to: /var/www/vhosts/example.com/www' . PHP_EOL
. ' excludes:' . PHP_EOL
. ($withReleases ? $releasesConfig : '')
. 'hosts:' . PHP_EOL
. 'tasks:' . PHP_EOL
. ' pre-deploy:' . PHP_EOL
. ' on-deploy:' . PHP_EOL
. ($withReleases ? (' post-release:' . PHP_EOL) : '')
. ' post-deploy:' . PHP_EOL;
. 'deployment:' . PHP_EOL
. ' user: dummy' . PHP_EOL
. ' from: ./' . PHP_EOL
. ' to: /var/www/vhosts/example.com/www' . PHP_EOL
. ' excludes:' . PHP_EOL
. ($withReleases ? $releasesConfig : '')
. 'hosts:' . PHP_EOL
. 'tasks:' . PHP_EOL
. ' pre-deploy:' . PHP_EOL
. ' on-deploy:' . PHP_EOL
. ($withReleases ? (' post-release:' . PHP_EOL) : '')
. ' post-deploy:' . PHP_EOL;
$result = file_put_contents($environmentConfigFile, $baseConfig);

View file

@ -24,12 +24,12 @@ class CompileCommand extends AbstractCommand
/**
* @see \Mage\Compile::compile()
*/
public function run ()
public function run()
{
if (ini_get('phar.readonly')) {
Console::output('The <purple>php.ini</purple> variable <light_red>phar.readonly</light_red> must be <yellow>Off</yellow>.', 1, 2);
return;
}
if (ini_get('phar.readonly')) {
Console::output('The <purple>php.ini</purple> variable <light_red>phar.readonly</light_red> must be <yellow>Off</yellow>.', 1, 2);
return;
}
$compiler = new Compiler;
$compiler->compile();

View file

@ -35,31 +35,31 @@ class DeployCommand extends AbstractCommand implements RequiresEnvironment
const DEPLOY_STRATEGY_RSYNC = 'rsync';
const DEPLOY_STRATEGY_TARGZ = 'targz';
const DEPLOY_STRATEGY_GIT_REBASE = 'git-rebase';
const DEPLOY_STRATEGY_GUESS = 'guess';
const DEPLOY_STRATEGY_GUESS = 'guess';
const DEFAULT_DEPLOY_STRATEGY = self::DEPLOY_STRATEGY_GUESS;
/**
* Deploy has Failed
* @var string
*/
const FAILED = 'failed';
* Deploy has Failed
* @var string
*/
const FAILED = 'failed';
/**
* Deploy has Succeded
* @var string
*/
const SUCCEDED = 'succeded';
/**
* Deploy has Succeded
* @var string
*/
const SUCCEDED = 'succeded';
/**
* Deploy is in progress
* @var string
*/
const IN_PROGRESS = 'in_progress';
/**
* Deploy is in progress
* @var string
*/
const IN_PROGRESS = 'in_progress';
/**
* Time the Deployment has Started
* @var integer
*/
/**
* Time the Deployment has Started
* @var integer
*/
protected $startTime = null;
/**
@ -99,7 +99,7 @@ class DeployCommand extends AbstractCommand implements RequiresEnvironment
*/
public static function getStatus()
{
return self::$deployStatus;
return self::$deployStatus;
}
/**
@ -109,20 +109,20 @@ class DeployCommand extends AbstractCommand implements RequiresEnvironment
public function run()
{
// Check if Environment is not Locked
$lockFile = getcwd() . '/.mage/' . $this->getConfig()->getEnvironment() . '.lock';
if (file_exists($lockFile)) {
Console::output('<red>This environment is locked!</red>', 1, 2);
echo file_get_contents($lockFile);
return;
}
$lockFile = getcwd() . '/.mage/' . $this->getConfig()->getEnvironment() . '.lock';
if (file_exists($lockFile)) {
Console::output('<red>This environment is locked!</red>', 1, 2);
echo file_get_contents($lockFile);
return;
}
// Check for running instance and Lock
if (file_exists(getcwd() . '/.mage/~working.lock')) {
Console::output('<red>There is already an instance of Magallanes running!</red>', 1, 2);
return;
} else {
touch(getcwd() . '/.mage/~working.lock');
}
// Check for running instance and Lock
if (file_exists(getcwd() . '/.mage/~working.lock')) {
Console::output('<red>There is already an instance of Magallanes running!</red>', 1, 2);
return;
} else {
touch(getcwd() . '/.mage/~working.lock');
}
// Release ID
$this->getConfig()->setReleaseId(date('YmdHis'));
@ -135,15 +135,15 @@ class DeployCommand extends AbstractCommand implements RequiresEnvironment
// Deploy Summary - Releases
if ($this->getConfig()->release('enabled', false)) {
Console::output('<dark_gray>Release ID:</dark_gray> <purple>' . $this->getConfig()->getReleaseId() . '</purple>', 2, 1);
Console::output('<dark_gray>Release ID:</dark_gray> <purple>' . $this->getConfig()->getReleaseId() . '</purple>', 2, 1);
}
// Deploy Summary - SCM
if ($this->getConfig()->deployment('scm', false)) {
$scmConfig = $this->getConfig()->deployment('scm');
if (isset($scmConfig['branch'])) {
Console::output('<dark_gray>SCM Branch:</dark_gray> <purple>' . $scmConfig['branch'] . '</purple>', 2, 1);
}
$scmConfig = $this->getConfig()->deployment('scm');
if (isset($scmConfig['branch'])) {
Console::output('<dark_gray>SCM Branch:</dark_gray> <purple>' . $scmConfig['branch'] . '</purple>', 2, 1);
}
}
// Deploy Summary - Separator Line
@ -156,21 +156,21 @@ class DeployCommand extends AbstractCommand implements RequiresEnvironment
// Check Status
if (self::$failedTasks > 0) {
self::$deployStatus = self::FAILED;
Console::output('A total of <dark_gray>' . self::$failedTasks . '</dark_gray> deployment tasks failed: <red>ABORTING</red>', 1, 2);
self::$deployStatus = self::FAILED;
Console::output('A total of <dark_gray>' . self::$failedTasks . '</dark_gray> deployment tasks failed: <red>ABORTING</red>', 1, 2);
} else {
// Run Deployment Tasks
$this->runDeploymentTasks();
// Run Deployment Tasks
$this->runDeploymentTasks();
// Check Status
if (self::$failedTasks > 0) {
self::$deployStatus = self::FAILED;
Console::output('A total of <dark_gray>' . self::$failedTasks . '</dark_gray> deployment tasks failed: <red>ABORTING</red>', 1, 2);
}
// Check Status
if (self::$failedTasks > 0) {
self::$deployStatus = self::FAILED;
Console::output('A total of <dark_gray>' . self::$failedTasks . '</dark_gray> deployment tasks failed: <red>ABORTING</red>', 1, 2);
}
// Run Post-Deployment Tasks
$this->runNonDeploymentTasks(AbstractTask::STAGE_POST_DEPLOY, $this->getConfig(), 'Post-Deployment');
// Run Post-Deployment Tasks
$this->runNonDeploymentTasks(AbstractTask::STAGE_POST_DEPLOY, $this->getConfig(), 'Post-Deployment');
}
// Time Information Hosts
@ -191,7 +191,7 @@ class DeployCommand extends AbstractCommand implements RequiresEnvironment
// Unlock
if (file_exists(getcwd() . '/.mage/~working.lock')) {
unlink(getcwd() . '/.mage/~working.lock');
unlink(getcwd() . '/.mage/~working.lock');
}
}
@ -209,33 +209,33 @@ class DeployCommand extends AbstractCommand implements RequiresEnvironment
// PreDeployment Hook
if ($stage == AbstractTask::STAGE_PRE_DEPLOY) {
// Look for Remote Source
if (is_array($config->deployment('source', null))) {
array_unshift($tasksToRun, 'scm/clone');
}
// Look for Remote Source
if (is_array($config->deployment('source', null))) {
array_unshift($tasksToRun, 'scm/clone');
}
// Change Branch
if ($config->deployment('scm', false)) {
array_unshift($tasksToRun, 'scm/change-branch');
}
// Change Branch
if ($config->deployment('scm', false)) {
array_unshift($tasksToRun, 'scm/change-branch');
}
}
// PostDeployment Hook
if ($stage == AbstractTask::STAGE_POST_DEPLOY) {
// If Deploy failed, clear post deploy tasks
if (self::$deployStatus == self::FAILED) {
$tasksToRun = array();
}
// If Deploy failed, clear post deploy tasks
if (self::$deployStatus == self::FAILED) {
$tasksToRun = array();
}
// Change Branch Back
if ($config->deployment('scm', false)) {
array_unshift($tasksToRun, 'scm/change-branch');
$config->addParameter('_changeBranchRevert');
}
// Change Branch Back
if ($config->deployment('scm', false)) {
array_unshift($tasksToRun, 'scm/change-branch');
$config->addParameter('_changeBranchRevert');
}
// Remove Remote Source
if (is_array($config->deployment('source', null))) {
array_push($tasksToRun, 'scm/remove-clone');
// Remove Remote Source
if (is_array($config->deployment('source', null))) {
array_push($tasksToRun, 'scm/remove-clone');
}
}
@ -255,7 +255,7 @@ class DeployCommand extends AbstractCommand implements RequiresEnvironment
if ($this->runTask($task)) {
$completedTasks++;
} else {
self::$failedTasks++;
self::$failedTasks++;
}
}
@ -271,151 +271,151 @@ class DeployCommand extends AbstractCommand implements RequiresEnvironment
protected function runDeploymentTasks()
{
if (self::$deployStatus == self::FAILED) {
return;
}
if (self::$deployStatus == self::FAILED) {
return;
}
// Run Tasks for Deployment
$hosts = $this->getConfig()->getHosts();
$this->hostsCount = count($hosts);
self::$failedTasks = 0;
// Run Tasks for Deployment
$hosts = $this->getConfig()->getHosts();
$this->hostsCount = count($hosts);
self::$failedTasks = 0;
if ($this->hostsCount == 0) {
Console::output('<light_purple>Warning!</light_purple> <dark_gray>No hosts defined, skipping deployment tasks.</dark_gray>', 1, 3);
if ($this->hostsCount == 0) {
Console::output('<light_purple>Warning!</light_purple> <dark_gray>No hosts defined, skipping deployment tasks.</dark_gray>', 1, 3);
} else {
$this->startTimeHosts = time();
foreach ($hosts as $hostKey => $host) {
} else {
$this->startTimeHosts = time();
foreach ($hosts as $hostKey => $host) {
// Check if Host has specific configuration
$hostConfig = null;
if (is_array($host)) {
$hostConfig = $host;
$host = $hostKey;
}
// Check if Host has specific configuration
$hostConfig = null;
if (is_array($host)) {
$hostConfig = $host;
$host = $hostKey;
}
// Set Host and Host Specific Config
$this->getConfig()->setHost($host);
$this->getConfig()->setHostConfig($hostConfig);
// Set Host and Host Specific Config
$this->getConfig()->setHost($host);
$this->getConfig()->setHostConfig($hostConfig);
// Prepare Tasks
$tasks = 0;
$completedTasks = 0;
// Prepare Tasks
$tasks = 0;
$completedTasks = 0;
Console::output('Deploying to <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray>');
Console::output('Deploying to <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray>');
$tasksToRun = $this->getConfig()->getTasks();
$tasksToRun = $this->getConfig()->getTasks();
$deployStrategy = $this->chooseDeployStrategy();
array_unshift($tasksToRun, $deployStrategy);
if (count($tasksToRun) == 0) {
Console::output('<light_purple>Warning!</light_purple> <dark_gray>No </dark_gray><light_cyan>Deployment</light_cyan> <dark_gray>tasks defined.</dark_gray>', 2);
Console::output('Deployment to <dark_gray>' . $host . '</dark_gray> skipped!', 1, 3);
if (count($tasksToRun) == 0) {
Console::output('<light_purple>Warning!</light_purple> <dark_gray>No </dark_gray><light_cyan>Deployment</light_cyan> <dark_gray>tasks defined.</dark_gray>', 2);
Console::output('Deployment to <dark_gray>' . $host . '</dark_gray> skipped!', 1, 3);
} else {
foreach ($tasksToRun as $taskData) {
$tasks++;
$task = Factory::get($taskData, $this->getConfig(), false, AbstractTask::STAGE_DEPLOY);
} else {
foreach ($tasksToRun as $taskData) {
$tasks++;
$task = Factory::get($taskData, $this->getConfig(), false, AbstractTask::STAGE_DEPLOY);
if ($this->runTask($task)) {
$completedTasks++;
} else {
self::$failedTasks++;
}
}
if ($this->runTask($task)) {
$completedTasks++;
} else {
self::$failedTasks++;
}
}
if ($completedTasks == $tasks) {
$tasksColor = 'green';
} else {
$tasksColor = 'red';
}
if ($completedTasks == $tasks) {
$tasksColor = 'green';
} else {
$tasksColor = 'red';
}
Console::output('Deployment to <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray> completed: <' . $tasksColor . '>' . $completedTasks . '/' . $tasks . '</' . $tasksColor . '> tasks done.', 1, 3);
}
Console::output('Deployment to <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray> completed: <' . $tasksColor . '>' . $completedTasks . '/' . $tasks . '</' . $tasksColor . '> tasks done.', 1, 3);
}
// Reset Host Config
$this->getConfig()->setHostConfig(null);
}
$this->endTimeHosts = time();
// Reset Host Config
$this->getConfig()->setHostConfig(null);
}
$this->endTimeHosts = time();
if (self::$failedTasks > 0) {
self::$deployStatus = self::FAILED;
} else {
self::$deployStatus = self::SUCCEDED;
}
if (self::$failedTasks > 0) {
self::$deployStatus = self::FAILED;
} else {
self::$deployStatus = self::SUCCEDED;
}
// Releasing
if (self::$deployStatus == self::SUCCEDED && $this->getConfig()->release('enabled', false) == true) {
// Execute the Releases
Console::output('Starting the <dark_gray>Releasing</dark_gray>');
foreach ($hosts as $hostKey => $host) {
// Releasing
if (self::$deployStatus == self::SUCCEDED && $this->getConfig()->release('enabled', false) == true) {
// Execute the Releases
Console::output('Starting the <dark_gray>Releasing</dark_gray>');
foreach ($hosts as $hostKey => $host) {
// Check if Host has specific configuration
$hostConfig = null;
if (is_array($host)) {
$hostConfig = $host;
$host = $hostKey;
}
// Check if Host has specific configuration
$hostConfig = null;
if (is_array($host)) {
$hostConfig = $host;
$host = $hostKey;
}
// Set Host
$this->getConfig()->setHost($host);
$this->getConfig()->setHostConfig($hostConfig);
// Set Host
$this->getConfig()->setHost($host);
$this->getConfig()->setHostConfig($hostConfig);
$task = Factory::get($this->chooseReleaseStrategy(), $this->getConfig(), false, AbstractTask::STAGE_DEPLOY);
$task = Factory::get($this->chooseReleaseStrategy(), $this->getConfig(), false, AbstractTask::STAGE_DEPLOY);
if ($this->runTask($task, 'Releasing on host <purple>' . $host . '</purple> ... ')) {
$completedTasks++;
}
if ($this->runTask($task, 'Releasing on host <purple>' . $host . '</purple> ... ')) {
$completedTasks++;
}
// Reset Host Config
$this->getConfig()->setHostConfig(null);
}
Console::output('Finished the <dark_gray>Releasing</dark_gray>', 1, 3);
// Reset Host Config
$this->getConfig()->setHostConfig(null);
}
Console::output('Finished the <dark_gray>Releasing</dark_gray>', 1, 3);
// Execute the Post-Release Tasks
foreach ($hosts as $hostKey => $host) {
// Execute the Post-Release Tasks
foreach ($hosts as $hostKey => $host) {
// Check if Host has specific configuration
$hostConfig = null;
if (is_array($host)) {
$hostConfig = $host;
$host = $hostKey;
}
// Check if Host has specific configuration
$hostConfig = null;
if (is_array($host)) {
$hostConfig = $host;
$host = $hostKey;
}
// Set Host
$this->getConfig()->setHost($host);
$this->getConfig()->setHostConfig($hostConfig);
// Set Host
$this->getConfig()->setHost($host);
$this->getConfig()->setHostConfig($hostConfig);
$tasksToRun = $this->getConfig()->getTasks(AbstractTask::STAGE_POST_RELEASE);
$tasks = count($tasksToRun);
$completedTasks = 0;
$tasksToRun = $this->getConfig()->getTasks(AbstractTask::STAGE_POST_RELEASE);
$tasks = count($tasksToRun);
$completedTasks = 0;
if (count($tasksToRun) > 0) {
Console::output('Starting <dark_gray>Post-Release</dark_gray> tasks for <dark_gray>' . $host . '</dark_gray>:');
if (count($tasksToRun) > 0) {
Console::output('Starting <dark_gray>Post-Release</dark_gray> tasks for <dark_gray>' . $host . '</dark_gray>:');
foreach ($tasksToRun as $task) {
$task = Factory::get($task, $this->getConfig(), false, AbstractTask::STAGE_POST_RELEASE);
foreach ($tasksToRun as $task) {
$task = Factory::get($task, $this->getConfig(), false, AbstractTask::STAGE_POST_RELEASE);
if ($this->runTask($task)) {
$completedTasks++;
}
}
if ($this->runTask($task)) {
$completedTasks++;
}
}
if ($completedTasks == $tasks) {
$tasksColor = 'green';
} else {
$tasksColor = 'red';
}
Console::output('Finished <dark_gray>Post-Release</dark_gray> tasks for <dark_gray>' . $host . '</dark_gray>: <' . $tasksColor . '>' . $completedTasks . '/' . $tasks . '</' . $tasksColor . '> tasks done.', 1, 3);
}
if ($completedTasks == $tasks) {
$tasksColor = 'green';
} else {
$tasksColor = 'red';
}
Console::output('Finished <dark_gray>Post-Release</dark_gray> tasks for <dark_gray>' . $host . '</dark_gray>: <' . $tasksColor . '>' . $completedTasks . '/' . $tasks . '</' . $tasksColor . '> tasks done.', 1, 3);
}
// Reset Host Config
$this->getConfig()->setHostConfig(null);
}
}
}
// Reset Host Config
$this->getConfig()->setHostConfig(null);
}
}
}
}
/**
@ -452,8 +452,8 @@ class DeployCommand extends AbstractCommand implements RequiresEnvironment
$result = false;
}
} catch (ErrorWithMessageException $e) {
Console::output('<red>FAIL</red> [Message: ' . $e->getMessage() . ']', 0);
$result = false;
Console::output('<red>FAIL</red> [Message: ' . $e->getMessage() . ']', 0);
$result = false;
} catch (SkipException $e) {
Console::output('<yellow>SKIPPED</yellow>', 0);
@ -506,21 +506,21 @@ class DeployCommand extends AbstractCommand implements RequiresEnvironment
*/
protected function sendNotification($result)
{
$projectName = $this->getConfig()->general('name', false);
$projectEmail = $this->getConfig()->general('email', false);
$notificationsEnabled = $this->getConfig()->general('notifications', false);
$projectName = $this->getConfig()->general('name', false);
$projectEmail = $this->getConfig()->general('email', false);
$notificationsEnabled = $this->getConfig()->general('notifications', false);
// We need notifications enabled, and a project name and email to send the notification
// We need notifications enabled, and a project name and email to send the notification
if (!$projectName || !$projectEmail || !$notificationsEnabled) {
return false;
}
$mailer = new Mailer;
$mailer->setAddress($projectEmail)
->setProject($projectName)
->setLogFile(Console::getLogFile())
->setEnvironment($this->getConfig()->getEnvironment())
->send($result);
->setProject($projectName)
->setLogFile(Console::getLogFile())
->setEnvironment($this->getConfig()->getEnvironment())
->send($result);
return true;
}
@ -532,30 +532,30 @@ class DeployCommand extends AbstractCommand implements RequiresEnvironment
{
// Guess a Deploy Strategy
switch ($this->getConfig()->deployment('strategy', self::DEFAULT_DEPLOY_STRATEGY)) {
case self::DEPLOY_STRATEGY_DISABLED:
$deployStrategy = 'deployment/strategy/disabled';
break;
case self::DEPLOY_STRATEGY_DISABLED:
$deployStrategy = 'deployment/strategy/disabled';
break;
case self::DEPLOY_STRATEGY_RSYNC:
$deployStrategy = 'deployment/strategy/rsync';
break;
case self::DEPLOY_STRATEGY_TARGZ:
$deployStrategy = 'deployment/strategy/tar-gz';
break;
case self::DEPLOY_STRATEGY_GIT_REBASE:
$deployStrategy = 'deployment/strategy/git-rebase';
break;
case self::DEPLOY_STRATEGY_GUESS:
default:
if ($this->getConfig()->release('enabled', false) == true) {
$deployStrategy = 'deployment/strategy/tar-gz';
} else {
case self::DEPLOY_STRATEGY_RSYNC:
$deployStrategy = 'deployment/strategy/rsync';
}
break;
break;
case self::DEPLOY_STRATEGY_TARGZ:
$deployStrategy = 'deployment/strategy/tar-gz';
break;
case self::DEPLOY_STRATEGY_GIT_REBASE:
$deployStrategy = 'deployment/strategy/git-rebase';
break;
case self::DEPLOY_STRATEGY_GUESS:
default:
if ($this->getConfig()->release('enabled', false) == true) {
$deployStrategy = 'deployment/strategy/tar-gz';
} else {
$deployStrategy = 'deployment/strategy/rsync';
}
break;
}
return $deployStrategy;
}

View file

@ -21,10 +21,10 @@ use Mage\Console;
class InitCommand extends AbstractCommand
{
/**
* Command for Initalize a new Configuration Proyect
* @see \Mage\Command\AbstractCommand::run()
*/
/**
* Command for Initalize a new Configuration Proyect
* @see \Mage\Command\AbstractCommand::run()
*/
public function run()
{
$configDir = getcwd() . '/.mage';
@ -61,32 +61,32 @@ class InitCommand extends AbstractCommand
*/
protected function getGeneralConfig()
{
// Assamble Global Settings
$projectName = $this->getConfig()->getParameter('name', '');
$notificationEmail = $this->getConfig()->getParameter('email', '');
$notificationEnabled = ($notificationEmail != '') ? 'true' : 'false';
// Assamble Global Settings
$projectName = $this->getConfig()->getParameter('name', '');
$notificationEmail = $this->getConfig()->getParameter('email', '');
$notificationEnabled = ($notificationEmail != '') ? 'true' : 'false';
$globalSettings = str_replace(
array(
'%projectName%',
'%notificationEmail%',
'%notificationEnabled%',
'%loggingEnabled%',
'%maxlogs%',
'%ssh_needs_tty%',
),
array(
$projectName,
$notificationEmail,
$notificationEnabled,
'true',
30,
'false'
),
$this->getGeneralConfigTemplate()
);
$globalSettings = str_replace(
array(
'%projectName%',
'%notificationEmail%',
'%notificationEnabled%',
'%loggingEnabled%',
'%maxlogs%',
'%ssh_needs_tty%',
),
array(
$projectName,
$notificationEmail,
$notificationEnabled,
'true',
30,
'false'
),
$this->getGeneralConfigTemplate()
);
return $globalSettings;
return $globalSettings;
}
/**
@ -95,14 +95,14 @@ class InitCommand extends AbstractCommand
*/
protected function getGeneralConfigTemplate()
{
$template = '# global settings' . PHP_EOL
. 'name: %projectName%' . PHP_EOL
. 'email: %notificationEmail%' . PHP_EOL
. 'notifications: %notificationEnabled%' . PHP_EOL
. 'logging: %loggingEnabled%' . PHP_EOL
. 'maxlogs: %maxlogs%' . PHP_EOL
. 'ssh_needs_tty: %ssh_needs_tty%' . PHP_EOL;
$template = '# global settings' . PHP_EOL
. 'name: %projectName%' . PHP_EOL
. 'email: %notificationEmail%' . PHP_EOL
. 'notifications: %notificationEnabled%' . PHP_EOL
. 'logging: %loggingEnabled%' . PHP_EOL
. 'maxlogs: %maxlogs%' . PHP_EOL
. 'ssh_needs_tty: %ssh_needs_tty%' . PHP_EOL;
return $template;
return $template;
}
}

View file

@ -20,60 +20,61 @@ use Mage\Console;
*/
class InstallCommand extends AbstractCommand
{
/**
* Installs Magallanes
* @see \Mage\Command\AbstractCommand::run()
*/
/**
* Installs Magallanes
* @see \Mage\Command\AbstractCommand::run()
*/
public function run()
{
Console::output('Installing <dark_gray>Magallanes</dark_gray>... ', 1, 0);
Console::output('Installing <dark_gray>Magallanes</dark_gray>... ', 1, 0);
// Vars
$installDir = $this->getConfig()->getParameter('installDir', '/opt/magallanes');
$systemWide = $this->getConfig()->getParameter('systemWide', false);
// Vars
$installDir = $this->getConfig()->getParameter('installDir', '/opt/magallanes');
$systemWide = $this->getConfig()->getParameter('systemWide', false);
// Clean vars
$baseDir = realpath(dirname($installDir));
$installDir = basename($installDir);
// Clean vars
$baseDir = realpath(dirname($installDir));
$installDir = basename($installDir);
// Check if install dir is available
if (!is_dir($baseDir) || !is_writable($baseDir)) {
Console::output('<red>Failure: install directory is invalid.</red>', 0, 2);
// Check if install dir is available
if (!is_dir($baseDir) || !is_writable($baseDir)) {
Console::output('<red>Failure: install directory is invalid.</red>', 0, 2);
// Chck if it is a system wide install the user is root
} else if ($systemWide && (getenv('LOGNAME') != 'root')) {
Console::output('<red>Failure: you have to be root to perform a system wide install.</red>', 0, 2);
// Chck if it is a system wide install the user is root
} else if ($systemWide && (getenv('LOGNAME') != 'root')) {
Console::output('<red>Failure: you have to be root to perform a system wide install.</red>', 0, 2);
} else {
$destinationDir = $baseDir . '/' . $installDir;
if (!is_dir($destinationDir)) {
mkdir($destinationDir);
}
} else {
$destinationDir = $baseDir . '/' . $installDir;
if (!is_dir($destinationDir)) {
mkdir($destinationDir);
}
// Copy
$this->recursiveCopy('./', $destinationDir . '/' . MAGALLANES_VERSION);
// Copy
$this->recursiveCopy('./', $destinationDir . '/' . MAGALLANES_VERSION);
// Check if there is already a symlink
if (file_exists($destinationDir . '/' . 'latest')
&& is_link($destinationDir . '/' . 'latest')) {
unlink($destinationDir . '/' . 'latest');
}
// Check if there is already a symlink
if (file_exists($destinationDir . '/' . 'latest')
&& is_link($destinationDir . '/' . 'latest')
) {
unlink($destinationDir . '/' . 'latest');
}
// Create "latest" symlink
symlink(
$destinationDir . '/' . MAGALLANES_VERSION,
$destinationDir . '/' . 'latest'
);
chmod($destinationDir . '/' . MAGALLANES_VERSION . '/bin/mage', 0755);
// Create "latest" symlink
symlink(
$destinationDir . '/' . MAGALLANES_VERSION,
$destinationDir . '/' . 'latest'
);
chmod($destinationDir . '/' . MAGALLANES_VERSION . '/bin/mage', 0755);
if ($systemWide) {
if (!file_exists('/usr/bin/mage')) {
symlink($destinationDir . '/latest/bin/mage', '/usr/bin/mage');
}
}
if ($systemWide) {
if (!file_exists('/usr/bin/mage')) {
symlink($destinationDir . '/latest/bin/mage', '/usr/bin/mage');
}
}
Console::output('<light_green>Success!</light_green>', 0, 2);
}
Console::output('<light_green>Success!</light_green>', 0, 2);
}
}
/**

View file

@ -24,11 +24,11 @@ use Exception;
*/
class ListCommand extends AbstractCommand
{
/**
* Command for Listing Configuration Elements
* @see \Mage\Command\AbstractCommand::run()
* @throws Exception
*/
/**
* Command for Listing Configuration Elements
* @see \Mage\Command\AbstractCommand::run()
* @throws Exception
*/
public function run()
{
$subCommand = $this->getConfig()->getArgument(1);
@ -53,24 +53,24 @@ class ListCommand extends AbstractCommand
*/
protected function listEnvironments()
{
$environments = array();
$environments = array();
$content = scandir(getcwd() . '/.mage/config/environment/');
foreach ($content as $file) {
if (strpos($file, '.yml') !== false) {
$environments[] = str_replace('.yml', '', $file);
$environments[] = str_replace('.yml', '', $file);
}
}
sort($environments);
if (count($environments) > 0) {
Console::output('<dark_gray>These are your configured environments:</dark_gray>', 1, 1);
foreach ($environments as $environment) {
Console::output('* <light_red>' . $environment . '</light_red>', 2, 1);
}
Console::output('', 1, 1);
Console::output('<dark_gray>These are your configured environments:</dark_gray>', 1, 1);
foreach ($environments as $environment) {
Console::output('* <light_red>' . $environment . '</light_red>', 2, 1);
}
Console::output('', 1, 1);
} else {
Console::output('<dark_gray>You don\'t have any environment configured.</dark_gray>', 1, 2);
Console::output('<dark_gray>You don\'t have any environment configured.</dark_gray>', 1, 2);
}
}
}

View file

@ -21,10 +21,10 @@ use Mage\Console;
*/
class LockCommand extends AbstractCommand implements RequiresEnvironment
{
/**
* Locks the Deployment to a Environment
* @see \Mage\Command\AbstractCommand::run()
*/
/**
* Locks the Deployment to a Environment
* @see \Mage\Command\AbstractCommand::run()
*/
public function run()
{
Console::output('Your name (enter to leave blank): ', 0, 0);

View file

@ -46,33 +46,33 @@ class ReleasesCommand extends AbstractCommand implements RequiresEnvironment
$this->getConfig()->setHost($host);
switch ($subCommand) {
case 'list':
$task = Factory::get('releases/list', $this->getConfig());
$task->init();
$result = $task->run();
break;
case 'list':
$task = Factory::get('releases/list', $this->getConfig());
$task->init();
$result = $task->run();
break;
case 'rollback':
if (!is_numeric($this->getConfig()->getParameter('release', ''))) {
Console::output('<red>Missing required releaseid.</red>', 1, 2);
case 'rollback':
if (!is_numeric($this->getConfig()->getParameter('release', ''))) {
Console::output('<red>Missing required releaseid.</red>', 1, 2);
return false;
}
return false;
}
$lockFile = getcwd() . '/.mage/' . $this->getConfig()->getEnvironment() . '.lock';
if (file_exists($lockFile)) {
Console::output('<red>This environment is locked!</red>', 1, 2);
echo file_get_contents($lockFile);
$lockFile = getcwd() . '/.mage/' . $this->getConfig()->getEnvironment() . '.lock';
if (file_exists($lockFile)) {
Console::output('<red>This environment is locked!</red>', 1, 2);
echo file_get_contents($lockFile);
return false;
}
return false;
}
$releaseId = $this->getConfig()->getParameter('release', '');
$task = Factory::get('releases/rollback', $this->getConfig());
$task->init();
$task->setRelease($releaseId);
$result = $task->run();
break;
$releaseId = $this->getConfig()->getParameter('release', '');
$task = Factory::get('releases/rollback', $this->getConfig());
$task->init();
$task->setRelease($releaseId);
$result = $task->run();
break;
}
}

View file

@ -22,10 +22,10 @@ use Mage\Console;
class UnlockCommand
extends AbstractCommand implements RequiresEnvironment
{
/**
* Unlocks an Environment
* @see \Mage\Command\AbstractCommand::run()
*/
/**
* Unlocks an Environment
* @see \Mage\Command\AbstractCommand::run()
*/
public function run()
{
$lockFile = getcwd() . '/.mage/' . $this->getConfig()->getEnvironment() . '.lock';

View file

@ -21,10 +21,10 @@ use Mage\Console;
*/
class UpdateCommand extends AbstractCommand
{
/**
* Updates the SCM Base Code
* @see \Mage\Command\AbstractCommand::run()
*/
/**
* Updates the SCM Base Code
* @see \Mage\Command\AbstractCommand::run()
*/
public function run()
{
$task = Factory::get('scm/update', $this->getConfig());

View file

@ -20,10 +20,10 @@ use Mage\Console;
*/
class UpgradeCommand extends AbstractCommand
{
/**
* Source for downloading
* @var string
*/
/**
* Source for downloading
* @var string
*/
const DOWNLOAD = 'http://download.magephp.com/magallanes.{version}.tar.gz';
/**
@ -51,47 +51,47 @@ class UpgradeCommand extends AbstractCommand
Console::output('You need to be the <dark_gray>' . $owner . '</dark_gray> user to perform the upgrade, or <dark_gray>root</dark_gray>.', 2);
} else {
// Check version
$version = json_decode(file_get_contents(self::UPGRADE));
// Check version
$version = json_decode(file_get_contents(self::UPGRADE));
if ($version !== false && $version !== null) {
$versionCompare = version_compare(MAGALLANES_VERSION, $version->latest);
if ($versionCompare == 0) {
Console::output('<yellow>SKIP</yellow>', 0, 1);
Console::output('Your current version is up to date.', 2);
if ($version !== false && $version !== null) {
$versionCompare = version_compare(MAGALLANES_VERSION, $version->latest);
if ($versionCompare == 0) {
Console::output('<yellow>SKIP</yellow>', 0, 1);
Console::output('Your current version is up to date.', 2);
} else if ($versionCompare == 1) {
Console::output('<yellow>SKIP</yellow>', 0, 1);
Console::output('Your current version is newer.', 2);
} else if ($versionCompare == 1) {
Console::output('<yellow>SKIP</yellow>', 0, 1);
Console::output('Your current version is newer.', 2);
} else if ($versionCompare == -1) {
// Download Package
$tarball = file_get_contents(str_replace('{version}', $version->latest, self::DOWNLOAD));
if ($tarball === false) {
Console::output('<red>FAIL</red>', 0, 1);
Console::output('Corrupted download.', 2);
} else if ($versionCompare == -1) {
// Download Package
$tarball = file_get_contents(str_replace('{version}', $version->latest, self::DOWNLOAD));
if ($tarball === false) {
Console::output('<red>FAIL</red>', 0, 1);
Console::output('Corrupted download.', 2);
} else {
$tarballFile = tempnam('/tmp', 'magallanes_download');
rename($tarballFile, $tarballFile . '.tar.gz');
$tarballFile .= '.tar.gz';
file_put_contents($tarballFile, $tarball);
} else {
$tarballFile = tempnam('/tmp', 'magallanes_download');
rename($tarballFile, $tarballFile . '.tar.gz');
$tarballFile .= '.tar.gz';
file_put_contents($tarballFile, $tarball);
Console::executeCommand('rm -rf ' . MAGALLANES_DIRECTORY);
Console::executeCommand('cd ' . dirname($tarballFile) . ' && tar xfz ' . $tarballFile);
Console::executeCommand('mv ' . dirname($tarballFile) . '/magallanes ' . MAGALLANES_DIRECTORY);
Console::executeCommand('rm -rf ' . MAGALLANES_DIRECTORY);
Console::executeCommand('cd ' . dirname($tarballFile) . ' && tar xfz ' . $tarballFile);
Console::executeCommand('mv ' . dirname($tarballFile) . '/magallanes ' . MAGALLANES_DIRECTORY);
Console::output('<green>OK</green>', 0, 1);
}
Console::output('<green>OK</green>', 0, 1);
}
} else {
Console::output('<red>FAIL</red>', 0, 1);
Console::output('Invalid version.', 2);
}
} else {
Console::output('<red>FAIL</red>', 0, 1);
Console::output('Invalid version.', 2);
}
} else {
Console::output('<red>FAIL</red>', 0, 1);
Console::output('Invalid version.', 2);
}
} else {
Console::output('<red>FAIL</red>', 0, 1);
Console::output('Invalid version.', 2);
}
}
}
}

View file

@ -20,13 +20,13 @@ use Mage\Console;
*/
class VersionCommand extends AbstractCommand
{
/**
* Display the Magallanes Version
* @see \Mage\Command\AbstractCommand::run()
*/
/**
* Display the Magallanes Version
* @see \Mage\Command\AbstractCommand::run()
*/
public function run()
{
Console::output('Running <blue>Magallanes</blue> version <dark_gray>' . MAGALLANES_VERSION .'</dark_gray>', 0, 2);
Console::output('Running <blue>Magallanes</blue> version <dark_gray>' . MAGALLANES_VERSION . '</dark_gray>', 0, 2);
}
}

View file

@ -40,7 +40,7 @@ class Factory
$className = 'Mage\\Command\\BuiltIn\\' . $commandName . 'Command';
/** @var AbstractCommand $instance */
$instance = new $className;
if(!is_a($instance, "Mage\Command\AbstractCommand")) {
if (!is_a($instance, "Mage\Command\AbstractCommand")) {
throw new Exception('The command ' . $commandName . ' must be an instance of Mage\Command\AbstractCommand.');
}

View file

@ -42,18 +42,18 @@ class Compiler
/** @var \SplFileInfo $path */
foreach ($iterator as $path) {
if ($path->isFile()) {
$phar->addFromString(str_replace(dirname(__DIR__).'/', '', $path->getPathname()), file_get_contents($path));
$phar->addFromString(str_replace(dirname(__DIR__) . '/', '', $path->getPathname()), file_get_contents($path));
}
}
$binary = file(__DIR__.'/../bin/mage');
$binary = file(__DIR__ . '/../bin/mage');
unset($binary[0]);
$binary = implode(PHP_EOL, $binary);
$phar->addFromString('mage', str_replace(
'$baseDir = dirname(dirname(__FILE__));',
'$baseDir = __DIR__;',
$binary
$binary
));
$phar->setStub("#!/usr/bin/env php\n<?php Phar::mapPhar('mage.phar'); require 'phar://mage.phar/mage'; __HALT_COMPILER();");

View file

@ -26,9 +26,9 @@ class Config
{
const HOST_NAME_LENGTH = 1000;
/**
* Arguments loaded
* @var array
*/
* Arguments loaded
* @var array
*/
private $arguments = array();
/**
@ -73,27 +73,27 @@ class Config
*/
protected function parse($arguments)
{
foreach ($arguments as $argument) {
if (preg_match('/to:[\w]+/i', $argument)) {
$this->environment = str_replace('to:', '', $argument);
foreach ($arguments as $argument) {
if (preg_match('/to:[\w]+/i', $argument)) {
$this->environment = str_replace('to:', '', $argument);
} else if (preg_match('/--[\w]+/i', $argument)) {
$optionValue = explode('=', substr($argument, 2));
if (count($optionValue) == 1) {
$this->parameters[$optionValue[0]] = true;
} else if (count($optionValue) == 2) {
if (strtolower($optionValue[1]) == 'true') {
$this->parameters[$optionValue[0]] = true;
} else if (strtolower($optionValue[1]) == 'false') {
$this->parameters[$optionValue[0]] = false;
} else {
$this->parameters[$optionValue[0]] = $optionValue[1];
}
}
} else {
$this->arguments[] = $argument;
}
}
} else if (preg_match('/--[\w]+/i', $argument)) {
$optionValue = explode('=', substr($argument, 2));
if (count($optionValue) == 1) {
$this->parameters[$optionValue[0]] = true;
} else if (count($optionValue) == 2) {
if (strtolower($optionValue[1]) == 'true') {
$this->parameters[$optionValue[0]] = true;
} else if (strtolower($optionValue[1]) == 'false') {
$this->parameters[$optionValue[0]] = false;
} else {
$this->parameters[$optionValue[0]] = $optionValue[1];
}
}
} else {
$this->arguments[] = $argument;
}
}
}
/**
@ -102,7 +102,7 @@ class Config
protected function initGeneral()
{
try {
$this->generalConfig = $this->loadGeneral(getcwd() . '/.mage/config/general.yml');
$this->generalConfig = $this->loadGeneral(getcwd() . '/.mage/config/general.yml');
} catch (ConfigNotFoundException $e) {
// normal situation
}
@ -116,7 +116,8 @@ class Config
* @return array
* @throws Config\ConfigNotFoundException
*/
protected function loadGeneral($filePath){
protected function loadGeneral($filePath)
{
return $this->parseConfigFile($filePath);
}
@ -142,6 +143,7 @@ class Config
return $settings;
}
/**
* Loads the Environment configuration
* @param $filePath string
@ -169,16 +171,15 @@ class Config
*/
protected function initEnvironment()
{
$environment = $this->getEnvironment();
$environment = $this->getEnvironment();
if(!empty($environment))
{
if (!empty($environment)) {
$configFilePath = getcwd() . '/.mage/config/environment/' . $environment . '.yml';
try {
$this->environmentConfig = $this->loadEnvironment($configFilePath);
$this->environmentConfig = $this->loadEnvironment($configFilePath);
} catch (ConfigNotFoundException $e) {
throw new RequiredConfigNotFoundException("Not found required config $configFilePath for environment $environment", 0 , $e);
throw new RequiredConfigNotFoundException("Not found required config $configFilePath for environment $environment", 0, $e);
}
}
@ -191,18 +192,17 @@ class Config
*/
protected function isRunInSpecialMode(array $parameters)
{
if(empty($parameters))
if (empty($parameters))
return true;
foreach($parameters as $parameter)
{
if(isset(Console::$paramsNotRequiringEnvironment[$parameter]))
{
foreach ($parameters as $parameter) {
if (isset(Console::$paramsNotRequiringEnvironment[$parameter])) {
return true;
}
}
return false;
}
/**
* Load the Configuration and parses the Arguments
*
@ -220,8 +220,8 @@ class Config
*/
public function reload()
{
$this->initGeneral();
$this->initEnvironment();
$this->initGeneral();
$this->initEnvironment();
}
/**
@ -286,7 +286,7 @@ class Config
*/
public function addParameter($name, $value = true)
{
$this->parameters[$name] = $value;
$this->parameters[$name] = $value;
}
/**
@ -307,24 +307,24 @@ class Config
*/
public function getTasks($stage = 'deploy')
{
if ($stage == 'deploy') {
$configStage = 'on-deploy';
} else {
$configStage = $stage;
}
if ($stage == 'deploy') {
$configStage = 'on-deploy';
} else {
$configStage = $stage;
}
$tasks = array();
$config = $this->getEnvironmentOption('tasks', array());
// Host Config
if (is_array($this->hostConfig) && isset($this->hostConfig['tasks'])) {
if (isset($this->hostConfig['tasks'][$configStage])) {
$config[$configStage] = $this->hostConfig['tasks'][$configStage];
}
if (isset($this->hostConfig['tasks'][$configStage])) {
$config[$configStage] = $this->hostConfig['tasks'][$configStage];
}
}
if (isset($config[$configStage])) {
$tasksData = ($config[$configStage] ? (array) $config[$configStage] : array());
$tasksData = ($config[$configStage] ? (array)$config[$configStage] : array());
foreach ($tasksData as $taskData) {
if (is_array($taskData)) {
$tasks[] = array(
@ -352,7 +352,7 @@ class Config
$envConfig = $this->getEnvironmentConfig();
if (isset($envConfig['hosts'])) {
if (is_array($envConfig['hosts'])) {
$hosts = (array) $envConfig['hosts'];
$hosts = (array)$envConfig['hosts'];
} else if (is_string($envConfig['hosts']) && file_exists($envConfig['hosts']) && is_readable($envConfig['hosts'])) {
$hosts = $this->getHostsFromFile($envConfig['hosts']);
}
@ -381,8 +381,8 @@ class Config
*/
public function setHostConfig($hostConfig = null)
{
$this->hostConfig = $hostConfig;
return $this;
$this->hostConfig = $hostConfig;
return $this;
}
/**
@ -458,7 +458,7 @@ class Config
*/
public function environmentConfig($option, $default = false)
{
return $this->getEnvironmentOption($option, $default);
return $this->getEnvironmentOption($option, $default);
}
/**
@ -470,14 +470,14 @@ class Config
*/
public function deployment($option, $default = false)
{
// Host Config
if (is_array($this->hostConfig) && isset($this->hostConfig['deployment'])) {
if (isset($this->hostConfig['deployment'][$option])) {
return $this->hostConfig['deployment'][$option];
}
}
// Host Config
if (is_array($this->hostConfig) && isset($this->hostConfig['deployment'])) {
if (isset($this->hostConfig['deployment'][$option])) {
return $this->hostConfig['deployment'][$option];
}
}
// Global Config
// Global Config
$config = $this->getEnvironmentOption('deployment', array());
if (isset($config[$option])) {
if (is_array($default) && ($config[$option] == '')) {
@ -499,12 +499,12 @@ class Config
*/
public function release($option, $default = false)
{
// Host Config
if (is_array($this->hostConfig) && isset($this->hostConfig['releases'])) {
if (isset($this->hostConfig['releases'][$option])) {
return $this->hostConfig['releases'][$option];
}
}
// Host Config
if (is_array($this->hostConfig) && isset($this->hostConfig['releases'])) {
if (isset($this->hostConfig['releases'][$option])) {
return $this->hostConfig['releases'][$option];
}
}
$config = $this->getEnvironmentOption('releases', array());
if (isset($config[$option])) {
@ -575,13 +575,13 @@ class Config
*/
public function parseConfigFile($filePath)
{
if(!file_exists($filePath))
{
if (!file_exists($filePath)) {
throw new ConfigNotFoundException("Cannot find the file at path $filePath");
}
return $this->parseConfigText(file_get_contents($filePath));
}
public function parseConfigText($input)
{
return Yaml::parse($input);

View file

@ -28,12 +28,12 @@ class Console
* TODO refactor into own static class
* @var array
*/
public static $paramsNotRequiringEnvironment = array('install'=>'install', 'upgrade'=>'upgrade', 'version'=>'version');
public static $paramsNotRequiringEnvironment = array('install' => 'install', 'upgrade' => 'upgrade', 'version' => 'version');
/**
* Handler to the current Log File.
* @var mixed
*/
/**
* Handler to the current Log File.
* @var mixed
*/
private static $log = null;
/**
@ -72,19 +72,19 @@ class Console
*/
public function run($arguments)
{
$exitCode = 10;
$exitCode = 10;
// Declare a Shutdown Closure
register_shutdown_function(function() {
// Only Unlock if there was an error
// Declare a Shutdown Closure
register_shutdown_function(function () {
// Only Unlock if there was an error
if (error_get_last() !== null) {
if (file_exists(getcwd() . '/.mage/~working.lock')) {
unlink(getcwd() . '/.mage/~working.lock');
}
if (file_exists(getcwd() . '/.mage/~working.lock')) {
unlink(getcwd() . '/.mage/~working.lock');
}
}
});
});
// Load configuration
// Load configuration
$configError = false;
try {
// Load Config
@ -126,7 +126,7 @@ class Console
self::output('<red>' . $configError . '</red>', 1, 2);
} else {
// Run Command and check for Command Requirements
// Run Command and check for Command Requirements
try {
$command = Factory::get($commandName, $config);
@ -146,7 +146,7 @@ class Console
if ($showGreetings) {
self::output('Finished <blue>Magallanes</blue>', 0, 2);
if (file_exists(getcwd() . '/.mage/~working.lock')) {
unlink(getcwd() . '/.mage/~working.lock');
unlink(getcwd() . '/.mage/~working.lock');
}
}
@ -168,12 +168,12 @@ class Console
self::log(strip_tags($message));
self::$screenBuffer .= str_repeat("\t", $tabs)
. strip_tags($message)
. str_repeat(PHP_EOL, $newLine);
. strip_tags($message)
. str_repeat(PHP_EOL, $newLine);
$output = str_repeat("\t", $tabs)
. Colors::color($message, self::$config)
. str_repeat(PHP_EOL, $newLine);
. Colors::color($message, self::$config)
. str_repeat(PHP_EOL, $newLine);
echo $output;
}
@ -215,7 +215,7 @@ class Console
{
if (self::$logEnabled) {
if (self::$log == null) {
self::$logFile = realpath(getcwd() . '/.mage/logs') . '/log-' . date('Ymd-His') . '.log';
self::$logFile = realpath(getcwd() . '/.mage/logs') . '/log-' . date('Ymd-His') . '.log';
self::$log = fopen(self::$logFile, 'w');
}
@ -230,7 +230,7 @@ class Console
*/
public static function getOutput()
{
return self::$screenBuffer;
return self::$screenBuffer;
}
/**
@ -239,7 +239,7 @@ class Console
*/
public static function getLogFile()
{
return self::$logFile;
return self::$logFile;
}
/**
@ -247,7 +247,7 @@ class Console
*/
public static function readInput()
{
$fp = fopen("php://stdin","r");
$fp = fopen("php://stdin", "r");
$line = '';
$line = fgets($fp);
@ -261,22 +261,22 @@ class Console
private static function checkLogs(Config $config)
{
if (self::$logEnabled) {
$maxLogs = $config->general('maxlogs', 30);
$maxLogs = $config->general('maxlogs', 30);
$logs = array();
foreach (new RecursiveDirectoryIterator(getcwd() . '/.mage/logs', RecursiveDirectoryIterator::SKIP_DOTS) as $log) {
if (strpos($log->getFilename(), 'log-') === 0) {
$logs[] = $log->getFilename();
}
}
$logs = array();
foreach (new RecursiveDirectoryIterator(getcwd() . '/.mage/logs', RecursiveDirectoryIterator::SKIP_DOTS) as $log) {
if (strpos($log->getFilename(), 'log-') === 0) {
$logs[] = $log->getFilename();
}
}
sort($logs);
if (count($logs) > $maxLogs) {
sort($logs);
if (count($logs) > $maxLogs) {
$logsToDelete = array_slice($logs, 0, count($logs) - $maxLogs);
foreach ($logsToDelete as $logToDeelte) {
unlink(getcwd() . '/.mage/logs/' . $logToDeelte);
unlink(getcwd() . '/.mage/logs/' . $logToDeelte);
}
}
}
}
}

View file

@ -19,27 +19,27 @@ use Mage\Config;
*/
class Colors
{
/**
* List of Colors and they Terminal/Console representation.
* @var array
*/
/**
* List of Colors and they Terminal/Console representation.
* @var array
*/
private static $foregroundColors = array(
'black' => '0;30',
'dark_gray' => '1;30',
'blue' => '0;34',
'light_blue' => '1;34',
'green' => '0;32',
'light_green' => '1;32',
'cyan' => '0;36',
'light_cyan' => '1;36',
'red' => '0;31',
'light_red' => '1;31',
'purple' => '0;35',
'black' => '0;30',
'dark_gray' => '1;30',
'blue' => '0;34',
'light_blue' => '1;34',
'green' => '0;32',
'light_green' => '1;32',
'cyan' => '0;36',
'light_cyan' => '1;36',
'red' => '0;31',
'light_red' => '1;31',
'purple' => '0;35',
'light_purple' => '1;35',
'brown' => '0;33',
'yellow' => '1;33',
'light_gray' => '0;37',
'white' => '1;37'
'brown' => '0;33',
'yellow' => '1;33',
'light_gray' => '0;37',
'white' => '1;37'
);
@ -52,17 +52,17 @@ class Colors
*/
public static function color($string, Config $config)
{
$disabled = $config->getParameter('no-color', !$config->general('colors', true));
$disabled = $config->getParameter('no-color', !$config->general('colors', true));
if ($disabled) {
$string = strip_tags($string);
return $string;
}
if ($disabled) {
$string = strip_tags($string);
return $string;
}
foreach (self::$foregroundColors as $key => $code) {
$replaceFrom = array(
'<' . $key . '>',
'</' . $key . '>'
'</' . $key . '>'
);
$replaceTo = array(

View file

@ -18,74 +18,72 @@ namespace Mage;
*/
class Mailer
{
const EOL = "\r\n";
const SUBJECT = '[Magallanes] Deployment of {project} to {environment}: {result}';
const EOL = "\r\n";
const SUBJECT = '[Magallanes] Deployment of {project} to {environment}: {result}';
protected $address;
protected $project;
protected $environment;
protected $logFile;
protected $address;
protected $project;
protected $environment;
protected $logFile;
public function setAddress($address)
{
public function setAddress($address)
{
$this->address = $address;
return $this;
}
}
public function setProject($project)
{
$this->project = $project;
return $this;
}
public function setProject($project)
{
$this->project = $project;
return $this;
}
public function setEnvironment($environment)
{
$this->environment = $environment;
return $this;
}
public function setEnvironment($environment)
{
$this->environment = $environment;
return $this;
}
public function setLogFile($logFile)
{
$this->logFile = $logFile;
return $this;
}
public function setLogFile($logFile)
{
$this->logFile = $logFile;
return $this;
}
public function send($result)
{
$boundary = md5(date('r', time()));
$boundary = md5(date('r', time()));
$headers = 'From: ' . $this->address
. self::EOL
. 'Reply-To: ' . $this->address
. self::EOL
. 'MIME-Version: 1.0'
. self::EOL
. 'Content-Type: multipart/mixed; boundary=Mage-mixed-' . $boundary;
$headers = 'From: ' . $this->address
. self::EOL
. 'Reply-To: ' . $this->address
. self::EOL
. 'MIME-Version: 1.0'
. self::EOL
. 'Content-Type: multipart/mixed; boundary=Mage-mixed-' . $boundary;
$subject = str_replace(
array('{project}', '{environment}', '{result}'),
array($this->project, $this->environment, $result ? 'SUCCESS' : 'FAILURE'),
self::SUBJECT
)
;
$attachment = chunk_split(base64_encode(file_get_contents($this->logFile)));
$subject = str_replace(
array('{project}', '{environment}', '{result}'),
array($this->project, $this->environment, $result ? 'SUCCESS' : 'FAILURE'),
self::SUBJECT
);
$attachment = chunk_split(base64_encode(file_get_contents($this->logFile)));
$message = 'This is a multi-part message in MIME format.' . self::EOL
. '--Mage-mixed-' . $boundary . self::EOL
. 'Content-Type: text/plain; charset=iso-8859-1' . self::EOL
. 'Content-Transfer-Encoding: quoted-printable' . self::EOL
. self::EOL
. strip_tags(Console::getOutput()) . self::EOL
. self::EOL
. '--Mage-mixed-' . $boundary . self::EOL
. 'Content-Type: text/plain; name="log.txt"' . self::EOL
. 'Content-Transfer-Encoding: base64' . self::EOL
. 'Content-Disposition: attachment' . self::EOL
. self::EOL
. $attachment . self::EOL
. '--Mage-mixed-' . $boundary . '--' . self::EOL
;
$message = 'This is a multi-part message in MIME format.' . self::EOL
. '--Mage-mixed-' . $boundary . self::EOL
. 'Content-Type: text/plain; charset=iso-8859-1' . self::EOL
. 'Content-Transfer-Encoding: quoted-printable' . self::EOL
. self::EOL
. strip_tags(Console::getOutput()) . self::EOL
. self::EOL
. '--Mage-mixed-' . $boundary . self::EOL
. 'Content-Type: text/plain; name="log.txt"' . self::EOL
. 'Content-Transfer-Encoding: base64' . self::EOL
. 'Content-Disposition: attachment' . self::EOL
. self::EOL
. $attachment . self::EOL
. '--Mage-mixed-' . $boundary . '--' . self::EOL;
@mail($this->address, $subject, $message, $headers);
@mail($this->address, $subject, $message, $headers);
}
}

View file

@ -23,287 +23,287 @@ use Exception;
*/
abstract class AbstractTask
{
/**
* Stage Constant for Pre Deployment
* @var string
*/
const STAGE_PRE_DEPLOY = 'pre-deploy';
/**
* Stage Constant for Pre Deployment
* @var string
*/
const STAGE_PRE_DEPLOY = 'pre-deploy';
/**
* Stage Constant for Deployment
* @var string
*/
const STAGE_DEPLOY = 'deploy';
/**
* Stage Constant for Deployment
* @var string
*/
const STAGE_DEPLOY = 'deploy';
/**
* Stage Constant for Post Deployment
* @var string
*/
const STAGE_POST_DEPLOY = 'post-deploy';
/**
* Stage Constant for Post Deployment
* @var string
*/
const STAGE_POST_DEPLOY = 'post-deploy';
/**
* Stage Constant for Post Release
* @var string
*/
const STAGE_POST_RELEASE = 'post-release';
/**
* Stage Constant for Post Release
* @var string
*/
const STAGE_POST_RELEASE = 'post-release';
/**
* Configuration
* @var Config;
*/
protected $config = null;
/**
* Configuration
* @var Config;
*/
protected $config = null;
/**
* Indicates if the Task is running in a Rollback
* @var boolean
*/
protected $inRollback = false;
/**
* Indicates if the Task is running in a Rollback
* @var boolean
*/
protected $inRollback = false;
/**
* Indicates the Stage the Task is running ing
* @var string
*/
protected $stage = null;
/**
* Indicates the Stage the Task is running ing
* @var string
*/
protected $stage = null;
/**
* Extra parameters
* @var array
*/
protected $parameters = array();
/**
* Extra parameters
* @var array
*/
protected $parameters = array();
/**
* Returns the Title of the Task
* @return string
*/
public abstract function getName();
/**
* Returns the Title of the Task
* @return string
*/
public abstract function getName();
/**
* Runs the task
*
* @return boolean
* @throws Exception
* @throws ErrorWithMessageException
* @throws SkipException
*/
public abstract function run();
/**
* Runs the task
*
* @return boolean
* @throws Exception
* @throws ErrorWithMessageException
* @throws SkipException
*/
public abstract function run();
/**
* Task Constructor
*
* @param Config $config
* @param boolean $inRollback
* @param string $stage
* @param array $parameters
*/
public final function __construct(Config $config, $inRollback = false, $stage = null, $parameters = array())
{
$this->config = $config;
$this->inRollback = $inRollback;
$this->stage = $stage;
$this->parameters = $parameters;
}
/**
* Task Constructor
*
* @param Config $config
* @param boolean $inRollback
* @param string $stage
* @param array $parameters
*/
public final function __construct(Config $config, $inRollback = false, $stage = null, $parameters = array())
{
$this->config = $config;
$this->inRollback = $inRollback;
$this->stage = $stage;
$this->parameters = $parameters;
}
/**
* Indicates if the Task is running in a Rollback operation
* @return boolean
*/
public function inRollback()
{
return $this->inRollback;
}
/**
* Indicates if the Task is running in a Rollback operation
* @return boolean
*/
public function inRollback()
{
return $this->inRollback;
}
/**
* Gets the Stage of the Deployment:
* - pre-deploy
* - deploy
* - post-deploy
* - post-release
* @return string
*/
public function getStage()
{
return $this->stage;
}
/**
* Gets the Stage of the Deployment:
* - pre-deploy
* - deploy
* - post-deploy
* - post-release
* @return string
*/
public function getStage()
{
return $this->stage;
}
/**
* Gets the Configuration
* @return Config;
*/
public function getConfig()
{
return $this->config;
}
/**
* Gets the Configuration
* @return Config;
*/
public function getConfig()
{
return $this->config;
}
/**
* Initializes the Task, optional to implement
*/
public function init()
{
}
/**
* Initializes the Task, optional to implement
*/
public function init()
{
}
/**
* Returns a Parameter, or a default if not found
*
* @param string $name
* @param mixed $default
* @return mixed
*/
public function getParameter($name, $default = null)
{
return $this->getConfig()->getParameter($name, $default, $this->getParameters());
}
/**
* Returns a Parameter, or a default if not found
*
* @param string $name
* @param mixed $default
* @return mixed
*/
public function getParameter($name, $default = null)
{
return $this->getConfig()->getParameter($name, $default, $this->getParameters());
}
/**
* @return array
*/
protected function getParameters()
{
return $this->parameters;
}
/**
* @return array
*/
protected function getParameters()
{
return $this->parameters;
}
/**
* Runs a Shell Command Localy
* @param string $command
* @param string $output
* @return boolean
*/
protected final function runCommandLocal($command, &$output = null)
{
return Console::executeCommand($command, $output);
}
/**
* Runs a Shell Command Localy
* @param string $command
* @param string $output
* @return boolean
*/
protected final function runCommandLocal($command, &$output = null)
{
return Console::executeCommand($command, $output);
}
/**
* Runs a Shell Command on the Remote Host
* @param string $command
* @param string $output
* @param boolean $cdToDirectoryFirst
* @return boolean
*/
protected final function runCommandRemote($command, &$output = null, $cdToDirectoryFirst = true)
{
if ($this->getConfig()->release('enabled', false) == true) {
if ($this instanceOf IsReleaseAware) {
$releasesDirectory = '';
/**
* Runs a Shell Command on the Remote Host
* @param string $command
* @param string $output
* @param boolean $cdToDirectoryFirst
* @return boolean
*/
protected final function runCommandRemote($command, &$output = null, $cdToDirectoryFirst = true)
{
if ($this->getConfig()->release('enabled', false) == true) {
if ($this instanceOf IsReleaseAware) {
$releasesDirectory = '';
} else {
$releasesDirectory = '/'
. $this->getConfig()->release('directory', 'releases')
. '/'
. $this->getConfig()->getReleaseId();
}
} else {
$releasesDirectory = '/'
. $this->getConfig()->release('directory', 'releases')
. '/'
. $this->getConfig()->getReleaseId();
}
} else {
$releasesDirectory = '';
}
} else {
$releasesDirectory = '';
}
// if general.yml includes "ssy_needs_tty: true", then add "-t" to the ssh command
$needs_tty = ($this->getConfig()->general('ssh_needs_tty',false) ? '-t' : '');
// if general.yml includes "ssy_needs_tty: true", then add "-t" to the ssh command
$needs_tty = ($this->getConfig()->general('ssh_needs_tty', false) ? '-t' : '');
$localCommand = 'ssh ' . $this->getConfig()->getHostIdentityFileOption() . $needs_tty . ' -p ' . $this->getConfig()->getHostPort() . ' '
. '-q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no '
. $this->getConfig()->deployment('user') . '@' . $this->getConfig()->getHostName();
$localCommand = 'ssh ' . $this->getConfig()->getHostIdentityFileOption() . $needs_tty . ' -p ' . $this->getConfig()->getHostPort() . ' '
. '-q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no '
. $this->getConfig()->deployment('user') . '@' . $this->getConfig()->getHostName();
$remoteCommand = str_replace('"', '\"', $command);
if($cdToDirectoryFirst){
$remoteCommand = 'cd ' . rtrim($this->getConfig()->deployment('to'), '/') . $releasesDirectory . ' && ' . $remoteCommand;
}
$localCommand .= ' ' . '"sh -c \"' . $remoteCommand . '\""';
$remoteCommand = str_replace('"', '\"', $command);
if ($cdToDirectoryFirst) {
$remoteCommand = 'cd ' . rtrim($this->getConfig()->deployment('to'), '/') . $releasesDirectory . ' && ' . $remoteCommand;
}
$localCommand .= ' ' . '"sh -c \"' . $remoteCommand . '\""';
Console::log('Run remote command ' . $remoteCommand);
Console::log('Run remote command ' . $remoteCommand);
return $this->runCommandLocal($localCommand, $output);
}
return $this->runCommandLocal($localCommand, $output);
}
/**
* Runs a Shell Command Localy or in the Remote Host based on the Task Stage.
* If the stage is "deploy" then it will be executed in the remote host.
* @param string $command
* @param string $output
* @return boolean
*/
protected final function runCommand($command, &$output = null)
{
if ($this->getStage() == self::STAGE_DEPLOY) {
return $this->runCommandRemote($command, $output);
} else {
return $this->runCommandLocal($command, $output);
}
}
/**
* Runs a Shell Command Localy or in the Remote Host based on the Task Stage.
* If the stage is "deploy" then it will be executed in the remote host.
* @param string $command
* @param string $output
* @return boolean
*/
protected final function runCommand($command, &$output = null)
{
if ($this->getStage() == self::STAGE_DEPLOY) {
return $this->runCommandRemote($command, $output);
} else {
return $this->runCommandLocal($command, $output);
}
}
/**
* adds a cd to the needed release if we work with releases.
*
* @param string $command
* @return string
*/
protected function getReleasesAwareCommand($command)
{
if ($this->getConfig()->release('enabled', false) == true) {
$releasesDirectory = $this->getConfig()->release('directory', 'releases');
/**
* adds a cd to the needed release if we work with releases.
*
* @param string $command
* @return string
*/
protected function getReleasesAwareCommand($command)
{
if ($this->getConfig()->release('enabled', false) == true) {
$releasesDirectory = $this->getConfig()->release('directory', 'releases');
$deployToDirectory = $releasesDirectory . '/' . $this->getConfig()->getReleaseId();
return 'cd ' . $deployToDirectory . ' && ' . $command;
}
$deployToDirectory = $releasesDirectory . '/' . $this->getConfig()->getReleaseId();
return 'cd ' . $deployToDirectory . ' && ' . $command;
}
return $command;
}
return $command;
}
/**
* @param integer $releaseId
* @return bool
*/
protected function tarRelease($releaseId)
{
$result = true;
// for given release, check if tarred
$output = '';
$releasesDirectory = $this->getConfig()->release('directory', 'releases');
protected function tarRelease($releaseId)
{
$result = true;
// for given release, check if tarred
$output = '';
$releasesDirectory = $this->getConfig()->release('directory', 'releases');
$currentReleaseDirectory = $releasesDirectory . '/' . $releaseId;
$currentReleaseDirectoryTemp = $currentReleaseDirectory . '_tmp/';
$currentRelease = $currentReleaseDirectory . '/' . $releaseId . '.tar.gz';
$currentReleaseDirectory = $releasesDirectory . '/' . $releaseId;
$currentReleaseDirectoryTemp = $currentReleaseDirectory . '_tmp/';
$currentRelease = $currentReleaseDirectory . '/' . $releaseId . '.tar.gz';
$command = 'test -e ' . $currentRelease . ' && echo "true" || echo ""';
$this->runCommandRemote($command, $output);
$command = 'test -e ' . $currentRelease . ' && echo "true" || echo ""';
$this->runCommandRemote($command, $output);
// if not, do so
if (!$output) {
$commands = array();
$commands[] = 'mv ' . $currentReleaseDirectory . ' ' . $currentReleaseDirectoryTemp;
$commands[] = 'mkdir ' . $currentReleaseDirectory;
$commands[] = 'tar cfz ' . $currentRelease . ' ' . $currentReleaseDirectoryTemp;
$commands[] = 'rm -rf ' . $currentReleaseDirectoryTemp;
$command = implode(' && ', $commands);
$result = $this->runCommandRemote($command, $output);
return $result;
}
return $result;
}
// if not, do so
if (!$output) {
$commands = array();
$commands[] = 'mv ' . $currentReleaseDirectory . ' ' . $currentReleaseDirectoryTemp;
$commands[] = 'mkdir ' . $currentReleaseDirectory;
$commands[] = 'tar cfz ' . $currentRelease . ' ' . $currentReleaseDirectoryTemp;
$commands[] = 'rm -rf ' . $currentReleaseDirectoryTemp;
$command = implode(' && ', $commands);
$result = $this->runCommandRemote($command, $output);
return $result;
}
return $result;
}
protected function untarRelease($releaseId)
{
$result = true;
// for given release, check if tarred
$output = '';
$releasesDirectory = $this->getConfig()->release('directory', 'releases');
protected function untarRelease($releaseId)
{
$result = true;
// for given release, check if tarred
$output = '';
$releasesDirectory = $this->getConfig()->release('directory', 'releases');
$currentReleaseDirectory = $releasesDirectory . '/' . $releaseId;
$currentReleaseDirectoryTemp = $currentReleaseDirectory . '_tmp/';
$currentRelease = $currentReleaseDirectory . '/' . $releaseId . '.tar.gz';
$currentReleaseDirectory = $releasesDirectory . '/' . $releaseId;
$currentReleaseDirectoryTemp = $currentReleaseDirectory . '_tmp/';
$currentRelease = $currentReleaseDirectory . '/' . $releaseId . '.tar.gz';
$command = 'test -e ' . $currentRelease . ' && echo "true" || echo ""';
$this->runCommandRemote($command, $output);
$command = 'test -e ' . $currentRelease . ' && echo "true" || echo ""';
$this->runCommandRemote($command, $output);
// if tarred, untar now
if ($output) {
$commands = array();
$commands[] = 'tar xfz ' . $currentRelease;
$commands[] = 'rm -rf ' . $currentReleaseDirectory;
$commands[] = 'mv ' .$currentReleaseDirectoryTemp . ' ' . $currentReleaseDirectory;
$command = implode(' && ', $commands);
$result = $this->runCommandRemote($command, $output);
return $result;
}
return $result;
}
// if tarred, untar now
if ($output) {
$commands = array();
$commands[] = 'tar xfz ' . $currentRelease;
$commands[] = 'rm -rf ' . $currentReleaseDirectory;
$commands[] = 'mv ' . $currentReleaseDirectoryTemp . ' ' . $currentReleaseDirectory;
$command = implode(' && ', $commands);
$result = $this->runCommandRemote($command, $output);
return $result;
}
return $result;
}
}

View file

@ -21,86 +21,86 @@ use Mage\Task\Releases\SkipOnOverride;
*/
class ReleaseTask extends AbstractTask implements IsReleaseAware, SkipOnOverride
{
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
public function getName()
{
return 'Releasing [built-in]';
}
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
public function getName()
{
return 'Releasing [built-in]';
}
/**
* Releases a Deployment: points the current symbolic link to the release directory
* @see \Mage\Task\AbstractTask::run()
*/
public function run()
{
if ($this->getConfig()->release('enabled', false) == true) {
$releasesDirectory = $this->getConfig()->release('directory', 'releases');
$symlink = $this->getConfig()->release('symlink', 'current');
/**
* Releases a Deployment: points the current symbolic link to the release directory
* @see \Mage\Task\AbstractTask::run()
*/
public function run()
{
if ($this->getConfig()->release('enabled', false) == true) {
$releasesDirectory = $this->getConfig()->release('directory', 'releases');
$symlink = $this->getConfig()->release('symlink', 'current');
if (substr($symlink, 0, 1) == '/') {
$releasesDirectory = rtrim($this->getConfig()->deployment('to'), '/') . '/' . $releasesDirectory;
}
if (substr($symlink, 0, 1) == '/') {
$releasesDirectory = rtrim($this->getConfig()->deployment('to'), '/') . '/' . $releasesDirectory;
}
$releaseId = $this->getConfig()->getReleaseId();
$releaseId = $this->getConfig()->getReleaseId();
if ($this->getConfig()->release('compressreleases', false) == true) {
// Tar.gz releases
$result = $this->tarReleases() && $result;
// Untar new release
$result = $this->untarRelease($releaseId) && $result;
}
if ($this->getConfig()->release('compressreleases', false) == true) {
// Tar.gz releases
$result = $this->tarReleases() && $result;
// Untar new release
$result = $this->untarRelease($releaseId) && $result;
}
$currentCopy = $releasesDirectory . '/' . $releaseId;
$currentCopy = $releasesDirectory . '/' . $releaseId;
//Check if target user:group is specified
$userGroup = $this->getConfig()->deployment('owner');
// Fetch the user and group from base directory; defaults usergroup to 33:33
if(empty($userGroup)){
$user = '33';
$group = '33';
$directoryInfos = '';
// Get raw directory info and parse it in php.
// "stat" command don't behave the same on different systems, ls output format also varies
// and awk parameters need special care depending on the executing shell
$resultFetch = $this->runCommandRemote("ls -ld .", $directoryInfos);
if(!empty($directoryInfos)){
//uniformize format as it depends on the system deployed on
$directoryInfos = trim(str_replace(array(" ", "\t"), ' ', $directoryInfos));
$infoArray = explode(' ', $directoryInfos);
if(!empty($infoArray[2])) {
$user = $infoArray[2];
}
if(!empty($infoArray[3])) {
$group = $infoArray[3];
}
$userGroup = $user . ':' . $group;
}
}
//Check if target user:group is specified
$userGroup = $this->getConfig()->deployment('owner');
// Fetch the user and group from base directory; defaults usergroup to 33:33
if (empty($userGroup)) {
$user = '33';
$group = '33';
$directoryInfos = '';
// Get raw directory info and parse it in php.
// "stat" command don't behave the same on different systems, ls output format also varies
// and awk parameters need special care depending on the executing shell
$resultFetch = $this->runCommandRemote("ls -ld .", $directoryInfos);
if (!empty($directoryInfos)) {
//uniformize format as it depends on the system deployed on
$directoryInfos = trim(str_replace(array(" ", "\t"), ' ', $directoryInfos));
$infoArray = explode(' ', $directoryInfos);
if (!empty($infoArray[2])) {
$user = $infoArray[2];
}
if (!empty($infoArray[3])) {
$group = $infoArray[3];
}
$userGroup = $user . ':' . $group;
}
}
// Remove symlink if exists; create new symlink and change owners
$command = 'rm -f ' . $symlink
. ' ; '
. 'ln -sf ' . $currentCopy . ' ' . $symlink;
// Remove symlink if exists; create new symlink and change owners
$command = 'rm -f ' . $symlink
. ' ; '
. 'ln -sf ' . $currentCopy . ' ' . $symlink;
if ($resultFetch && $userGroup != '') {
$command .= ' && '
. 'chown -h ' . $userGroup . ' ' . $symlink
. ' && '
. 'chown -R ' . $userGroup . ' ' . $currentCopy
. ' && '
. 'chown ' . $userGroup . ' ' . $releasesDirectory;
}
if ($resultFetch && $userGroup != '') {
$command .= ' && '
. 'chown -h ' . $userGroup . ' ' . $symlink
. ' && '
. 'chown -R ' . $userGroup . ' ' . $currentCopy
. ' && '
. 'chown ' . $userGroup . ' ' . $releasesDirectory;
}
$result = $this->runCommandRemote($command);
$result = $this->runCommandRemote($command);
return $result;
return $result;
} else {
return false;
}
}
} else {
return false;
}
}
}

View file

@ -32,7 +32,7 @@ abstract class BaseStrategyTaskAbstract extends AbstractTask implements IsReleas
if ($overrideRelease == true) {
$releaseToOverride = false;
$resultFetch = $this->runCommandRemote('ls -ld '.$symlink.' | cut -d"/" -f2', $releaseToOverride);
$resultFetch = $this->runCommandRemote('ls -ld ' . $symlink . ' | cut -d"/" -f2', $releaseToOverride);
if ($resultFetch && is_numeric($releaseToOverride)) {
$this->getConfig()->setReleaseId($releaseToOverride);
}

View file

@ -21,10 +21,10 @@ use Mage\Task\SkipException;
*/
class DisabledTask extends AbstractTask implements IsReleaseAware
{
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
public function getName()
{
return 'Disabled Deployment [built-in]';

View file

@ -44,8 +44,8 @@ class GitRebaseTask extends BaseStrategyTaskAbstract implements IsReleaseAware
$releasesDirectory = $this->getConfig()->release('directory', 'releases');
$deployToDirectory = rtrim($this->getConfig()->deployment('to'), '/')
. '/' . $releasesDirectory
. '/' . $this->getConfig()->getReleaseId();
. '/' . $releasesDirectory
. '/' . $this->getConfig()->getReleaseId();
$this->runCommandRemote('mkdir -p ' . $releasesDirectory . '/' . $this->getConfig()->getReleaseId());
}
@ -78,11 +78,11 @@ class GitRebaseTask extends BaseStrategyTaskAbstract implements IsReleaseAware
$result = $this->runCommandRemote($command) && $result;
// Stash if Working Copy is not clean
if(!$status) {
if (!$status) {
$stashResult = '';
$command = $this->getReleasesAwareCommand('git stash');
$result = $this->runCommandRemote($command, $stashResult) && $result;
if($stashResult != "No local changes to save") {
if ($stashResult != "No local changes to save") {
$stashed = true;
}
}

View file

@ -21,10 +21,10 @@ use Mage\Task\Releases\IsReleaseAware;
*/
class RsyncTask extends BaseStrategyTaskAbstract implements IsReleaseAware
{
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
public function getName()
{
if ($this->getConfig()->release('enabled', false) == true) {
@ -32,14 +32,14 @@ class RsyncTask extends BaseStrategyTaskAbstract implements IsReleaseAware
return 'Deploy via Rsync (with Releases override) [built-in]';
} else {
$rsync_copy = $this->getConfig()->deployment("rsync");
if ( $rsync_copy && is_array($rsync_copy) && $rsync_copy['copy'] ) {
if ($rsync_copy && is_array($rsync_copy) && $rsync_copy['copy']) {
return 'Deploy via Rsync (with Releases) [built-in, incremental]';
} else {
return 'Deploy via Rsync (with Releases) [built-in]';
}
}
} else {
return 'Deploy via Rsync [built-in]';
return 'Deploy via Rsync [built-in]';
}
}
@ -61,8 +61,8 @@ class RsyncTask extends BaseStrategyTaskAbstract implements IsReleaseAware
$currentRelease = false;
$deployToDirectory = rtrim($this->getConfig()->deployment('to'), '/')
. '/' . $releasesDirectory
. '/' . $this->getConfig()->getReleaseId();
. '/' . $releasesDirectory
. '/' . $this->getConfig()->getReleaseId();
Console::log('Deploy to ' . $deployToDirectory);
$resultFetch = $this->runCommandRemote('ls -ld ' . $symlink . ' | cut -d"/" -f2', $currentRelease);
@ -72,10 +72,10 @@ class RsyncTask extends BaseStrategyTaskAbstract implements IsReleaseAware
// rsync: { copy: yes }
$rsync_copy = $this->getConfig()->deployment('rsync');
// If copy_tool_rsync, use rsync rather than cp for finer control of what is copied
if ( $rsync_copy && is_array($rsync_copy) && $rsync_copy['copy'] && isset($rsync_copy['copy_tool_rsync']) ) {
if ($rsync_copy && is_array($rsync_copy) && $rsync_copy['copy'] && isset($rsync_copy['copy_tool_rsync'])) {
$this->runCommandRemote("rsync -a {$this->excludes(array_merge($excludes, $rsync_copy['rsync_excludes']))} "
. "$releasesDirectory/$currentRelease/ $releasesDirectory/{$this->getConfig()->getReleaseId()}");
} elseif ( $rsync_copy && is_array($rsync_copy) && $rsync_copy['copy'] ) {
. "$releasesDirectory/$currentRelease/ $releasesDirectory/{$this->getConfig()->getReleaseId()}");
} elseif ($rsync_copy && is_array($rsync_copy) && $rsync_copy['copy']) {
$this->runCommandRemote('cp -R ' . $releasesDirectory . '/' . $currentRelease . ' ' . $releasesDirectory . '/' . $this->getConfig()->getReleaseId());
} else {
$this->runCommandRemote('mkdir -p ' . $releasesDirectory . '/' . $this->getConfig()->getReleaseId());
@ -84,10 +84,10 @@ class RsyncTask extends BaseStrategyTaskAbstract implements IsReleaseAware
}
$command = 'rsync -avz '
. '--rsh="ssh ' . $this->getConfig()->getHostIdentityFileOption() . '-p' . $this->getConfig()->getHostPort() . '" '
. $this->excludes($excludes) . ' '
. $this->getConfig()->deployment('from') . ' '
. $this->getConfig()->deployment('user') . '@' . $this->getConfig()->getHostName() . ':' . $deployToDirectory;
. '--rsh="ssh ' . $this->getConfig()->getHostIdentityFileOption() . '-p' . $this->getConfig()->getHostPort() . '" '
. $this->excludes($excludes) . ' '
. $this->getConfig()->deployment('from') . ' '
. $this->getConfig()->deployment('user') . '@' . $this->getConfig()->getHostName() . ':' . $deployToDirectory;
$result = $this->runCommandLocal($command);

View file

@ -21,10 +21,10 @@ use Mage\Task\Releases\IsReleaseAware;
*/
class TarGzTask extends BaseStrategyTaskAbstract implements IsReleaseAware
{
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
public function getName()
{
if ($this->getConfig()->release('enabled', false) == true) {
@ -34,7 +34,7 @@ class TarGzTask extends BaseStrategyTaskAbstract implements IsReleaseAware
return 'Deploy via TarGz (with Releases) [built-in]';
}
} else {
return 'Deploy via TarGz [built-in]';
return 'Deploy via TarGz [built-in]';
}
}
@ -53,10 +53,10 @@ class TarGzTask extends BaseStrategyTaskAbstract implements IsReleaseAware
if ($this->getConfig()->release('enabled', false) == true) {
$releasesDirectory = $this->getConfig()->release('directory', 'releases');
$deployToDirectory = rtrim($this->getConfig()->deployment('to'), '/')
. '/' . $releasesDirectory
. '/' . $this->getConfig()->getReleaseId();
. '/' . $releasesDirectory
. '/' . $this->getConfig()->getReleaseId();
$output = null;
$this->runCommandRemote('mkdir -p ' . $deployToDirectory, $output , false);
$this->runCommandRemote('mkdir -p ' . $deployToDirectory, $output, false);
}
// Create Tar Gz
@ -68,19 +68,19 @@ class TarGzTask extends BaseStrategyTaskAbstract implements IsReleaseAware
}
$command = 'tar cfz ' . $localTarGz . '.tar.gz ' . $excludeCmd . ' -C ' . $this->getConfig()->deployment('from') . ' .';
$result = $this->runCommandLocal($command);
$result = $this->runCommandLocal($command);
// Copy Tar Gz to Remote Host
$command = 'scp ' . $this->getConfig()->getHostIdentityFileOption() . '-P ' . $this->getConfig()->getHostPort() . ' ' . $localTarGz . '.tar.gz '
. $this->getConfig()->deployment('user') . '@' . $this->getConfig()->getHostName() . ':' . $deployToDirectory;
$result = $this->runCommandLocal($command) && $result;
// Copy Tar Gz to Remote Host
$command = 'scp ' . $this->getConfig()->getHostIdentityFileOption() . '-P ' . $this->getConfig()->getHostPort() . ' ' . $localTarGz . '.tar.gz '
. $this->getConfig()->deployment('user') . '@' . $this->getConfig()->getHostName() . ':' . $deployToDirectory;
$result = $this->runCommandLocal($command) && $result;
// Extract Tar Gz
$command = $this->getReleasesAwareCommand('tar xfz ' . $remoteTarGz . '.tar.gz');
$command = $this->getReleasesAwareCommand('tar xfz ' . $remoteTarGz . '.tar.gz');
$result = $this->runCommandRemote($command) && $result;
// Delete Tar Gz from Remote Host
$command = $this->getReleasesAwareCommand('rm ' . $remoteTarGz . '.tar.gz');
$command = $this->getReleasesAwareCommand('rm ' . $remoteTarGz . '.tar.gz');
$result = $this->runCommandRemote($command) && $result;
// Delete Tar Gz from Local

File diff suppressed because it is too large Load diff

View file

@ -19,10 +19,10 @@ use Mage\Task\AbstractTask;
*/
class ClearCacheTask extends AbstractTask
{
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
public function getName()
{
return 'Magento - Clean Cache [built-in]';

View file

@ -19,10 +19,10 @@ use Mage\Task\AbstractTask;
*/
class ClearFullPageCacheTask extends AbstractTask
{
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
public function getName()
{
return 'Magento - Clean Full Page Cache [built-in]';

View file

@ -54,22 +54,22 @@ class ListTask extends AbstractTask implements IsReleaseAware
Console::output('<dark_gray>No releases available</dark_gray> ... ', 2);
} else {
rsort($releases);
$releases = array_slice($releases, 0, 10);
$releases = array_slice($releases, 0, 10);
foreach ($releases as $releaseIndex => $release) {
$release = trim($release);
$releaseIndex = str_pad($releaseIndex * -1, 2, ' ', STR_PAD_LEFT);
$releaseDate = $release[0] . $release[1] . $release[2] .$release[3]
. '-'
. $release[4] . $release[5]
. '-'
. $release[6] . $release[7]
. ' '
. $release[8] . $release[9]
. ':'
. $release[10] . $release[11]
. ':'
. $release[12] . $release[13];
$releaseDate = $release[0] . $release[1] . $release[2] . $release[3]
. '-'
. $release[4] . $release[5]
. '-'
. $release[6] . $release[7]
. ' '
. $release[8] . $release[9]
. ':'
. $release[10] . $release[11]
. ':'
. $release[12] . $release[13];
$isCurrent = '';
if ($currentRelease == $release) {
@ -80,8 +80,8 @@ class ListTask extends AbstractTask implements IsReleaseAware
Console::output(
'Release: <purple>' . $release . '</purple> '
. '- Date: <dark_gray>' . $releaseDate . '</dark_gray> '
. '- Index: <dark_gray>' . $releaseIndex . '</dark_gray>' . $dateDiff . $isCurrent, 2);
. '- Date: <dark_gray>' . $releaseDate . '</dark_gray> '
. '- Index: <dark_gray>' . $releaseIndex . '</dark_gray>' . $dateDiff . $isCurrent, 2);
}
}

View file

@ -23,179 +23,179 @@ use Mage\Task\Releases\RollbackAware;
*/
class RollbackTask extends AbstractTask implements IsReleaseAware
{
/**
* The Relase ID to Rollback To
* @var integer
*/
protected $release = null;
/**
* The Relase ID to Rollback To
* @var integer
*/
protected $release = null;
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
public function getName()
{
return 'Rollback release [built-in]';
}
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
public function getName()
{
return 'Rollback release [built-in]';
}
/**
* Sets the Release ID to Rollback To
* @param integer $releaseId
* @return \Mage\Task\BuiltIn\Releases\RollbackTask
*/
public function setRelease($releaseId)
{
$this->release = $releaseId;
return $this;
}
/**
* Sets the Release ID to Rollback To
* @param integer $releaseId
* @return \Mage\Task\BuiltIn\Releases\RollbackTask
*/
public function setRelease($releaseId)
{
$this->release = $releaseId;
return $this;
}
/**
* Gets the Release ID to Rollback To
* @return integer
*/
public function getRelease()
{
return $this->release;
}
/**
* Gets the Release ID to Rollback To
* @return integer
*/
public function getRelease()
{
return $this->release;
}
/**
* Performs a Rollback Operation
* @see \Mage\Task\AbstractTask::run()
*/
public function run()
{
if ($this->getConfig()->release('enabled', false) == true) {
$releasesDirectory = $this->getConfig()->release('directory', 'releases');
$symlink = $this->getConfig()->release('symlink', 'current');
/**
* Performs a Rollback Operation
* @see \Mage\Task\AbstractTask::run()
*/
public function run()
{
if ($this->getConfig()->release('enabled', false) == true) {
$releasesDirectory = $this->getConfig()->release('directory', 'releases');
$symlink = $this->getConfig()->release('symlink', 'current');
$output = '';
$result = $this->runCommandRemote('ls -1 ' . $releasesDirectory, $output);
$releases = ($output == '') ? array() : explode(PHP_EOL, $output);
$output = '';
$result = $this->runCommandRemote('ls -1 ' . $releasesDirectory, $output);
$releases = ($output == '') ? array() : explode(PHP_EOL, $output);
if (count($releases) == 0) {
Console::output('Release are not available for <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray> ... <red>FAIL</red>');
if (count($releases) == 0) {
Console::output('Release are not available for <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray> ... <red>FAIL</red>');
} else {
rsort($releases);
} else {
rsort($releases);
$releaseIsAvailable = false;
if ($this->getRelease() == '') {
$releaseId = $releases[0];
$releaseIsAvailable = true;
$releaseIsAvailable = false;
if ($this->getRelease() == '') {
$releaseId = $releases[0];
$releaseIsAvailable = true;
} else if ($this->getRelease() <= 0) {
$index = $this->getRelease() * -1;
if (isset($releases[$index])) {
$releaseId = $releases[$index];
$releaseIsAvailable = true;
}
} else {
if (in_array($this->getRelease(), $releases)) {
$releaseId = $this->getRelease();
$releaseIsAvailable = true;
}
}
} else if ($this->getRelease() <= 0) {
$index = $this->getRelease() * -1;
if (isset($releases[$index])) {
$releaseId = $releases[$index];
$releaseIsAvailable = true;
}
} else {
if (in_array($this->getRelease(), $releases)) {
$releaseId = $this->getRelease();
$releaseIsAvailable = true;
}
}
if (!$releaseIsAvailable) {
Console::output('Release <dark_gray>' . $this->getRelease() . '</dark_gray> is invalid or unavailable for <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray> ... <red>FAIL</red>');
if (!$releaseIsAvailable) {
Console::output('Release <dark_gray>' . $this->getRelease() . '</dark_gray> is invalid or unavailable for <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray> ... <red>FAIL</red>');
} else {
Console::output('Rollback release on <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray>');
$rollbackTo = $releasesDirectory . '/' . $releaseId;
} else {
Console::output('Rollback release on <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray>');
$rollbackTo = $releasesDirectory . '/' . $releaseId;
// Tasks
$tasks = 1;
$completedTasks = 0;
$tasksToRun = $this->getConfig()->getTasks();
$this->getConfig()->setReleaseId($releaseId);
// Tasks
$tasks = 1;
$completedTasks = 0;
$tasksToRun = $this->getConfig()->getTasks();
$this->getConfig()->setReleaseId($releaseId);
// Run Deploy Tasks
foreach ($tasksToRun as $taskData) {
$task = Factory::get($taskData, $this->getConfig(), true, self::STAGE_DEPLOY);
$task->init();
Console::output('Running <purple>' . $task->getName() . '</purple> ... ', 2, false);
// Run Deploy Tasks
foreach ($tasksToRun as $taskData) {
$task = Factory::get($taskData, $this->getConfig(), true, self::STAGE_DEPLOY);
$task->init();
Console::output('Running <purple>' . $task->getName() . '</purple> ... ', 2, false);
if ($task instanceOf RollbackAware) {
$tasks++;
$result = $task->run();
if ($task instanceOf RollbackAware) {
$tasks++;
$result = $task->run();
if ($result == true) {
Console::output('<green>OK</green>', 0);
$completedTasks++;
} else {
Console::output('<red>FAIL</red>', 0);
}
} else {
Console::output('<yellow>SKIPPED</yellow>', 0);
}
}
if ($result == true) {
Console::output('<green>OK</green>', 0);
$completedTasks++;
} else {
Console::output('<red>FAIL</red>', 0);
}
} else {
Console::output('<yellow>SKIPPED</yellow>', 0);
}
}
if ($this->getConfig()->release('compressreleases', false) == true) {
// Tar the current
$result = $this->tarReleases() && $result;
// Untar the rollbackto
$result = $this->untarRelease($releaseId) && $result;
}
if ($this->getConfig()->release('compressreleases', false) == true) {
// Tar the current
$result = $this->tarReleases() && $result;
// Untar the rollbackto
$result = $this->untarRelease($releaseId) && $result;
}
// Changing Release
Console::output('Running <purple>Rollback Release [id=' . $releaseId . ']</purple> ... ', 2, false);
// Changing Release
Console::output('Running <purple>Rollback Release [id=' . $releaseId . ']</purple> ... ', 2, false);
$userGroup = '';
$resultFetch = $this->runCommandRemote('ls -ld ' . $rollbackTo . ' | awk \'{print \$3":"\$4}\'', $userGroup);
$command = 'rm -f ' . $symlink
. ' && '
. 'ln -sf ' . $rollbackTo . ' ' . $symlink;
$userGroup = '';
$resultFetch = $this->runCommandRemote('ls -ld ' . $rollbackTo . ' | awk \'{print \$3":"\$4}\'', $userGroup);
$command = 'rm -f ' . $symlink
. ' && '
. 'ln -sf ' . $rollbackTo . ' ' . $symlink;
if ($resultFetch) {
$command .= ' && chown -h ' . $userGroup . ' ' . $symlink;
}
if ($resultFetch) {
$command .= ' && chown -h ' . $userGroup . ' ' . $symlink;
}
$result = $this->runCommandRemote($command);
$result = $this->runCommandRemote($command);
if ($result) {
Console::output('<green>OK</green>', 0);
$completedTasks++;
} else {
Console::output('<red>FAIL</red>', 0);
}
if ($result) {
Console::output('<green>OK</green>', 0);
$completedTasks++;
} else {
Console::output('<red>FAIL</red>', 0);
}
// Run Post Release Tasks
$tasksToRun = $this->getConfig()->getTasks(AbstractTask::STAGE_POST_DEPLOY);
foreach ($tasksToRun as $taskData) {
$task = Factory::get($taskData, $this->getConfig(), true, self::STAGE_POST_DEPLOY);
$task->init();
Console::output('Running <purple>' . $task->getName() . '</purple> ... ', 2, false);
// Run Post Release Tasks
$tasksToRun = $this->getConfig()->getTasks(AbstractTask::STAGE_POST_DEPLOY);
foreach ($tasksToRun as $taskData) {
$task = Factory::get($taskData, $this->getConfig(), true, self::STAGE_POST_DEPLOY);
$task->init();
Console::output('Running <purple>' . $task->getName() . '</purple> ... ', 2, false);
if ($task instanceOf RollbackAware) {
$tasks++;
$result = $task->run();
if ($task instanceOf RollbackAware) {
$tasks++;
$result = $task->run();
if ($result == true) {
Console::output('<green>OK</green>', 0);
$completedTasks++;
} else {
Console::output('<red>FAIL</red>', 0);
}
} else {
Console::output('<yellow>SKIPPED</yellow>', 0);
}
}
if ($result == true) {
Console::output('<green>OK</green>', 0);
$completedTasks++;
} else {
Console::output('<red>FAIL</red>', 0);
}
} else {
Console::output('<yellow>SKIPPED</yellow>', 0);
}
}
if ($completedTasks == $tasks) {
$tasksColor = 'green';
} else {
$tasksColor = 'red';
}
if ($completedTasks == $tasks) {
$tasksColor = 'green';
} else {
$tasksColor = 'red';
}
Console::output('Release rollback on <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray> compted: <' . $tasksColor . '>' . $completedTasks . '/' . $tasks . '</' . $tasksColor . '> tasks done.', 1, 3);
}
}
Console::output('Release rollback on <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray> compted: <' . $tasksColor . '>' . $completedTasks . '/' . $tasks . '</' . $tasksColor . '> tasks done.', 1, 3);
}
}
return $result;
return $result;
} else {
return false;
}
}
} else {
return false;
}
}
}

View file

@ -21,16 +21,16 @@ use Mage\Task\ErrorWithMessageException;
*/
class ChangeBranchTask extends AbstractTask
{
/**
* Branch the executiong began with
* @var string
*/
protected static $startingBranch = 'master';
/**
* Branch the executiong began with
* @var string
*/
protected static $startingBranch = 'master';
/**
* Name of the Task
* @var string
*/
/**
* Name of the Task
* @var string
*/
private $name = 'SCM Changing branch [built-in]';
/**
@ -48,7 +48,7 @@ class ChangeBranchTask extends AbstractTask
*/
public function init()
{
$scmType = $this->getConfig()->general('scm');
$scmType = $this->getConfig()->general('scm');
switch ($scmType) {
case 'git':
@ -65,35 +65,35 @@ class ChangeBranchTask extends AbstractTask
{
switch ($this->getConfig()->general('scm')) {
case 'git':
if ($this->getParameter('_changeBranchRevert', false)) {
$command = 'git checkout ' . self::$startingBranch;
$result = $this->runCommandLocal($command);
if ($this->getParameter('_changeBranchRevert', false)) {
$command = 'git checkout ' . self::$startingBranch;
$result = $this->runCommandLocal($command);
} else {
$command = 'git branch | grep \'*\' | cut -d\' \' -f 2';
$currentBranch = 'master';
$result = $this->runCommandLocal($command, $currentBranch);
} else {
$command = 'git branch | grep \'*\' | cut -d\' \' -f 2';
$currentBranch = 'master';
$result = $this->runCommandLocal($command, $currentBranch);
$scmData = $this->getConfig()->deployment('scm', false);
$scmData = $this->getConfig()->deployment('scm', false);
if ($result && is_array($scmData) && isset($scmData['branch']) && $scmData['branch'] != $currentBranch) {
$command = 'git branch | grep \'' . $scmData['branch'] . '\' | tr -s \' \' | sed \'s/^[ ]//g\'';
$isBranchTracked = '';
$result = $this->runCommandLocal($command, $isBranchTracked);
if ($result && is_array($scmData) && isset($scmData['branch']) && $scmData['branch'] != $currentBranch) {
$command = 'git branch | grep \'' . $scmData['branch'] . '\' | tr -s \' \' | sed \'s/^[ ]//g\'';
$isBranchTracked = '';
$result = $this->runCommandLocal($command, $isBranchTracked);
if ($isBranchTracked == '') {
throw new ErrorWithMessageException('The branch <purple>' . $scmData['branch'] . '</purple> must be tracked.');
}
if ($isBranchTracked == '') {
throw new ErrorWithMessageException('The branch <purple>' . $scmData['branch'] . '</purple> must be tracked.');
}
$branch = $this->getParameter('branch', $scmData['branch']);
$command = 'git checkout ' . $branch;
$result = $this->runCommandLocal($command) && $result;
$branch = $this->getParameter('branch', $scmData['branch']);
$command = 'git checkout ' . $branch;
$result = $this->runCommandLocal($command) && $result;
self::$startingBranch = $currentBranch;
} else {
throw new SkipException;
}
}
self::$startingBranch = $currentBranch;
} else {
throw new SkipException;
}
}
break;
default:

View file

@ -20,10 +20,10 @@ use Mage\Task\SkipException;
*/
class CloneTask extends AbstractTask
{
/**
* Name of the Task
* @var string
*/
/**
* Name of the Task
* @var string
*/
private $name = 'SCM Clone [built-in]';
/**
@ -66,12 +66,12 @@ class CloneTask extends AbstractTask
case 'git':
// Clone Repo
$command = 'cd ' . $this->source['temporal'] . ' ; '
. 'git clone ' . $this->source['repository'] . ' . ';
. 'git clone ' . $this->source['repository'] . ' . ';
$result = $this->runCommandLocal($command);
// Checkout Branch
$command = 'cd ' . $this->source['temporal'] . ' ; '
. 'git checkout ' . $this->source['from'];
. 'git checkout ' . $this->source['from'];
$result = $result && $this->runCommandLocal($command);
$this->getConfig()->setFrom($this->source['temporal']);

View file

@ -19,10 +19,10 @@ use Mage\Task\AbstractTask;
*/
class RemoveCloneTask extends AbstractTask
{
/**
* Name of the Task
* @var string
*/
/**
* Name of the Task
* @var string
*/
private $name = 'SCM Remove Clone [built-in]';
/**
@ -49,8 +49,8 @@ class RemoveCloneTask extends AbstractTask
$this->source = $this->getConfig()->deployment('source');
switch ($this->source['type']) {
case 'git':
$this->name = 'SCM Remove Clone (GIT) [built-in]';
break;
$this->name = 'SCM Remove Clone (GIT) [built-in]';
break;
}
}

View file

@ -20,10 +20,10 @@ use Mage\Task\SkipException;
*/
class UpdateTask extends AbstractTask
{
/**
* Name of the Task
* @var string
*/
/**
* Name of the Task
* @var string
*/
private $name = 'SCM Update [built-in]';
/**

View file

@ -19,10 +19,10 @@ use Mage\Task\AbstractTask;
*/
class AsseticDumpTask extends AbstractTask
{
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
public function getName()
{
return 'Symfony v2 - Assetic Dump [built-in]';
@ -34,8 +34,8 @@ class AsseticDumpTask extends AbstractTask
*/
public function run()
{
// Options
$env = $this->getParameter('env', 'dev');
// Options
$env = $this->getParameter('env', 'dev');
$command = 'app/console assetic:dump --env=' . $env;
$result = $this->runCommand($command);

View file

@ -19,10 +19,10 @@ use Mage\Task\AbstractTask;
*/
class AssetsInstallTask extends AbstractTask
{
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
public function getName()
{
return 'Symfony v2 - Assets Install [built-in]';
@ -34,17 +34,17 @@ class AssetsInstallTask extends AbstractTask
*/
public function run()
{
// Options
$target = $this->getParameter('target', 'web');
$symlink = $this->getParameter('symlink', false);
$relative = $this->getParameter('relative', false);
$env = $this->getParameter('env', 'dev');
// Options
$target = $this->getParameter('target', 'web');
$symlink = $this->getParameter('symlink', false);
$relative = $this->getParameter('relative', false);
$env = $this->getParameter('env', 'dev');
if ($relative) {
$symlink = true;
}
if ($relative) {
$symlink = true;
}
$command = 'app/console assets:install ' . ($symlink ? '--symlink' : '') . ' ' . ($relative ? '--relative' : '') . ' --env=' . $env . ' ' . $target;
$command = 'app/console assets:install ' . ($symlink ? '--symlink' : '') . ' ' . ($relative ? '--relative' : '') . ' --env=' . $env . ' ' . $target;
$result = $this->runCommand($command);
return $result;

View file

@ -19,10 +19,10 @@ use Mage\Task\AbstractTask;
*/
class CacheClearTask extends AbstractTask
{
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
public function getName()
{
return 'Symfony v2 - Cache Clear [built-in]';
@ -34,8 +34,8 @@ class CacheClearTask extends AbstractTask
*/
public function run()
{
// Options
$env = $this->getParameter('env', 'dev');
// Options
$env = $this->getParameter('env', 'dev');
$command = 'app/console cache:clear --env=' . $env;
$result = $this->runCommand($command);

View file

@ -19,10 +19,10 @@ use Mage\Task\AbstractTask;
*/
class CacheWarmupTask extends AbstractTask
{
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
public function getName()
{
return 'Symfony v2 - Cache Warmup [built-in]';
@ -34,8 +34,8 @@ class CacheWarmupTask extends AbstractTask
*/
public function run()
{
// Options
$env = $this->getParameter('env', 'dev');
// Options
$env = $this->getParameter('env', 'dev');
$command = 'app/console cache:warmup --env=' . $env;
$result = $this->runCommand($command);

View file

@ -56,8 +56,8 @@ class Factory
$instance = new $className($taskConfig, $inRollback, $stage, $taskParameters);
if (!is_a($instance,'Mage\Task\AbstractTask')) {
throw new Exception('The Task ' . $taskName . ' must be an instance of Mage\Task\AbstractTask.');
if (!is_a($instance, 'Mage\Task\AbstractTask')) {
throw new Exception('The Task ' . $taskName . ' must be an instance of Mage\Task\AbstractTask.');
}
return $instance;

View file

@ -30,21 +30,21 @@ class Dumper
/**
* Sets the indentation.
*
* @param int $num The amount of spaces to use for indentation of nested nodes.
* @param int $num The amount of spaces to use for indentation of nested nodes.
*/
public function setIndentation($num)
{
$this->indentation = (int) $num;
$this->indentation = (int)$num;
}
/**
* Dumps a PHP value to YAML.
*
* @param mixed $input The PHP value
* @param int $inline The level where you switch to inline YAML
* @param int $indent The level of indentation (used internally)
* @param bool $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
* @param bool $objectSupport true if object support is enabled, false otherwise
* @param mixed $input The PHP value
* @param int $inline The level where you switch to inline YAML
* @param int $indent The level of indentation (used internally)
* @param bool $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
* @param bool $objectSupport true if object support is enabled, false otherwise
*
* @return string The YAML representation of the PHP value
*/
@ -54,7 +54,7 @@ class Dumper
$prefix = $indent ? str_repeat(' ', $indent) : '';
if ($inline <= 0 || !is_array($input) || empty($input)) {
$output .= $prefix.Inline::dump($input, $exceptionOnInvalidType, $objectSupport);
$output .= $prefix . Inline::dump($input, $exceptionOnInvalidType, $objectSupport);
} else {
$isAHash = array_keys($input) !== range(0, count($input) - 1);
@ -63,10 +63,10 @@ class Dumper
$output .= sprintf('%s%s%s%s',
$prefix,
$isAHash ? Inline::dump($key, $exceptionOnInvalidType, $objectSupport).':' : '-',
$isAHash ? Inline::dump($key, $exceptionOnInvalidType, $objectSupport) . ':' : '-',
$willBeInlined ? ' ' : "\n",
$this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + $this->indentation, $exceptionOnInvalidType, $objectSupport)
).($willBeInlined ? "\n" : '');
) . ($willBeInlined ? "\n" : '');
}
}

View file

@ -27,16 +27,16 @@ class Escaper
// on the input arrays. This ordering of the characters avoids the use of strtr,
// which performs more slowly.
private static $escapees = array('\\\\', '\\"', '"',
"\x00", "\x01", "\x02", "\x03", "\x04", "\x05", "\x06", "\x07",
"\x08", "\x09", "\x0a", "\x0b", "\x0c", "\x0d", "\x0e", "\x0f",
"\x10", "\x11", "\x12", "\x13", "\x14", "\x15", "\x16", "\x17",
"\x18", "\x19", "\x1a", "\x1b", "\x1c", "\x1d", "\x1e", "\x1f",
"\x00", "\x01", "\x02", "\x03", "\x04", "\x05", "\x06", "\x07",
"\x08", "\x09", "\x0a", "\x0b", "\x0c", "\x0d", "\x0e", "\x0f",
"\x10", "\x11", "\x12", "\x13", "\x14", "\x15", "\x16", "\x17",
"\x18", "\x19", "\x1a", "\x1b", "\x1c", "\x1d", "\x1e", "\x1f",
"\xc2\x85", "\xc2\xa0", "\xe2\x80\xa8", "\xe2\x80\xa9");
private static $escaped = array('\\"', '\\\\', '\\"',
"\\0", "\\x01", "\\x02", "\\x03", "\\x04", "\\x05", "\\x06", "\\a",
"\\b", "\\t", "\\n", "\\v", "\\f", "\\r", "\\x0e", "\\x0f",
private static $escaped = array('\\"', '\\\\', '\\"',
"\\0", "\\x01", "\\x02", "\\x03", "\\x04", "\\x05", "\\x06", "\\a",
"\\b", "\\t", "\\n", "\\v", "\\f", "\\r", "\\x0e", "\\x0f",
"\\x10", "\\x11", "\\x12", "\\x13", "\\x14", "\\x15", "\\x16", "\\x17",
"\\x18", "\\x19", "\\x1a", "\\e", "\\x1c", "\\x1d", "\\x1e", "\\x1f",
"\\x18", "\\x19", "\\x1a", "\\e", "\\x1c", "\\x1d", "\\x1e", "\\x1f",
"\\N", "\\_", "\\L", "\\P");
/**
@ -48,7 +48,7 @@ class Escaper
*/
public static function requiresDoubleQuoting($value)
{
return preg_match('/'.self::REGEX_CHARACTER_TO_ESCAPE.'/u', $value);
return preg_match('/' . self::REGEX_CHARACTER_TO_ESCAPE . '/u', $value);
}
/**

View file

@ -35,11 +35,11 @@ class ParseException extends RuntimeException
/**
* Constructor.
*
* @param string $message The error message
* @param int $parsedLine The line where the error occurred
* @param int $snippet The snippet of code near the problem
* @param string $parsedFile The file name where the error occurred
* @param \Exception $previous The previous exception
* @param string $message The error message
* @param int $parsedLine The line where the error occurred
* @param int $snippet The snippet of code near the problem
* @param string $parsedFile The file name where the error occurred
* @param \Exception $previous The previous exception
*/
public function __construct($message, $parsedLine = -1, $snippet = null, $parsedFile = null, \Exception $previous = null)
{
@ -112,7 +112,7 @@ class ParseException extends RuntimeException
/**
* Sets the line where the error occurred.
*
* @param int $parsedLine The file line
* @param int $parsedLine The file line
*/
public function setParsedLine($parsedLine)
{

View file

@ -34,10 +34,10 @@ class Inline
/**
* Converts a YAML string to a PHP array.
*
* @param string $value A YAML string
* @param bool $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
* @param bool $objectSupport true if object support is enabled, false otherwise
* @param bool $objectForMap true if maps should return a stdClass instead of array()
* @param string $value A YAML string
* @param bool $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
* @param bool $objectSupport true if object support is enabled, false otherwise
* @param bool $objectForMap true if maps should return a stdClass instead of array()
*
* @return array A PHP array representing the YAML string
*
@ -55,7 +55,7 @@ class Inline
return '';
}
if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) {
if (function_exists('mb_internal_encoding') && ((int)ini_get('mbstring.func_overload')) & 2) {
$mbEncoding = mb_internal_encoding();
mb_internal_encoding('ASCII');
}
@ -89,9 +89,9 @@ class Inline
/**
* Dumps a given PHP variable to a YAML string.
*
* @param mixed $value The PHP variable to convert
* @param bool $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
* @param bool $objectSupport true if object support is enabled, false otherwise
* @param mixed $value The PHP variable to convert
* @param bool $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
* @param bool $objectSupport true if object support is enabled, false otherwise
*
* @return string The YAML string representing the PHP array
*
@ -108,7 +108,7 @@ class Inline
return 'null';
case is_object($value):
if ($objectSupport) {
return '!!php/object:'.serialize($value);
return '!!php/object:' . serialize($value);
}
if ($exceptionOnInvalidType) {
@ -125,7 +125,7 @@ class Inline
case false === $value:
return 'false';
case ctype_digit($value):
return is_string($value) ? "'$value'" : (int) $value;
return is_string($value) ? "'$value'" : (int)$value;
case is_numeric($value):
$locale = setlocale(LC_NUMERIC, 0);
if (false !== $locale) {
@ -155,9 +155,9 @@ class Inline
/**
* Dumps a PHP array to a YAML string.
*
* @param array $value The PHP array to dump
* @param bool $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
* @param bool $objectSupport true if object support is enabled, false otherwise
* @param array $value The PHP array to dump
* @param bool $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
* @param bool $objectSupport true if object support is enabled, false otherwise
*
* @return string The YAML string representing the PHP array
*/
@ -166,7 +166,9 @@ class Inline
// array
$keys = array_keys($value);
if ((1 == count($keys) && '0' == $keys[0])
|| (count($keys) > 1 && array_reduce($keys, function ($v, $w) { return (int) $v + $w; }, 0) == count($keys) * (count($keys) - 1) / 2)
|| (count($keys) > 1 && array_reduce($keys, function ($v, $w) {
return (int)$v + $w;
}, 0) == count($keys) * (count($keys) - 1) / 2)
) {
$output = array();
foreach ($value as $val) {
@ -188,11 +190,11 @@ class Inline
/**
* Parses a scalar to a YAML string.
*
* @param scalar $scalar
* @param string $delimiters
* @param array $stringDelimiters
* @param int &$i
* @param bool $evaluate
* @param scalar $scalar
* @param string $delimiters
* @param array $stringDelimiters
* @param int &$i
* @param bool $evaluate
*
* @return string A YAML string
*
@ -220,7 +222,7 @@ class Inline
if (false !== $strpos = strpos($output, ' #')) {
$output = rtrim(substr($output, 0, $strpos));
}
} elseif (preg_match('/^(.+?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) {
} elseif (preg_match('/^(.+?)(' . implode('|', $delimiters) . ')/', substr($scalar, $i), $match)) {
$output = $match[1];
$i += strlen($output);
} else {
@ -239,7 +241,7 @@ class Inline
* Parses a quoted scalar to YAML.
*
* @param string $scalar
* @param int &$i
* @param int &$i
*
* @return string A YAML string
*
@ -247,7 +249,7 @@ class Inline
*/
private static function parseQuotedScalar($scalar, &$i)
{
if (!preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) {
if (!preg_match('/' . self::REGEX_QUOTED_STRING . '/Au', substr($scalar, $i), $match)) {
throw new ParseException(sprintf('Malformed inline YAML string (%s).', substr($scalar, $i)));
}
@ -268,8 +270,8 @@ class Inline
/**
* Parses a sequence to a YAML string.
*
* @param string $sequence
* @param int &$i
* @param string $sequence
* @param int &$i
*
* @return string A YAML string
*
@ -304,7 +306,7 @@ class Inline
if (!$isQuoted && false !== strpos($value, ': ')) {
// embedded mapping?
try {
$value = self::parseMapping('{'.$value.'}');
$value = self::parseMapping('{' . $value . '}');
} catch (\InvalidArgumentException $e) {
// no, it's not
}
@ -324,8 +326,8 @@ class Inline
/**
* Parses a mapping to a YAML string.
*
* @param string $mapping
* @param int &$i
* @param string $mapping
* @param int &$i
*
* @return string A YAML string
*
@ -346,7 +348,7 @@ class Inline
continue 2;
case '}':
if (self::$objectForMap) {
return (object) $output;
return (object)$output;
}
return $output;
@ -425,7 +427,7 @@ class Inline
case '' === $scalar:
case '~' === $scalar:
/** @noinspection PhpInconsistentReturnPointsInspection */
return;
return;
case 'true' === $scalarLower:
return true;
case 'false' === $scalarLower:
@ -435,7 +437,7 @@ class Inline
case $scalar[0] === '+' || $scalar[0] === '-' || $scalar[0] === '.' || $scalar[0] === '!' || is_numeric($scalar[0]):
switch (true) {
case 0 === strpos($scalar, '!str'):
return (string) substr($scalar, 5);
return (string)substr($scalar, 5);
case 0 === strpos($scalar, '! '):
return intval(self::parseScalar(substr($scalar, 2)));
case 0 === strpos($scalar, '!!php/object:'):
@ -453,14 +455,14 @@ class Inline
$raw = $scalar;
$cast = intval($scalar);
return '0' == $scalar[0] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw);
return '0' == $scalar[0] ? octdec($scalar) : (((string)$raw == (string)$cast) ? $cast : $raw);
case '-' === $scalar[0] && ctype_digit(substr($scalar, 1)):
$raw = $scalar;
$cast = intval($scalar);
return '0' == $scalar[1] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw);
return '0' == $scalar[1] ? octdec($scalar) : (((string)$raw == (string)$cast) ? $cast : $raw);
case is_numeric($scalar):
return '0x' == $scalar[0].$scalar[1] ? hexdec($scalar) : floatval($scalar);
return '0x' == $scalar[0] . $scalar[1] ? hexdec($scalar) : floatval($scalar);
case '.inf' === $scalarLower:
case '.nan' === $scalarLower:
return -log(0);
@ -472,7 +474,7 @@ class Inline
return strtotime($scalar);
}
default:
return (string) $scalar;
return (string)$scalar;
}
}

View file

@ -23,16 +23,16 @@ class Parser
{
const FOLDED_SCALAR_PATTERN = '(?P<separator>\||>)(?P<modifiers>\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P<comments> +#.*)?';
private $offset = 0;
private $lines = array();
private $currentLineNb = -1;
private $currentLine = '';
private $refs = array();
private $offset = 0;
private $lines = array();
private $currentLineNb = -1;
private $currentLine = '';
private $refs = array();
/**
* Constructor
*
* @param int $offset The offset of YAML document (used for line numbers in error messages)
* @param int $offset The offset of YAML document (used for line numbers in error messages)
*/
public function __construct($offset = 0)
{
@ -42,10 +42,10 @@ class Parser
/**
* Parses a YAML string to a PHP value.
*
* @param string $value A YAML string
* @param bool $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
* @param bool $objectSupport true if object support is enabled, false otherwise
* @param bool $objectForMap true if maps should return a stdClass instead of array()
* @param string $value A YAML string
* @param bool $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
* @param bool $objectSupport true if object support is enabled, false otherwise
* @param bool $objectForMap true if maps should return a stdClass instead of array()
*
* @return mixed A PHP value
*
@ -61,7 +61,7 @@ class Parser
throw new ParseException('The YAML value does not appear to be valid UTF-8.');
}
if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) {
if (function_exists('mb_internal_encoding') && ((int)ini_get('mbstring.func_overload')) & 2) {
$mbEncoding = mb_internal_encoding();
mb_internal_encoding('UTF-8');
}
@ -99,7 +99,7 @@ class Parser
} else {
if (isset($values['leadspaces'])
&& ' ' == $values['leadspaces']
&& preg_match('#^(?P<key>'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\{\[].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $values['value'], $matches)
&& preg_match('#^(?P<key>' . Inline::REGEX_QUOTED_STRING . '|[^ \'"\{\[].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $values['value'], $matches)
) {
// this is a compact notation element, add to next block and parse
$c = $this->getRealCurrentLineNb();
@ -108,7 +108,7 @@ class Parser
$block = $values['value'];
if ($this->isNextLineIndented()) {
$block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + 2);
$block .= "\n" . $this->getNextEmbedBlock($this->getCurrentLineIndentation() + 2);
}
$data[] = $parser->parse($block, $exceptionOnInvalidType, $objectSupport, $objectForMap);
@ -116,7 +116,7 @@ class Parser
$data[] = $this->parseValue($values['value'], $exceptionOnInvalidType, $objectSupport, $objectForMap);
}
}
} elseif (preg_match('#^(?P<key>'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\[\{].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $this->currentLine, $values) && false === strpos($values['key'],' #')) {
} elseif (preg_match('#^(?P<key>' . Inline::REGEX_QUOTED_STRING . '|[^ \'"\[\{].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $this->currentLine, $values) && false === strpos($values['key'], ' #')) {
if ($context && 'sequence' == $context) {
throw new ParseException('You cannot define a mapping item when in a sequence');
}
@ -300,7 +300,7 @@ class Parser
/**
* Returns the next embed block of YAML.
*
* @param int $indentation The indent level at which the block is to be read, or null for default
* @param int $indentation The indent level at which the block is to be read, or null for default
*
* @return string A YAML string
*
@ -327,7 +327,7 @@ class Parser
$isItUnindentedCollection = $this->isStringUnIndentedCollectionItem($this->currentLine);
// Comments must not be removed inside a string block (ie. after a line ending with "|")
$removeCommentsPattern = '~'.self::FOLDED_SCALAR_PATTERN.'$~';
$removeCommentsPattern = '~' . self::FOLDED_SCALAR_PATTERN . '$~';
$removeComments = !preg_match($removeCommentsPattern, $this->currentLine);
while ($this->moveToNextLine()) {
@ -392,10 +392,10 @@ class Parser
/**
* Parses a YAML value.
*
* @param string $value A YAML value
* @param bool $exceptionOnInvalidType True if an exception must be thrown on invalid types false otherwise
* @param bool $objectSupport True if object support is enabled, false otherwise
* @param bool $objectForMap true if maps should return a stdClass instead of array()
* @param string $value A YAML value
* @param bool $exceptionOnInvalidType True if an exception must be thrown on invalid types false otherwise
* @param bool $objectSupport True if object support is enabled, false otherwise
* @param bool $objectForMap true if maps should return a stdClass instead of array()
*
* @return mixed A PHP value
*
@ -417,7 +417,7 @@ class Parser
return $this->refs[$value];
}
if (preg_match('/^'.self::FOLDED_SCALAR_PATTERN.'$/', $value, $matches)) {
if (preg_match('/^' . self::FOLDED_SCALAR_PATTERN . '$/', $value, $matches)) {
$modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';
return $this->parseFoldedScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), intval(abs($modifiers)));
@ -436,9 +436,9 @@ class Parser
/**
* Parses a folded scalar.
*
* @param string $separator The separator that was used to begin this folded scalar (| or >)
* @param string $indicator The indicator that was used to begin this folded scalar (+ or -)
* @param int $indentation The indentation that was used to begin this folded scalar
* @param string $separator The separator that was used to begin this folded scalar (| or >)
* @param string $indicator The indicator that was used to begin this folded scalar (+ or -)
* @param int $indentation The indentation that was used to begin this folded scalar
*
* @return string The text value
*/

View file

@ -55,7 +55,7 @@ class Unescaper
};
// evaluate the string
return preg_replace_callback('/'.self::REGEX_ESCAPED_CHARACTER.'/u', $callback, $value);
return preg_replace_callback('/' . self::REGEX_ESCAPED_CHARACTER . '/u', $callback, $value);
}
/**
@ -131,12 +131,12 @@ class Unescaper
return chr($c);
}
if (0x800 > $c) {
return chr(0xC0 | $c>>6).chr(0x80 | $c & 0x3F);
return chr(0xC0 | $c >> 6) . chr(0x80 | $c & 0x3F);
}
if (0x10000 > $c) {
return chr(0xE0 | $c>>12).chr(0x80 | $c>>6 & 0x3F).chr(0x80 | $c & 0x3F);
return chr(0xE0 | $c >> 12) . chr(0x80 | $c >> 6 & 0x3F) . chr(0x80 | $c & 0x3F);
}
return chr(0xF0 | $c>>18).chr(0x80 | $c>>12 & 0x3F).chr(0x80 | $c>>6 & 0x3F).chr(0x80 | $c & 0x3F);
return chr(0xF0 | $c >> 18) . chr(0x80 | $c >> 12 & 0x3F) . chr(0x80 | $c >> 6 & 0x3F) . chr(0x80 | $c & 0x3F);
}
}

View file

@ -40,9 +40,9 @@ class Yaml
* you must validate the input before calling this method. Passing a file
* as an input is a deprecated feature and will be removed in 3.0.
*
* @param string $input Path to a YAML file or a string containing YAML
* @param bool $exceptionOnInvalidType True if an exception must be thrown on invalid types false otherwise
* @param bool $objectSupport True if object support is enabled, false otherwise
* @param string $input Path to a YAML file or a string containing YAML
* @param bool $exceptionOnInvalidType True if an exception must be thrown on invalid types false otherwise
* @param bool $objectSupport True if object support is enabled, false otherwise
*
* @return array The YAML converted to a PHP array
*
@ -82,11 +82,11 @@ class Yaml
* The dump method, when supplied with an array, will do its best
* to convert the array into friendly YAML.
*
* @param array $array PHP array
* @param int $inline The level where you switch to inline YAML
* @param int $indent The amount of spaces to use for indentation of nested nodes.
* @param bool $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
* @param bool $objectSupport true if object support is enabled, false otherwise
* @param array $array PHP array
* @param int $inline The level where you switch to inline YAML
* @param int $indent The amount of spaces to use for indentation of nested nodes.
* @param bool $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
* @param bool $objectSupport true if object support is enabled, false otherwise
*
* @return string A YAML string representing the original PHP array
*