Skip to content

Instantly share code, notes, and snippets.

@partageit
Created January 26, 2015 16:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save partageit/869fa0fbf9f89582d5f0 to your computer and use it in GitHub Desktop.
Save partageit/869fa0fbf9f89582d5f0 to your computer and use it in GitHub Desktop.
Code indentation shifter : Shift code to the left, preserving indentation
<?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