diff --git a/Mage/Autoload.php b/Mage/Autoload.php
index ab088ba..f0032eb 100644
--- a/Mage/Autoload.php
+++ b/Mage/Autoload.php
@@ -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;
diff --git a/Mage/Command/AbstractCommand.php b/Mage/Command/AbstractCommand.php
index 051564b..de92a8b 100644
--- a/Mage/Command/AbstractCommand.php
+++ b/Mage/Command/AbstractCommand.php
@@ -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;
/**
diff --git a/Mage/Command/BuiltIn/AddCommand.php b/Mage/Command/BuiltIn/AddCommand.php
index fd9806e..fab6f71 100644
--- a/Mage/Command/BuiltIn/AddCommand.php
+++ b/Mage/Command/BuiltIn/AddCommand.php
@@ -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: ' . $environmentName . '');
$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);
diff --git a/Mage/Command/BuiltIn/CompileCommand.php b/Mage/Command/BuiltIn/CompileCommand.php
index 344a516..4f17543 100644
--- a/Mage/Command/BuiltIn/CompileCommand.php
+++ b/Mage/Command/BuiltIn/CompileCommand.php
@@ -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 php.ini variable phar.readonly must be Off.', 1, 2);
- return;
- }
+ if (ini_get('phar.readonly')) {
+ Console::output('The php.ini variable phar.readonly must be Off.', 1, 2);
+ return;
+ }
$compiler = new Compiler;
$compiler->compile();
diff --git a/Mage/Command/BuiltIn/DeployCommand.php b/Mage/Command/BuiltIn/DeployCommand.php
index a4fa92b..e6e7e02 100644
--- a/Mage/Command/BuiltIn/DeployCommand.php
+++ b/Mage/Command/BuiltIn/DeployCommand.php
@@ -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 Succeded
- * @var string
- */
- const SUCCEDED = 'succeded';
-
- /**
- * Deploy is in progress
- * @var string
- */
- const IN_PROGRESS = 'in_progress';
-
- /**
- * Time the Deployment has Started
- * @var integer
- */
+ * Deploy has Failed
+ * @var string
+ */
+ const FAILED = 'failed';
+
+ /**
+ * Deploy has Succeded
+ * @var string
+ */
+ const SUCCEDED = 'succeded';
+
+ /**
+ * Deploy is in progress
+ * @var string
+ */
+ const IN_PROGRESS = 'in_progress';
+
+ /**
+ * 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('This environment is locked!', 1, 2);
- echo file_get_contents($lockFile);
- return;
- }
-
- // Check for running instance and Lock
- if (file_exists(getcwd() . '/.mage/~working.lock')) {
- Console::output('There is already an instance of Magallanes running!', 1, 2);
- return;
- } else {
- touch(getcwd() . '/.mage/~working.lock');
- }
+ $lockFile = getcwd() . '/.mage/' . $this->getConfig()->getEnvironment() . '.lock';
+ if (file_exists($lockFile)) {
+ Console::output('This environment is locked!', 1, 2);
+ echo file_get_contents($lockFile);
+ return;
+ }
+
+ // Check for running instance and Lock
+ if (file_exists(getcwd() . '/.mage/~working.lock')) {
+ Console::output('There is already an instance of Magallanes running!', 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('Release ID: ' . $this->getConfig()->getReleaseId() . '', 2, 1);
+ Console::output('Release ID: ' . $this->getConfig()->getReleaseId() . '', 2, 1);
}
// Deploy Summary - SCM
if ($this->getConfig()->deployment('scm', false)) {
- $scmConfig = $this->getConfig()->deployment('scm');
- if (isset($scmConfig['branch'])) {
- Console::output('SCM Branch: ' . $scmConfig['branch'] . '', 2, 1);
- }
+ $scmConfig = $this->getConfig()->deployment('scm');
+ if (isset($scmConfig['branch'])) {
+ Console::output('SCM Branch: ' . $scmConfig['branch'] . '', 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 ' . self::$failedTasks . ' deployment tasks failed: ABORTING', 1, 2);
+ self::$deployStatus = self::FAILED;
+ Console::output('A total of ' . self::$failedTasks . ' deployment tasks failed: ABORTING', 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 ' . self::$failedTasks . ' deployment tasks failed: ABORTING', 1, 2);
- }
+ // Check Status
+ if (self::$failedTasks > 0) {
+ self::$deployStatus = self::FAILED;
+ Console::output('A total of ' . self::$failedTasks . ' deployment tasks failed: ABORTING', 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');
- }
-
- // Change Branch
- if ($config->deployment('scm', false)) {
- array_unshift($tasksToRun, 'scm/change-branch');
- }
+ // 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');
+ }
}
// PostDeployment Hook
if ($stage == AbstractTask::STAGE_POST_DEPLOY) {
- // 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');
- }
-
- // Remove Remote Source
- if (is_array($config->deployment('source', null))) {
- array_push($tasksToRun, 'scm/remove-clone');
+ // 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');
+ }
+
+ // 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;
- }
-
- // Run Tasks for Deployment
- $hosts = $this->getConfig()->getHosts();
- $this->hostsCount = count($hosts);
- self::$failedTasks = 0;
+ if (self::$deployStatus == self::FAILED) {
+ return;
+ }
- if ($this->hostsCount == 0) {
- Console::output('Warning! No hosts defined, skipping deployment tasks.', 1, 3);
+ // Run Tasks for Deployment
+ $hosts = $this->getConfig()->getHosts();
+ $this->hostsCount = count($hosts);
+ self::$failedTasks = 0;
- } else {
- $this->startTimeHosts = time();
- foreach ($hosts as $hostKey => $host) {
+ if ($this->hostsCount == 0) {
+ Console::output('Warning! No hosts defined, skipping deployment tasks.', 1, 3);
- // Check if Host has specific configuration
- $hostConfig = null;
- if (is_array($host)) {
- $hostConfig = $host;
- $host = $hostKey;
- }
+ } 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;
+ }
- // 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 ' . $this->getConfig()->getHost() . '');
+ Console::output('Deploying to ' . $this->getConfig()->getHost() . '');
- $tasksToRun = $this->getConfig()->getTasks();
+ $tasksToRun = $this->getConfig()->getTasks();
$deployStrategy = $this->chooseDeployStrategy();
array_unshift($tasksToRun, $deployStrategy);
- if (count($tasksToRun) == 0) {
- Console::output('Warning! No Deployment tasks defined.', 2);
- Console::output('Deployment to ' . $host . ' skipped!', 1, 3);
-
- } 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 ($completedTasks == $tasks) {
- $tasksColor = 'green';
- } else {
- $tasksColor = 'red';
- }
-
- Console::output('Deployment to ' . $this->getConfig()->getHost() . ' completed: <' . $tasksColor . '>' . $completedTasks . '/' . $tasks . '' . $tasksColor . '> tasks done.', 1, 3);
- }
-
- // Reset Host Config
- $this->getConfig()->setHostConfig(null);
- }
- $this->endTimeHosts = time();
-
- 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 Releasing');
- foreach ($hosts as $hostKey => $host) {
-
- // 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);
-
- $task = Factory::get($this->chooseReleaseStrategy(), $this->getConfig(), false, AbstractTask::STAGE_DEPLOY);
-
- if ($this->runTask($task, 'Releasing on host ' . $host . ' ... ')) {
- $completedTasks++;
- }
-
- // Reset Host Config
- $this->getConfig()->setHostConfig(null);
- }
- Console::output('Finished the Releasing', 1, 3);
-
- // 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;
- }
-
- // Set Host
- $this->getConfig()->setHost($host);
- $this->getConfig()->setHostConfig($hostConfig);
-
- $tasksToRun = $this->getConfig()->getTasks(AbstractTask::STAGE_POST_RELEASE);
- $tasks = count($tasksToRun);
- $completedTasks = 0;
-
- if (count($tasksToRun) > 0) {
- Console::output('Starting Post-Release tasks for ' . $host . ':');
-
- foreach ($tasksToRun as $task) {
- $task = Factory::get($task, $this->getConfig(), false, AbstractTask::STAGE_POST_RELEASE);
-
- if ($this->runTask($task)) {
- $completedTasks++;
- }
- }
-
- if ($completedTasks == $tasks) {
- $tasksColor = 'green';
- } else {
- $tasksColor = 'red';
- }
- Console::output('Finished Post-Release tasks for ' . $host . ': <' . $tasksColor . '>' . $completedTasks . '/' . $tasks . '' . $tasksColor . '> tasks done.', 1, 3);
- }
-
- // Reset Host Config
- $this->getConfig()->setHostConfig(null);
- }
- }
- }
+ if (count($tasksToRun) == 0) {
+ Console::output('Warning! No Deployment tasks defined.', 2);
+ Console::output('Deployment to ' . $host . ' skipped!', 1, 3);
+
+ } 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 ($completedTasks == $tasks) {
+ $tasksColor = 'green';
+ } else {
+ $tasksColor = 'red';
+ }
+
+ Console::output('Deployment to ' . $this->getConfig()->getHost() . ' completed: <' . $tasksColor . '>' . $completedTasks . '/' . $tasks . '' . $tasksColor . '> tasks done.', 1, 3);
+ }
+
+ // Reset Host Config
+ $this->getConfig()->setHostConfig(null);
+ }
+ $this->endTimeHosts = time();
+
+ 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 Releasing');
+ foreach ($hosts as $hostKey => $host) {
+
+ // 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);
+
+ $task = Factory::get($this->chooseReleaseStrategy(), $this->getConfig(), false, AbstractTask::STAGE_DEPLOY);
+
+ if ($this->runTask($task, 'Releasing on host ' . $host . ' ... ')) {
+ $completedTasks++;
+ }
+
+ // Reset Host Config
+ $this->getConfig()->setHostConfig(null);
+ }
+ Console::output('Finished the Releasing', 1, 3);
+
+ // 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;
+ }
+
+ // Set Host
+ $this->getConfig()->setHost($host);
+ $this->getConfig()->setHostConfig($hostConfig);
+
+ $tasksToRun = $this->getConfig()->getTasks(AbstractTask::STAGE_POST_RELEASE);
+ $tasks = count($tasksToRun);
+ $completedTasks = 0;
+
+ if (count($tasksToRun) > 0) {
+ Console::output('Starting Post-Release tasks for ' . $host . ':');
+
+ foreach ($tasksToRun as $task) {
+ $task = Factory::get($task, $this->getConfig(), false, AbstractTask::STAGE_POST_RELEASE);
+
+ if ($this->runTask($task)) {
+ $completedTasks++;
+ }
+ }
+
+ if ($completedTasks == $tasks) {
+ $tasksColor = 'green';
+ } else {
+ $tasksColor = 'red';
+ }
+ Console::output('Finished Post-Release tasks for ' . $host . ': <' . $tasksColor . '>' . $completedTasks . '/' . $tasks . '' . $tasksColor . '> tasks done.', 1, 3);
+ }
+
+ // Reset Host Config
+ $this->getConfig()->setHostConfig(null);
+ }
+ }
+ }
}
/**
@@ -452,8 +452,8 @@ class DeployCommand extends AbstractCommand implements RequiresEnvironment
$result = false;
}
} catch (ErrorWithMessageException $e) {
- Console::output('FAIL [Message: ' . $e->getMessage() . ']', 0);
- $result = false;
+ Console::output('FAIL [Message: ' . $e->getMessage() . ']', 0);
+ $result = false;
} catch (SkipException $e) {
Console::output('SKIPPED', 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_RSYNC:
+ $deployStrategy = 'deployment/strategy/rsync';
+ break;
- case self::DEPLOY_STRATEGY_TARGZ:
- $deployStrategy = 'deployment/strategy/tar-gz';
- 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_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;
+ 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;
}
diff --git a/Mage/Command/BuiltIn/InitCommand.php b/Mage/Command/BuiltIn/InitCommand.php
index 84f3069..6f478c0 100644
--- a/Mage/Command/BuiltIn/InitCommand.php
+++ b/Mage/Command/BuiltIn/InitCommand.php
@@ -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;
}
}
diff --git a/Mage/Command/BuiltIn/InstallCommand.php b/Mage/Command/BuiltIn/InstallCommand.php
index 090651b..b69404e 100644
--- a/Mage/Command/BuiltIn/InstallCommand.php
+++ b/Mage/Command/BuiltIn/InstallCommand.php
@@ -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 Magallanes... ', 1, 0);
-
- // Vars
- $installDir = $this->getConfig()->getParameter('installDir', '/opt/magallanes');
- $systemWide = $this->getConfig()->getParameter('systemWide', false);
-
- // Clean vars
- $baseDir = realpath(dirname($installDir));
- $installDir = basename($installDir);
-
- // Check if install dir is available
- if (!is_dir($baseDir) || !is_writable($baseDir)) {
- Console::output('Failure: install directory is invalid.', 0, 2);
-
- // Chck if it is a system wide install the user is root
- } else if ($systemWide && (getenv('LOGNAME') != 'root')) {
- Console::output('Failure: you have to be root to perform a system wide install.', 0, 2);
-
- } else {
- $destinationDir = $baseDir . '/' . $installDir;
- if (!is_dir($destinationDir)) {
- mkdir($destinationDir);
- }
-
- // 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');
- }
-
- // 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');
- }
- }
-
- Console::output('Success!', 0, 2);
- }
+ Console::output('Installing Magallanes... ', 1, 0);
+
+ // Vars
+ $installDir = $this->getConfig()->getParameter('installDir', '/opt/magallanes');
+ $systemWide = $this->getConfig()->getParameter('systemWide', false);
+
+ // Clean vars
+ $baseDir = realpath(dirname($installDir));
+ $installDir = basename($installDir);
+
+ // Check if install dir is available
+ if (!is_dir($baseDir) || !is_writable($baseDir)) {
+ Console::output('Failure: install directory is invalid.', 0, 2);
+
+ // Chck if it is a system wide install the user is root
+ } else if ($systemWide && (getenv('LOGNAME') != 'root')) {
+ Console::output('Failure: you have to be root to perform a system wide install.', 0, 2);
+
+ } else {
+ $destinationDir = $baseDir . '/' . $installDir;
+ if (!is_dir($destinationDir)) {
+ mkdir($destinationDir);
+ }
+
+ // 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');
+ }
+
+ // 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');
+ }
+ }
+
+ Console::output('Success!', 0, 2);
+ }
}
/**
diff --git a/Mage/Command/BuiltIn/ListCommand.php b/Mage/Command/BuiltIn/ListCommand.php
index b088eac..0e67a0f 100644
--- a/Mage/Command/BuiltIn/ListCommand.php
+++ b/Mage/Command/BuiltIn/ListCommand.php
@@ -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('These are your configured environments:', 1, 1);
- foreach ($environments as $environment) {
- Console::output('* ' . $environment . '', 2, 1);
- }
- Console::output('', 1, 1);
+ Console::output('These are your configured environments:', 1, 1);
+ foreach ($environments as $environment) {
+ Console::output('* ' . $environment . '', 2, 1);
+ }
+ Console::output('', 1, 1);
} else {
- Console::output('You don\'t have any environment configured.', 1, 2);
+ Console::output('You don\'t have any environment configured.', 1, 2);
}
}
}
diff --git a/Mage/Command/BuiltIn/LockCommand.php b/Mage/Command/BuiltIn/LockCommand.php
index 1444762..b34e5e9 100644
--- a/Mage/Command/BuiltIn/LockCommand.php
+++ b/Mage/Command/BuiltIn/LockCommand.php
@@ -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);
diff --git a/Mage/Command/BuiltIn/ReleasesCommand.php b/Mage/Command/BuiltIn/ReleasesCommand.php
index fadedfa..2be055e 100644
--- a/Mage/Command/BuiltIn/ReleasesCommand.php
+++ b/Mage/Command/BuiltIn/ReleasesCommand.php
@@ -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('Missing required releaseid.', 1, 2);
+ case 'rollback':
+ if (!is_numeric($this->getConfig()->getParameter('release', ''))) {
+ Console::output('Missing required releaseid.', 1, 2);
- return false;
- }
+ return false;
+ }
- $lockFile = getcwd() . '/.mage/' . $this->getConfig()->getEnvironment() . '.lock';
- if (file_exists($lockFile)) {
- Console::output('This environment is locked!', 1, 2);
- echo file_get_contents($lockFile);
+ $lockFile = getcwd() . '/.mage/' . $this->getConfig()->getEnvironment() . '.lock';
+ if (file_exists($lockFile)) {
+ Console::output('This environment is locked!', 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;
}
}
diff --git a/Mage/Command/BuiltIn/UnlockCommand.php b/Mage/Command/BuiltIn/UnlockCommand.php
index d18fc24..b582d1a 100644
--- a/Mage/Command/BuiltIn/UnlockCommand.php
+++ b/Mage/Command/BuiltIn/UnlockCommand.php
@@ -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';
diff --git a/Mage/Command/BuiltIn/UpdateCommand.php b/Mage/Command/BuiltIn/UpdateCommand.php
index cbcbcc7..2e1fb4f 100644
--- a/Mage/Command/BuiltIn/UpdateCommand.php
+++ b/Mage/Command/BuiltIn/UpdateCommand.php
@@ -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());
diff --git a/Mage/Command/BuiltIn/UpgradeCommand.php b/Mage/Command/BuiltIn/UpgradeCommand.php
index 25907bc..86bb0aa 100644
--- a/Mage/Command/BuiltIn/UpgradeCommand.php
+++ b/Mage/Command/BuiltIn/UpgradeCommand.php
@@ -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 ' . $owner . ' user to perform the upgrade, or root.', 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('SKIP', 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('SKIP', 0, 1);
+ Console::output('Your current version is up to date.', 2);
- } else if ($versionCompare == 1) {
- Console::output('SKIP', 0, 1);
- Console::output('Your current version is newer.', 2);
+ } else if ($versionCompare == 1) {
+ Console::output('SKIP', 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('FAIL', 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('FAIL', 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('OK', 0, 1);
- }
+ Console::output('OK', 0, 1);
+ }
- } else {
- Console::output('FAIL', 0, 1);
- Console::output('Invalid version.', 2);
- }
- } else {
- Console::output('FAIL', 0, 1);
- Console::output('Invalid version.', 2);
- }
+ } else {
+ Console::output('FAIL', 0, 1);
+ Console::output('Invalid version.', 2);
+ }
+ } else {
+ Console::output('FAIL', 0, 1);
+ Console::output('Invalid version.', 2);
+ }
}
}
}
diff --git a/Mage/Command/BuiltIn/VersionCommand.php b/Mage/Command/BuiltIn/VersionCommand.php
index 906a384..d2f8827 100644
--- a/Mage/Command/BuiltIn/VersionCommand.php
+++ b/Mage/Command/BuiltIn/VersionCommand.php
@@ -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 Magallanes version ' . MAGALLANES_VERSION .'', 0, 2);
+ Console::output('Running Magallanes version ' . MAGALLANES_VERSION . '', 0, 2);
}
}
\ No newline at end of file
diff --git a/Mage/Command/Factory.php b/Mage/Command/Factory.php
index 19c9452..a006efa 100644
--- a/Mage/Command/Factory.php
+++ b/Mage/Command/Factory.php
@@ -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.');
}
diff --git a/Mage/Compiler.php b/Mage/Compiler.php
index beb30a0..ad209fc 100644
--- a/Mage/Compiler.php
+++ b/Mage/Compiler.php
@@ -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\nenvironment = 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;
- }
- }
+ 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;
+ }
+ }
}
/**
@@ -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);
diff --git a/Mage/Console.php b/Mage/Console.php
index b6f9865..ab02351 100644
--- a/Mage/Console.php
+++ b/Mage/Console.php
@@ -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('' . $configError . '', 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 Magallanes', 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);
}
- }
+ }
}
}
diff --git a/Mage/Console/Colors.php b/Mage/Console/Colors.php
index fa320a3..84bfb62 100644
--- a/Mage/Console/Colors.php
+++ b/Mage/Console/Colors.php
@@ -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(
diff --git a/Mage/Mailer.php b/Mage/Mailer.php
index 96ec30b..e0b3443 100644
--- a/Mage/Mailer.php
+++ b/Mage/Mailer.php
@@ -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);
}
}
\ No newline at end of file
diff --git a/Mage/Task/AbstractTask.php b/Mage/Task/AbstractTask.php
index a13c844..c61f87d 100644
--- a/Mage/Task/AbstractTask.php
+++ b/Mage/Task/AbstractTask.php
@@ -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 Deployment
- * @var string
- */
- const STAGE_DEPLOY = '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';
-
- /**
- * Configuration
- * @var Config;
- */
- protected $config = null;
-
- /**
- * 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;
-
- /**
- * Extra parameters
- * @var array
- */
- protected $parameters = array();
-
- /**
- * 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();
-
- /**
- * 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;
- }
-
- /**
- * 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;
- }
-
- /**
- * 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());
- }
-
- /**
- * @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 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 = '';
- }
-
- // 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();
-
- $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);
-
- 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);
- }
- }
-
- /**
- * 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;
- }
-
- return $command;
- }
+ /**
+ * 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 Post Deployment
+ * @var string
+ */
+ const STAGE_POST_DEPLOY = 'post-deploy';
+
+ /**
+ * Stage Constant for Post Release
+ * @var string
+ */
+ const STAGE_POST_RELEASE = 'post-release';
+
+ /**
+ * Configuration
+ * @var Config;
+ */
+ protected $config = null;
+
+ /**
+ * 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;
+
+ /**
+ * Extra parameters
+ * @var array
+ */
+ protected $parameters = array();
+
+ /**
+ * 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();
+
+ /**
+ * 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;
+ }
+
+ /**
+ * 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;
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * @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 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 = '';
+ }
+
+ // 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();
+
+ $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);
+
+ 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);
+ }
+ }
+
+ /**
+ * 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;
+ }
+
+ 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');
-
- $currentReleaseDirectory = $releasesDirectory . '/' . $releaseId;
- $currentReleaseDirectoryTemp = $currentReleaseDirectory . '_tmp/';
- $currentRelease = $currentReleaseDirectory . '/' . $releaseId . '.tar.gz';
-
- $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;
- }
-
- 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';
-
- $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;
- }
+ 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';
+
+ $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;
+ }
+
+ 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';
+
+ $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;
+ }
}
diff --git a/Mage/Task/BuiltIn/Deployment/ReleaseTask.php b/Mage/Task/BuiltIn/Deployment/ReleaseTask.php
index 5abcb52..c8f1e37 100644
--- a/Mage/Task/BuiltIn/Deployment/ReleaseTask.php
+++ b/Mage/Task/BuiltIn/Deployment/ReleaseTask.php
@@ -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;
+ }
+ }
}
diff --git a/Mage/Task/BuiltIn/Deployment/Strategy/BaseStrategyTaskAbstract.php b/Mage/Task/BuiltIn/Deployment/Strategy/BaseStrategyTaskAbstract.php
index d939026..a5f354c 100644
--- a/Mage/Task/BuiltIn/Deployment/Strategy/BaseStrategyTaskAbstract.php
+++ b/Mage/Task/BuiltIn/Deployment/Strategy/BaseStrategyTaskAbstract.php
@@ -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);
}
diff --git a/Mage/Task/BuiltIn/Deployment/Strategy/DisabledTask.php b/Mage/Task/BuiltIn/Deployment/Strategy/DisabledTask.php
index 567b867..958faef 100644
--- a/Mage/Task/BuiltIn/Deployment/Strategy/DisabledTask.php
+++ b/Mage/Task/BuiltIn/Deployment/Strategy/DisabledTask.php
@@ -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]';
diff --git a/Mage/Task/BuiltIn/Deployment/Strategy/GitRebaseTask.php b/Mage/Task/BuiltIn/Deployment/Strategy/GitRebaseTask.php
index 61ac5e9..4f82761 100644
--- a/Mage/Task/BuiltIn/Deployment/Strategy/GitRebaseTask.php
+++ b/Mage/Task/BuiltIn/Deployment/Strategy/GitRebaseTask.php
@@ -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;
}
}
diff --git a/Mage/Task/BuiltIn/Deployment/Strategy/RsyncTask.php b/Mage/Task/BuiltIn/Deployment/Strategy/RsyncTask.php
index 94662a5..d9591b6 100644
--- a/Mage/Task/BuiltIn/Deployment/Strategy/RsyncTask.php
+++ b/Mage/Task/BuiltIn/Deployment/Strategy/RsyncTask.php
@@ -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);
diff --git a/Mage/Task/BuiltIn/Deployment/Strategy/TarGzTask.php b/Mage/Task/BuiltIn/Deployment/Strategy/TarGzTask.php
index 76ddc44..f8dc3c9 100644
--- a/Mage/Task/BuiltIn/Deployment/Strategy/TarGzTask.php
+++ b/Mage/Task/BuiltIn/Deployment/Strategy/TarGzTask.php
@@ -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
diff --git a/Mage/Task/BuiltIn/Ioncube/EncryptTask.php b/Mage/Task/BuiltIn/Ioncube/EncryptTask.php
index a4fe358..f147be8 100644
--- a/Mage/Task/BuiltIn/Ioncube/EncryptTask.php
+++ b/Mage/Task/BuiltIn/Ioncube/EncryptTask.php
@@ -43,590 +43,602 @@ use Mage\Task\ErrorWithMessageException;
*/
class EncryptTask extends AbstractTask
{
- /**
- * Name of the task
- *
- * @var string
- */
- private $name = 'IonCube Encoder';
-
- /**
- * Array of default Ioncube
- * options
- *
- * @var array
- */
- private $default = array ();
-
- /**
- * Array of YAML Ioncube
- * options
- *
- * @var array
- */
- private $yaml = array ();
-
- /**
- * Array of file Ioncube
- * options (taken from additional
- * external config file if supplied)
- *
- * @var array
- */
- private $file = array ();
-
- /**
- * Source directory as used by
- * main scripts
- *
- * @var string
- */
- private $source = '';
-
- /**
- * Name of tempory folder
- * for source code to be moved
- * to.
- *
- * @var string
- */
- private $ionSource = '';
-
- /**
- * How the default/yaml/project
- * files interact with each other
- *
- * @var string
- */
- private $ionOverRide = '';
-
- /**
- * Config options from the
- * enviroment config file
- *
- * @var array
- */
- private $mageConfig = array ();
-
- /**
- * Final version of the IonCube
- * options, after merging all
- * sources together
- *
- * @var array
- */
- private $ionCubeConfig = array ();
-
- /**
- * Default encoder version to use
- * for the ioncube encoder
- *
- * @var string
- */
- private $encoder = 'ioncube_encoder54';
-
- /**
- * Name of tempory IonCube Project
- * file, used when running encoder
- *
- * @var string
- */
- private $projectFile = '';
-
- /**
- * If true then run a check on
- * all files after encoding and
- * report which ones are not encoded
- * if any are found to not be encoded
- * then prompt if we should continue
- * with the process
- * If not then clean up the temp files
- * and exit with cancled code.
- *
- * @var bool
- */
- private $checkEncoding = false;
-
- /**
- * List of file extensions to exclude
- * from encrypted/encoded test
- *
- * @var array
- */
- private $checkIgnoreExtens = array();
-
- /**
- * List of paths to exclude from
- * encrypted/encoded test
- * Paths must begin with '/'
- * and are all relative to the
- * project root
- *
- * @var array
- */
- private $checkIgnorePaths = array();
-
- /**
- * (non-PHPdoc)
- *
- * @see \Mage\Task\AbstractTask::getName()
- */
- public function getName() {
- return $this->name;
- }
-
- /**
- * (non-PHPdoc)
- *
- * @see \Mage\Task\AbstractTask::init()
- */
- public function init() {
- // Set the default extensions to ignore
- $this->checkIgnoreExtens = array (
- 'jpg',
- 'jpeg',
- 'png',
- 'js',
- 'gif',
- 'css',
- 'ttf',
- 'svg',
- 'map',
- 'ico',
-
- );
- // Get any options specfic to this task
- $this->mageConfig = $this->getConfig()->environmentConfig( 'ioncube' );
- /*
- * Get all our IonCube config options
- */
- $this->_getAllIonCubeConfigs();
- /*
- * get the source code location
- */
- $this->source = $this->getConfig ()->deployment ( 'from' );
- /*
- * remove trailing slash if present
- */
- if (substr ( $this->source, - 1 ) == DIRECTORY_SEPARATOR) {
- $this->source = substr ( $this->source, 0, - 1 );
- }
- /*
- * Set the name of the folder that the un-encrypted
- * files will be moved into
- */
- $this->ionSource = $this->source . '.raw';
- /*
- * set the filename for the ioncube project build file
- */
- $this->projectFile = $this->source . '.prj';
- /*
- * Check if we have been given an encoder script
- * If not then we will just use the default
- */
- if (isset ( $this->mageConfig ['encoder'] )) {
- $this->encoder = $this->mageConfig ['encoder'];
- }
- /*
- * Check if a differant merge type has been
- * supplied, this defines how the 3 differant
- * config files will be merged together.
- */
- if (isset ( $this->mageConfig ['override'] )) {
- $this->ionOverRide = $this->mageConfig ['override'];
- }
- /*
- * Check if we have been asked to
- * confirm all encodings
- */
- if (isset ( $this->mageConfig ['checkencoding'])) {
- $this->checkEncoding=true;
- }
- /*
- * Check if we have been passed any extra
- * file extensions to exclude from
- * encrypt/encode file check
- *
- */
- if (isset ( $this->mageConfig ['checkignoreextens'])) {
- $this->checkIgnoreExtens=array_merge($this->ignoreExtens, $this->mageConfig['ignoreextens']);
- }
-
- /*
- * Check if we have been passed any extra
- * file paths/files to exclude from
- * encrypt/encode file check
- *
- */
- if (isset ( $this->mageConfig ['checkignorepaths'])) {
- $this->checkIgnorePaths=array_merge($this->checkIgnorePaths, $this->mageConfig['checkignorepaths']);
- }
-
-
- /*
- * now merge all the config options together
- */
- $this->ionCubeConfig = $this->mergeConfigFiles ();
- }
-
- /**
- * This gets all the Ioncube configs
- * Basicly it gets the default options contianed within this script
- * It reads any project options from the enviroment.yaml config file
- * It reads any additional options from external project file if set
- *
- * @return void
- */
- private function _getAllIonCubeConfigs()
- {
-
- /*
- * Get a set of default IonCube options
- */
- $this->default = $this->getOptionsDefault ();
- /*
- * Check if there is a 'project' section,
- * if so then get the options from there
- */
- if (isset ( $this->mageConfig ['project'] )) {
- $this->yaml = $this->getOptionsFromYaml ( $this->mageConfig ['project'] );
- } else {
- $this->yaml = array (
- 's' => array (),
- 'p' => array ()
- );
- }
- /*
- * Check if a seperate projectfile has been specified, and if so
- * then read the options from there.
- */
- if (isset ( $this->mageConfig ['projectfile'] )) {
- $this->file = $this->getOptionsFromFile ( $this->mageConfig ['projectfile'] );
- } else {
- $this->file = array (
- 's' => array (),
- 'p' => array ()
- );
- }
- }
-
- /**
- * Encrypt the project
- * Steps are as follows :
- * Switch our current source dir to the ioncube srouce dir and create new empty dir to encrypt into
- * Write the IonCube project file (this is the file that controls IonCube encoder)
- * Run IonCube encoder
- * Delete the temporary files that we created (so long as we hadn't set 'keeptemp')
- * Return the result of the IonCube encoder
- *
- * @see \Mage\Task\AbstractTask::run()
- *
- * @return bool
+ /**
+ * Name of the task
+ *
+ * @var string
+ */
+ private $name = 'IonCube Encoder';
+
+ /**
+ * Array of default Ioncube
+ * options
+ *
+ * @var array
+ */
+ private $default = array();
+
+ /**
+ * Array of YAML Ioncube
+ * options
+ *
+ * @var array
+ */
+ private $yaml = array();
+
+ /**
+ * Array of file Ioncube
+ * options (taken from additional
+ * external config file if supplied)
+ *
+ * @var array
+ */
+ private $file = array();
+
+ /**
+ * Source directory as used by
+ * main scripts
+ *
+ * @var string
+ */
+ private $source = '';
+
+ /**
+ * Name of tempory folder
+ * for source code to be moved
+ * to.
+ *
+ * @var string
+ */
+ private $ionSource = '';
+
+ /**
+ * How the default/yaml/project
+ * files interact with each other
+ *
+ * @var string
+ */
+ private $ionOverRide = '';
+
+ /**
+ * Config options from the
+ * enviroment config file
+ *
+ * @var array
+ */
+ private $mageConfig = array();
+
+ /**
+ * Final version of the IonCube
+ * options, after merging all
+ * sources together
+ *
+ * @var array
+ */
+ private $ionCubeConfig = array();
+
+ /**
+ * Default encoder version to use
+ * for the ioncube encoder
+ *
+ * @var string
+ */
+ private $encoder = 'ioncube_encoder54';
+
+ /**
+ * Name of tempory IonCube Project
+ * file, used when running encoder
+ *
+ * @var string
+ */
+ private $projectFile = '';
+
+ /**
+ * If true then run a check on
+ * all files after encoding and
+ * report which ones are not encoded
+ * if any are found to not be encoded
+ * then prompt if we should continue
+ * with the process
+ * If not then clean up the temp files
+ * and exit with cancled code.
+ *
+ * @var bool
+ */
+ private $checkEncoding = false;
+
+ /**
+ * List of file extensions to exclude
+ * from encrypted/encoded test
+ *
+ * @var array
+ */
+ private $checkIgnoreExtens = array();
+
+ /**
+ * List of paths to exclude from
+ * encrypted/encoded test
+ * Paths must begin with '/'
+ * and are all relative to the
+ * project root
+ *
+ * @var array
+ */
+ private $checkIgnorePaths = array();
+
+ /**
+ * (non-PHPdoc)
+ *
+ * @see \Mage\Task\AbstractTask::getName()
+ */
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ /**
+ * (non-PHPdoc)
+ *
+ * @see \Mage\Task\AbstractTask::init()
+ */
+ public function init()
+ {
+ // Set the default extensions to ignore
+ $this->checkIgnoreExtens = array(
+ 'jpg',
+ 'jpeg',
+ 'png',
+ 'js',
+ 'gif',
+ 'css',
+ 'ttf',
+ 'svg',
+ 'map',
+ 'ico',
+
+ );
+ // Get any options specfic to this task
+ $this->mageConfig = $this->getConfig()->environmentConfig('ioncube');
+ /*
+ * Get all our IonCube config options
+ */
+ $this->_getAllIonCubeConfigs();
+ /*
+ * get the source code location
+ */
+ $this->source = $this->getConfig()->deployment('from');
+ /*
+ * remove trailing slash if present
+ */
+ if (substr($this->source, -1) == DIRECTORY_SEPARATOR) {
+ $this->source = substr($this->source, 0, -1);
+ }
+ /*
+ * Set the name of the folder that the un-encrypted
+ * files will be moved into
+ */
+ $this->ionSource = $this->source . '.raw';
+ /*
+ * set the filename for the ioncube project build file
+ */
+ $this->projectFile = $this->source . '.prj';
+ /*
+ * Check if we have been given an encoder script
+ * If not then we will just use the default
+ */
+ if (isset ($this->mageConfig ['encoder'])) {
+ $this->encoder = $this->mageConfig ['encoder'];
+ }
+ /*
+ * Check if a differant merge type has been
+ * supplied, this defines how the 3 differant
+ * config files will be merged together.
+ */
+ if (isset ($this->mageConfig ['override'])) {
+ $this->ionOverRide = $this->mageConfig ['override'];
+ }
+ /*
+ * Check if we have been asked to
+ * confirm all encodings
+ */
+ if (isset ($this->mageConfig ['checkencoding'])) {
+ $this->checkEncoding = true;
+ }
+ /*
+ * Check if we have been passed any extra
+ * file extensions to exclude from
+ * encrypt/encode file check
+ *
+ */
+ if (isset ($this->mageConfig ['checkignoreextens'])) {
+ $this->checkIgnoreExtens = array_merge($this->ignoreExtens, $this->mageConfig['ignoreextens']);
+ }
+
+ /*
+ * Check if we have been passed any extra
+ * file paths/files to exclude from
+ * encrypt/encode file check
+ *
+ */
+ if (isset ($this->mageConfig ['checkignorepaths'])) {
+ $this->checkIgnorePaths = array_merge($this->checkIgnorePaths, $this->mageConfig['checkignorepaths']);
+ }
+
+
+ /*
+ * now merge all the config options together
+ */
+ $this->ionCubeConfig = $this->mergeConfigFiles();
+ }
+
+ /**
+ * This gets all the Ioncube configs
+ * Basicly it gets the default options contianed within this script
+ * It reads any project options from the enviroment.yaml config file
+ * It reads any additional options from external project file if set
+ *
+ * @return void
+ */
+ private function _getAllIonCubeConfigs()
+ {
+
+ /*
+ * Get a set of default IonCube options
+ */
+ $this->default = $this->getOptionsDefault();
+ /*
+ * Check if there is a 'project' section,
+ * if so then get the options from there
+ */
+ if (isset ($this->mageConfig ['project'])) {
+ $this->yaml = $this->getOptionsFromYaml($this->mageConfig ['project']);
+ } else {
+ $this->yaml = array(
+ 's' => array(),
+ 'p' => array()
+ );
+ }
+ /*
+ * Check if a seperate projectfile has been specified, and if so
+ * then read the options from there.
+ */
+ if (isset ($this->mageConfig ['projectfile'])) {
+ $this->file = $this->getOptionsFromFile($this->mageConfig ['projectfile']);
+ } else {
+ $this->file = array(
+ 's' => array(),
+ 'p' => array()
+ );
+ }
+ }
+
+ /**
+ * Encrypt the project
+ * Steps are as follows :
+ * Switch our current source dir to the ioncube srouce dir and create new empty dir to encrypt into
+ * Write the IonCube project file (this is the file that controls IonCube encoder)
+ * Run IonCube encoder
+ * Delete the temporary files that we created (so long as we hadn't set 'keeptemp')
+ * Return the result of the IonCube encoder
+ *
+ * @see \Mage\Task\AbstractTask::run()
+ *
+ * @return bool
* @throws \Mage\Task\ErrorWithMessageException
- */
- public function run() {
- $this->switchSrcToTmp ();
- $this->writeProjectFile ();
- $result = $this->runIonCube ();
- Console::output("Encoding result :".($result ? 'OK' : 'Bad!')."\n", 0, 2);
- if (!$result) {
- $this->deleteTmpFiles ();
- throw new ErrorWithMessageException('Ioncube failed to encode your project :'.$result);
- }
- if (($this->checkEncoding) && (!$this->checkEncoding())) {
- $this->deleteTmpFiles();
- throw new ErrorWithMessageException('Operation canceled by user.');
- }
- $this->deleteTmpFiles ();
- return $result;
- }
-
- /**
- * Runs through all files in the encoded
- * folders and lists any that are not
- * encoded. If any are found then prompt
- * user to continue or quit.
- * If user quites, then clean out encoded
- * files, and return true to indicate error
- *
- * @return bool
- */
- private function checkEncoding() {
- $src = $this->source;
- // $ask holds flag to indicate we need to prompt the end user
- $ask = false;
- // scan through the directory
- $rit = new \RecursiveDirectoryIterator ( $src );
- foreach ( new \RecursiveIteratorIterator ( $rit ) as $filename => $cur ) {
- // get the 'base dir' for the project, eg. relative to the temp folder
- $srcFileName = (str_replace ( $this->source, '', $filename ));
- /*
- * Scan through the ignor directorys array
- * and if it matches the current path/filename
- * then mark the file to be skipped from testing
- */
- $skip = false;
- foreach ( $this->checkIgnorePaths as $path ) {
- if (fnmatch ( $path, $srcFileName )) {
- $skip = true;
- }
- }
- // check if we should test this file
- if (! $skip) {
- // get the file exten for this file and compare to our fileexten exclude array
- $exten = pathinfo ( $filename, PATHINFO_EXTENSION );
- if (! in_array ( strtolower ( $exten ), $this->checkIgnoreExtens )) {
- // ok, this extension needs to be checked
- if ($this->checkFileCoding ( $filename )) {
- // file was encrypted/encoded
- } else {
- // file was not encrypted/encoded
- Console::output("File :" . $srcFileName . " -> Was not encrypted", 0, 1);
- $ask = true;
- }
- }
- }
- }
- if ($ask) {
- // ok lets ask the user if they want to procede
- Console::output("\n\nDo you wish to procede (y/N):", 0, 0);
- if (! $this->promptYn ()) {
- return false;
- }
- }
-
- return true;
- }
-
- /**
- * This simply for user to enter
- * 'y' or 'Y' and press enter, if
- * a single 'y' is not entered then
- * false is returned, otherwise
- * true is returned.
- *
- * @return bool True if 'y' pressed
- */
- private function promptYn() {
- $handle = fopen ("php://stdin","r");
- $line = strtolower(fgets($handle));
- if(trim($line) != 'y'){
- return false;
- }
- return true;
- }
-
- /**
- * This will take the passed file and try to
- * work out if it is an encoded/encrypted
- * ioncube file.
- * It dosent test the file exten, as it
- * expects the calling method to have done
- * that before.
- *
- * @param string $filename Filename, with path, to check
- *
- * @return boolean True if file was encoded/encrypted
- */
- private function checkFileCoding($filename) {
- // check to see if this is an encrypted file
- $ioncube = ioncube_read_file($filename, $ioncubeType);
- if (is_int ( $ioncube )) {
- // we got an error from ioncube, so its encrypted
- return true;
- }
- // read first line of file
- $f = fopen ( $filename, 'r' );
- $line = trim ( fgets ( $f, 32 ) );
- fclose ( $f );
- // if first line is longer than 30, then this isnt a php file
- if (strlen ( $line ) > 30) {
- return false;
- }
- // if first line starts 'mageConfig ['keeptemp'] )) {
- return;
- }
- Console::log('Deleting tempory files :', 1);
- $ret1 = Console::executeCommand ( 'rm -Rf ' . $this->ionSource, $out1 );
- $ret2 = Console::executeCommand ( 'rm ' . $this->projectFile, $out2 );
- if ($ret1 && $ret2) {
- return;
- }
- throw new ErrorWithMessageException ( 'Error deleting temp files :' . $out1 . ' : ' . $out2, 40 );
- }
-
- /**
- * Builds the ioncube command
- * and runs it, returning the result
- *
- * @return bool
- */
- private function runIonCube() {
- $cli = $this->encoder . ' --project-file ' . $this->projectFile . ' ' . $this->ionSource . DIRECTORY_SEPARATOR.'*';
- $ret = Console::executeCommand ( $cli, $out );
- return $ret;
- }
-
- /**
- * Write the config options into
- * a project file ready for use
- * with ioncube cli
- *
- * @throws ErrorWithMessageException If it cant write the project file
- *
- * @return void
- */
- private function writeProjectFile() {
- // array used to build config file into
- $out = array ();
- // set the project destination
- $out [] = '--into ' . $this->source . PHP_EOL;
- // output the switches
- foreach ( $this->ionCubeConfig ['s'] as $key => $value ) {
- if ($value) {
- // switch was set to true, so output it
- $out [] = '--' . $key . PHP_EOL;
- }
- }
- // output the options
- foreach ( $this->ionCubeConfig ['p'] as $key => $value ) {
- // check if we have an array of values
- if (is_array ( $value )) {
- foreach ( $value as $entry ) {
- $out [] = '--' . $key . ' "' . $entry . '"' . PHP_EOL;
- }
- } else {
- // ok just a normal single option
- if (strlen ( $value ) > 0) {
- $out [] = '--' . $key . ' "' . $value . '"' . PHP_EOL;
- }
- }
- }
- $ret = file_put_contents ( $this->projectFile, $out );
- if (! $ret) {
- // something went wrong
- $this->deleteTmpFiles ();
- throw new ErrorWithMessageException ( 'Unable to create project file.', 20 );
- }
- }
-
- /**
- * This merges the 3 config arrays
- * depending on the 'override' option
- *
- * @return array Final config array
- */
- private function mergeConfigFiles() {
- /*
- * Options are the order the arrays are in
- * F - Project File
- * Y - YAML config options (enviroment file)
- * D - Default options as stored in script
- *
- * more options could be added to make this a bit more flexable
- * @todo I'm sure this could be combined into a loop to make it easier and shorter
- *
- */
- $s = array ();
- $p = array ();
- switch (strtolower ( $this->ionOverRide )) {
- case 'fyd' :
- // FILE / YAML / DEFAULT
- $s = array_merge ( $this->file ['s'], $this->yaml ['s'], $this->default ['s'] );
- $p = array_merge ( $this->file ['p'], $this->yaml ['p'], $this->default ['p'] );
- break;
-
- case 'yfd' :
- // YAML / FILE / DEFAULT
- $s = array_merge ( $this->yaml ['s'], $this->file ['s'], $this->default ['s'] );
- $p = array_merge ( $this->yaml ['p'], $this->file ['p'], $this->default ['p'] );
- break;
- case 'dyf' :
- // DEFAULT / YAML / FILE
- $s = array_merge ( $this->default ['s'], $this->yaml ['s'], $this->file ['s'] );
- $p = array_merge ( $this->default ['p'], $this->yaml ['p'], $this->file ['p'] );
- break;
- case 'd' :
- default :
- // Use defaults only
- $s = $this->default ['s'];
- $p = $this->default ['p'];
- break;
- }
- return array (
- 's' => $s,
- 'p' => $p
- );
- }
-
- /**
- * Switches the original source
- * code dir to tempory name
- * and recreates orginal dir
- * allows encryption to be done
- * into source dir, so other functions
- * work without changing
- *
- * @throws ErrorWithMessageException If source dir can't be renamed
- * @throws ErrorWithMessageException If original source dir cant be created
- *
- * @return bool
- */
- private function switchSrcToTmp() {
- $ret = Console::executeCommand ( 'mv ' . $this->source . ' ' . $this->ionSource, $out );
- if (! $ret) {
- throw new ErrorWithMessageException ( 'Cant create tmp dir :' . $out, $ret );
- }
- $ret = Console::executeCommand ( 'mkdir -p ' . $this->source, $out );
- if (! $ret) {
- throw new ErrorWithMessageException ( 'Cant re-create dir :' . $out, $ret );
- }
- return true;
- }
-
- /**
- * Reads a set of options taken from the YAML config
- * Compares keys against the default ioncube settings
- * if a key doesnt appear in the default options, it
- * is ignored
- *
- * return array
- */
- private function getOptionsFromYaml($options) {
- $s = array ();
- $p = array ();
- foreach ( $options as $key => $value ) {
- if (array_key_exists ( $key, $this->default ['s'] )) {
- $s [$key] = true;
- }
- if (array_key_exists ( $key, $this->default ['p'] )) {
- $p [$key] = $value;
- }
- }
- return array (
- 's' => $s,
- 'p' => $p
- );
- }
+ */
+ public function run()
+ {
+ $this->switchSrcToTmp();
+ $this->writeProjectFile();
+ $result = $this->runIonCube();
+ Console::output("Encoding result :" . ($result ? 'OK' : 'Bad!') . "\n", 0, 2);
+ if (!$result) {
+ $this->deleteTmpFiles();
+ throw new ErrorWithMessageException('Ioncube failed to encode your project :' . $result);
+ }
+ if (($this->checkEncoding) && (!$this->checkEncoding())) {
+ $this->deleteTmpFiles();
+ throw new ErrorWithMessageException('Operation canceled by user.');
+ }
+ $this->deleteTmpFiles();
+ return $result;
+ }
+
+ /**
+ * Runs through all files in the encoded
+ * folders and lists any that are not
+ * encoded. If any are found then prompt
+ * user to continue or quit.
+ * If user quites, then clean out encoded
+ * files, and return true to indicate error
+ *
+ * @return bool
+ */
+ private function checkEncoding()
+ {
+ $src = $this->source;
+ // $ask holds flag to indicate we need to prompt the end user
+ $ask = false;
+ // scan through the directory
+ $rit = new \RecursiveDirectoryIterator ($src);
+ foreach (new \RecursiveIteratorIterator ($rit) as $filename => $cur) {
+ // get the 'base dir' for the project, eg. relative to the temp folder
+ $srcFileName = (str_replace($this->source, '', $filename));
+ /*
+ * Scan through the ignor directorys array
+ * and if it matches the current path/filename
+ * then mark the file to be skipped from testing
+ */
+ $skip = false;
+ foreach ($this->checkIgnorePaths as $path) {
+ if (fnmatch($path, $srcFileName)) {
+ $skip = true;
+ }
+ }
+ // check if we should test this file
+ if (!$skip) {
+ // get the file exten for this file and compare to our fileexten exclude array
+ $exten = pathinfo($filename, PATHINFO_EXTENSION);
+ if (!in_array(strtolower($exten), $this->checkIgnoreExtens)) {
+ // ok, this extension needs to be checked
+ if ($this->checkFileCoding($filename)) {
+ // file was encrypted/encoded
+ } else {
+ // file was not encrypted/encoded
+ Console::output("File :" . $srcFileName . " -> Was not encrypted", 0, 1);
+ $ask = true;
+ }
+ }
+ }
+ }
+ if ($ask) {
+ // ok lets ask the user if they want to procede
+ Console::output("\n\nDo you wish to procede (y/N):", 0, 0);
+ if (!$this->promptYn()) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * This simply for user to enter
+ * 'y' or 'Y' and press enter, if
+ * a single 'y' is not entered then
+ * false is returned, otherwise
+ * true is returned.
+ *
+ * @return bool True if 'y' pressed
+ */
+ private function promptYn()
+ {
+ $handle = fopen("php://stdin", "r");
+ $line = strtolower(fgets($handle));
+ if (trim($line) != 'y') {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * This will take the passed file and try to
+ * work out if it is an encoded/encrypted
+ * ioncube file.
+ * It dosent test the file exten, as it
+ * expects the calling method to have done
+ * that before.
+ *
+ * @param string $filename Filename, with path, to check
+ *
+ * @return boolean True if file was encoded/encrypted
+ */
+ private function checkFileCoding($filename)
+ {
+ // check to see if this is an encrypted file
+ $ioncube = ioncube_read_file($filename, $ioncubeType);
+ if (is_int($ioncube)) {
+ // we got an error from ioncube, so its encrypted
+ return true;
+ }
+ // read first line of file
+ $f = fopen($filename, 'r');
+ $line = trim(fgets($f, 32));
+ fclose($f);
+ // if first line is longer than 30, then this isnt a php file
+ if (strlen($line) > 30) {
+ return false;
+ }
+ // if first line starts 'mageConfig ['keeptemp'])) {
+ return;
+ }
+ Console::log('Deleting tempory files :', 1);
+ $ret1 = Console::executeCommand('rm -Rf ' . $this->ionSource, $out1);
+ $ret2 = Console::executeCommand('rm ' . $this->projectFile, $out2);
+ if ($ret1 && $ret2) {
+ return;
+ }
+ throw new ErrorWithMessageException ('Error deleting temp files :' . $out1 . ' : ' . $out2, 40);
+ }
+
+ /**
+ * Builds the ioncube command
+ * and runs it, returning the result
+ *
+ * @return bool
+ */
+ private function runIonCube()
+ {
+ $cli = $this->encoder . ' --project-file ' . $this->projectFile . ' ' . $this->ionSource . DIRECTORY_SEPARATOR . '*';
+ $ret = Console::executeCommand($cli, $out);
+ return $ret;
+ }
+
+ /**
+ * Write the config options into
+ * a project file ready for use
+ * with ioncube cli
+ *
+ * @throws ErrorWithMessageException If it cant write the project file
+ *
+ * @return void
+ */
+ private function writeProjectFile()
+ {
+ // array used to build config file into
+ $out = array();
+ // set the project destination
+ $out [] = '--into ' . $this->source . PHP_EOL;
+ // output the switches
+ foreach ($this->ionCubeConfig ['s'] as $key => $value) {
+ if ($value) {
+ // switch was set to true, so output it
+ $out [] = '--' . $key . PHP_EOL;
+ }
+ }
+ // output the options
+ foreach ($this->ionCubeConfig ['p'] as $key => $value) {
+ // check if we have an array of values
+ if (is_array($value)) {
+ foreach ($value as $entry) {
+ $out [] = '--' . $key . ' "' . $entry . '"' . PHP_EOL;
+ }
+ } else {
+ // ok just a normal single option
+ if (strlen($value) > 0) {
+ $out [] = '--' . $key . ' "' . $value . '"' . PHP_EOL;
+ }
+ }
+ }
+ $ret = file_put_contents($this->projectFile, $out);
+ if (!$ret) {
+ // something went wrong
+ $this->deleteTmpFiles();
+ throw new ErrorWithMessageException ('Unable to create project file.', 20);
+ }
+ }
+
+ /**
+ * This merges the 3 config arrays
+ * depending on the 'override' option
+ *
+ * @return array Final config array
+ */
+ private function mergeConfigFiles()
+ {
+ /*
+ * Options are the order the arrays are in
+ * F - Project File
+ * Y - YAML config options (enviroment file)
+ * D - Default options as stored in script
+ *
+ * more options could be added to make this a bit more flexable
+ * @todo I'm sure this could be combined into a loop to make it easier and shorter
+ *
+ */
+ $s = array();
+ $p = array();
+ switch (strtolower($this->ionOverRide)) {
+ case 'fyd' :
+ // FILE / YAML / DEFAULT
+ $s = array_merge($this->file ['s'], $this->yaml ['s'], $this->default ['s']);
+ $p = array_merge($this->file ['p'], $this->yaml ['p'], $this->default ['p']);
+ break;
+
+ case 'yfd' :
+ // YAML / FILE / DEFAULT
+ $s = array_merge($this->yaml ['s'], $this->file ['s'], $this->default ['s']);
+ $p = array_merge($this->yaml ['p'], $this->file ['p'], $this->default ['p']);
+ break;
+ case 'dyf' :
+ // DEFAULT / YAML / FILE
+ $s = array_merge($this->default ['s'], $this->yaml ['s'], $this->file ['s']);
+ $p = array_merge($this->default ['p'], $this->yaml ['p'], $this->file ['p']);
+ break;
+ case 'd' :
+ default :
+ // Use defaults only
+ $s = $this->default ['s'];
+ $p = $this->default ['p'];
+ break;
+ }
+ return array(
+ 's' => $s,
+ 'p' => $p
+ );
+ }
+
+ /**
+ * Switches the original source
+ * code dir to tempory name
+ * and recreates orginal dir
+ * allows encryption to be done
+ * into source dir, so other functions
+ * work without changing
+ *
+ * @throws ErrorWithMessageException If source dir can't be renamed
+ * @throws ErrorWithMessageException If original source dir cant be created
+ *
+ * @return bool
+ */
+ private function switchSrcToTmp()
+ {
+ $ret = Console::executeCommand('mv ' . $this->source . ' ' . $this->ionSource, $out);
+ if (!$ret) {
+ throw new ErrorWithMessageException ('Cant create tmp dir :' . $out, $ret);
+ }
+ $ret = Console::executeCommand('mkdir -p ' . $this->source, $out);
+ if (!$ret) {
+ throw new ErrorWithMessageException ('Cant re-create dir :' . $out, $ret);
+ }
+ return true;
+ }
+
+ /**
+ * Reads a set of options taken from the YAML config
+ * Compares keys against the default ioncube settings
+ * if a key doesnt appear in the default options, it
+ * is ignored
+ *
+ * return array
+ */
+ private function getOptionsFromYaml($options)
+ {
+ $s = array();
+ $p = array();
+ foreach ($options as $key => $value) {
+ if (array_key_exists($key, $this->default ['s'])) {
+ $s [$key] = true;
+ }
+ if (array_key_exists($key, $this->default ['p'])) {
+ $p [$key] = $value;
+ }
+ }
+ return array(
+ 's' => $s,
+ 'p' => $p
+ );
+ }
/**
* reads an existing ioncube project
@@ -635,163 +647,166 @@ class EncryptTask extends AbstractTask
* @param $fileName
* @return array
*/
- private function getOptionsFromFile($fileName) {
- $s = array ();
- $p = array ();
- $fileContents = file_get_contents ( $fileName );
- /*
- * split the config file on every occurance of '--' at start of a line
- * Adds a PHP_EOL at the start, so we can catch the first '--'
- */
- $entrys = explode ( PHP_EOL . '--', PHP_EOL . $fileContents );
- foreach ( $entrys as $line ) {
- $line = trim ( $line );
- if ($line != '') {
- /*
- * get position of first space
- * so we can split the options out
- */
- $str = strpos ( $line, ' ' );
- if ($str === false) {
- /*
- * Ok, no spaces found, so take this as a single line
- */
- $str = strlen ( $line );
- }
- $key = substr ( $line, $str );
- $value = substr ( $line, $str + 1 );
- if ((array_key_exists ( $key, $this->default ['s'] ))) {
- /*
- * ok this key appears in the switch config
- * so store it as a switch
- */
- $s [$key] = true;
- }
- if ((array_key_exists ( $key, $this->default ['p'] ))) {
- /*
- * Ok this key exists in the parameter section,
- * So store it allong with its value
- */
- $p [$key] = $this->splitParam ( $value );
- }
- }
- }
- return array (
- 's' => $s,
- 'p' => $p
- );
- }
-
- /**
- * Takes supplied line and splits it if required
- * into an array
- * returns ether the array, or a plain
- * string.
- * Allows options to be spread accross several lines
- *
- * @param $string String to split
- *
- * @return mixed
- */
- private function splitParam($string) {
- $split = explode ( PHP_EOL, $string );
- if ($split === false) {
- // nothing found, so return a blank string
- return '';
- }
- if (count ( $split ) == 1) {
- return $split [0];
- } else {
- return $split;
- }
- }
-
- /**
- * returns an array of default ioncube options
- * This is also used as a 'filter' for the YAML
- * and Config files, if an option hasnt got an
- * entry in this list, then it can not be set
- * via the VAML or Config files
- *
- * @return array
- */
- private function getOptionsDefault() {
- $s = array ();
- $p = array ();
- // Set the switches
- $s ['allow-encoding-into-source'] = false;
-
- $s ['ascii'] = false;
- $s ['binary'] = true;
-
- $s ['replace-target'] = true;
- $s ['merge-target'] = false;
- $s ['rename-target'] = false;
- $s ['update-target'] = false;
-
- $s ['only-include-encoded-files'] = false;
-
- $s ['use-hard-links'] = false;
-
- $s ['without-keeping-file-perms'] = false;
- $s ['without-keeping-file-times'] = false;
- $s ['without-keeping-file-owner'] = false;
-
- $s ['no-short-open-tags'] = false;
-
- $s ['ignore-strict-warnings'] = false;
- $s ['ignore-deprecated-warnings'] = false;
-
- $s ['without-runtime-loader-support'] = false;
- $s ['without-loader-check'] = false;
-
- $s ['disable-auto-prepend-append'] = true;
-
- $s ['no-doc-comments'] = true;
-
- // Now set the params
- $p ['encrypt'] [] = '*.tpl.html';
- $p ['encode'] = array ();
- $p ['copy'] = array ();
- $p ['ignore'] = array (
- '.git',
- '.svn',
- getcwd() . '/.mage',
- '.gitignore',
- '.gitkeep',
- 'nohup.out'
- );
- $p ['keep'] = array ();
- $p ['obfuscate'] = '';
- $p ['obfuscation-key'] = '';
- $p ['obfuscation-exclusion-file'] = '';
- $p ['expire-in'] = '7d';
- $p ['expire-on'] = '';
- $p ['allowed-server'] = '';
- $p ['with-license'] = 'license.txt';
- $p ['passphrase'] = '';
- $p ['license-check'] = '';
- $p ['apply-file-user'] = '';
- $p ['apply-file-group'] = '';
- $p ['register-autoglobal'] = array ();
- $p ['message-if-no-loader'] = '';
- $p ['action-if-no-loader'] = '';
- $p ['loader-path'] = '';
- $p ['preamble-file'] = '';
- $p ['add-comment'] = array ();
- $p ['add-comments'] = '';
- $p ['loader-event'] = array ();
- $p ['callback-file'] = '';
- $p ['property'] = '';
- $p ['propertys'] = '';
- $p ['include-if-property'] = array ();
- $p ['optimise'] = 'max';
- $p ['shell-script-line'] = '';
- $p ['min-loader-version'] = '';
-
- return array (
- 's' => $s,
- 'p' => $p
- );
- }
+ private function getOptionsFromFile($fileName)
+ {
+ $s = array();
+ $p = array();
+ $fileContents = file_get_contents($fileName);
+ /*
+ * split the config file on every occurance of '--' at start of a line
+ * Adds a PHP_EOL at the start, so we can catch the first '--'
+ */
+ $entrys = explode(PHP_EOL . '--', PHP_EOL . $fileContents);
+ foreach ($entrys as $line) {
+ $line = trim($line);
+ if ($line != '') {
+ /*
+ * get position of first space
+ * so we can split the options out
+ */
+ $str = strpos($line, ' ');
+ if ($str === false) {
+ /*
+ * Ok, no spaces found, so take this as a single line
+ */
+ $str = strlen($line);
+ }
+ $key = substr($line, $str);
+ $value = substr($line, $str + 1);
+ if ((array_key_exists($key, $this->default ['s']))) {
+ /*
+ * ok this key appears in the switch config
+ * so store it as a switch
+ */
+ $s [$key] = true;
+ }
+ if ((array_key_exists($key, $this->default ['p']))) {
+ /*
+ * Ok this key exists in the parameter section,
+ * So store it allong with its value
+ */
+ $p [$key] = $this->splitParam($value);
+ }
+ }
+ }
+ return array(
+ 's' => $s,
+ 'p' => $p
+ );
+ }
+
+ /**
+ * Takes supplied line and splits it if required
+ * into an array
+ * returns ether the array, or a plain
+ * string.
+ * Allows options to be spread accross several lines
+ *
+ * @param $string String to split
+ *
+ * @return mixed
+ */
+ private function splitParam($string)
+ {
+ $split = explode(PHP_EOL, $string);
+ if ($split === false) {
+ // nothing found, so return a blank string
+ return '';
+ }
+ if (count($split) == 1) {
+ return $split [0];
+ } else {
+ return $split;
+ }
+ }
+
+ /**
+ * returns an array of default ioncube options
+ * This is also used as a 'filter' for the YAML
+ * and Config files, if an option hasnt got an
+ * entry in this list, then it can not be set
+ * via the VAML or Config files
+ *
+ * @return array
+ */
+ private function getOptionsDefault()
+ {
+ $s = array();
+ $p = array();
+ // Set the switches
+ $s ['allow-encoding-into-source'] = false;
+
+ $s ['ascii'] = false;
+ $s ['binary'] = true;
+
+ $s ['replace-target'] = true;
+ $s ['merge-target'] = false;
+ $s ['rename-target'] = false;
+ $s ['update-target'] = false;
+
+ $s ['only-include-encoded-files'] = false;
+
+ $s ['use-hard-links'] = false;
+
+ $s ['without-keeping-file-perms'] = false;
+ $s ['without-keeping-file-times'] = false;
+ $s ['without-keeping-file-owner'] = false;
+
+ $s ['no-short-open-tags'] = false;
+
+ $s ['ignore-strict-warnings'] = false;
+ $s ['ignore-deprecated-warnings'] = false;
+
+ $s ['without-runtime-loader-support'] = false;
+ $s ['without-loader-check'] = false;
+
+ $s ['disable-auto-prepend-append'] = true;
+
+ $s ['no-doc-comments'] = true;
+
+ // Now set the params
+ $p ['encrypt'] [] = '*.tpl.html';
+ $p ['encode'] = array();
+ $p ['copy'] = array();
+ $p ['ignore'] = array(
+ '.git',
+ '.svn',
+ getcwd() . '/.mage',
+ '.gitignore',
+ '.gitkeep',
+ 'nohup.out'
+ );
+ $p ['keep'] = array();
+ $p ['obfuscate'] = '';
+ $p ['obfuscation-key'] = '';
+ $p ['obfuscation-exclusion-file'] = '';
+ $p ['expire-in'] = '7d';
+ $p ['expire-on'] = '';
+ $p ['allowed-server'] = '';
+ $p ['with-license'] = 'license.txt';
+ $p ['passphrase'] = '';
+ $p ['license-check'] = '';
+ $p ['apply-file-user'] = '';
+ $p ['apply-file-group'] = '';
+ $p ['register-autoglobal'] = array();
+ $p ['message-if-no-loader'] = '';
+ $p ['action-if-no-loader'] = '';
+ $p ['loader-path'] = '';
+ $p ['preamble-file'] = '';
+ $p ['add-comment'] = array();
+ $p ['add-comments'] = '';
+ $p ['loader-event'] = array();
+ $p ['callback-file'] = '';
+ $p ['property'] = '';
+ $p ['propertys'] = '';
+ $p ['include-if-property'] = array();
+ $p ['optimise'] = 'max';
+ $p ['shell-script-line'] = '';
+ $p ['min-loader-version'] = '';
+
+ return array(
+ 's' => $s,
+ 'p' => $p
+ );
+ }
}
diff --git a/Mage/Task/BuiltIn/Magento/ClearCacheTask.php b/Mage/Task/BuiltIn/Magento/ClearCacheTask.php
index 406a7aa..8a8cf55 100644
--- a/Mage/Task/BuiltIn/Magento/ClearCacheTask.php
+++ b/Mage/Task/BuiltIn/Magento/ClearCacheTask.php
@@ -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]';
diff --git a/Mage/Task/BuiltIn/Magento/ClearFullPageCacheTask.php b/Mage/Task/BuiltIn/Magento/ClearFullPageCacheTask.php
index be45a3f..8dd0b49 100644
--- a/Mage/Task/BuiltIn/Magento/ClearFullPageCacheTask.php
+++ b/Mage/Task/BuiltIn/Magento/ClearFullPageCacheTask.php
@@ -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]';
diff --git a/Mage/Task/BuiltIn/Releases/ListTask.php b/Mage/Task/BuiltIn/Releases/ListTask.php
index c70fdbf..ef88004 100644
--- a/Mage/Task/BuiltIn/Releases/ListTask.php
+++ b/Mage/Task/BuiltIn/Releases/ListTask.php
@@ -54,22 +54,22 @@ class ListTask extends AbstractTask implements IsReleaseAware
Console::output('No releases available ... ', 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: ' . $release . ' '
- . '- Date: ' . $releaseDate . ' '
- . '- Index: ' . $releaseIndex . '' . $dateDiff . $isCurrent, 2);
+ . '- Date: ' . $releaseDate . ' '
+ . '- Index: ' . $releaseIndex . '' . $dateDiff . $isCurrent, 2);
}
}
diff --git a/Mage/Task/BuiltIn/Releases/RollbackTask.php b/Mage/Task/BuiltIn/Releases/RollbackTask.php
index cfc0a54..fe2f8e5 100644
--- a/Mage/Task/BuiltIn/Releases/RollbackTask.php
+++ b/Mage/Task/BuiltIn/Releases/RollbackTask.php
@@ -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;
-
- /**
- * (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;
- }
-
- /**
- * 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');
-
- $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 ' . $this->getConfig()->getHost() . ' ... FAIL');
-
- } else {
- rsort($releases);
-
- $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;
- }
- }
-
- if (!$releaseIsAvailable) {
- Console::output('Release ' . $this->getRelease() . ' is invalid or unavailable for ' . $this->getConfig()->getHost() . ' ... FAIL');
-
- } else {
- Console::output('Rollback release on ' . $this->getConfig()->getHost() . '');
- $rollbackTo = $releasesDirectory . '/' . $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 ' . $task->getName() . ' ... ', 2, false);
-
- if ($task instanceOf RollbackAware) {
- $tasks++;
- $result = $task->run();
-
- if ($result == true) {
- Console::output('OK', 0);
- $completedTasks++;
- } else {
- Console::output('FAIL', 0);
- }
- } else {
- Console::output('SKIPPED', 0);
- }
- }
-
- 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 Rollback Release [id=' . $releaseId . '] ... ', 2, false);
-
- $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;
- }
-
- $result = $this->runCommandRemote($command);
-
- if ($result) {
- Console::output('OK', 0);
- $completedTasks++;
- } else {
- Console::output('FAIL', 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 ' . $task->getName() . ' ... ', 2, false);
-
- if ($task instanceOf RollbackAware) {
- $tasks++;
- $result = $task->run();
-
- if ($result == true) {
- Console::output('OK', 0);
- $completedTasks++;
- } else {
- Console::output('FAIL', 0);
- }
- } else {
- Console::output('SKIPPED', 0);
- }
- }
-
- if ($completedTasks == $tasks) {
- $tasksColor = 'green';
- } else {
- $tasksColor = 'red';
- }
-
- Console::output('Release rollback on ' . $this->getConfig()->getHost() . ' compted: <' . $tasksColor . '>' . $completedTasks . '/' . $tasks . '' . $tasksColor . '> tasks done.', 1, 3);
- }
- }
-
- return $result;
-
- } else {
- return false;
- }
- }
+ /**
+ * 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]';
+ }
+
+ /**
+ * 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;
+ }
+
+ /**
+ * 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);
+
+ if (count($releases) == 0) {
+ Console::output('Release are not available for ' . $this->getConfig()->getHost() . ' ... FAIL');
+
+ } else {
+ rsort($releases);
+
+ $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;
+ }
+ }
+
+ if (!$releaseIsAvailable) {
+ Console::output('Release ' . $this->getRelease() . ' is invalid or unavailable for ' . $this->getConfig()->getHost() . ' ... FAIL');
+
+ } else {
+ Console::output('Rollback release on ' . $this->getConfig()->getHost() . '');
+ $rollbackTo = $releasesDirectory . '/' . $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 ' . $task->getName() . ' ... ', 2, false);
+
+ if ($task instanceOf RollbackAware) {
+ $tasks++;
+ $result = $task->run();
+
+ if ($result == true) {
+ Console::output('OK', 0);
+ $completedTasks++;
+ } else {
+ Console::output('FAIL', 0);
+ }
+ } else {
+ Console::output('SKIPPED', 0);
+ }
+ }
+
+ 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 Rollback Release [id=' . $releaseId . '] ... ', 2, false);
+
+ $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;
+ }
+
+ $result = $this->runCommandRemote($command);
+
+ if ($result) {
+ Console::output('OK', 0);
+ $completedTasks++;
+ } else {
+ Console::output('FAIL', 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 ' . $task->getName() . ' ... ', 2, false);
+
+ if ($task instanceOf RollbackAware) {
+ $tasks++;
+ $result = $task->run();
+
+ if ($result == true) {
+ Console::output('OK', 0);
+ $completedTasks++;
+ } else {
+ Console::output('FAIL', 0);
+ }
+ } else {
+ Console::output('SKIPPED', 0);
+ }
+ }
+
+ if ($completedTasks == $tasks) {
+ $tasksColor = 'green';
+ } else {
+ $tasksColor = 'red';
+ }
+
+ Console::output('Release rollback on ' . $this->getConfig()->getHost() . ' compted: <' . $tasksColor . '>' . $completedTasks . '/' . $tasks . '' . $tasksColor . '> tasks done.', 1, 3);
+ }
+ }
+
+ return $result;
+
+ } else {
+ return false;
+ }
+ }
}
\ No newline at end of file
diff --git a/Mage/Task/BuiltIn/Scm/ChangeBranchTask.php b/Mage/Task/BuiltIn/Scm/ChangeBranchTask.php
index 9d5ea7e..dfb6127 100644
--- a/Mage/Task/BuiltIn/Scm/ChangeBranchTask.php
+++ b/Mage/Task/BuiltIn/Scm/ChangeBranchTask.php
@@ -21,16 +21,16 @@ use Mage\Task\ErrorWithMessageException;
*/
class ChangeBranchTask extends AbstractTask
{
- /**
- * Branch the executiong began with
- * @var string
- */
- protected static $startingBranch = 'master';
-
- /**
- * Name of the Task
- * @var string
- */
+ /**
+ * Branch the executiong began with
+ * @var string
+ */
+ protected static $startingBranch = 'master';
+
+ /**
+ * 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);
-
- } else {
- $command = 'git branch | grep \'*\' | cut -d\' \' -f 2';
- $currentBranch = 'master';
- $result = $this->runCommandLocal($command, $currentBranch);
-
- $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 ($isBranchTracked == '') {
- throw new ErrorWithMessageException('The branch ' . $scmData['branch'] . ' must be tracked.');
- }
-
- $branch = $this->getParameter('branch', $scmData['branch']);
- $command = 'git checkout ' . $branch;
- $result = $this->runCommandLocal($command) && $result;
-
- self::$startingBranch = $currentBranch;
- } else {
- throw new SkipException;
- }
- }
+ 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);
+
+ $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 ($isBranchTracked == '') {
+ throw new ErrorWithMessageException('The branch ' . $scmData['branch'] . ' must be tracked.');
+ }
+
+ $branch = $this->getParameter('branch', $scmData['branch']);
+ $command = 'git checkout ' . $branch;
+ $result = $this->runCommandLocal($command) && $result;
+
+ self::$startingBranch = $currentBranch;
+ } else {
+ throw new SkipException;
+ }
+ }
break;
default:
diff --git a/Mage/Task/BuiltIn/Scm/CloneTask.php b/Mage/Task/BuiltIn/Scm/CloneTask.php
index 29acc3a..786b75a 100644
--- a/Mage/Task/BuiltIn/Scm/CloneTask.php
+++ b/Mage/Task/BuiltIn/Scm/CloneTask.php
@@ -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']);
diff --git a/Mage/Task/BuiltIn/Scm/RemoveCloneTask.php b/Mage/Task/BuiltIn/Scm/RemoveCloneTask.php
index a3b8291..5084622 100644
--- a/Mage/Task/BuiltIn/Scm/RemoveCloneTask.php
+++ b/Mage/Task/BuiltIn/Scm/RemoveCloneTask.php
@@ -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;
}
}
diff --git a/Mage/Task/BuiltIn/Scm/UpdateTask.php b/Mage/Task/BuiltIn/Scm/UpdateTask.php
index 877937d..e883a2c 100644
--- a/Mage/Task/BuiltIn/Scm/UpdateTask.php
+++ b/Mage/Task/BuiltIn/Scm/UpdateTask.php
@@ -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]';
/**
diff --git a/Mage/Task/BuiltIn/Symfony2/AsseticDumpTask.php b/Mage/Task/BuiltIn/Symfony2/AsseticDumpTask.php
index 8c1faad..0a303e7 100644
--- a/Mage/Task/BuiltIn/Symfony2/AsseticDumpTask.php
+++ b/Mage/Task/BuiltIn/Symfony2/AsseticDumpTask.php
@@ -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);
diff --git a/Mage/Task/BuiltIn/Symfony2/AssetsInstallTask.php b/Mage/Task/BuiltIn/Symfony2/AssetsInstallTask.php
index c993956..3834f4c 100644
--- a/Mage/Task/BuiltIn/Symfony2/AssetsInstallTask.php
+++ b/Mage/Task/BuiltIn/Symfony2/AssetsInstallTask.php
@@ -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;
diff --git a/Mage/Task/BuiltIn/Symfony2/CacheClearTask.php b/Mage/Task/BuiltIn/Symfony2/CacheClearTask.php
index 0d11adb..9b1c2ec 100644
--- a/Mage/Task/BuiltIn/Symfony2/CacheClearTask.php
+++ b/Mage/Task/BuiltIn/Symfony2/CacheClearTask.php
@@ -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);
diff --git a/Mage/Task/BuiltIn/Symfony2/CacheWarmupTask.php b/Mage/Task/BuiltIn/Symfony2/CacheWarmupTask.php
index ac77d58..912b183 100644
--- a/Mage/Task/BuiltIn/Symfony2/CacheWarmupTask.php
+++ b/Mage/Task/BuiltIn/Symfony2/CacheWarmupTask.php
@@ -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);
diff --git a/Mage/Task/Factory.php b/Mage/Task/Factory.php
index ecbc2b2..2fe7d87 100644
--- a/Mage/Task/Factory.php
+++ b/Mage/Task/Factory.php
@@ -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;
diff --git a/Mage/Yaml/Dumper.php b/Mage/Yaml/Dumper.php
index fff6913..5090513 100644
--- a/Mage/Yaml/Dumper.php
+++ b/Mage/Yaml/Dumper.php
@@ -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" : '');
}
}
diff --git a/Mage/Yaml/Escaper.php b/Mage/Yaml/Escaper.php
index b1a87f1..021b7ea 100644
--- a/Mage/Yaml/Escaper.php
+++ b/Mage/Yaml/Escaper.php
@@ -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);
}
/**
diff --git a/Mage/Yaml/Exception/ParseException.php b/Mage/Yaml/Exception/ParseException.php
index d8ea2b3..3c4465b 100644
--- a/Mage/Yaml/Exception/ParseException.php
+++ b/Mage/Yaml/Exception/ParseException.php
@@ -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)
{
diff --git a/Mage/Yaml/Inline.php b/Mage/Yaml/Inline.php
index 5e49cc7..2586dde 100644
--- a/Mage/Yaml/Inline.php
+++ b/Mage/Yaml/Inline.php
@@ -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;
}
}
diff --git a/Mage/Yaml/Parser.php b/Mage/Yaml/Parser.php
index c5e1fb8..ce74210 100644
--- a/Mage/Yaml/Parser.php
+++ b/Mage/Yaml/Parser.php
@@ -23,16 +23,16 @@ class Parser
{
const FOLDED_SCALAR_PATTERN = '(?P\||>)(?P\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P +#.*)?';
- 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'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\{\[].*?) *\:(\s+(?P.+?))?\s*$#u', $values['value'], $matches)
+ && preg_match('#^(?P' . Inline::REGEX_QUOTED_STRING . '|[^ \'"\{\[].*?) *\:(\s+(?P.+?))?\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'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\[\{].*?) *\:(\s+(?P.+?))?\s*$#u', $this->currentLine, $values) && false === strpos($values['key'],' #')) {
+ } elseif (preg_match('#^(?P' . Inline::REGEX_QUOTED_STRING . '|[^ \'"\[\{].*?) *\:(\s+(?P.+?))?\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
*/
diff --git a/Mage/Yaml/Unescaper.php b/Mage/Yaml/Unescaper.php
index 7c9091b..fc3bbcf 100644
--- a/Mage/Yaml/Unescaper.php
+++ b/Mage/Yaml/Unescaper.php
@@ -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);
}
}
\ No newline at end of file
diff --git a/Mage/Yaml/Yaml.php b/Mage/Yaml/Yaml.php
index 25944a4..a476c60 100644
--- a/Mage/Yaml/Yaml.php
+++ b/Mage/Yaml/Yaml.php
@@ -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
*