Skip to content

Instantly share code, notes, and snippets.

@justinrainbow
Created April 8, 2011 19:48
Show Gist options
  • Save justinrainbow/910577 to your computer and use it in GitHub Desktop.
Save justinrainbow/910577 to your computer and use it in GitHub Desktop.
Runs through a bunch of *.tpl files to update syntax from Smarty2 to Smarty3 -- no whitespace around tags
<?php
$dir = new RecursiveDirectoryIterator(dirname(__FILE__));
$iterator = new RecursiveIteratorIterator($dir);
$pattern = '~\{(.+?)\}~im';
$start_char = '{';
$end_char = '}';
class FileParser implements Iterator
{
private $position = 0;
private $contents = null;
public function __construct($contents) {
$this->position = 0;
$this->contents = $contents;
}
function rewind() {
$this->position = 0;
}
function current() {
return $this->contents{$this->position};
}
function key() {
return $this->position;
}
function next() {
++$this->position;
}
function valid() {
return isset($this->contents{$this->position});
}
function moveTo($char) {
while ($this->valid()) {
if ($this->current() === $char) {
return $this->current();
}
$this->next();
}
return false;
}
function captureUntil($char) {
$chars = '';
while ($this->valid()) {
$chars .= $this->current();
if ($this->current() === $char) {
return $chars;
}
$this->next();
}
return $chars;
}
}
foreach (new RegexIterator($iterator, '/^.+\.tpl$/i', RecursiveRegexIterator::GET_MATCH) AS $tpl) {
$contents = file_get_contents($tpl[0]);
printf("Checking: %s\n", str_replace(dirname(__FILE__), '', $tpl[0]));
$parser = new FileParser($contents);
$dirty = false;
while ($parser->moveTo($start_char) !== false) {
$start = $parser->key();
$tag = $parser->captureUntil($end_char);
if ($tag == '{literal}') {
while ($tag !== '{/literal}') {
if ($parser->moveTo($start_char) === false) {
break;
}
$tag = $parser->captureUntil($end_char);
}
break;
}
$tagContents = substr($tag, 1, -1);
if (trim($tagContents) === $tagContents) {
// no whitespace == all good
continue;
}
$end = $parser->key();
$newTag = sprintf('{%s}', trim($tagContents));
$contents = str_replace($tag, $newTag, $contents);
$dirty = true;
}
if ($dirty === true) {
file_put_contents($tpl[0], $contents);
printf("Fixed: %s\n", str_replace(dirname(__FILE__), '', $tpl[0]));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment