Browse Source

PHPStorm refactoring.

1.0
Andrés Montañez 11 years ago
parent
commit
fddeebe59a
  1. 5
      Mage/Autoload.php
  2. 2
      Mage/Command/BuiltIn/CompileCommand.php
  3. 3
      Mage/Command/BuiltIn/InstallCommand.php
  4. 2
      Mage/Command/BuiltIn/VersionCommand.php
  5. 2
      Mage/Command/Factory.php
  6. 4
      Mage/Compiler.php
  7. 26
      Mage/Config.php
  8. 6
      Mage/Console.php
  9. 6
      Mage/Mailer.php
  10. 6
      Mage/Task/AbstractTask.php
  11. 8
      Mage/Task/BuiltIn/Deployment/ReleaseTask.php
  12. 2
      Mage/Task/BuiltIn/Deployment/Strategy/BaseStrategyTaskAbstract.php
  13. 4
      Mage/Task/BuiltIn/Deployment/Strategy/GitRebaseTask.php
  14. 6
      Mage/Task/BuiltIn/Deployment/Strategy/RsyncTask.php
  15. 2
      Mage/Task/BuiltIn/Deployment/Strategy/TarGzTask.php
  16. 285
      Mage/Task/BuiltIn/Ioncube/EncryptTask.php
  17. 2
      Mage/Task/BuiltIn/Releases/ListTask.php
  18. 2
      Mage/Task/Factory.php
  19. 8
      Mage/Yaml/Dumper.php
  20. 2
      Mage/Yaml/Escaper.php
  21. 28
      Mage/Yaml/Inline.php
  22. 12
      Mage/Yaml/Parser.php
  23. 8
      Mage/Yaml/Unescaper.php

5
Mage/Autoload.php

@ -30,8 +30,7 @@ class Autoload
//Try to load a normal Mage class (or Task). Think that Mage component is compiled to .phar //Try to load a normal Mage class (or Task). Think that Mage component is compiled to .phar
$baseDir = dirname(dirname(__FILE__)); $baseDir = dirname(dirname(__FILE__));
$classFileWithinPhar = $baseDir . $postfix; $classFileWithinPhar = $baseDir . $postfix;
if($this->isReadable($classFileWithinPhar)) if ($this->isReadable($classFileWithinPhar)) {
{
/** @noinspection PhpIncludeInspection */ /** @noinspection PhpIncludeInspection */
require_once $classFileWithinPhar; require_once $classFileWithinPhar;
return true; return true;
@ -39,7 +38,7 @@ class Autoload
//Try to load a custom Task or Class. Notice that the path is absolute to CWD //Try to load a custom Task or Class. Notice that the path is absolute to CWD
$classFileOutsidePhar = getcwd() . '/.mage/tasks' . $postfix; $classFileOutsidePhar = getcwd() . '/.mage/tasks' . $postfix;
if($this->isReadable($classFileOutsidePhar)){ if ($this->isReadable($classFileOutsidePhar)) {
/** @noinspection PhpIncludeInspection */ /** @noinspection PhpIncludeInspection */
require_once $classFileOutsidePhar; require_once $classFileOutsidePhar;
return true; return true;

2
Mage/Command/BuiltIn/CompileCommand.php

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

3
Mage/Command/BuiltIn/InstallCommand.php

@ -55,7 +55,8 @@ class InstallCommand extends AbstractCommand
// Check if there is already a symlink // Check if there is already a symlink
if (file_exists($destinationDir . '/' . 'latest') if (file_exists($destinationDir . '/' . 'latest')
&& is_link($destinationDir . '/' . 'latest')) { && is_link($destinationDir . '/' . 'latest')
) {
unlink($destinationDir . '/' . 'latest'); unlink($destinationDir . '/' . 'latest');
} }

2
Mage/Command/BuiltIn/VersionCommand.php

@ -26,7 +26,7 @@ class VersionCommand extends AbstractCommand
*/ */
public function run() public function run()
{ {
Console::output('Running <blue>Magallanes</blue> version <dark_gray>' . MAGALLANES_VERSION .'</dark_gray>', 0, 2); Console::output('Running <blue>Magallanes</blue> version <dark_gray>' . MAGALLANES_VERSION . '</dark_gray>', 0, 2);
} }
} }

2
Mage/Command/Factory.php

@ -40,7 +40,7 @@ class Factory
$className = 'Mage\\Command\\BuiltIn\\' . $commandName . 'Command'; $className = 'Mage\\Command\\BuiltIn\\' . $commandName . 'Command';
/** @var AbstractCommand $instance */ /** @var AbstractCommand $instance */
$instance = new $className; $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.'); throw new Exception('The command ' . $commandName . ' must be an instance of Mage\Command\AbstractCommand.');
} }

4
Mage/Compiler.php

