Ejemplo n.º 1
0
 public static function decorate(CodeFormatter $fmt)
 {
     $fmt->enablePass('PSR2ModifierVisibilityStaticOrder');
     $fmt->enablePass('TranslateNativeCalls');
     $fmt->enablePass('UpdateVisibility');
     $fmt->enablePass('ExtractMethods');
 }
Ejemplo n.º 2
0
 public static function PSR2(CodeFormatter $fmt)
 {
     $fmt->enablePass('PSR2KeywordsLowerCase');
     $fmt->enablePass('PSR2IndentWithSpace');
     $fmt->enablePass('PSR2LnAfterNamespace');
     $fmt->enablePass('PSR2CurlyOpenNextLine');
     $fmt->enablePass('PSR2ModifierVisibilityStaticOrder');
     $fmt->enablePass('PSR2SingleEmptyLineAndStripClosingTag');
     $fmt->enablePass('ReindentSwitchBlocks');
     $fmt->disablePass('ReindentComments');
 }
Ejemplo n.º 3
0
                break;
            }
            echo '!';
        } else {
            echo '.';
        }
        stopAtStep();
        $isCoverage && $coverage->stop();
    }
}
$cases = glob(__DIR__ . '/tests-Php2Go/' . $testNumber . '*.in');
if (!$bailOut) {
    foreach ($cases as $caseIn) {
        ++$count;
        $isCoverage && $coverage->start($caseIn);
        $fmt = new CodeFormatter();
        $caseOut = str_replace('.in', '.out', $caseIn);
        $content = file_get_contents($caseIn);
        $tokens = token_get_all($content);
        $specialPasses = false;
        foreach ($tokens as $token) {
            list($id, $text) = getToken($token);
            if (T_COMMENT == $id && '//version:' == substr($text, 0, 10)) {
                $version = str_replace('//version:', '', $text);
                if (version_compare(PHP_VERSION, $version, '<')) {
                    echo 'S';
                    continue 2;
                }
            } elseif (!$shortTagEnabled && T_INLINE_HTML == $id && false !== strpos($text, '//skipShortTag')) {
                echo 'S';
                continue 2;
Ejemplo n.º 4
0
     $options = ['--from=from, --to=to' => 'Search for "from" and replace with "to" - context aware search and replace', '-h, --help' => 'this help message', '-o=file' => 'output the formatted code to "file"'];
     $maxLen = max(array_map(function ($v) {
         return strlen($v);
     }, array_keys($options)));
     foreach ($options as $k => $v) {
         echo '  ', str_pad($k, $maxLen), '  ', $v, PHP_EOL;
     }
     echo PHP_EOL, 'If <target> is blank, it reads from stdin', PHP_EOL;
     die;
 }
 if (isset($opts['from']) && !isset($opts['to'])) {
     fwrite(STDERR, 'Refactor must have --from and --to parameters' . PHP_EOL);
     exit(255);
 }
 $debug = false;
 $fmt = new CodeFormatter($debug);
 if (isset($opts['from']) && isset($opts['to'])) {
     $argv = array_values(array_filter($argv, function ($v) {
         $param_from = '--from';
         $param_to = '--to';
         return substr($v, 0, strlen($param_from)) !== $param_from && substr($v, 0, strlen($param_to)) !== $param_to;
     }));
     $fmt->addPass(new RefactorPass($opts['from'], $opts['to']));
 }
 if (isset($opts['o'])) {
     unset($argv[1]);
     unset($argv[2]);
     $argv = array_values($argv);
     file_put_contents($opts['o'], $fmt->formatCode(file_get_contents($argv[1])));
 } elseif (isset($argv[1]) && is_file($argv[1])) {
     echo $fmt->formatCode(file_get_contents($argv[1]));
Ejemplo n.º 5
0
            $bailOut = true;
            break;
        }
        echo '!';
    } else {
        echo '.';
    }
    stopAtStep();
    $isCoverage && $coverage->stop();
}
$cases = glob(__DIR__ . '/tests-PSR/' . $testNumber . '*.in');
if (!$bailOut) {
    foreach ($cases as $caseIn) {
        ++$count;
        $isCoverage && $coverage->start($caseIn);
        $fmt = new CodeFormatter();
        $caseOut = str_replace('.in', '.out', $caseIn);
        $content = file_get_contents($caseIn);
        $tokens = token_get_all($content);
        $specialPasses = false;
        foreach ($tokens as $token) {
            list($id, $text) = getToken($token);
            if (T_COMMENT == $id && '//version:' == substr($text, 0, 10)) {
                $version = str_replace('//version:', '', $text);
                if (version_compare(PHP_VERSION, $version, '<')) {
                    $skippedTests[] = $caseIn;
                    echo 'S';
                    continue 2;
                }
            } elseif (!$shortTagEnabled && T_INLINE_HTML == $id && false !== strpos($text, '//skipShortTag')) {
                $skippedTests[] = $caseIn;
Ejemplo n.º 6
0
     $options = ['--from=from, --to=to' => 'Search for "from" and replace with "to" - context aware search and replace', '-h, --help' => 'this help message', '-o=file' => 'output the formatted code to "file"'];
     $maxLen = max(array_map(function ($v) {
         return strlen($v);
     }, array_keys($options)));
     foreach ($options as $k => $v) {
         echo '  ', str_pad($k, $maxLen), '  ', $v, PHP_EOL;
     }
     echo PHP_EOL, 'If <target> is blank, it reads from stdin', PHP_EOL;
     die;
 }
 if (isset($opts['from']) && !isset($opts['to'])) {
     fwrite(STDERR, "Refactor must have --from and --to parameters" . PHP_EOL);
     exit(255);
 }
 $debug = false;
 $fmt = new CodeFormatter($debug);
 if (isset($opts['from']) && isset($opts['to'])) {
     $argv = array_values(array_filter($argv, function ($v) {
         $param_from = '--from';
         $param_to = '--to';
         return substr($v, 0, strlen($param_from)) !== $param_from && substr($v, 0, strlen($param_to)) !== $param_to;
     }));
     $fmt->addPass(new RefactorPass($opts['from'], $opts['to']));
 }
 if (isset($opts['o'])) {
     unset($argv[1]);
     unset($argv[2]);
     $argv = array_values($argv);
     file_put_contents($opts['o'], $fmt->formatCode(file_get_contents($argv[1])));
 } elseif (isset($argv[1]) && is_file($argv[1])) {
     echo $fmt->formatCode(file_get_contents($argv[1]));
Ejemplo n.º 7
0
 public static function decorate(CodeFormatter &$fmt)
 {
     $fmt->disablePass('AlignEquals');
     $fmt->disablePass('AlignDoubleArrow');
     $fmt->enablePass('NamespaceMergeWithOpenTag');
     $fmt->enablePass('LaravelAllmanStyleBraces');
     $fmt->enablePass('RTrim');
     $fmt->enablePass('TightConcat');
     $fmt->enablePass('NoSpaceBetweenFunctionAndBracket');
     $fmt->enablePass('SpaceAroundExclamationMark');
     $fmt->enablePass('NonDocBlockMinorCleanUp');
     $fmt->enablePass('SortUseNameSpace');
     $fmt->enablePass('AlignEqualsByConsecutiveBlocks');
     $fmt->enablePass('EliminateDuplicatedEmptyLines');
 }
Ejemplo n.º 8
0
    $argv = extractFromArgv($argv, 'dry-run');
    $dryRun = true;
}
$ignore_list = null;
if (isset($opts['ignore'])) {
    $argv = extractFromArgv($argv, 'ignore');
    $ignore_list = array_map(function ($v) {
        return trim($v);
    }, explode(',', $opts['ignore']));
}
$lintBefore = false;
if (isset($opts['lint-before'])) {
    $argv = extractFromArgv($argv, 'lint-before');
    $lintBefore = true;
}
$fmt = new CodeFormatter();
if (isset($opts['setters_and_getters'])) {
    $argv = extractFromArgv($argv, 'setters_and_getters');
    $fmt->enablePass('SettersAndGettersPass', $opts['setters_and_getters']);
}
if (isset($opts['constructor'])) {
    $argv = extractFromArgv($argv, 'constructor');
    $fmt->enablePass('ConstructorPass', $opts['constructor']);
}
if (isset($opts['oracleDB'])) {
    $argv = extractFromArgv($argv, 'oracleDB');
    if ('scan' == $opts['oracleDB']) {
        $oracle = getcwd() . DIRECTORY_SEPARATOR . 'oracle.sqlite';
        $lastoracle = '';
        while (!is_file($oracle) && $lastoracle != $oracle) {
            $lastoracle = $oracle;
Ejemplo n.º 9
0
		case 1:
		if($a){
			noop();
		}
		break;

		case 2:
			noop();
		break;
	}
}

if($a)
	noop3();
';
$fmt = new CodeFormatter();
$fmt->addPass(new TwoCommandsInSameLine());
$fmt->addPass(new RemoveIncludeParentheses());
$fmt->addPass(new NormalizeIsNotEquals());
$fmt->addPass(new OrderUseClauses());
$fmt->addPass(new AddMissingCurlyBraces());
$fmt->addPass(new ExtraCommaInArray());
$fmt->addPass(new NormalizeLnAndLtrimLines());
$fmt->addPass(new MergeParenCloseWithCurlyOpen());
$fmt->addPass(new MergeCurlyCloseAndDoWhile());
$fmt->addPass(new MergeDoubleArrowAndArray());
$fmt->addPass(new ResizeSpaces());
$fmt->addPass(new Tree());
$fmt->addPass(new ReindentColonBlocks());
$fmt->addPass(new ReindentLoopColonBlocks());
$fmt->addPass(new ReindentIfColonBlocks());
Ejemplo n.º 10
0
 public static function decorate(CodeFormatter $fmt)
 {
     $fmt->addPass(new PSR1OpenTags());
     $fmt->addPass(new PSR1BOMMark());
     $fmt->addPass(new PSR1ClassNames());
     $fmt->addPass(new PSR1ClassConstants());
     $fmt->addPass(new PSR1MethodNames());
     $fmt->addPass(new PSR2IndentWithSpace());
     $fmt->addPass(new PSR2LnAfterNamespace());
     $fmt->addPass(new PSR2CurlyOpenNextLine());
     $fmt->addPass(new PSR2ModifierVisibilityStaticOrder());
     $fmt->addPass(new PSR2SingleEmptyLineAndStripClosingTag());
 }
Ejemplo n.º 11
0
 private function Evaluate()
 {
     $this->Normalize();
     $text = $this->m_text;
     $references = [];
     $footnotes = [];
     $escape_sequence_map = [];
     $header_map = [];
     $rm = new ReplacementManager();
     // encode escape sequences
     // (I tried using a ReplacementManager for this, but it was slower)
     if (strpos($text, '\\') !== false) {
         $escape_sequences = ['\\\\', '\\~', '\\`', '\\*', '\\_', '\\{', '\\}', '\\[', '\\]', '\\(', '\\)', '\\>', '\\#', '\\+', '\\-', '\\.', '\\!'];
         foreach ($escape_sequences as $index => $escape_sequence) {
             if (strpos($text, $escape_sequence) !== false) {
                 $code = "" . '\\' . $index;
                 $text = str_replace($escape_sequence, $code, $text);
                 $escape_sequence_map[$code] = $escape_sequence[1];
             }
         }
     }
     // extract abbreviations
     /*if (preg_match_all('/^\*?+\[(?<short>[^]]++)\]:[\t ]++(?<long>[^\n]++)$/m', $text, $matches, PREG_SET_ORDER)) {
     			foreach ($matches as $match) {
     				// save
     				$rm->Add($match[0], '');
     			}
     			$text = $rm->Replace($text);
     		}*/
     // find code blocks
     if (strpos($text, '~~~') !== false || strpos($text, '```') !== false) {
         if (preg_match_all('/^[\\t ]*+\\K((?:~|`){3})(?: ?{(?<extra>[^}]++)})?+[^\\n]*+(?<code>.+?)^[\\t ]*+\\1/ms', $text, $matches, PREG_SET_ORDER)) {
             foreach ($matches as $match) {
                 $code = $match['code'];
                 // replace tabs with spaces (make this an option?)
                 //$code = str_replace("\t", '    ', $code);
                 // adjust whitespace alignment using first line as a guide
                 $code = trim($code, "\n");
                 $leading_whitespace_len = strlen($code) - strlen(ltrim($code, "\t "));
                 if ($leading_whitespace_len > 0) {
                     $leading_whitespace = substr($code, 0, $leading_whitespace_len);
                     $code_lines = explode("\n", $code);
                     foreach ($code_lines as &$line) {
                         if ($line !== '' && strncmp($line, $leading_whitespace, $leading_whitespace_len) !== 0) {
                             $skip_whitespace_handling = true;
                             break;
                         }
                         $line = substr($line, $leading_whitespace_len);
                     }
                     if (!$skip_whitespace_handling) {
                         $code = implode("\n", $code_lines);
                     }
                 }
                 $extra = isset($match['extra']) ? explode(' ', $match['extra']) : NULL;
                 $handlers = [];
                 foreach ($extra as $handler) {
                     $options = NULL;
                     if (($handler_pos = strpos($handler, '[')) !== false) {
                         $options_str = substr($handler, $handler_pos + 1, -1);
                         $options = explode(',', $options_str);
                         $handler = substr($handler, 0, $handler_pos);
                     }
                     $handlers[$handler] = $options;
                 }
                 if ($this->m_enableCodeFormatting) {
                     $element = CodeFormatter::Format($code, $handlers);
                 } else {
                     $element = '<pre><code>' . htmlentities($code) . '</code></pre>';
                 }
                 $rm->Add($match[0], $element, 'block');
             }
             $text = $rm->Replace($text);
         }
     }
     // find inline code
     if (strpos($text, '`') !== false) {
         if (preg_match_all('/`(?<code>[^`]++)`/', $text, $matches, PREG_SET_ORDER)) {
             foreach ($matches as $match) {
                 $element = sprintf('<code>%s</code>', htmlentities($match['code'], ENT_NOQUOTES));
                 $rm->Add($match[0], $element);
             }
             $text = $rm->Replace($text);
         }
     }
     // removable lines
     if (strpos($text, ']:') !== false) {
         // extract footnotes
         if (strpos($text, '[^') !== false) {
             if (preg_match_all('/^[\\t ]*+\\[\\^(?<id>[^]]++)\\]:[\\t ]++(?<text>.*)$/m', $text, $matches, PREG_SET_ORDER)) {
                 foreach ($matches as $match) {
                     // check for duplicates?
                     $footnotes[strtolower($match['id'])] = ['text' => $match['text']];
                     $rm->Add($match[0], '');
                 }
                 $text = $rm->Replace($text);
             }
         }
         // extract references
         if (preg_match_all('/^[\\t ]*+\\[(?<id>[^]]++)\\]:[\\t ]++(?<url>[^\\n\\t ]++)[\\t ]*+(?:"(?<title>[^"]*+)")?$/m', $text, $matches, PREG_SET_ORDER)) {
             foreach ($matches as $match) {
                 // check for duplicates?
                 $references[strtolower($match['id'])] = ['url' => $match['url'], 'title' => isset($match['title']) ? $match['title'] : ''];
                 $rm->Add($match[0], '');
             }
             $text = $rm->Replace($text);
         }
     }
     // images
     if (strpos($text, '![') !== false) {
         // find inline images
         if (preg_match_all('/!\\[(?<alt>[^][]*+)\\]\\((?<src>[^) ]++)(?: "(?<title>[^"]++)")?+\\)(?:{(?<extra>[^}]++)})?+/', $text, $matches, PREG_SET_ORDER)) {
             foreach ($matches as $match) {
                 $attr_str = $this->GetAttributeString($match, ['src' => true, 'alt' => true, 'title' => false], 'extra', $this->m_imageCallback);
                 $element = sprintf('<img%s />', $attr_str);
                 $rm->Add($match[0], $element);
             }
             $text = $rm->Replace($text);
         }
         // find ref images
         if (preg_match_all('/!\\[(?<alt>[^][]*+)\\]\\[(?<id>[^]]++)\\](?:{(?<extra>[^}]++)})?+/', $text, $matches, PREG_SET_ORDER)) {
             foreach ($matches as $match) {
                 $ref = $references[$match['id']];
                 $match['src'] = $ref['url'];
                 $match['title'] = $ref['title'];
                 $attr_str = $this->GetAttributeString($match, ['src' => true, 'alt' => true, 'title' => false], 'extra', $this->m_imageCallback);
                 $element = sprintf('<img%s />', $attr_str);
                 $rm->Add($match[0], $element);
             }
             $text = $rm->Replace($text);
         }
     }
     // find inline links
     if (preg_match_all('/\\[(?<text>[^][]*+)\\]\\((?<href>[^) ]++)(?: "(?<title>[^"]++)")?+\\)/', $text, $matches, PREG_SET_ORDER)) {
         foreach ($matches as $match) {
             $attr_str = $this->GetAttributeString($match, ['href' => true, 'title' => false], NULL, $this->m_linkCallback);
             $element = sprintf('<a%s>%s</a>', $attr_str, $match['text']);
             $rm->Add($match[0], $element);
         }
         $text = $rm->Replace($text);
     }
     // find ref links
     if (preg_match_all('/\\[(?<text>[^][]*+)\\] ?+\\[(?<id>[^]]*+)\\]/', $text, $matches, PREG_SET_ORDER)) {
         foreach ($matches as $match) {
             $id = $match['id'];
             // implicit link name
             empty($id) and $id = strtolower($match['text']);
             $ref = $references[$id];
             $match['href'] = $ref['url'];
             $match['title'] = $ref['title'];
             $attr_str = $this->GetAttributeString($match, ['href' => true, 'title' => false], NULL, $this->m_linkCallback);
             $element = sprintf('<a%s>%s</a>', $attr_str, $match['text']);
             $rm->Add($match[0], $element);
         }
         $text = $rm->Replace($text);
     }
     // find footnote links
     if ($footnotes) {
         if (preg_match_all('/\\[\\^(?<id>[^]]++)\\]/', $text, $matches, PREG_SET_ORDER)) {
             $i = 1;
             foreach ($matches as $match) {
                 $id = $match['id'];
                 if (!isset($footnotes[$id])) {
                     continue;
                 }
                 if (!isset($footnotes[$id]['index'])) {
                     $footnotes[$id]['index'] = $i;
                 }
                 $element = sprintf('<sup id="fnref-%1$d"><a href="#fn-%1$d" class="footnote-ref">%1$d</a></sup>', $i);
                 $rm->Add($match[0], $element);
                 ++$i;
             }
             $text = $rm->Replace($text);
         }
     }
     // find horizontal rule
     if (preg_match_all('/^( ?+\\*){3}$/m', $text, $matches, PREG_SET_ORDER)) {
         foreach ($matches as $match) {
             $element = '<hr />';
             $rm->Add($match[0], $element);
         }
         $text = $rm->Replace($text);
     }
     // header underline characters?
     // =-`:'"~^_*+#<>
     // or just these for now?
     // =-*
     // header underlines
     if (preg_match_all('/^(?<text>[^\\s].*+)\\n(?<underline>[-=*]{4,})$/m', $text, $matches, PREG_SET_ORDER)) {
         // map chars to h1-6 (as available) by order of first occurrance
         foreach ($matches as $match) {
             if (strlen($match['underline']) < strlen($match['text'])) {
                 continue;
             }
             $underline_char = $match['underline'][0];
             if (isset($header_map[$underline_char])) {
                 $header_level = $header_map[$underline_char];
             } else {
                 $header_level = $this->m_headerLevel + count($header_map);
                 $header_map[$underline_char] = $header_level;
             }
             $element = sprintf('<h%1$d>%2$s</h%1$d>', $header_level, $match['text']);
             $rm->Add($match[0], $element, 'block');
         }
         $text = $rm->Replace($text);
     }
     // remove extra line terminators and whitespace on empty lines
     $text = preg_replace('/\\n\\s+\\n/', "\n\n", $text);
     // parse
     $lines = explode("\n", $text);
     $elements = $this->ParseBlockElements($lines);
     $text = $this->RenderElements($elements);
     // restore extracted content
     $text = $rm->Reconstitute($text);
     // restore nested content
     $text = $rm->Reconstitute($text);
     // restore escaped characters
     $text = strtr($text, $escape_sequence_map);
     // append footnotes
     if (count($footnotes)) {
         $footnote_list = '';
         foreach ($footnotes as $id => $footnote) {
             if (isset($footnote['index'])) {
                 $footnote_list .= sprintf('<li id="fn-%2$d"><p>%1$s<a href="#fnref-%2$d" class="footnote-backref">&#8617;</a></p></li>', $footnote['text'], $footnote['index']);
             }
         }
         $text .= sprintf('<div class="footnotes"><ol>%s</ol></div>', $footnote_list);
     }
     return $text;
 }
Ejemplo n.º 12
0
    echo PHP_EOL, 'It reads input from stdin, and outputs content on stdout.', PHP_EOL;
    echo PHP_EOL, 'It will derive "Pass" into a file in local directory appended with ".php" ("Pass.php"). Make sure it inherits from SandboxedPass.', PHP_EOL;
}
$getoptLongOptions = ['help', 'pass::'];
if ($inPhar) {
    $getoptLongOptions[] = 'version';
}
$opts = getopt('h', $getoptLongOptions);
if (isset($opts['version'])) {
    if ($inPhar) {
        echo $argv[0], ' ', VERSION, PHP_EOL;
    }
    exit(0);
}
if (!isset($opts['pass'])) {
    fwrite(STDERR, 'pass is not declared. cannot run.');
    exit(1);
}
$pass = sprintf('%s.php', basename($opts['pass']));
if (!file_get_contents($pass)) {
    fwrite(STDERR, sprintf('pass file "%s" is not found. cannot run.', $pass));
    exit(1);
}
include $pass;
if (isset($opts['h']) || isset($opts['help'])) {
    showHelp($argv, $enableCache, $inPhar);
    exit(0);
}
$fmt = new CodeFormatter(basename($opts['pass']));
echo $fmt->formatCode(file_get_contents('php://stdin'));
exit(0);