Subversion Repositories PHPX

Rev

Blame | Last modification | View Log | RSS feed

1
<?php

namespace de\pointedears\css\least;

require_once 'Base.php';

require_once 'Parser.php';

define('DEBUG', 2);

/**
 * @author Thomas 'PointedEars' Lahn
 */

class LEAST
{
  /**
   * Default name of parsed file
   *
   * @var string
   */

  protected $_filename;
 
  /**
   * Default name of parsed file
   *
   * @param string $filename
   */

  public function __construct ($code = null)
  {
    if ($code !== null)
    {
       $this->_code = $code;
    }
  }
 
  /**
   * Gets a template variable or a property
   *
   * @param string $name
   * @throws InvalidArgumentException
   * @return mixed
   */

  public function __get($name)
  {
    if (property_exists($this, "_$name"))
    {
      return $this->{"_$name"};
    }
   
    if (array_key_exists($name, $this->_vars))
    {
      return $this->_vars[$name];
    }
   
    throw new InvalidArgumentException("no property '{$name}'");
  }
 
  /**
   * Sets a template variable
   *
   * @param string $name
   * @param mixed $value
   */

  public function __set($name, $value)
  {
    $this->_vars[$name] = $value;
  }
 
  /**
   * Replaces characters in LEAST source code
   *
   * @param string $count
   *   Number of characters to replace
   * @param string $replacement
   *   Replacement string
   * @param string $haystack
   *   String to be searched
   * @param int $start
   *   Start replace from here
   * @return string
   */

  protected static function replace ($count, $replacement, $haystack, $start)
  {
    return substr($haystack, 0, $start) . $replacement . substr($haystack, $start + $count);
  }
 
  /**
   * Parses LEAST source code, replacing special tokens, and returns the result
   *
   * @param string[optional] $code
   * @return string
   */

  public function parse ($code = null)
  {
    if ($code === null)
    {
      $code = $this->_code;
    }

    static $nl = 'n';

    \mb_internal_encoding(mb_detect_encoding($code));
    $parser = new \de\pointedears\css\least\Parser($code);
    $parser->parse();

    return $parser->compiled;
//     return $code;
  }
 
  /**
   * Parses a LEAST file and returns the result
   *
   * @param string $filename
   * @return string
   */

  public function parse_file ($filename = null)
  {
    $contents = file_get_contents(
      $filename === null ? $this->filename : $filename);
    return $this->parse($contents);
  }
 
  /**
   * Compiles a CSS file from a LEAST file
   *
   * @param string $source
   * @param string $target
   */

  public static function compile ($source, $target)
  {
    if (@filemtime($target) < @filemtime($source))
    {
      $least = new self();
      file_put_contents($target, $least->parse_file($source));
    }
  }
}