Created
January 26, 2015 16:55
-
-
Save partageit/869fa0fbf9f89582d5f0 to your computer and use it in GitHub Desktop.
Code indentation shifter : Shift code to the left, preserving indentation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Shift code to the left, preserving indentation. | |
* | |
* This is useful when reading code extract in a not-displayed nested structures. | |
* There is no use of closure here in order to remain compatible with older versions of PHP. | |
* This method is code agnostic. | |
* @example | |
* $code = ""; | |
* $code .= " while ($a) {"; | |
* $code .= " if ($b) {"; | |
* $code .= " echo $c;"; | |
* $code .= " }"; | |
* $code .= " }"; | |
* $cis = new CodeIndentationShifter(); | |
* echo $cis->shift($code); | |
* Displays: | |
* while ($a) { | |
* if ($b) { | |
* echo $c; | |
* } | |
* } | |
*/ | |
class CodeIndentationShifter { | |
private $minIndent = null; | |
/** | |
* Shift the provided content | |
* @param string The code content to shift | |
* @return string The shifted content | |
*/ | |
public function shift($content) { | |
$content = explode("\n", str_replace("\r\n", "\n", $content)); | |
$this->minIndent = null; | |
array_map(array($this, "whiteSpacesCount"), $content); | |
return implode("\n", array_map(array($this, "removeStartingWhiteSpaces"), $content)); | |
} | |
/** | |
* Store the white spaces amount in the provided code line into $this::minIndent if it is smaller | |
* @param string $line A code line | |
*/ | |
private function whiteSpacesCount($line) { | |
if (trim($line) === "") return; | |
$startingSpacesCount = strlen($line) - strlen(ltrim($line)); | |
if ($this->minIndent === null || $this->minIndent > $startingSpacesCount) | |
$this->minIndent = $startingSpacesCount; | |
return; | |
} | |
/** | |
* Remove the mininum amount from the provided line | |
* @param string $line A code line | |
* @return string The line, without the first not needed white spaces | |
*/ | |
private function removeStartingWhiteSpaces($line) { | |
return substr($line, $this->minIndent, strlen($line) - $this->minIndent); | |
} | |
} | |
/* | |
// Test part: | |
$content = " 23146544; | |
12321465487; | |
3654654; | |
587997; | |
156654; | |
3565654; | |
03354654;"; | |
$cis = new CodeIndentationShifter(); | |
echo $cis->shift($content); | |
*/ | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment