#!/usr/bin/php
<?php
/**
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * @package smarty-lint
 * @link http://github.com/mofodojodino/smarty-lint/
 * @author Jon Ursenbach <jon@ursenba.ch>
 * @author Dean Tedesco <dino@tedesco.net.au>
 * @version 3.0.0
 */

error_reporting(E_ALL);

if (!defined('PHP_VERSION')) {
  $version = 0;
} else {
  $version = $version{0} = $version = PHP_VERSION;
}

if ($version < 5) {
  echo "Error:\nsmarty-lint is only compatible with PHP 5 and greater.\n";
  exit;
}

$me = array_shift($_SERVER['argv']);
if (count($_SERVER['argv']) < 1) {
  echo "Usage:\n" . $me . " <template> <show all errors [y\\n]>\n";
  exit;
}

$template = array_shift($_SERVER['argv']);
if (!file_exists($template)) {
  echo "Error:\n" . $template . " does not exist\n";
  exit;
}

$template = realpath($template);

$show_all_errors = strtolower(array_shift($_SERVER['argv']));
$show_all_errors = (empty($show_all_errors) || $show_all_errors == 'n') ? false : true;

require_once __DIR__.'/vendor/autoload.php';

class smarty_lint extends Smarty {
    static public $lint_errors = array();
    static public $lint_file = '';
    static public $lint_result = '';
    static public $show_all_errors;

    public function __construct() {
        parent::__construct();

        /* Turn Smarty template caching off */
        $this->caching = self::CACHING_OFF;
    }

    /** {@inheritdoc} */
    public function fetch($template = null, $cache_id = NULL, $compile_id = NULL, $parent = NULL) {
        try {
            self::$lint_file = $template;
            parent::fetch($template, null, null, false);
            $this->remove_compiled_template($template);
        } catch (SmartyCompilerException $e) {
            self::$lint_errors[] = array(
                'errno' => $e->getCode(),
                'errstr' => $e->getMessage(),
                'errfile' => $e->getFile(),
                'errline' => $e->getLine()
            );
        }
    }

    /**
     * Remove the template that was just compiled, no need to let it sitting
     * around collecting template-dust.
     *
     * @param string $template
     */
    private function remove_compiled_template($template) {
        foreach (glob($this->compile_dir . '/*' . basename($template) . '*') as $c) {
            if (file_exists($c)) {
                unlink($c);
            }
        }
    }

    /**
     * Custom error handler so we can parse out errors triggered deep inside
     * the Smarty compiling classes.
     *
     * @param const $errno
     * @param string $errstr
     * @param string $errfile
     * @param int $errline
     * @return bool
     */
    static public function check_errors($errno, $errstr, $errfile, $errline) {
        switch ($errno) {
            case 'E_USER_ERROR':
            default:
                if (!self::$show_all_errors) {
                    if ($errno !== E_USER_ERROR) {
                        return true;
                    }
                }

                self::$lint_errors[] = array(
                    'errno' => $errno,
                    'errstr' => $errstr,
                    'errfile' => $errfile,
                    'errline' => $errline
                );
                break;
        }
    }

    /**
     * Shutdown smarty-lint and display errors (if any). If no errors, alert
     * the user to a successful template compile.
     *
     */
    static public function shutdown() {
        ob_end_clean();

        if (!empty(self::$lint_file)) {
            if (count(self::$lint_errors) > 0) {
                foreach (self::$lint_errors as $err) {
                    self::$lint_result .= $err['errstr'] . "\n";
                }
            } else {
                self::$lint_result = 'No errors present in ' . self::$lint_file . "\n";
            }

            echo self::$lint_result;
        }
    }
}

ob_start();

set_error_handler(array('smarty_lint', 'check_errors'));
register_shutdown_function(array('smarty_lint', 'shutdown'));

$smarty_lint = new smarty_lint;
$smarty_lint->setTemplateDir(dirname($template));
$smarty_lint->setCompileDir(dirname(__FILE__) . '/smarty/templates_c');

smarty_lint::$show_all_errors = $show_all_errors;

$smarty_lint->fetch($template);