@ -42,11 +42,11 @@ class Compiler
/** @var \SplFileInfo $path */ /** @var \SplFileInfo $path */
foreach ($iterator as $path) { foreach ($iterator as $path) {
if ($path->isFile()) { 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]); unset($binary[0]);
$binary = implode(PHP_EOL, $binary); $binary = implode(PHP_EOL, $binary);

26
Mage/Config.php

@ -116,7 +116,8 @@ class Config
* @return array * @return array
* @throws Config\ConfigNotFoundException * @throws Config\ConfigNotFoundException
*/ */
protected function loadGeneral($filePath){ protected function loadGeneral($filePath)
{
return $this->parseConfigFile($filePath); return $this->parseConfigFile($filePath);
} }
@ -142,6 +143,7 @@ class Config
return $settings; return $settings;
} }
/** /**
* Loads the Environment configuration * Loads the Environment configuration
* @param $filePath string * @param $filePath string
@ -171,14 +173,13 @@ class Config
{ {
$environment = $this->getEnvironment(); $environment = $this->getEnvironment();
if(!empty($environment)) if (!empty($environment)) {
{
$configFilePath = getcwd() . '/.mage/config/environment/' . $environment . '.yml'; $configFilePath = getcwd() . '/.mage/config/environment/' . $environment . '.yml';
try { try {
$this->environmentConfig = $this->loadEnvironment($configFilePath); $this->environmentConfig = $this->loadEnvironment($configFilePath);
} catch (ConfigNotFoundException $e) { } 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) protected function isRunInSpecialMode(array $parameters)
{ {
if(empty($parameters)) if (empty($parameters))
return true; return true;
foreach($parameters as $parameter) foreach ($parameters as $parameter) {
{ if (isset(Console::$paramsNotRequiringEnvironment[$parameter])) {
if(isset(Console::$paramsNotRequiringEnvironment[$parameter]))
{
return true; return true;
} }
} }
return false; return false;
} }
/** /**
* Load the Configuration and parses the Arguments * Load the Configuration and parses the Arguments
* *
@ -324,7 +324,7 @@ class Config
} }
if (isset($config[$configStage])) { if (isset($config[$configStage])) {
$tasksData = ($config[$configStage] ? (array) $config[$configStage] : array()); $tasksData = ($config[$configStage] ? (array)$config[$configStage] : array());
foreach ($tasksData as $taskData) { foreach ($tasksData as $taskData) {
if (is_array($taskData)) { if (is_array($taskData)) {
$tasks[] = array( $tasks[] = array(
@ -352,7 +352,7 @@ class Config
$envConfig = $this->getEnvironmentConfig(); $envConfig = $this->getEnvironmentConfig();
if (isset($envConfig['hosts'])) { if (isset($envConfig['hosts'])) {
if (is_array($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'])) { } else if (is_string($envConfig['hosts']) && file_exists($envConfig['hosts']) && is_readable($envConfig['hosts'])) {
$hosts = $this->getHostsFromFile($envConfig['hosts']); $hosts = $this->getHostsFromFile($envConfig['hosts']);
} }
@ -575,13 +575,13 @@ class Config
*/ */
public function parseConfigFile($filePath) public function parseConfigFile($filePath)
{ {
if(!file_exists($filePath)) if (!file_exists($filePath)) {
{
throw new ConfigNotFoundException("Cannot find the file at path $filePath"); throw new ConfigNotFoundException("Cannot find the file at path $filePath");
} }
return $this->parseConfigText(file_get_contents($filePath)); return $this->parseConfigText(file_get_contents($filePath));
} }
public function parseConfigText($input) public function parseConfigText($input)
{ {
return Yaml::parse($input); return Yaml::parse($input);

6
Mage/Console.php

@ -28,7 +28,7 @@ class Console
* TODO refactor into own static class * TODO refactor into own static class
* @var array * @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. * Handler to the current Log File.
@ -75,7 +75,7 @@ class Console
$exitCode = 10; $exitCode = 10;
// Declare a Shutdown Closure // Declare a Shutdown Closure
register_shutdown_function(function() { register_shutdown_function(function () {
// Only Unlock if there was an error // Only Unlock if there was an error
if (error_get_last() !== null) { if (error_get_last() !== null) {
if (file_exists(getcwd() . '/.mage/~working.lock')) { if (file_exists(getcwd() . '/.mage/~working.lock')) {
@ -247,7 +247,7 @@ class Console
*/ */
public static function readInput() public static function readInput()
{ {
$fp = fopen("php://stdin","r"); $fp = fopen("php://stdin", "r");
$line = ''; $line = '';
$line = fgets($fp); $line = fgets($fp);

6
Mage/Mailer.php

@ -66,8 +66,7 @@ class Mailer
array('{project}', '{environment}', '{result}'), array('{project}', '{environment}', '{result}'),
array($this->project, $this->environment, $result ? 'SUCCESS' : 'FAILURE'), array($this->project, $this->environment, $result ? 'SUCCESS' : 'FAILURE'),
self::SUBJECT self::SUBJECT
) );
;
$attachment = chunk_split(base64_encode(file_get_contents($this->logFile))); $attachment = chunk_split(base64_encode(file_get_contents($this->logFile)));
$message = 'This is a multi-part message in MIME format.' . self::EOL $message = 'This is a multi-part message in MIME format.' . self::EOL
@ -83,8 +82,7 @@ class Mailer
. 'Content-Disposition: attachment' . self::EOL . 'Content-Disposition: attachment' . self::EOL
. self::EOL . self::EOL
. $attachment . self::EOL . $attachment . self::EOL
. '--Mage-mixed-' . $boundary . '--' . self::EOL . '--Mage-mixed-' . $boundary . '--' . self::EOL;
;
@mail($this->address, $subject, $message, $headers); @mail($this->address, $subject, $message, $headers);
} }

6
Mage/Task/AbstractTask.php

@ -197,14 +197,14 @@ abstract class AbstractTask
} }
// if general.yml includes "ssy_needs_tty: true", then add "-t" to the ssh command // 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' : ''); $needs_tty = ($this->getConfig()->general('ssh_needs_tty', false) ? '-t' : '');
$localCommand = 'ssh ' . $this->getConfig()->getHostIdentityFileOption() . $needs_tty . ' -p ' . $this->getConfig()->getHostPort() . ' ' $localCommand = 'ssh ' . $this->getConfig()->getHostIdentityFileOption() . $needs_tty . ' -p ' . $this->getConfig()->getHostPort() . ' '
. '-q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no ' . '-q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no '
. $this->getConfig()->deployment('user') . '@' . $this->getConfig()->getHostName(); . $this->getConfig()->deployment('user') . '@' . $this->getConfig()->getHostName();
$remoteCommand = str_replace('"', '\"', $command); $remoteCommand = str_replace('"', '\"', $command);
if($cdToDirectoryFirst){ if ($cdToDirectoryFirst) {
$remoteCommand = 'cd ' . rtrim($this->getConfig()->deployment('to'), '/') . $releasesDirectory . ' && ' . $remoteCommand; $remoteCommand = 'cd ' . rtrim($this->getConfig()->deployment('to'), '/') . $releasesDirectory . ' && ' . $remoteCommand;
} }
$localCommand .= ' ' . '"sh -c \"' . $remoteCommand . '\""'; $localCommand .= ' ' . '"sh -c \"' . $remoteCommand . '\""';
@ -299,7 +299,7 @@ abstract class AbstractTask
$commands = array(); $commands = array();
$commands[] = 'tar xfz ' . $currentRelease; $commands[] = 'tar xfz ' . $currentRelease;
$commands[] = 'rm -rf ' . $currentReleaseDirectory; $commands[] = 'rm -rf ' . $currentReleaseDirectory;
$commands[] = 'mv ' .$currentReleaseDirectoryTemp . ' ' . $currentReleaseDirectory; $commands[] = 'mv ' . $currentReleaseDirectoryTemp . ' ' . $currentReleaseDirectory;
$command = implode(' && ', $commands); $command = implode(' && ', $commands);
$result = $this->runCommandRemote($command, $output); $result = $this->runCommandRemote($command, $output);
return $result; return $result;

8
Mage/Task/BuiltIn/Deployment/ReleaseTask.php

@ -58,7 +58,7 @@ class ReleaseTask extends AbstractTask implements IsReleaseAware, SkipOnOverride
//Check if target user:group is specified //Check if target user:group is specified
$userGroup = $this->getConfig()->deployment('owner'); $userGroup = $this->getConfig()->deployment('owner');
// Fetch the user and group from base directory; defaults usergroup to 33:33 // Fetch the user and group from base directory; defaults usergroup to 33:33
if(empty($userGroup)){ if (empty($userGroup)) {
$user = '33'; $user = '33';
$group = '33'; $group = '33';
$directoryInfos = ''; $directoryInfos = '';
@ -66,14 +66,14 @@ class ReleaseTask extends AbstractTask implements IsReleaseAware, SkipOnOverride
// "stat" command don't behave the same on different systems, ls output format also varies // "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 // and awk parameters need special care depending on the executing shell
$resultFetch = $this->runCommandRemote("ls -ld .", $directoryInfos); $resultFetch = $this->runCommandRemote("ls -ld .", $directoryInfos);
if(!empty($directoryInfos)){ if (!empty($directoryInfos)) {
//uniformize format as it depends on the system deployed on //uniformize format as it depends on the system deployed on
$directoryInfos = trim(str_replace(array(" ", "\t"), ' ', $directoryInfos)); $directoryInfos = trim(str_replace(array(" ", "\t"), ' ', $directoryInfos));
$infoArray = explode(' ', $directoryInfos); $infoArray = explode(' ', $directoryInfos);
if(!empty($infoArray[2])) { if (!empty($infoArray[2])) {
$user = $infoArray[2]; $user = $infoArray[2];
} }
if(!empty($infoArray[3])) { if (!empty($infoArray[3])) {
$group = $infoArray[3]; $group = $infoArray[3];
} }
$userGroup = $user . ':' . $group; $userGroup = $user . ':' . $group;

2
Mage/Task/BuiltIn/Deployment/Strategy/BaseStrategyTaskAbstract.php

@ -32,7 +32,7 @@ abstract class BaseStrategyTaskAbstract extends AbstractTask implements IsReleas
if ($overrideRelease == true) { if ($overrideRelease == true) {
$releaseToOverride = false; $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)) { if ($resultFetch && is_numeric($releaseToOverride)) {
$this->getConfig()->setReleaseId($releaseToOverride); $this->getConfig()->setReleaseId($releaseToOverride);
} }

4
Mage/Task/BuiltIn/Deployment/Strategy/GitRebaseTask.php

@ -78,11 +78,11 @@ class GitRebaseTask extends BaseStrategyTaskAbstract implements IsReleaseAware
$result = $this->runCommandRemote($command) && $result; $result = $this->runCommandRemote($command) && $result;
// Stash if Working Copy is not clean // Stash if Working Copy is not clean
if(!$status) { if (!$status) {
$stashResult = ''; $stashResult = '';
$command = $this->getReleasesAwareCommand('git stash'); $command = $this->getReleasesAwareCommand('git stash');
$result = $this->runCommandRemote($command, $stashResult) && $result; $result = $this->runCommandRemote($command, $stashResult) && $result;
if($stashResult != "No local changes to save") { if ($stashResult != "No local changes to save") {
$stashed = true; $stashed = true;
} }
} }

6
Mage/Task/BuiltIn/Deployment/Strategy/RsyncTask.php

@ -32,7 +32,7 @@ class RsyncTask extends BaseStrategyTaskAbstract implements IsReleaseAware
return 'Deploy via Rsync (with Releases override) [built-in]'; return 'Deploy via Rsync (with Releases override) [built-in]';
} else { } else {
$rsync_copy = $this->getConfig()->deployment("rsync"); $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]'; return 'Deploy via Rsync (with Releases) [built-in, incremental]';
} else { } else {
return 'Deploy via Rsync (with Releases) [built-in]'; return 'Deploy via Rsync (with Releases) [built-in]';
@ -72,10 +72,10 @@ class RsyncTask extends BaseStrategyTaskAbstract implements IsReleaseAware
// rsync: { copy: yes } // rsync: { copy: yes }
$rsync_copy = $this->getConfig()->deployment('rsync'); $rsync_copy = $this->getConfig()->deployment('rsync');
// If copy_tool_rsync, use rsync rather than cp for finer control of what is copied // 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']))} " $this->runCommandRemote("rsync -a {$this->excludes(array_merge($excludes, $rsync_copy['rsync_excludes']))} "
. "$releasesDirectory/$currentRelease/ $releasesDirectory/{$this->getConfig()->getReleaseId()}"); . "$releasesDirectory/$currentRelease/ $releasesDirectory/{$this->getConfig()->getReleaseId()}");
} elseif ( $rsync_copy && is_array($rsync_copy) && $rsync_copy['copy'] ) { } elseif ($rsync_copy && is_array($rsync_copy) && $rsync_copy['copy']) {
$this->runCommandRemote('cp -R ' . $releasesDirectory . '/' . $currentRelease . ' ' . $releasesDirectory . '/' . $this->getConfig()->getReleaseId()); $this->runCommandRemote('cp -R ' . $releasesDirectory . '/' . $currentRelease . ' ' . $releasesDirectory . '/' . $this->getConfig()->getReleaseId());
} else { } else {
$this->runCommandRemote('mkdir -p ' . $releasesDirectory . '/' . $this->getConfig()->getReleaseId()); $this->runCommandRemote('mkdir -p ' . $releasesDirectory . '/' . $this->getConfig()->getReleaseId());

2
Mage/Task/BuiltIn/Deployment/Strategy/TarGzTask.php

@ -56,7 +56,7 @@ class TarGzTask extends BaseStrategyTaskAbstract implements IsReleaseAware
. '/' . $releasesDirectory . '/' . $releasesDirectory
. '/' . $this->getConfig()->getReleaseId(); . '/' . $this->getConfig()->getReleaseId();
$output = null; $output = null;
$this->runCommandRemote('mkdir -p ' . $deployToDirectory, $output , false); $this->runCommandRemote('mkdir -p ' . $deployToDirectory, $output, false);
} }
// Create Tar Gz // Create Tar Gz

285
Mage/Task/BuiltIn/Ioncube/EncryptTask.php

@ -56,7 +56,7 @@ class EncryptTask extends AbstractTask
* *
* @var array * @var array
*/ */
private $default = array (); private $default = array();
/** /**
* Array of YAML Ioncube * Array of YAML Ioncube
@ -64,7 +64,7 @@ class EncryptTask extends AbstractTask
* *
* @var array * @var array
*/ */
private $yaml = array (); private $yaml = array();
/** /**
* Array of file Ioncube * Array of file Ioncube
@ -73,7 +73,7 @@ class EncryptTask extends AbstractTask
* *
* @var array * @var array
*/ */
private $file = array (); private $file = array();
/** /**
* Source directory as used by * Source directory as used by
@ -106,7 +106,7 @@ class EncryptTask extends AbstractTask
* *
* @var array * @var array
*/ */
private $mageConfig = array (); private $mageConfig = array();
/** /**
* Final version of the IonCube * Final version of the IonCube
@ -115,7 +115,7 @@ class EncryptTask extends AbstractTask
* *
* @var array * @var array
*/ */
private $ionCubeConfig = array (); private $ionCubeConfig = array();
/** /**
* Default encoder version to use * Default encoder version to use
@ -171,7 +171,8 @@ class EncryptTask extends AbstractTask
* *
* @see \Mage\Task\AbstractTask::getName() * @see \Mage\Task\AbstractTask::getName()
*/ */
public function getName() { public function getName()
{
return $this->name; return $this->name;
} }
@ -180,9 +181,10 @@ class EncryptTask extends AbstractTask
* *
* @see \Mage\Task\AbstractTask::init() * @see \Mage\Task\AbstractTask::init()
*/ */
public function init() { public function init()
{
// Set the default extensions to ignore // Set the default extensions to ignore
$this->checkIgnoreExtens = array ( $this->checkIgnoreExtens = array(
'jpg', 'jpg',
'jpeg', 'jpeg',
'png', 'png',
@ -196,7 +198,7 @@ class EncryptTask extends AbstractTask
); );
// Get any options specfic to this task // Get any options specfic to this task
$this->mageConfig = $this->getConfig()->environmentConfig( 'ioncube' ); $this->mageConfig = $this->getConfig()->environmentConfig('ioncube');
/* /*
* Get all our IonCube config options * Get all our IonCube config options
*/ */
@ -204,12 +206,12 @@ class EncryptTask extends AbstractTask
/* /*
* get the source code location * get the source code location
*/ */
$this->source = $this->getConfig ()->deployment ( 'from' ); $this->source = $this->getConfig()->deployment('from');
/* /*
* remove trailing slash if present * remove trailing slash if present
*/ */
if (substr ( $this->source, - 1 ) == DIRECTORY_SEPARATOR) { if (substr($this->source, -1) == DIRECTORY_SEPARATOR) {
$this->source = substr ( $this->source, 0, - 1 ); $this->source = substr($this->source, 0, -1);
} }
/* /*
* Set the name of the folder that the un-encrypted * Set the name of the folder that the un-encrypted
@ -224,7 +226,7 @@ class EncryptTask extends AbstractTask
* Check if we have been given an encoder script * Check if we have been given an encoder script
* If not then we will just use the default * If not then we will just use the default
*/ */
if (isset ( $this->mageConfig ['encoder'] )) { if (isset ($this->mageConfig ['encoder'])) {
$this->encoder = $this->mageConfig ['encoder']; $this->encoder = $this->mageConfig ['encoder'];
} }
/* /*
@ -232,15 +234,15 @@ class EncryptTask extends AbstractTask
* supplied, this defines how the 3 differant * supplied, this defines how the 3 differant
* config files will be merged together. * config files will be merged together.
*/ */
if (isset ( $this->mageConfig ['override'] )) { if (isset ($this->mageConfig ['override'])) {
$this->ionOverRide = $this->mageConfig ['override']; $this->ionOverRide = $this->mageConfig ['override'];
} }
/* /*
* Check if we have been asked to * Check if we have been asked to
* confirm all encodings * confirm all encodings
*/ */
if (isset ( $this->mageConfig ['checkencoding'])) { if (isset ($this->mageConfig ['checkencoding'])) {
$this->checkEncoding=true; $this->checkEncoding = true;
} }
/* /*
* Check if we have been passed any extra * Check if we have been passed any extra
@ -248,8 +250,8 @@ class EncryptTask extends AbstractTask
* encrypt/encode file check * encrypt/encode file check
* *
*/ */
if (isset ( $this->mageConfig ['checkignoreextens'])) { if (isset ($this->mageConfig ['checkignoreextens'])) {
$this->checkIgnoreExtens=array_merge($this->ignoreExtens, $this->mageConfig['ignoreextens']); $this->checkIgnoreExtens = array_merge($this->ignoreExtens, $this->mageConfig['ignoreextens']);
} }
/* /*
@ -258,15 +260,15 @@ class EncryptTask extends AbstractTask
* encrypt/encode file check * encrypt/encode file check
* *
*/ */
if (isset ( $this->mageConfig ['checkignorepaths'])) { if (isset ($this->mageConfig ['checkignorepaths'])) {
$this->checkIgnorePaths=array_merge($this->checkIgnorePaths, $this->mageConfig['checkignorepaths']); $this->checkIgnorePaths = array_merge($this->checkIgnorePaths, $this->mageConfig['checkignorepaths']);
} }
/* /*
* now merge all the config options together * now merge all the config options together
*/ */
$this->ionCubeConfig = $this->mergeConfigFiles (); $this->ionCubeConfig = $this->mergeConfigFiles();
} }
/** /**
@ -283,29 +285,29 @@ class EncryptTask extends AbstractTask
/* /*
* Get a set of default IonCube options * Get a set of default IonCube options
*/ */
$this->default = $this->getOptionsDefault (); $this->default = $this->getOptionsDefault();
/* /*
* Check if there is a 'project' section, * Check if there is a 'project' section,
* if so then get the options from there * if so then get the options from there
*/ */
if (isset ( $this->mageConfig ['project'] )) { if (isset ($this->mageConfig ['project'])) {
$this->yaml = $this->getOptionsFromYaml ( $this->mageConfig ['project'] ); $this->yaml = $this->getOptionsFromYaml($this->mageConfig ['project']);
} else { } else {
$this->yaml = array ( $this->yaml = array(
's' => array (), 's' => array(),
'p' => array () 'p' => array()
); );
} }
/* /*
* Check if a seperate projectfile has been specified, and if so * Check if a seperate projectfile has been specified, and if so
* then read the options from there. * then read the options from there.
*/ */
if (isset ( $this->mageConfig ['projectfile'] )) { if (isset ($this->mageConfig ['projectfile'])) {
$this->file = $this->getOptionsFromFile ( $this->mageConfig ['projectfile'] ); $this->file = $this->getOptionsFromFile($this->mageConfig ['projectfile']);
} else { } else {
$this->file = array ( $this->file = array(
's' => array (), 's' => array(),
'p' => array () 'p' => array()
); );
} }
} }
@ -324,20 +326,21 @@ class EncryptTask extends AbstractTask
* @return bool * @return bool
* @throws \Mage\Task\ErrorWithMessageException * @throws \Mage\Task\ErrorWithMessageException
*/ */
public function run() { public function run()
$this->switchSrcToTmp (); {
$this->writeProjectFile (); $this->switchSrcToTmp();
$result = $this->runIonCube (); $this->writeProjectFile();
Console::output("Encoding result :".($result ? '<green>OK</green>' : '<red>Bad!</red>')."\n", 0, 2); $result = $this->runIonCube();
Console::output("Encoding result :" . ($result ? '<green>OK</green>' : '<red>Bad!</red>') . "\n", 0, 2);
if (!$result) { if (!$result) {
$this->deleteTmpFiles (); $this->deleteTmpFiles();
throw new ErrorWithMessageException('Ioncube failed to encode your project :'.$result); throw new ErrorWithMessageException('Ioncube failed to encode your project :' . $result);
} }
if (($this->checkEncoding) && (!$this->checkEncoding())) { if (($this->checkEncoding) && (!$this->checkEncoding())) {
$this->deleteTmpFiles(); $this->deleteTmpFiles();
throw new ErrorWithMessageException('Operation canceled by user.'); throw new ErrorWithMessageException('Operation canceled by user.');
} }
$this->deleteTmpFiles (); $this->deleteTmpFiles();
return $result; return $result;
} }
@ -351,33 +354,34 @@ class EncryptTask extends AbstractTask
* *
* @return bool * @return bool
*/ */
private function checkEncoding() { private function checkEncoding()
{
$src = $this->source; $src = $this->source;
// $ask holds flag to indicate we need to prompt the end user // $ask holds flag to indicate we need to prompt the end user
$ask = false; $ask = false;
// scan through the directory // scan through the directory
$rit = new \RecursiveDirectoryIterator ( $src ); $rit = new \RecursiveDirectoryIterator ($src);
foreach ( new \RecursiveIteratorIterator ( $rit ) as $filename => $cur ) { foreach (new \RecursiveIteratorIterator ($rit) as $filename => $cur) {
// get the 'base dir' for the project, eg. relative to the temp folder // get the 'base dir' for the project, eg. relative to the temp folder
$srcFileName = (str_replace ( $this->source, '', $filename )); $srcFileName = (str_replace($this->source, '', $filename));
/* /*
* Scan through the ignor directorys array * Scan through the ignor directorys array
* and if it matches the current path/filename * and if it matches the current path/filename
* then mark the file to be skipped from testing * then mark the file to be skipped from testing
*/ */
$skip = false; $skip = false;
foreach ( $this->checkIgnorePaths as $path ) { foreach ($this->checkIgnorePaths as $path) {
if (fnmatch ( $path, $srcFileName )) { if (fnmatch($path, $srcFileName)) {
$skip = true; $skip = true;
} }
} }
// check if we should test this file // check if we should test this file
if (! $skip) { if (!$skip) {
// get the file exten for this file and compare to our fileexten exclude array // get the file exten for this file and compare to our fileexten exclude array
$exten = pathinfo ( $filename, PATHINFO_EXTENSION ); $exten = pathinfo($filename, PATHINFO_EXTENSION);
if (! in_array ( strtolower ( $exten ), $this->checkIgnoreExtens )) { if (!in_array(strtolower($exten), $this->checkIgnoreExtens)) {
// ok, this extension needs to be checked // ok, this extension needs to be checked
if ($this->checkFileCoding ( $filename )) { if ($this->checkFileCoding($filename)) {
// file was encrypted/encoded // file was encrypted/encoded
} else { } else {
// file was not encrypted/encoded // file was not encrypted/encoded
@ -390,7 +394,7 @@ class EncryptTask extends AbstractTask
if ($ask) { if ($ask) {
// ok lets ask the user if they want to procede // ok lets ask the user if they want to procede
Console::output("\n\nDo you wish to procede (y/N):", 0, 0); Console::output("\n\nDo you wish to procede (y/N):", 0, 0);
if (! $this->promptYn ()) { if (!$this->promptYn()) {
return false; return false;
} }
} }
@ -407,10 +411,11 @@ class EncryptTask extends AbstractTask
* *
* @return bool True if 'y' pressed * @return bool True if 'y' pressed
*/ */
private function promptYn() { private function promptYn()
$handle = fopen ("php://stdin","r"); {
$handle = fopen("php://stdin", "r");
$line = strtolower(fgets($handle)); $line = strtolower(fgets($handle));
if(trim($line) != 'y'){ if (trim($line) != 'y') {
return false; return false;
} }
return true; return true;
@ -428,23 +433,24 @@ class EncryptTask extends AbstractTask
* *
* @return boolean True if file was encoded/encrypted * @return boolean True if file was encoded/encrypted
*/ */
private function checkFileCoding($filename) { private function checkFileCoding($filename)
{
// check to see if this is an encrypted file // check to see if this is an encrypted file
$ioncube = ioncube_read_file($filename, $ioncubeType); $ioncube = ioncube_read_file($filename, $ioncubeType);
if (is_int ( $ioncube )) { if (is_int($ioncube)) {
// we got an error from ioncube, so its encrypted // we got an error from ioncube, so its encrypted
return true; return true;
} }
// read first line of file // read first line of file
$f = fopen ( $filename, 'r' ); $f = fopen($filename, 'r');
$line = trim ( fgets ( $f, 32 ) ); $line = trim(fgets($f, 32));
fclose ( $f ); fclose($f);
// if first line is longer than 30, then this isnt a php file // if first line is longer than 30, then this isnt a php file
if (strlen ( $line ) > 30) { if (strlen($line) > 30) {
return false; return false;
} }
// if first line starts '<?php //0' then we can be pretty certain its encoded // if first line starts '<?php //0' then we can be pretty certain its encoded
if (substr ( $line, 0, 9 ) == '<?php //0') { if (substr($line, 0, 9) == '<?php //0') {
return true; return true;
} }
// otherwise its most likley un-encrypted/encoded // otherwise its most likley un-encrypted/encoded
@ -461,17 +467,18 @@ class EncryptTask extends AbstractTask
* *
* @return void * @return void
*/ */
private function deleteTmpFiles() { private function deleteTmpFiles()
if (isset ( $this->mageConfig ['keeptemp'] )) { {
if (isset ($this->mageConfig ['keeptemp'])) {
return; return;
} }
Console::log('Deleting tempory files :', 1); Console::log('Deleting tempory files :', 1);
$ret1 = Console::executeCommand ( 'rm -Rf ' . $this->ionSource, $out1 ); $ret1 = Console::executeCommand('rm -Rf ' . $this->ionSource, $out1);
$ret2 = Console::executeCommand ( 'rm ' . $this->projectFile, $out2 ); $ret2 = Console::executeCommand('rm ' . $this->projectFile, $out2);
if ($ret1 && $ret2) { if ($ret1 && $ret2) {
return; return;
} }
throw new ErrorWithMessageException ( 'Error deleting temp files :' . $out1 . ' : ' . $out2, 40 ); throw new ErrorWithMessageException ('Error deleting temp files :' . $out1 . ' : ' . $out2, 40);
} }
/** /**
@ -480,9 +487,10 @@ class EncryptTask extends AbstractTask
* *
* @return bool * @return bool
*/ */
private function runIonCube() { private function runIonCube()
$cli = $this->encoder . ' --project-file ' . $this->projectFile . ' ' . $this->ionSource . DIRECTORY_SEPARATOR.'*'; {
$ret = Console::executeCommand ( $cli, $out ); $cli = $this->encoder . ' --project-file ' . $this->projectFile . ' ' . $this->ionSource . DIRECTORY_SEPARATOR . '*';
$ret = Console::executeCommand($cli, $out);
return $ret; return $ret;
} }
@ -495,37 +503,38 @@ class EncryptTask extends AbstractTask
* *
* @return void * @return void
*/ */
private function writeProjectFile() { private function writeProjectFile()
{
// array used to build config file into // array used to build config file into
$out = array (); $out = array();
// set the project destination // set the project destination
$out [] = '--into ' . $this->source . PHP_EOL; $out [] = '--into ' . $this->source . PHP_EOL;
// output the switches // output the switches
foreach ( $this->ionCubeConfig ['s'] as $key => $value ) { foreach ($this->ionCubeConfig ['s'] as $key => $value) {
if ($value) { if ($value) {
// switch was set to true, so output it // switch was set to true, so output it
$out [] = '--' . $key . PHP_EOL; $out [] = '--' . $key . PHP_EOL;
} }
} }
// output the options // output the options
foreach ( $this->ionCubeConfig ['p'] as $key => $value ) { foreach ($this->ionCubeConfig ['p'] as $key => $value) {
// check if we have an array of values // check if we have an array of values
if (is_array ( $value )) { if (is_array($value)) {
foreach ( $value as $entry ) { foreach ($value as $entry) {
$out [] = '--' . $key . ' "' . $entry . '"' . PHP_EOL; $out [] = '--' . $key . ' "' . $entry . '"' . PHP_EOL;
} }
} else { } else {
// ok just a normal single option // ok just a normal single option
if (strlen ( $value ) > 0) { if (strlen($value) > 0) {
$out [] = '--' . $key . ' "' . $value . '"' . PHP_EOL; $out [] = '--' . $key . ' "' . $value . '"' . PHP_EOL;
} }
} }
} }
$ret = file_put_contents ( $this->projectFile, $out ); $ret = file_put_contents($this->projectFile, $out);
if (! $ret) { if (!$ret) {
// something went wrong // something went wrong
$this->deleteTmpFiles (); $this->deleteTmpFiles();
throw new ErrorWithMessageException ( 'Unable to create project file.', 20 ); throw new ErrorWithMessageException ('Unable to create project file.', 20);
} }
} }
@ -535,7 +544,8 @@ class EncryptTask extends AbstractTask
* *
* @return array Final config array * @return array Final config array
*/ */
private function mergeConfigFiles() { private function mergeConfigFiles()
{
/* /*
* Options are the order the arrays are in * Options are the order the arrays are in
* F - Project File * F - Project File
@ -546,24 +556,24 @@ class EncryptTask extends AbstractTask
* @todo I'm sure this could be combined into a loop to make it easier and shorter * @todo I'm sure this could be combined into a loop to make it easier and shorter
* *
*/ */
$s = array (); $s = array();
$p = array (); $p = array();
switch (strtolower ( $this->ionOverRide )) { switch (strtolower($this->ionOverRide)) {
case 'fyd' : case 'fyd' :
// FILE / YAML / DEFAULT // FILE / YAML / DEFAULT
$s = array_merge ( $this->file ['s'], $this->yaml ['s'], $this->default ['s'] ); $s = array_merge($this->file ['s'], $this->yaml ['s'], $this->default ['s']);
$p = array_merge ( $this->file ['p'], $this->yaml ['p'], $this->default ['p'] ); $p = array_merge($this->file ['p'], $this->yaml ['p'], $this->default ['p']);
break; break;
case 'yfd' : case 'yfd' :
// YAML / FILE / DEFAULT // YAML / FILE / DEFAULT
$s = array_merge ( $this->yaml ['s'], $this->file ['s'], $this->default ['s'] ); $s = array_merge($this->yaml ['s'], $this->file ['s'], $this->default ['s']);
$p = array_merge ( $this->yaml ['p'], $this->file ['p'], $this->default ['p'] ); $p = array_merge($this->yaml ['p'], $this->file ['p'], $this->default ['p']);
break; break;
case 'dyf' : case 'dyf' :
// DEFAULT / YAML / FILE // DEFAULT / YAML / FILE
$s = array_merge ( $this->default ['s'], $this->yaml ['s'], $this->file ['s'] ); $s = array_merge($this->default ['s'], $this->yaml ['s'], $this->file ['s']);
$p = array_merge ( $this->default ['p'], $this->yaml ['p'], $this->file ['p'] ); $p = array_merge($this->default ['p'], $this->yaml ['p'], $this->file ['p']);
break; break;
case 'd' : case 'd' :
default : default :
@ -572,7 +582,7 @@ class EncryptTask extends AbstractTask
$p = $this->default ['p']; $p = $this->default ['p'];
break; break;
} }
return array ( return array(
's' => $s, 's' => $s,
'p' => $p 'p' => $p
); );
@ -591,14 +601,15 @@ class EncryptTask extends AbstractTask
* *
* @return bool * @return bool
*/ */
private function switchSrcToTmp() { private function switchSrcToTmp()
$ret = Console::executeCommand ( 'mv ' . $this->source . ' ' . $this->ionSource, $out ); {
if (! $ret) { $ret = Console::executeCommand('mv ' . $this->source . ' ' . $this->ionSource, $out);
throw new ErrorWithMessageException ( 'Cant create tmp dir :' . $out, $ret ); if (!$ret) {
throw new ErrorWithMessageException ('Cant create tmp dir :' . $out, $ret);
} }
$ret = Console::executeCommand ( 'mkdir -p ' . $this->source, $out ); $ret = Console::executeCommand('mkdir -p ' . $this->source, $out);
if (! $ret) { if (!$ret) {
throw new ErrorWithMessageException ( 'Cant re-create dir :' . $out, $ret ); throw new ErrorWithMessageException ('Cant re-create dir :' . $out, $ret);
} }
return true; return true;
} }
@ -611,18 +622,19 @@ class EncryptTask extends AbstractTask
* *
* return array * return array
*/ */
private function getOptionsFromYaml($options) { private function getOptionsFromYaml($options)
$s = array (); {
$p = array (); $s = array();
foreach ( $options as $key => $value ) { $p = array();
if (array_key_exists ( $key, $this->default ['s'] )) { foreach ($options as $key => $value) {
if (array_key_exists($key, $this->default ['s'])) {
$s [$key] = true; $s [$key] = true;
} }
if (array_key_exists ( $key, $this->default ['p'] )) { if (array_key_exists($key, $this->default ['p'])) {
$p [$key] = $value; $p [$key] = $value;
} }
} }
return array ( return array(
's' => $s, 's' => $s,
'p' => $p 'p' => $p
); );
@ -635,48 +647,49 @@ class EncryptTask extends AbstractTask
* @param $fileName * @param $fileName
* @return array * @return array
*/ */
private function getOptionsFromFile($fileName) { private function getOptionsFromFile($fileName)
$s = array (); {
$p = array (); $s = array();
$fileContents = file_get_contents ( $fileName ); $p = array();
$fileContents = file_get_contents($fileName);
/* /*
* split the config file on every occurance of '--' at start of a line * 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 '--' * Adds a PHP_EOL at the start, so we can catch the first '--'
*/ */
$entrys = explode ( PHP_EOL . '--', PHP_EOL . $fileContents ); $entrys = explode(PHP_EOL . '--', PHP_EOL . $fileContents);
foreach ( $entrys as $line ) { foreach ($entrys as $line) {
$line = trim ( $line ); $line = trim($line);
if ($line != '') { if ($line != '') {
/* /*
* get position of first space * get position of first space
* so we can split the options out * so we can split the options out
*/ */
$str = strpos ( $line, ' ' ); $str = strpos($line, ' ');
if ($str === false) { if ($str === false) {
/* /*
* Ok, no spaces found, so take this as a single line * Ok, no spaces found, so take this as a single line
*/ */
$str = strlen ( $line ); $str = strlen($line);
} }
$key = substr ( $line, $str ); $key = substr($line, $str);
$value = substr ( $line, $str + 1 ); $value = substr($line, $str + 1);
if ((array_key_exists ( $key, $this->default ['s'] ))) { if ((array_key_exists($key, $this->default ['s']))) {
/* /*
* ok this key appears in the switch config * ok this key appears in the switch config
* so store it as a switch * so store it as a switch
*/ */
$s [$key] = true; $s [$key] = true;
} }
if ((array_key_exists ( $key, $this->default ['p'] ))) { if ((array_key_exists($key, $this->default ['p']))) {
/* /*
* Ok this key exists in the parameter section, * Ok this key exists in the parameter section,
* So store it allong with its value * So store it allong with its value
*/ */
$p [$key] = $this->splitParam ( $value ); $p [$key] = $this->splitParam($value);
} }
} }
} }
return array ( return array(
's' => $s, 's' => $s,
'p' => $p 'p' => $p
); );
@ -693,13 +706,14 @@ class EncryptTask extends AbstractTask
* *
* @return mixed * @return mixed
*/ */
private function splitParam($string) { private function splitParam($string)
$split = explode ( PHP_EOL, $string ); {
$split = explode(PHP_EOL, $string);
if ($split === false) { if ($split === false) {
// nothing found, so return a blank string // nothing found, so return a blank string
return ''; return '';
} }
if (count ( $split ) == 1) { if (count($split) == 1) {
return $split [0]; return $split [0];
} else { } else {
return $split; return $split;
@ -715,9 +729,10 @@ class EncryptTask extends AbstractTask
* *
* @return array * @return array
*/ */
private function getOptionsDefault() { private function getOptionsDefault()
$s = array (); {
$p = array (); $s = array();
$p = array();
// Set the switches // Set the switches
$s ['allow-encoding-into-source'] = false; $s ['allow-encoding-into-source'] = false;
@ -751,9 +766,9 @@ class EncryptTask extends AbstractTask
// Now set the params // Now set the params
$p ['encrypt'] [] = '*.tpl.html'; $p ['encrypt'] [] = '*.tpl.html';
$p ['encode'] = array (); $p ['encode'] = array();
$p ['copy'] = array (); $p ['copy'] = array();
$p ['ignore'] = array ( $p ['ignore'] = array(
'.git', '.git',
'.svn', '.svn',
getcwd() . '/.mage', getcwd() . '/.mage',
@ -761,7 +776,7 @@ class EncryptTask extends AbstractTask
'.gitkeep', '.gitkeep',
'nohup.out' 'nohup.out'
); );
$p ['keep'] = array (); $p ['keep'] = array();
$p ['obfuscate'] = ''; $p ['obfuscate'] = '';
$p ['obfuscation-key'] = ''; $p ['obfuscation-key'] = '';
$p ['obfuscation-exclusion-file'] = ''; $p ['obfuscation-exclusion-file'] = '';
@ -773,23 +788,23 @@ class EncryptTask extends AbstractTask
$p ['license-check'] = ''; $p ['license-check'] = '';
$p ['apply-file-user'] = ''; $p ['apply-file-user'] = '';
$p ['apply-file-group'] = ''; $p ['apply-file-group'] = '';
$p ['register-autoglobal'] = array (); $p ['register-autoglobal'] = array();
$p ['message-if-no-loader'] = ''; $p ['message-if-no-loader'] = '';
$p ['action-if-no-loader'] = ''; $p ['action-if-no-loader'] = '';
$p ['loader-path'] = ''; $p ['loader-path'] = '';
$p ['preamble-file'] = ''; $p ['preamble-file'] = '';
$p ['add-comment'] = array (); $p ['add-comment'] = array();
$p ['add-comments'] = ''; $p ['add-comments'] = '';
$p ['loader-event'] = array (); $p ['loader-event'] = array();
$p ['callback-file'] = ''; $p ['callback-file'] = '';
$p ['property'] = ''; $p ['property'] = '';
$p ['propertys'] = ''; $p ['propertys'] = '';
$p ['include-if-property'] = array (); $p ['include-if-property'] = array();
$p ['optimise'] = 'max'; $p ['optimise'] = 'max';
$p ['shell-script-line'] = ''; $p ['shell-script-line'] = '';
$p ['min-loader-version'] = ''; $p ['min-loader-version'] = '';
return array ( return array(
's' => $s, 's' => $s,
'p' => $p 'p' => $p
); );

2
Mage/Task/BuiltIn/Releases/ListTask.php

@ -59,7 +59,7 @@ class ListTask extends AbstractTask implements IsReleaseAware
foreach ($releases as $releaseIndex => $release) { foreach ($releases as $releaseIndex => $release) {
$release = trim($release); $release = trim($release);
$releaseIndex = str_pad($releaseIndex * -1, 2, ' ', STR_PAD_LEFT); $releaseIndex = str_pad($releaseIndex * -1, 2, ' ', STR_PAD_LEFT);
$releaseDate = $release[0] . $release[1] . $release[2] .$release[3] $releaseDate = $release[0] . $release[1] . $release[2] . $release[3]
. '-' . '-'
. $release[4] . $release[5] . $release[4] . $release[5]
. '-' . '-'

2
Mage/Task/Factory.php

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

8
Mage/Yaml/Dumper.php

@ -34,7 +34,7 @@ class Dumper
*/ */
public function setIndentation($num) public function setIndentation($num)
{ {
$this->indentation = (int) $num; $this->indentation = (int)$num;
} }
/** /**
@ -54,7 +54,7 @@ class Dumper
$prefix = $indent ? str_repeat(' ', $indent) : ''; $prefix = $indent ? str_repeat(' ', $indent) : '';
if ($inline <= 0 || !is_array($input) || empty($input)) { if ($inline <= 0 || !is_array($input) || empty($input)) {
$output .= $prefix.Inline::dump($input, $exceptionOnInvalidType, $objectSupport); $output .= $prefix . Inline::dump($input, $exceptionOnInvalidType, $objectSupport);
} else { } else {
$isAHash = array_keys($input) !== range(0, count($input) - 1); $isAHash = array_keys($input) !== range(0, count($input) - 1);
@ -63,10 +63,10 @@ class Dumper
$output .= sprintf('%s%s%s%s', $output .= sprintf('%s%s%s%s',
$prefix, $prefix,
$isAHash ? Inline::dump($key, $exceptionOnInvalidType, $objectSupport).':' : '-', $isAHash ? Inline::dump($key, $exceptionOnInvalidType, $objectSupport) . ':' : '-',
$willBeInlined ? ' ' : "\n", $willBeInlined ? ' ' : "\n",
$this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + $this->indentation, $exceptionOnInvalidType, $objectSupport) $this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + $this->indentation, $exceptionOnInvalidType, $objectSupport)
).($willBeInlined ? "\n" : ''); ) . ($willBeInlined ? "\n" : '');
} }
} }

2
Mage/Yaml/Escaper.php

@ -48,7 +48,7 @@ class Escaper
*/ */
public static function requiresDoubleQuoting($value) 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);
} }
/** /**

28
Mage/Yaml/Inline.php

@ -55,7 +55,7 @@ class Inline
return ''; 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(); $mbEncoding = mb_internal_encoding();
mb_internal_encoding('ASCII'); mb_internal_encoding('ASCII');
} }
@ -108,7 +108,7 @@ class Inline
return 'null'; return 'null';
case is_object($value): case is_object($value):
if ($objectSupport) { if ($objectSupport) {
return '!!php/object:'.serialize($value); return '!!php/object:' . serialize($value);
} }
if ($exceptionOnInvalidType) { if ($exceptionOnInvalidType) {
@ -125,7 +125,7 @@ class Inline
case false === $value: case false === $value:
return 'false'; return 'false';
case ctype_digit($value): case ctype_digit($value):
return is_string($value) ? "'$value'" : (int) $value; return is_string($value) ? "'$value'" : (int)$value;
case is_numeric($value): case is_numeric($value):
$locale = setlocale(LC_NUMERIC, 0); $locale = setlocale(LC_NUMERIC, 0);
if (false !== $locale) { if (false !== $locale) {
@ -166,7 +166,9 @@ class Inline
// array // array
$keys = array_keys($value); $keys = array_keys($value);
if ((1 == count($keys) && '0' == $keys[0]) 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(); $output = array();
foreach ($value as $val) { foreach ($value as $val) {
@ -220,7 +222,7 @@ class Inline
if (false !== $strpos = strpos($output, ' #')) { if (false !== $strpos = strpos($output, ' #')) {
$output = rtrim(substr($output, 0, $strpos)); $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]; $output = $match[1];
$i += strlen($output); $i += strlen($output);
} else { } else {
@ -247,7 +249,7 @@ class Inline
*/ */
private static function parseQuotedScalar($scalar, &$i) 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))); throw new ParseException(sprintf('Malformed inline YAML string (%s).', substr($scalar, $i)));
} }
@ -304,7 +306,7 @@ class Inline
if (!$isQuoted && false !== strpos($value, ': ')) { if (!$isQuoted && false !== strpos($value, ': ')) {
// embedded mapping? // embedded mapping?
try { try {
$value = self::parseMapping('{'.$value.'}'); $value = self::parseMapping('{' . $value . '}');
} catch (\InvalidArgumentException $e) { } catch (\InvalidArgumentException $e) {
// no, it's not // no, it's not
} }
@ -346,7 +348,7 @@ class Inline
continue 2; continue 2;
case '}': case '}':
if (self::$objectForMap) { if (self::$objectForMap) {
return (object) $output; return (object)$output;
} }
return $output; return $output;
@ -435,7 +437,7 @@ class Inline
case $scalar[0] === '+' || $scalar[0] === '-' || $scalar[0] === '.' || $scalar[0] === '!' || is_numeric($scalar[0]): case $scalar[0] === '+' || $scalar[0] === '-' || $scalar[0] === '.' || $scalar[0] === '!' || is_numeric($scalar[0]):
switch (true) { switch (true) {
case 0 === strpos($scalar, '!str'): case 0 === strpos($scalar, '!str'):
return (string) substr($scalar, 5); return (string)substr($scalar, 5);
case 0 === strpos($scalar, '! '): case 0 === strpos($scalar, '! '):
return intval(self::parseScalar(substr($scalar, 2))); return intval(self::parseScalar(substr($scalar, 2)));
case 0 === strpos($scalar, '!!php/object:'): case 0 === strpos($scalar, '!!php/object:'):
@ -453,14 +455,14 @@ class Inline
$raw = $scalar; $raw = $scalar;
$cast = intval($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)): case '-' === $scalar[0] && ctype_digit(substr($scalar, 1)):
$raw = $scalar; $raw = $scalar;
$cast = intval($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): 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 '.inf' === $scalarLower:
case '.nan' === $scalarLower: case '.nan' === $scalarLower:
return -log(0); return -log(0);
@ -472,7 +474,7 @@ class Inline
return strtotime($scalar); return strtotime($scalar);
} }
default: default:
return (string) $scalar; return (string)$scalar;
} }
} }

12
Mage/Yaml/Parser.php

@ -61,7 +61,7 @@ class Parser
throw new ParseException('The YAML value does not appear to be valid UTF-8.'); 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(); $mbEncoding = mb_internal_encoding();
mb_internal_encoding('UTF-8'); mb_internal_encoding('UTF-8');
} }
@ -99,7 +99,7 @@ class Parser
} else { } else {
if (isset($values['leadspaces']) if (isset($values['leadspaces'])
&& ' ' == $values['leadspaces'] && ' ' == $values['leadspaces']
&& preg_match('#^(?P<key>'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\{\[].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $values['value'], $matches) && preg_match('#^(?P<key>' . Inline::REGEX_QUOTED_STRING . '|[^ \'"\{\[].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $values['value'], $matches)
) { ) {
// this is a compact notation element, add to next block and parse // this is a compact notation element, add to next block and parse
$c = $this->getRealCurrentLineNb(); $c = $this->getRealCurrentLineNb();
@ -108,7 +108,7 @@ class Parser
$block = $values['value']; $block = $values['value'];
if ($this->isNextLineIndented()) { if ($this->isNextLineIndented()) {
$block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + 2); $block .= "\n" . $this->getNextEmbedBlock($this->getCurrentLineIndentation() + 2);
} }
$data[] = $parser->parse($block, $exceptionOnInvalidType, $objectSupport, $objectForMap); $data[] = $parser->parse($block, $exceptionOnInvalidType, $objectSupport, $objectForMap);
@ -116,7 +116,7 @@ class Parser
$data[] = $this->parseValue($values['value'], $exceptionOnInvalidType, $objectSupport, $objectForMap); $data[] = $this->parseValue($values['value'], $exceptionOnInvalidType, $objectSupport, $objectForMap);
} }
} }
} elseif (preg_match('#^(?P<key>'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\[\{].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $this->currentLine, $values) && false === strpos($values['key'],' #')) { } elseif (preg_match('#^(?P<key>' . Inline::REGEX_QUOTED_STRING . '|[^ \'"\[\{].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $this->currentLine, $values) && false === strpos($values['key'], ' #')) {
if ($context && 'sequence' == $context) { if ($context && 'sequence' == $context) {
throw new ParseException('You cannot define a mapping item when in a sequence'); throw new ParseException('You cannot define a mapping item when in a sequence');
} }
@ -327,7 +327,7 @@ class Parser
$isItUnindentedCollection = $this->isStringUnIndentedCollectionItem($this->currentLine); $isItUnindentedCollection = $this->isStringUnIndentedCollectionItem($this->currentLine);
// Comments must not be removed inside a string block (ie. after a line ending with "|") // 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); $removeComments = !preg_match($removeCommentsPattern, $this->currentLine);
while ($this->moveToNextLine()) { while ($this->moveToNextLine()) {
@ -417,7 +417,7 @@ class Parser
return $this->refs[$value]; 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'] : ''; $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';
return $this->parseFoldedScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), intval(abs($modifiers))); return $this->parseFoldedScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), intval(abs($modifiers)));

8
Mage/Yaml/Unescaper.php

@ -55,7 +55,7 @@ class Unescaper
}; };
// evaluate the string // 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); return chr($c);
} }
if (0x800 > $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) { 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);
} }
} }
Loading…
Cancel
Save