Less 4.2.0(2.5.3)

https://github.com/wikimedia/less.php/releases/tag/v4.2.0
This commit is contained in:
gtbu 2024-02-19 21:47:59 +01:00
parent f3c4a92eb4
commit aee10265f0
127 changed files with 12870 additions and 900 deletions

View file

@ -0,0 +1,2 @@
.easymin
Autoloader.php

View file

@ -19,7 +19,7 @@ class Less_Autoloader {
return;
}
if ( !spl_autoload_register( [ 'Less_Autoloader', 'loadClass' ] ) ) {
if ( !spl_autoload_register( [ __CLASS__, 'loadClass' ] ) ) {
throw new Exception( 'Unable to register Less_Autoloader::loadClass as an autoloading method.' );
}
@ -32,7 +32,7 @@ class Less_Autoloader {
* @return void
*/
public static function unregister() {
spl_autoload_unregister( [ 'Less_Autoloader', 'loadClass' ] );
spl_autoload_unregister( [ __CLASS__, 'loadClass' ] );
self::$registered = false;
}

View file

@ -1,8 +1,53 @@
# Changelog
## 4.2.0
Added:
* Add `isruleset()` function (Hannah Okwelum) [T354895](https://phabricator.wikimedia.org/T354895)
* Add source details to "Operation on an invalid type" error (Hannah Okwelum) [T344197](https://phabricator.wikimedia.org/T344197)
* Add support for `method=relative` parameter in color functions (Hannah Okwelum) [T354895](https://phabricator.wikimedia.org/T354895)
* Add support for comments in variables and function parameters (Hannah Okwelum) [T354895](https://phabricator.wikimedia.org/T354895)
* Less_Parser: Add `functions` parser option API (Hannah Okwelum)
Changed, to match Less.js 2.5.3:
* Preserve original color keywords and shorthand hex (Hannah Okwelum) [T352866](https://phabricator.wikimedia.org/T352866)
Fixed:
* Fix PHP Warning when using a dynamic variable name like `@@name` (Hannah Okwelum) [T352830](https://phabricator.wikimedia.org/T352830)
* Fix PHP Warning when `@extend` path contains non-quoted attribute (Gr8b) [T349433](https://phabricator.wikimedia.org/T349433)
* Less_Parser: Faster `skipWhitespace` by using native `strspn` (Umherirrender)
* Less_Parser: Fix Less_Tree_JavaScript references to consistently be in camel-case (Stefan Fröhlich)
* Fix `!important` in nested mixins (Hannah Okwelum) [T353141](https://phabricator.wikimedia.org/T353141)
* Fix crash when using recursive mixins (Timo Tijhof) [T352829](https://phabricator.wikimedia.org/T352829)
* Fix disappearing selectors in certain nested blocks (Hannah Okwelum) [T352859](https://phabricator.wikimedia.org/T352859)
* Fix Less_Exception_Compiler when passing unquoted value to `color()` (Hannah Okwelum) [T353289](https://phabricator.wikimedia.org/T353289)
* Fix order of comments in `@font-face` blocks (Timo Tijhof) [T356706](https://phabricator.wikimedia.org/T356706)
* Fix string comparison to ignore quote type (Timo Tijhof) [T357160](https://phabricator.wikimedia.org/T357160)
* Fix string interpolation in selectors (Hannah Okwelum) [T353142](https://phabricator.wikimedia.org/T353142)
## 4.1.1
* Less_Parser: Faster `MatchQuoted` by using native `strcspn`. (Thiemo Kreuz)
* Less_Parser: Faster `parseEntitiesQuoted` by inlining `MatchQuoted`. (Thiemo Kreuz)
* Less_Parser: Faster `parseUnicodeDescriptor` and `parseEntitiesJavascript` by first-char checks. (Thiemo Kreuz)
* Less_Tree_Mixin_Call: Include mixin name in error message (Jeremy P)
* Fix mismatched casing in class names to fix autoloading on case-sensitive filesystems (Jeremy P)
## 4.1.0
* Add support for `@supports` blocks. (Anne Tomasevich) [T332923](http://phabricator.wikimedia.org/T332923)
* Less_Parser: Returning a URI from `SetImportDirs()` callbacks is now optional. (Timo Tijhof)
## 4.0.0
* Remove support for PHP 7.2 and 7.3. Raise requirement to PHP 7.4+.
* Remove support for `cache_method=php` and `cache_method=var_export`, only the faster and more secure `cache_method=serialize` is now available. The built-in cache remains disabled by default.
* Fix `url(#myid)` to be treated as absolute URL. [T331649](https://phabricator.wikimedia.org/T331688)
* Fix "Undefined property" PHP 8.1 warning when `calc()` is used with CSS `var()`. [T331688](https://phabricator.wikimedia.org/T331688)
* Less_Parser: Improve performance by removing MatchFuncs and NewObj overhead. (Timo Tijhof)
## 3.2.1
* [All changes](https://gerrit.wikimedia.org/g/mediawiki/libs/less.php/+log/v3.2.1)
* Tree_Ruleset: Fix support for nested parent selectors (Timo Tijhof) [T204816](https://phabricator.wikimedia.org/T204816)
* Fix ParseError when interpolating variable after colon in selector (Timo Tijhof) [T327163](https://phabricator.wikimedia.org/T327163)
* Functions: Fix "Undefined property" warning on bad minmax arg
@ -10,7 +55,6 @@
## 3.2.0
* [All changes](https://github.com/wikimedia/less.php/compare/v3.1.0...v3.2.0)
* Fix "Implicit conversion" PHP 8.1 warnings (Ayokunle Odusan)
* Fix "Creation of dynamic property" PHP 8.2 warnings (Bas Couwenberg)
* Fix "Creation of dynamic property" PHP 8.2 warnings (Rajesh Kumar)
@ -19,25 +63,21 @@
## 3.1.0
* [All changes](https://github.com/wikimedia/less.php/compare/v3.0.0...v3.1.0)
* Add PHP 8.0 support: Drop use of curly braces for sub-string eval (James D. Forrester)
* Make `Directive::__construct` $rules arg optional (fix PHP 7.4 warning) (Sam Reed)
* ProcessExtends: Improve performance by using a map for selectors and parents (Andrey Legayev)
## 3.0.0
* [All changes](https://github.com/wikimedia/less.php/compare/v2.0.0...v3.0.0)
* Raise PHP requirement from 7.1 to 7.2.9 (James Forrester)
## 2.0.0
* [All changes](https://github.com/wikimedia/less.php/compare/v1.8.2...v2.0.0)
* Relax PHP requirement down to 7.1, from 7.2.9 (Franz Liedke)
* Reflect recent breaking changes properly with the semantic versioning (James Forrester)
## 1.8.2
* [All changes](https://github.com/wikimedia/less.php/compare/v1.8.1...v1.8.2)
* Require PHP 7.2.9+, up from 5.3+ (James Forrester)
* release: Update Version.php with the current release ID (COBadger)
* Fix access array offset on value of type null (Michele Locati)
@ -45,38 +85,32 @@
## 1.8.1
* [All changes](https://github.com/wikimedia/less.php/compare/v1.8.0...v1.8.1)
* Another PHP 7.3 compatibility tweak
## 1.8.0
Library forked by Wikimedia, from [oyejorge/less.php](https://github.com/oyejorge/less.php).
* [All changes](https://github.com/wikimedia/less.php/compare/v1.7.0.13...v1.8.0)
* Supports up to PHP 7.3
* No longer tested against PHP 5, though it's still remains allowed in `composer.json` for HHVM compatibility
* Switched to [semantic versioning](https://semver.org/), hence version numbers now use 3 digits
## 1.7.0.13
* [All changes](https://github.com/wikimedia/less.php/compare/v1.7.0.12...v1.7.0.13)
* Fix composer.json (PSR-4 was invalid)
## 1.7.0.12
* [All changes](https://github.com/wikimedia/less.php/compare/v1.7.0.11...v1.7.0.12)
* set bin/lessc bit executable
* Add `gettingVariables` method to `Less_Parser`
## 1.7.0.11
* [All changes](https://github.com/wikimedia/less.php/compare/v1.7.0.10...v1.7.0.11)
* Fix realpath issue (windows)
* Set Less_Tree_Call property back to public ( Fix 258 266 267 issues from oyejorge/less.php)
## 1.7.0.10
* [All changes](https://github.com/wikimedia/less.php/compare/v1.7.0.9...v1.7.10)
* Add indentation option
* Add `optional` modifier for `@import`
* Fix $color in Exception messages
@ -86,6 +120,5 @@ Library forked by Wikimedia, from [oyejorge/less.php](https://github.com/oyejorg
## 1.7.0.9
* [All changes](https://github.com/wikimedia/less.php/compare/v1.7.0.8...v1.7.0.9)
* Remove space at beginning of Version.php
* Revert require() paths in test interface

View file

@ -5,16 +5,19 @@
*/
class Less_Cache {
// directory less.php can use for storing data
/** @var string|false Directory less.php can use for storing data */
public static $cache_dir = false;
// prefix for the storing data
/** @var string Prefix for the storing data */
public static $prefix = 'lessphp_';
// prefix for the storing vars
/** @var string Prefix for the storing vars */
public static $prefix_vars = 'lessphpvars_';
// specifies the number of seconds after which data created by less.php will be seen as 'garbage' and potentially cleaned up
/**
* @var int Specifies the number of seconds after which data created by less.php will be seen
* as 'garbage' and potentially cleaned up
*/
public static $gc_lifetime = 604800;
/**
@ -146,7 +149,7 @@ class Less_Cache {
$compiled = $parser->getCss();
$less_files = $parser->allParsedFiles();
$less_files = $parser->AllParsedFiles();
return $compiled;
}
@ -213,7 +216,7 @@ class Less_Cache {
// only remove files with extensions created by less.php
// css files removed based on the list files
$remove_types = [ 'lesscache' => 1,'list' => 1,'less' => 1,'map' => 1 ];
$remove_types = [ 'lesscache' => 1, 'list' => 1, 'less' => 1, 'map' => 1 ];
$files = scandir( self::$cache_dir );
if ( !$files ) {
@ -261,7 +264,7 @@ class Less_Cache {
/**
* Get the list of less files and generated css file from a list file
*/
static function ListFiles( $list_file, &$list, &$css_file_name ) {
public static function ListFiles( $list_file, &$list, &$css_file_name ) {
$list = explode( "\n", file_get_contents( $list_file ) );
// pop the cached name that should match $compiled_name

View file

@ -19,12 +19,7 @@ abstract class Less_Configurable {
protected $defaultOptions = [];
/**
* Set options
*
* If $options is an object it will be converted into an array by called
* it's toArray method.
*
* @param array|object $options
* @param array $options
*/
public function setOptions( $options ) {
$options = array_intersect_key( $options, $this->defaultOptions );

View file

@ -9,11 +9,11 @@ class Less_Environment {
*
* - rootpath: rootpath to append to URLs
*
* @var array|null $currentFileInfo;
* @var array|null
*/
public $currentFileInfo;
/* Whether we are currently importing multiple copies */
/** @var bool Whether we are currently importing multiple copies */
public $importMultiple = false;
/**
@ -21,14 +21,9 @@ class Less_Environment {
*/
public $frames = [];
/**
* @var array
*/
/** @var Less_Tree_Media[] */
public $mediaBlocks = [];
/**
* @var array
*/
/** @var Less_Tree_Media[] */
public $mediaPath = [];
public static $parensStack = 0;
@ -41,6 +36,8 @@ class Less_Environment {
public static $mixin_stack = 0;
public static $mathOn = true;
/**
* @var array
*/
@ -88,17 +85,29 @@ class Less_Environment {
}
public function copyEvalEnv( $frames = [] ) {
$new_env = new Less_Environment();
$new_env = new self();
$new_env->frames = $frames;
return $new_env;
}
/**
* @return bool
* @see Eval.prototype.isMathOn in less.js 3.0.0 https://github.com/less/less.js/blob/v3.0.0/dist/less.js#L1007
*/
public static function isMathOn() {
if ( !self::$mathOn ) {
return false;
}
return !Less_Parser::$options['strictMath'] || self::$parensStack;
}
/**
* @param string $path
* @return bool
* @see less-2.5.3.js#Eval.isPathRelative
*/
public static function isPathRelative( $path ) {
return !preg_match( '/^(?:[a-z-]+:|\/)/', $path );
return !preg_match( '/^(?:[a-z-]+:|\/|#)/', $path );
}
/**

View file

@ -43,6 +43,7 @@ class Less_Exception_Chunk extends Less_Exception_Parser {
$lastMultiComment = null;
$lastParen = null;
// phpcs:ignore Generic.CodeAnalysis.JumbledIncrementer
for ( $this->parserCurrentIndex = 0; $this->parserCurrentIndex < $this->input_len; $this->parserCurrentIndex++ ) {
$cc = $this->CharCode( $this->parserCurrentIndex );
if ( ( ( $cc >= 97 ) && ( $cc <= 122 ) ) || ( $cc < 34 ) ) {
@ -102,10 +103,12 @@ class Less_Exception_Chunk extends Less_Exception_Parser {
$currentChunkStartIndex = $this->parserCurrentIndex;
for ( $this->parserCurrentIndex += 1; $this->parserCurrentIndex < $this->input_len; $this->parserCurrentIndex++ ) {
$cc2 = $this->CharCode( $this->parserCurrentIndex );
if ( $cc2 > 96 ) { continue;
if ( $cc2 > 96 ) {
continue;
}
if ( $cc2 == $cc ) { $matched = 1;
break;
if ( $cc2 == $cc ) {
$matched = 1;
break;
}
if ( $cc2 == 92 ) { // \
if ( $this->parserCurrentIndex == $this->input_len - 1 ) {
@ -114,20 +117,23 @@ break;
$this->parserCurrentIndex++;
}
}
if ( $matched ) { break;
if ( $matched ) {
break;
}
return $this->fail( "unmatched `" . chr( $cc ) . "`", $currentChunkStartIndex );
// /, check for comment
case 47:
if ( $parenLevel || ( $this->parserCurrentIndex == $this->input_len - 1 ) ) { break;
if ( $parenLevel || ( $this->parserCurrentIndex == $this->input_len - 1 ) ) {
break;
}
$cc2 = $this->CharCode( $this->parserCurrentIndex + 1 );
if ( $cc2 == 47 ) {
// //, find lnfeed
for ( $this->parserCurrentIndex += 2; $this->parserCurrentIndex < $this->input_len; $this->parserCurrentIndex++ ) {
$cc2 = $this->CharCode( $this->parserCurrentIndex );
if ( ( $cc2 <= 13 ) && ( ( $cc2 == 10 ) || ( $cc2 == 13 ) ) ) { break;
if ( ( $cc2 <= 13 ) && ( ( $cc2 == 10 ) || ( $cc2 == 13 ) ) ) {
break;
}
}
} elseif ( $cc2 == 42 ) {
@ -135,11 +141,14 @@ break;
$lastMultiComment = $currentChunkStartIndex = $this->parserCurrentIndex;
for ( $this->parserCurrentIndex += 2; $this->parserCurrentIndex < $this->input_len - 1; $this->parserCurrentIndex++ ) {
$cc2 = $this->CharCode( $this->parserCurrentIndex );
if ( $cc2 == 125 ) { $lastMultiCommentEndBrace = $this->parserCurrentIndex;
if ( $cc2 == 125 ) {
$lastMultiCommentEndBrace = $this->parserCurrentIndex;
}
if ( $cc2 != 42 ) { continue;
if ( $cc2 != 42 ) {
continue;
}
if ( $this->CharCode( $this->parserCurrentIndex + 1 ) == 47 ) { break;
if ( $this->CharCode( $this->parserCurrentIndex + 1 ) == 47 ) {
break;
}
}
if ( $this->parserCurrentIndex == $this->input_len - 1 ) {

View file

@ -9,7 +9,7 @@ class Less_Functions {
public $env;
public $currentFileInfo;
function __construct( $env, array $currentFileInfo = null ) {
public function __construct( $env, array $currentFileInfo = null ) {
$this->env = $env;
$this->currentFileInfo = $currentFileInfo;
}
@ -75,7 +75,7 @@ class Less_Functions {
public function rgba( $r = null, $g = null, $b = null, $a = null ) {
$rgb = [ $r, $g, $b ];
$rgb = array_map( [ 'Less_Functions','scaled' ], $rgb );
$rgb = array_map( [ __CLASS__, 'scaled' ], $rgb );
$a = self::number( $a );
return new Less_Tree_Color( $rgb, $a );
@ -137,7 +137,7 @@ class Less_Functions {
$v = self::number( $v );
$a = self::number( $a );
$i = floor( (int)( $h / 60 ) % 6 );
$i = (int)floor( (int)( $h / 60 ) % 6 );
$f = ( $h / 60 ) - $i;
$vs = [
@ -170,7 +170,7 @@ class Less_Functions {
}
$c = $color->toHSL();
return new Less_Tree_Dimension( Less_Parser::round( $c['h'] ) );
return new Less_Tree_Dimension( $c['h'] );
}
public function saturation( $color = null ) {
@ -179,7 +179,7 @@ class Less_Functions {
}
$c = $color->toHSL();
return new Less_Tree_Dimension( Less_Parser::round( $c['s'] * 100 ), '%' );
return new Less_Tree_Dimension( $c['s'] * 100, '%' );
}
public function lightness( $color = null ) {
@ -188,7 +188,7 @@ class Less_Functions {
}
$c = $color->toHSL();
return new Less_Tree_Dimension( Less_Parser::round( $c['l'] * 100 ), '%' );
return new Less_Tree_Dimension( $c['l'] * 100, '%' );
}
public function hsvhue( $color = null ) {
@ -197,7 +197,7 @@ class Less_Functions {
}
$hsv = $color->toHSV();
return new Less_Tree_Dimension( Less_Parser::round( $hsv['h'] ) );
return new Less_Tree_Dimension( $hsv['h'] );
}
public function hsvsaturation( $color = null ) {
@ -206,7 +206,7 @@ class Less_Functions {
}
$hsv = $color->toHSV();
return new Less_Tree_Dimension( Less_Parser::round( $hsv['s'] * 100 ), '%' );
return new Less_Tree_Dimension( $hsv['s'] * 100, '%' );
}
public function hsvvalue( $color = null ) {
@ -215,7 +215,7 @@ class Less_Functions {
}
$hsv = $color->toHSV();
return new Less_Tree_Dimension( Less_Parser::round( $hsv['v'] * 100 ), '%' );
return new Less_Tree_Dimension( $hsv['v'] * 100, '%' );
}
public function red( $color = null ) {
@ -256,7 +256,7 @@ class Less_Functions {
throw new Less_Exception_Compiler( 'The first argument to luma must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) );
}
return new Less_Tree_Dimension( Less_Parser::round( $color->luma() * $color->alpha * 100 ), '%' );
return new Less_Tree_Dimension( $color->luma() * $color->alpha * 100, '%' );
}
public function luminance( $color = null ) {
@ -269,10 +269,10 @@ class Less_Functions {
+ ( 0.7152 * $color->rgb[1] / 255 )
+ ( 0.0722 * $color->rgb[2] / 255 );
return new Less_Tree_Dimension( Less_Parser::round( $luminance * $color->alpha * 100 ), '%' );
return new Less_Tree_Dimension( $luminance * $color->alpha * 100, '%' );
}
public function saturate( $color = null, $amount = null ) {
public function saturate( $color = null, $amount = null, $method = null ) {
// filter: saturate(3.2);
// should be kept as is, so check for color
if ( $color instanceof Less_Tree_Dimension ) {
@ -288,8 +288,11 @@ class Less_Functions {
$hsl = $color->toHSL();
$hsl['s'] += $amount->value / 100;
$hsl['s'] = self::clamp( $hsl['s'] );
if ( isset( $method ) && $method->value === "relative" ) {
$hsl['s'] += $hsl['s'] * $amount->value / 100;
} else {
$hsl['s'] += $amount->value / 100;
} $hsl['s'] = self::clamp( $hsl['s'] );
return $this->hsla( $hsl['h'], $hsl['s'], $hsl['l'], $hsl['a'] );
}
@ -298,7 +301,7 @@ class Less_Functions {
* @param Less_Tree_Color|null $color
* @param Less_Tree_Dimension|null $amount
*/
public function desaturate( $color = null, $amount = null ) {
public function desaturate( $color = null, $amount = null, $method = null ) {
if ( !$color instanceof Less_Tree_Color ) {
throw new Less_Exception_Compiler( 'The first argument to desaturate must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) );
}
@ -307,13 +310,19 @@ class Less_Functions {
}
$hsl = $color->toHSL();
$hsl['s'] -= $amount->value / 100;
if ( isset( $method ) && $method->value === "relative" ) {
$hsl['s'] -= $hsl['s'] * $amount->value / 100;
} else {
$hsl['s'] -= $amount->value / 100;
}
$hsl['s'] = self::clamp( $hsl['s'] );
return $this->hsla( $hsl['h'], $hsl['s'], $hsl['l'], $hsl['a'] );
}
public function lighten( $color = null, $amount = null ) {
public function lighten( $color = null, $amount = null, $method = null ) {
if ( !$color instanceof Less_Tree_Color ) {
throw new Less_Exception_Compiler( 'The first argument to lighten must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) );
}
@ -323,13 +332,18 @@ class Less_Functions {
$hsl = $color->toHSL();
$hsl['l'] += $amount->value / 100;
if ( isset( $method ) && $method->value === "relative" ) {
$hsl['l'] += $hsl['l'] * $amount->value / 100;
} else {
$hsl['l'] += $amount->value / 100;
}
$hsl['l'] = self::clamp( $hsl['l'] );
return $this->hsla( $hsl['h'], $hsl['s'], $hsl['l'], $hsl['a'] );
}
public function darken( $color = null, $amount = null ) {
public function darken( $color = null, $amount = null, $method = null ) {
if ( !$color instanceof Less_Tree_Color ) {
throw new Less_Exception_Compiler( 'The first argument to darken must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) );
}
@ -338,13 +352,17 @@ class Less_Functions {
}
$hsl = $color->toHSL();
$hsl['l'] -= $amount->value / 100;
if ( isset( $method ) && $method->value === "relative" ) {
$hsl['l'] -= $hsl['l'] * $amount->value / 100;
} else {
$hsl['l'] -= $amount->value / 100;
}
$hsl['l'] = self::clamp( $hsl['l'] );
return $this->hsla( $hsl['h'], $hsl['s'], $hsl['l'], $hsl['a'] );
}
public function fadein( $color = null, $amount = null ) {
public function fadein( $color = null, $amount = null, $method = null ) {
if ( !$color instanceof Less_Tree_Color ) {
throw new Less_Exception_Compiler( 'The first argument to fadein must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) );
}
@ -353,12 +371,18 @@ class Less_Functions {
}
$hsl = $color->toHSL();
$hsl['a'] += $amount->value / 100;
if ( isset( $method ) && $method->value === "relative" ) {
$hsl['a'] += $hsl['a'] * $amount->value / 100;
} else {
$hsl['a'] += $amount->value / 100;
}
$hsl['a'] = self::clamp( $hsl['a'] );
return $this->hsla( $hsl['h'], $hsl['s'], $hsl['l'], $hsl['a'] );
}
public function fadeout( $color = null, $amount = null ) {
public function fadeout( $color = null, $amount = null, $method = null ) {
if ( !$color instanceof Less_Tree_Color ) {
throw new Less_Exception_Compiler( 'The first argument to fadeout must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) );
}
@ -367,7 +391,13 @@ class Less_Functions {
}
$hsl = $color->toHSL();
$hsl['a'] -= $amount->value / 100;
if ( isset( $method ) && $method->value === "relative" ) {
$hsl['a'] -= $hsl['a'] * $amount->value / 100;
} else {
$hsl['a'] -= $amount->value / 100;
}
$hsl['a'] = self::clamp( $hsl['a'] );
return $this->hsla( $hsl['h'], $hsl['s'], $hsl['l'], $hsl['a'] );
}
@ -498,7 +528,7 @@ class Less_Functions {
}
public function escape( $str ) {
$revert = [ '%21' => '!', '%2A' => '*', '%27' => "'",'%3F' => '?','%26' => '&','%2C' => ',','%2F' => '/','%40' => '@','%2B' => '+','%24' => '$' ];
$revert = [ '%21' => '!', '%2A' => '*', '%27' => "'", '%3F' => '?', '%26' => '&', '%2C' => ',', '%2F' => '/', '%40' => '@', '%2B' => '+', '%24' => '$' ];
return new Less_Tree_Anonymous( strtr( rawurlencode( $str->value ), $revert ) );
}
@ -514,52 +544,44 @@ class Less_Functions {
if ( $flags && $flags->value ) {
$expr .= self::replace_flags( $flags->value );
}
$replacement = ( $replacement instanceof Less_Tree_Quoted ) ?
$replacement->value : $replacement->toCSS();
$result = preg_replace( $expr, $replacement->value, $result );
$result = preg_replace( $expr, $replacement, $result, 1 );
if ( property_exists( $string, 'quote' ) ) {
if ( $flags && $flags->value && preg_match( '/g/', $flags->value ) ) {
$result = preg_replace( $expr, $replacement, $result );
}
if ( $string instanceof Less_Tree_Quoted ) {
return new Less_Tree_Quoted( $string->quote, $result, $string->escaped );
}
return new Less_Tree_Quoted( '', $result );
}
public static function replace_flags( $flags ) {
$flags = str_split( $flags, 1 );
$new_flags = '';
foreach ( $flags as $flag ) {
switch ( $flag ) {
case 'e':
case 'g':
break;
default:
$new_flags .= $flag;
break;
}
}
return $new_flags;
return str_replace( [ 'e', 'g' ], '', $flags );
}
public function _percent() {
$string = func_get_arg( 0 );
$args = func_get_args();
array_shift( $args );
public function _percent( $string, ...$args ) {
$result = $string->value;
foreach ( $args as $arg ) {
if ( preg_match( '/%[sda]/i', $result, $token ) ) {
$token = $token[0];
$value = stristr( $token, 's' ) ? $arg->value : $arg->toCSS();
$value = ( ( $arg instanceof Less_Tree_Quoted ) &&
stristr( $token, 's' ) ? $arg->value : $arg->toCSS() );
$value = preg_match( '/[A-Z]$/', $token ) ? urlencode( $value ) : $value;
$result = preg_replace( '/%[sda]/i', $value, $result, 1 );
}
}
$result = str_replace( '%%', '%', $result );
return new Less_Tree_Quoted( $string->quote, $result, $string->escaped );
if ( $string instanceof Less_Tree_Quoted ) {
return new Less_Tree_Quoted( $string->quote, $result, $string->escaped );
}
return new Less_Tree_Quoted( '', $result );
}
public function unit( $val, $unit = null ) {
@ -589,7 +611,7 @@ class Less_Functions {
$fraction = $f->value;
}
return $this->_math( 'Less_Parser::round', null, $n, $fraction );
return $this->_math( [ Less_Parser::class, 'round' ], null, $n, $fraction );
}
public function pi() {
@ -617,7 +639,7 @@ class Less_Functions {
}
public function floor( $n ) {
return $this->_math( 'floor', null, $n );
return $this->_math( 'floor', null, $n );
}
public function sqrt( $n ) {
@ -652,22 +674,17 @@ class Less_Functions {
return $this->_math( 'acos', 'rad', $n );
}
private function _math() {
$args = func_get_args();
$fn = array_shift( $args );
$unit = array_shift( $args );
private function _math( $fn, $unit, ...$args ) {
if ( $args[0] instanceof Less_Tree_Dimension ) {
if ( $unit === null ) {
$unit = $args[0]->unit;
} else {
$args[0] = $args[0]->unify();
}
$args[0] = (float)$args[0]->value;
return new Less_Tree_Dimension( call_user_func_array( $fn, $args ), $unit );
return new Less_Tree_Dimension( $fn( ...$args ), $unit );
} elseif ( is_numeric( $args[0] ) ) {
return call_user_func_array( $fn, $args );
return $fn( ...$args );
} else {
throw new Less_Exception_Compiler( "math functions take numbers as parameters" );
}
@ -697,9 +714,7 @@ class Less_Functions {
for ( $i = 0; $i < $arg_count; $i++ ) {
$current = $args[$i];
if ( !( $current instanceof Less_Tree_Dimension ) ) {
// @phan-suppress-next-line PhanUndeclaredProperty Checked Less_Tree->value
if ( property_exists( $args[$i], 'value' ) && is_array( $args[$i]->value ) ) {
// @phan-suppress-next-line PhanUndeclaredProperty Checked Less_Tree->value
if ( $args[$i] instanceof Less_Tree_HasValueProperty && is_array( $args[$i]->value ) ) {
$args[] = $args[$i]->value;
}
continue;
@ -763,13 +778,11 @@ class Less_Functions {
return new Less_Tree_Anonymous( ( $isMin ? 'min(' : 'max(' ) . implode( Less_Environment::$_outputMap[','], $args ) . ')' );
}
public function min() {
$args = func_get_args();
public function min( ...$args ) {
return $this->_minmax( true, $args );
}
public function max() {
$args = func_get_args();
public function max( ...$args ) {
return $this->_minmax( false, $args );
}
@ -789,40 +802,48 @@ class Less_Functions {
return new Less_Tree_Dimension( $n->value * 100, '%' );
}
public function color( $n ) {
if ( $n instanceof Less_Tree_Quoted ) {
$colorCandidate = $n->value;
$returnColor = Less_Tree_Color::fromKeyword( $colorCandidate );
if ( $returnColor ) {
return $returnColor;
}
if ( preg_match( '/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/', $colorCandidate ) ) {
return new Less_Tree_Color( substr( $colorCandidate, 1 ) );
}
throw new Less_Exception_Compiler( "argument must be a color keyword or 3/6 digit hex e.g. #FFF" );
} else {
throw new Less_Exception_Compiler( "argument must be a string" );
/**
* @see less-2.5.3.js#colorFunctions.color
* @param Less_Tree_Quoted|Less_Tree_Color|Less_Tree_Keyword $c
* @return Less_Tree_Color
*/
public function color( $c ) {
if ( ( $c instanceof Less_Tree_Quoted ) &&
preg_match( '/^#([a-f0-9]{6}|[a-f0-9]{3})/', $c->value )
) {
return new Less_Tree_Color( substr( $c->value, 1 ) );
}
if ( ( $c instanceof Less_Tree_Color ) || ( $c = Less_Tree_Color::fromKeyword( $c->value ) ) ) {
$c->value = null;
return $c;
}
throw new Less_Exception_Compiler( "argument must be a color keyword or 3/6 digit hex e.g. #FFF" );
}
public function isruleset( $n ) {
return new Less_Tree_Keyword( $n instanceof Less_Tree_DetachedRuleset ? 'true' : 'false' );
}
public function iscolor( $n ) {
return $this->_isa( $n, 'Less_Tree_Color' );
return new Less_Tree_Keyword( $n instanceof Less_Tree_Color ? 'true' : 'false' );
}
public function isnumber( $n ) {
return $this->_isa( $n, 'Less_Tree_Dimension' );
return new Less_Tree_Keyword( $n instanceof Less_Tree_Dimension ? 'true' : 'false' );
}
public function isstring( $n ) {
return $this->_isa( $n, 'Less_Tree_Quoted' );
return new Less_Tree_Keyword( $n instanceof Less_Tree_Quoted ? 'true' : 'false' );
}
public function iskeyword( $n ) {
return $this->_isa( $n, 'Less_Tree_Keyword' );
return new Less_Tree_Keyword( $n instanceof Less_Tree_Keyword ? 'true' : 'false' );
}
public function isurl( $n ) {
return $this->_isa( $n, 'Less_Tree_Url' );
return new Less_Tree_Keyword( $n instanceof Less_Tree_Url ? 'true' : 'false' );
}
public function ispixel( $n ) {
@ -842,20 +863,11 @@ class Less_Functions {
* @param Less_Tree|string $unit
*/
public function isunit( $n, $unit ) {
if ( is_object( $unit ) && property_exists( $unit, 'value' ) ) {
// @phan-suppress-next-line PhanUndeclaredProperty Checked Less_Tree->value
if ( $unit instanceof Less_Tree_Keyword || $unit instanceof Less_Tree_Quoted ) {
$unit = $unit->value;
}
return ( $n instanceof Less_Tree_Dimension ) && $n->unit->is( $unit ) ? new Less_Tree_Keyword( 'true' ) : new Less_Tree_Keyword( 'false' );
}
/**
* @param Less_Tree $n
* @param string $type
*/
private function _isa( $n, $type ) {
return is_a( $n, $type ) ? new Less_Tree_Keyword( 'true' ) : new Less_Tree_Keyword( 'false' );
return new Less_Tree_Keyword( $n instanceof Less_Tree_Dimension && $n->unit->is( $unit ) ? 'true' : 'false' );
}
public function tint( $color, $amount = null ) {
@ -870,7 +882,7 @@ class Less_Functions {
$index = (int)$index->value - 1; // (1-based index)
// handle non-array values as an array of length 1
// return 'undefined' if index is invalid
if ( property_exists( $values, 'value' ) && is_array( $values->value ) ) {
if ( !( $values instanceof Less_Tree_Color ) && is_array( $values->value ) ) {
if ( isset( $values->value[$index] ) ) {
return $values->value[$index];
}
@ -884,7 +896,8 @@ class Less_Functions {
}
public function length( $values ) {
$n = ( property_exists( $values, 'value' ) && is_array( $values->value ) ) ? count( $values->value ) : 1;
$n = ( $values instanceof Less_Tree_Expression || $values instanceof Less_Tree_Value ) ?
count( $values->value ) : 1;
return new Less_Tree_Dimension( $n );
}
@ -931,7 +944,8 @@ class Less_Functions {
$charset = Less_Mime::charsets_lookup( $mimetype );
$useBase64 = !in_array( $charset, [ 'US-ASCII', 'UTF-8' ] );
if ( $useBase64 ) { $mimetype .= ';base64';
if ( $useBase64 ) {
$mimetype .= ';base64';
}
} else {
@ -962,15 +976,13 @@ class Less_Functions {
}
// svg-gradient
public function svggradient( $direction ) {
public function svggradient( $direction, ...$stops ) {
$throw_message = 'svg-gradient expects direction, start_color [start_position], [color position,]..., end_color [end_position]';
$arguments = func_get_args();
if ( count( $arguments ) < 3 ) {
if ( count( $stops ) < 2 ) {
throw new Less_Exception_Compiler( $throw_message );
}
$stops = array_slice( $arguments, 1 );
$gradientType = 'linear';
$rectangleDimension = 'x="0" y="0" width="1" height="1"';
$useBase64 = true;
@ -1004,7 +1016,8 @@ class Less_Functions {
'<' . $gradientType . 'Gradient id="gradient" gradientUnits="userSpaceOnUse" ' . $gradientDirectionSvg . '>';
for ( $i = 0; $i < count( $stops ); $i++ ) {
if ( is_object( $stops[$i] ) && property_exists( $stops[$i], 'value' ) ) {
if ( $stops[$i] instanceof Less_Tree_Expression ) {
$color = $stops[$i]->value[0];
$position = $stops[$i]->value[1];
} else {
@ -1034,7 +1047,7 @@ class Less_Functions {
$returner = "'data:image/svg+xml," . $returner . "'";
}
return new Less_Tree_URL( new Less_Tree_Anonymous( $returner ) );
return new Less_Tree_Url( new Less_Tree_Anonymous( $returner ) );
}
/**
@ -1061,7 +1074,7 @@ class Less_Functions {
for ( $i = 0; $i < 3; $i++ ) {
$cb = $color1->rgb[$i] / 255;
$cs = $color2->rgb[$i] / 255;
$cr = call_user_func( $mode, $cb, $cs );
$cr = $mode( $cb, $cs );
if ( $ar ) {
$cr = ( $as * $cs + $ab * ( $cb - $as * ( $cb + $cs - $cr ) ) ) / $ar;
}
@ -1079,7 +1092,7 @@ class Less_Functions {
throw new Less_Exception_Compiler( 'The second argument to multiply must be a color' . ( $color2 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) );
}
return $this->colorBlend( [ $this,'colorBlendMultiply' ], $color1, $color2 );
return $this->colorBlend( [ $this, 'colorBlendMultiply' ], $color1, $color2 );
}
private function colorBlendMultiply( $cb, $cs ) {
@ -1094,7 +1107,7 @@ class Less_Functions {
throw new Less_Exception_Compiler( 'The second argument to screen must be a color' . ( $color2 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) );
}
return $this->colorBlend( [ $this,'colorBlendScreen' ], $color1, $color2 );
return $this->colorBlend( [ $this, 'colorBlendScreen' ], $color1, $color2 );
}
private function colorBlendScreen( $cb, $cs ) {
@ -1109,7 +1122,7 @@ class Less_Functions {
throw new Less_Exception_Compiler( 'The second argument to overlay must be a color' . ( $color2 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) );
}
return $this->colorBlend( [ $this,'colorBlendOverlay' ], $color1, $color2 );
return $this->colorBlend( [ $this, 'colorBlendOverlay' ], $color1, $color2 );
}
private function colorBlendOverlay( $cb, $cs ) {
@ -1127,7 +1140,7 @@ class Less_Functions {
throw new Less_Exception_Compiler( 'The second argument to softlight must be a color' . ( $color2 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) );
}
return $this->colorBlend( [ $this,'colorBlendSoftlight' ], $color1, $color2 );
return $this->colorBlend( [ $this, 'colorBlendSoftlight' ], $color1, $color2 );
}
private function colorBlendSoftlight( $cb, $cs ) {
@ -1149,7 +1162,7 @@ class Less_Functions {
throw new Less_Exception_Compiler( 'The second argument to hardlight must be a color' . ( $color2 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) );
}
return $this->colorBlend( [ $this,'colorBlendHardlight' ], $color1, $color2 );
return $this->colorBlend( [ $this, 'colorBlendHardlight' ], $color1, $color2 );
}
private function colorBlendHardlight( $cb, $cs ) {
@ -1164,7 +1177,7 @@ class Less_Functions {
throw new Less_Exception_Compiler( 'The second argument to difference must be a color' . ( $color2 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) );
}
return $this->colorBlend( [ $this,'colorBlendDifference' ], $color1, $color2 );
return $this->colorBlend( [ $this, 'colorBlendDifference' ], $color1, $color2 );
}
private function colorBlendDifference( $cb, $cs ) {
@ -1179,7 +1192,7 @@ class Less_Functions {
throw new Less_Exception_Compiler( 'The second argument to exclusion must be a color' . ( $color2 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) );
}
return $this->colorBlend( [ $this,'colorBlendExclusion' ], $color1, $color2 );
return $this->colorBlend( [ $this, 'colorBlendExclusion' ], $color1, $color2 );
}
private function colorBlendExclusion( $cb, $cs ) {
@ -1194,7 +1207,7 @@ class Less_Functions {
throw new Less_Exception_Compiler( 'The second argument to average must be a color' . ( $color2 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) );
}
return $this->colorBlend( [ $this,'colorBlendAverage' ], $color1, $color2 );
return $this->colorBlend( [ $this, 'colorBlendAverage' ], $color1, $color2 );
}
// non-w3c functions:
@ -1210,7 +1223,7 @@ class Less_Functions {
throw new Less_Exception_Compiler( 'The second argument to negation must be a color' . ( $color2 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) );
}
return $this->colorBlend( [ $this,'colorBlendNegation' ], $color1, $color2 );
return $this->colorBlend( [ $this, 'colorBlendNegation' ], $color1, $color2 );
}
public function colorBlendNegation( $cb, $cs ) {

View file

@ -6,8 +6,11 @@
*/
class Less_Mime {
// this map is intentionally incomplete
// if you want more, install 'mime' dep
/**
* this map is intentionally incomplete
* if you want more, install 'mime' dep
* @var array<string,string>
*/
private static $types = [
'.htm' => 'text/html',
'.html' => 'text/html',

View file

@ -19,7 +19,7 @@ class Less_Output {
* @param string $chunk The chunk to output
* @param array|null $fileInfo The file information
* @param int $index The index
* @param mixed $mapLines
* @param bool|null $mapLines
*/
public function add( $chunk, $fileInfo = null, $index = 0, $mapLines = null ) {
$this->strs[] = $chunk;

View file

@ -52,7 +52,7 @@ class Less_Output_Mapped extends Less_Output {
* @param string $chunk
* @param array|null $fileInfo
* @param int $index
* @param mixed $mapLines
* @param bool|null $mapLines
*/
public function add( $chunk, $fileInfo = null, $index = 0, $mapLines = null ) {
// ignore adding empty strings
@ -84,19 +84,19 @@ class Less_Output_Mapped extends Less_Output {
if ( !$mapLines ) {
$this->generator->addMapping(
$this->lineNumber + 1, // generated_line
$this->column, // generated_column
count( $sourceLines ), // original_line
strlen( $sourceColumns ), // original_column
$this->lineNumber + 1, // generated_line
$this->column, // generated_column
count( $sourceLines ), // original_line
strlen( $sourceColumns ), // original_column
$fileInfo
);
} else {
for ( $i = 0, $count = count( $lines ); $i < $count; $i++ ) {
$this->generator->addMapping(
$this->lineNumber + $i + 1, // generated_line
$i === 0 ? $this->column : 0, // generated_column
count( $sourceLines ) + $i, // original_line
$i === 0 ? strlen( $sourceColumns ) : 0, // original_column
$this->lineNumber + $i + 1, // generated_line
$i === 0 ? $this->column : 0, // generated_column
count( $sourceLines ) + $i, // original_line
$i === 0 ? strlen( $sourceColumns ) : 0, // original_column
$fileInfo
);
}

File diff suppressed because it is too large Load diff

View file

@ -75,3 +75,8 @@ Less.php can be used with [Drupal's less module](https://drupal.org/project/less
## Credits
Less.php was originally ported to PHP in 2011 by [Matt Agar](https://github.com/agar) and then updated by [Martin Jantošovič](https://github.com/Mordred) in 2012. From 2013 to 2017, [Josh Schmidt](https://github.com/oyejorge) lead development of the library. Since 2019, the library is maintained by Wikimedia Foundation.
## Contribute
* Issue tracker: https://phabricator.wikimedia.org/tag/less.php/
* Source code: https://gerrit.wikimedia.org/g/mediawiki/libs/less.php ([Get started with Gerrit](https://www.mediawiki.org/wiki/Gerrit/Tutorial/tl;dr))

View file

@ -34,14 +34,14 @@ class Less_SourceMap_Base64VLQ {
*/
private $charToIntMap = [
'A' => 0, 'B' => 1, 'C' => 2, 'D' => 3, 'E' => 4, 'F' => 5, 'G' => 6,
'H' => 7,'I' => 8, 'J' => 9, 'K' => 10, 'L' => 11, 'M' => 12, 'N' => 13,
'H' => 7, 'I' => 8, 'J' => 9, 'K' => 10, 'L' => 11, 'M' => 12, 'N' => 13,
'O' => 14, 'P' => 15, 'Q' => 16, 'R' => 17, 'S' => 18, 'T' => 19, 'U' => 20,
'V' => 21, 'W' => 22, 'X' => 23, 'Y' => 24, 'Z' => 25, 'a' => 26, 'b' => 27,
'c' => 28, 'd' => 29, 'e' => 30, 'f' => 31, 'g' => 32, 'h' => 33, 'i' => 34,
'j' => 35, 'k' => 36, 'l' => 37, 'm' => 38, 'n' => 39, 'o' => 40, 'p' => 41,
'q' => 42, 'r' => 43, 's' => 44, 't' => 45, 'u' => 46, 'v' => 47, 'w' => 48,
'x' => 49, 'y' => 50, 'z' => 51, 0 => 52, 1 => 53, 2 => 54, 3 => 55, 4 => 56,
5 => 57, 6 => 58, 7 => 59, 8 => 60, 9 => 61, '+' => 62, '/' => 63,
5 => 57, 6 => 58, 7 => 59, 8 => 60, 9 => 61, '+' => 62, '/' => 63,
];
/**
@ -111,8 +111,7 @@ class Less_SourceMap_Base64VLQ {
public function encode( $aValue ) {
$encoded = '';
$vlq = $this->toVLQSigned( $aValue );
do
{
do {
$digit = $vlq & $this->mask;
$vlq = $this->zeroFill( $vlq, $this->shift );
if ( $vlq > 0 ) {
@ -133,8 +132,7 @@ class Less_SourceMap_Base64VLQ {
public function decode( $encoded ) {
$vlq = 0;
$i = 0;
do
{
do {
$digit = $this->base64Decode( $encoded[$i] );
$vlq |= ( $digit & $this->mask ) << ( $i * $this->shift );
$i++;
@ -163,7 +161,7 @@ class Less_SourceMap_Base64VLQ {
*/
public function base64Encode( $number ) {
if ( $number < 0 || $number > 63 ) {
throw new Exception( sprintf( 'Invalid number "%s" given. Must be between 0 and 63.', (string)$number ) );
throw new Exception( "Invalid number \"$number\" given. Must be between 0 and 63." );
}
return $this->intToCharMap[$number];
}

View file

@ -2,16 +2,9 @@
/**
* Tree
*
* TODO: Callers often use `property_exists(, 'value')` to distinguish
* tree nodes that are considerd value-holding. Refactor this to move
* the 'value' property that most subclasses implement to there, and use
* something else (special value, method, or intermediate class?) to
* signal whether a subclass is considered value-holding.
*/
class Less_Tree {
public $cache_string;
public $parensInOp = false;
public $extendOnEveryPath;
public $allExtends;
@ -71,6 +64,63 @@ class Less_Tree {
public function accept( $visitor ) {
}
/**
* @param Less_Tree $a
* @param Less_Tree $b
* @return int|null
* @see less-2.5.3.js#Node.compare
*/
public static function nodeCompare( $a, $b ) {
// Less_Tree subclasses that implement compare() are:
// Anonymous, Color, Dimension, Keyword, Quoted, Unit
if ( $b instanceof Less_Tree_Quoted || $b instanceof Less_Tree_Anonymous ) {
// for "symmetric results" force toCSS-based comparison via b.compare()
// of Quoted or Anonymous if either value is one of those
return -$b->compare( $a );
} elseif ( $a instanceof Less_Tree_Anonymous || $a instanceof Less_Tree_Color
|| $a instanceof Less_Tree_Dimension || $a instanceof Less_Tree_Keyword
|| $a instanceof Less_Tree_Quoted || $a instanceof Less_Tree_Unit
) {
return $a->compare( $b );
} elseif ( get_class( $a ) !== get_class( $b ) ) {
return null;
}
// Less_Tree subclasses that have an array value: Less_Tree_Expression, Less_Tree_Value
// @phan-suppress-next-line PhanUndeclaredProperty
$aval = $a->value ?? [];
// @phan-suppress-next-line PhanUndeclaredProperty
$bval = $b->value ?? [];
if ( !( $a instanceof Less_Tree_Expression || $a instanceof Less_Tree_Value ) ) {
return $aval === $bval ? 0 : null;
}
if ( count( $aval ) !== count( $bval ) ) {
return null;
}
foreach ( $aval as $i => $item ) {
if ( self::nodeCompare( $item, $bval[$i] ) !== 0 ) {
return null;
}
}
return 0;
}
/**
* @param string|float|int $a
* @param string|float|int $b
* @return int|null
* @see less-2.5.3.js#Node.numericCompare
*/
public static function numericCompare( $a, $b ) {
return $a < $b ? -1
: ( $a === $b ? 0
: ( $a > $b ? 1
// NAN is not greater, less, or equal
: null
)
);
}
public static function ReferencedArray( $rules ) {
foreach ( $rules as $rule ) {
if ( method_exists( $rule, 'markReferenced' ) ) {

View file

@ -2,9 +2,8 @@
/**
* @private
*/
class Less_Tree_Alpha extends Less_Tree {
class Less_Tree_Alpha extends Less_Tree implements Less_Tree_HasValueProperty {
public $value;
public $type = 'Alpha';
public function __construct( $val ) {
$this->value = $val;

View file

@ -1,43 +1,47 @@
<?php
/**
* @private
* @see less-2.5.3.js#Anonymous.prototype
*/
class Less_Tree_Anonymous extends Less_Tree {
class Less_Tree_Anonymous extends Less_Tree implements Less_Tree_HasValueProperty {
public $value;
public $quote;
public $index;
public $mapLines;
public $currentFileInfo;
public $type = 'Anonymous';
/** @var bool */
public $rulesetLike;
/**
* @param int $index
* @param string $value
* @param int|null $index
* @param array|null $currentFileInfo
* @param bool|null $mapLines
* @param bool $rulesetLike
*/
public function __construct( $value, $index = null, $currentFileInfo = null, $mapLines = null ) {
public function __construct( $value, $index = null, $currentFileInfo = null, $mapLines = null, $rulesetLike = false ) {
$this->value = $value;
$this->index = $index;
$this->mapLines = $mapLines;
$this->currentFileInfo = $currentFileInfo;
$this->rulesetLike = $rulesetLike;
}
public function compile( $env ) {
return new Less_Tree_Anonymous( $this->value, $this->index, $this->currentFileInfo, $this->mapLines );
return new self( $this->value, $this->index, $this->currentFileInfo, $this->mapLines );
}
/**
* @param Less_Tree|mixed $x
* @return int|null
* @see less-2.5.3.js#Anonymous.prototype.compare
*/
public function compare( $x ) {
if ( !is_object( $x ) ) {
return -1;
}
return ( is_object( $x ) && $this->toCSS() === $x->toCSS() ) ? 0 : null;
}
$left = $this->toCSS();
$right = $x->toCSS();
if ( $left === $right ) {
return 0;
}
return $left < $right ? -1 : 1;
public function isRulesetLike() {
return $this->rulesetLike;
}
/**

View file

@ -2,11 +2,10 @@
/**
* @private
*/
class Less_Tree_Assignment extends Less_Tree {
class Less_Tree_Assignment extends Less_Tree implements Less_Tree_HasValueProperty {
public $key;
public $value;
public $type = 'Assignment';
public function __construct( $key, $val ) {
$this->key = $key;
@ -18,7 +17,7 @@ class Less_Tree_Assignment extends Less_Tree {
}
public function compile( $env ) {
return new Less_Tree_Assignment( $this->key, $this->value->compile( $env ) );
return new self( $this->key, $this->value->compile( $env ) );
}
/**

View file

@ -2,12 +2,11 @@
/**
* @private
*/
class Less_Tree_Attribute extends Less_Tree {
class Less_Tree_Attribute extends Less_Tree implements Less_Tree_HasValueProperty {
public $key;
public $op;
public $value;
public $type = 'Attribute';
public function __construct( $key, $op, $value ) {
$this->key = $key;
@ -23,7 +22,7 @@ class Less_Tree_Attribute extends Less_Tree {
return $this;
}
return new Less_Tree_Attribute(
return new self(
$key_obj ? $this->key->compile( $env ) : $this->key,
$this->op,
$val_obj ? $this->value->compile( $env ) : $this->value );

View file

@ -1,19 +1,22 @@
<?php
/**
* @private
* @see less.tree.Call in less.js 3.0.0 https://github.com/less/less.js/blob/v3.0.0/dist/less.js#L6336
*/
class Less_Tree_Call extends Less_Tree {
class Less_Tree_Call extends Less_Tree implements Less_Tree_HasValueProperty {
public $value;
public $name;
public $args;
/** @var bool */
public $mathOn;
public $index;
public $currentFileInfo;
public $type = 'Call';
public function __construct( $name, $args, $index, $currentFileInfo = null ) {
$this->name = $name;
$this->args = $args;
$this->mathOn = ( $name !== 'calc' );
$this->index = $index;
$this->currentFileInfo = $currentFileInfo;
}
@ -24,38 +27,54 @@ class Less_Tree_Call extends Less_Tree {
//
// When evaluating a function call,
// we either find the function in `tree.functions` [1],
// in which case we call it, passing the evaluated arguments,
// or we simply print it out as it appeared originally [2].
// we either find the function in Less_Functions,
// in which case we call it, passing the evaluated arguments,
// or we simply print it out as it literal CSS.
//
// The *functions.js* file contains the built-in functions.
//
// The reason why we evaluate the arguments, is in the case where
// we try to pass a variable to a function, like: `saturate(@color)`.
// The reason why we compile the arguments, is in the case one
// of them is a LESS variable that only PHP knows the value of,
// like: `saturate(@mycolor)`.
// The function should receive the value, not the variable.
//
public function compile( $env = null ) {
// Turn off math for calc(). https://phabricator.wikimedia.org/T331688
$currentMathContext = Less_Environment::$mathOn;
Less_Environment::$mathOn = $this->mathOn;
$args = [];
foreach ( $this->args as $a ) {
$args[] = $a->compile( $env );
}
foreach ( $args as $key => $arg ) {
if ( $arg instanceof Less_Tree_Expression ) {
$arg->throwAwayComments();
if ( count( $arg->value ) === 1 ) {
$subNode = $arg->value[0];
array_splice( $args, $key, 1, [ $subNode ] );
}
}
}
Less_Environment::$mathOn = $currentMathContext;
$nameLC = strtolower( $this->name );
switch ( $nameLC ) {
case '%':
$nameLC = '_percent';
$nameLC = '_percent';
break;
case 'get-unit':
$nameLC = 'getunit';
$nameLC = 'getunit';
break;
case 'data-uri':
$nameLC = 'datauri';
$nameLC = 'datauri';
break;
case 'svg-gradient':
$nameLC = 'svggradient';
$nameLC = 'svggradient';
break;
}
@ -64,7 +83,7 @@ class Less_Tree_Call extends Less_Tree {
$result = Less_Tree_DefaultFunc::compile();
} else {
$func = null;
if ( method_exists( 'Less_Functions', $nameLC ) ) {
if ( method_exists( Less_Functions::class, $nameLC ) ) {
$functions = new Less_Functions( $env, $this->currentFileInfo );
$func = [ $functions, $nameLC ];
} elseif ( isset( $env->functions[$nameLC] ) && is_callable( $env->functions[$nameLC] ) ) {
@ -73,7 +92,7 @@ class Less_Tree_Call extends Less_Tree {
// If the function name isn't known to LESS, output it unchanged as CSS.
if ( $func ) {
try {
$result = call_user_func_array( $func, $args );
$result = $func( ...$args );
} catch ( Exception $e ) {
// Preserve original trace, especially from custom functions.
// https://github.com/wikimedia/less.php/issues/38
@ -90,7 +109,7 @@ class Less_Tree_Call extends Less_Tree {
return $result;
}
return new Less_Tree_Call( $this->name, $args, $this->index, $this->currentFileInfo );
return new self( $this->name, $args, $this->index, $this->currentFileInfo );
}
/**

View file

@ -6,15 +6,18 @@ class Less_Tree_Color extends Less_Tree {
public $rgb;
public $alpha;
public $isTransparentKeyword;
public $type = 'Color';
public $value;
public function __construct( $rgb, $a = 1, $isTransparentKeyword = null ) {
public function __construct( $rgb, $a = 1, $isTransparentKeyword = null, $originalForm = null ) {
if ( $isTransparentKeyword ) {
$this->rgb = $rgb;
$this->alpha = $a;
$this->isTransparentKeyword = true;
return;
}
if ( isset( $originalForm ) ) {
$this->value = $originalForm;
}
$this->rgb = [];
if ( is_array( $rgb ) ) {
@ -53,7 +56,9 @@ class Less_Tree_Color extends Less_Tree {
public function toCSS( $doNotCompress = false ) {
$compress = Less_Parser::$options['compress'] && !$doNotCompress;
$alpha = Less_Functions::fround( $this->alpha );
if ( $this->value ) {
return $this->value;
}
//
// If we have some transparency, the only way to represent it
// is via `rgba`. Otherwise, we use the hex representation,
@ -98,6 +103,7 @@ class Less_Tree_Color extends Less_Tree {
/**
* @param string $op
* @param self $other
*/
public function operate( $op, $other ) {
$rgb = [];
@ -105,7 +111,7 @@ class Less_Tree_Color extends Less_Tree {
for ( $c = 0; $c < 3; $c++ ) {
$rgb[$c] = Less_Functions::operate( $op, $this->rgb[$c], $other->rgb[$c] );
}
return new Less_Tree_Color( $rgb, $alpha );
return new self( $rgb, $alpha );
}
public function toRGB() {
@ -185,15 +191,20 @@ class Less_Tree_Color extends Less_Tree {
return $this->toHex( $argb );
}
/**
* @param mixed $x
* @return int|null
* @see less-2.5.3.js#Color.prototype.compare
*/
public function compare( $x ) {
if ( !property_exists( $x, 'rgb' ) ) {
if ( !$x instanceof self ) {
return -1;
}
return ( $x->rgb[0] === $this->rgb[0] &&
$x->rgb[1] === $this->rgb[1] &&
$x->rgb[2] === $this->rgb[2] &&
$x->alpha === $this->alpha ) ? 0 : -1;
$x->alpha === $this->alpha ) ? 0 : null;
}
public function toHex( $v ) {
@ -213,15 +224,20 @@ class Less_Tree_Color extends Less_Tree {
* @param string $keyword
*/
public static function fromKeyword( $keyword ) {
$keyword = strtolower( $keyword );
$c = $keyword = strtolower( $keyword );
if ( Less_Colors::hasOwnProperty( $keyword ) ) {
// detect named color
return new Less_Tree_Color( substr( Less_Colors::color( $keyword ), 1 ) );
$c = new self( substr( Less_Colors::color( $keyword ), 1 ) );
}
if ( $keyword === 'transparent' ) {
return new Less_Tree_Color( [ 0, 0, 0 ], 0, true );
$c = new self( [ 0, 0, 0 ], 0, true );
}
if ( isset( $c ) && is_object( $c ) ) {
$c->value = $keyword;
return $c;
}
}

View file

@ -2,13 +2,12 @@
/**
* @private
*/
class Less_Tree_Comment extends Less_Tree {
class Less_Tree_Comment extends Less_Tree implements Less_Tree_HasValueProperty {
public $value;
public $silent;
public $isReferenced;
public $currentFileInfo;
public $type = 'Comment';
public function __construct( $value, $silent, $index = null, $currentFileInfo = null ) {
$this->value = $value;

View file

@ -9,7 +9,6 @@ class Less_Tree_Condition extends Less_Tree {
public $rvalue;
public $index;
public $negate;
public $type = 'Condition';
public function __construct( $op, $l, $r, $i = 0, $negate = false ) {
$this->op = trim( $op );
@ -24,6 +23,11 @@ class Less_Tree_Condition extends Less_Tree {
$this->rvalue = $visitor->visitObj( $this->rvalue );
}
/**
* @param Less_Environment $env
* @return bool
* @see less-2.5.3.js#Condition.prototype.eval
*/
public function compile( $env ) {
$a = $this->lvalue->compile( $env );
$b = $this->rvalue->compile( $env );
@ -38,26 +42,18 @@ class Less_Tree_Condition extends Less_Tree {
break;
default:
if ( Less_Parser::is_method( $a, 'compare' ) ) {
$result = $a->compare( $b );
} elseif ( Less_Parser::is_method( $b, 'compare' ) ) {
$result = $b->compare( $a );
} else {
throw new Less_Exception_Compiler( 'Unable to perform comparison', null, $this->index );
}
switch ( $result ) {
switch ( Less_Tree::nodeCompare( $a, $b ) ) {
case -1:
$result = $this->op === '<' || $this->op === '=<' || $this->op === '<=';
$result = $this->op === '<' || $this->op === '=<' || $this->op === '<=';
break;
case 0:
$result = $this->op === '=' || $this->op === '>=' || $this->op === '=<' || $this->op === '<=';
$result = $this->op === '=' || $this->op === '>=' || $this->op === '=<' || $this->op === '<=';
break;
case 1:
$result = $this->op === '>' || $this->op === '>=';
$result = $this->op === '>' || $this->op === '>=';
break;
default:
$result = false;
}
break;
}

View file

@ -4,8 +4,8 @@
*/
class Less_Tree_DefaultFunc {
static $error_;
static $value_;
private static $error_;
private static $value_;
public static function compile() {
if ( self::$error_ ) {

View file

@ -6,7 +6,6 @@ class Less_Tree_DetachedRuleset extends Less_Tree {
public $ruleset;
public $frames;
public $type = 'DetachedRuleset';
public function __construct( $ruleset, $frames = null ) {
$this->ruleset = $ruleset;
@ -23,7 +22,7 @@ class Less_Tree_DetachedRuleset extends Less_Tree {
} else {
$frames = $env->frames;
}
return new Less_Tree_DetachedRuleset( $this->ruleset, $frames );
return new self( $this->ruleset, $frames );
}
public function callEval( $env ) {

View file

@ -2,16 +2,16 @@
/**
* @private
*/
class Less_Tree_Dimension extends Less_Tree {
class Less_Tree_Dimension extends Less_Tree implements Less_Tree_HasValueProperty {
/** @var float */
public $value;
public $unit;
public $type = 'Dimension';
public function __construct( $value, $unit = null ) {
$this->value = floatval( $value );
if ( $unit && ( $unit instanceof Less_Tree_Unit ) ) {
if ( $unit instanceof Less_Tree_Unit ) {
$this->unit = $unit;
} elseif ( $unit ) {
$this->unit = new Less_Tree_Unit( [ $unit ] );
@ -72,6 +72,7 @@ class Less_Tree_Dimension extends Less_Tree {
/**
* @param string $op
* @param self $other
*/
public function operate( $op, $other ) {
$value = Less_Functions::operate( $op, $this->value, $other->value );
@ -106,35 +107,31 @@ class Less_Tree_Dimension extends Less_Tree {
sort( $unit->denominator );
$unit->cancel();
}
return new Less_Tree_Dimension( $value, $unit );
return new self( $value, $unit );
}
/**
* @param Less_Tree $other
* @return int|null
* @see less-2.5.3.js#Dimension.prototype.compare
*/
public function compare( $other ) {
if ( $other instanceof Less_Tree_Dimension ) {
if ( $this->unit->isEmpty() || $other->unit->isEmpty() ) {
$a = $this;
$b = $other;
} else {
$a = $this->unify();
$b = $other->unify();
if ( $a->unit->compare( $b->unit ) !== 0 ) {
return -1;
}
}
$aValue = $a->value;
$bValue = $b->value;
if ( $bValue > $aValue ) {
return -1;
} elseif ( $bValue < $aValue ) {
return 1;
} else {
return 0;
}
} else {
return -1;
if ( !$other instanceof self ) {
return null;
}
if ( $this->unit->isEmpty() || $other->unit->isEmpty() ) {
$a = $this;
$b = $other;
} else {
$a = $this->unify();
$b = $other->unify();
if ( $a->unit->compare( $b->unit ) !== 0 ) {
return null;
}
}
return Less_Tree::numericCompare( $a->value, $b->value );
}
public function unify() {
@ -165,7 +162,7 @@ class Less_Tree_Dimension extends Less_Tree {
continue;
}
$value = $value * ( $group[$atomicUnit] / $group[$targetUnit] );
$value *= $group[$atomicUnit] / $group[$targetUnit];
$unit->numerator[$i] = $targetUnit;
}
@ -177,7 +174,7 @@ class Less_Tree_Dimension extends Less_Tree {
continue;
}
$value = $value / ( $group[$atomicUnit] / $group[$targetUnit] );
$value /= $group[$atomicUnit] / $group[$targetUnit];
$unit->denominator[$i] = $targetUnit;
}
@ -185,6 +182,6 @@ class Less_Tree_Dimension extends Less_Tree {
$unit->cancel();
return new Less_Tree_Dimension( $value, $unit );
return new self( $value, $unit );
}
}

View file

@ -1,40 +1,58 @@
<?php
/**
* @private
* @see less-2.5.3.js#Anonymous.prototype
*/
class Less_Tree_Directive extends Less_Tree {
class Less_Tree_Directive extends Less_Tree implements Less_Tree_HasValueProperty {
public $name;
public $value;
public $rules;
public $index;
public $isReferenced;
public $isRooted;
public $currentFileInfo;
public $debugInfo;
public $type = 'Directive';
public function __construct( $name, $value = null, $rules = null, $index = null, $currentFileInfo = null, $debugInfo = null ) {
public function __construct( $name, $value = null, $rules = null, $index = null, $isRooted = false, $currentFileInfo = null, $debugInfo = null ) {
$this->name = $name;
$this->value = $value;
if ( $rules ) {
$this->rules = $rules;
$this->rules->allowImports = true;
if ( is_array( $rules ) ) {
$this->rules = $rules;
} else {
$this->rules = [ $rules ];
$this->rules[0]->selectors = $this->emptySelectors();
}
foreach ( $this->rules as $rule ) {
$rule->allowImports = true;
}
}
$this->index = $index;
$this->isRooted = $isRooted;
$this->currentFileInfo = $currentFileInfo;
$this->debugInfo = $debugInfo;
}
public function accept( $visitor ) {
if ( $this->rules ) {
$this->rules = $visitor->visitObj( $this->rules );
$this->rules = $visitor->visitArray( $this->rules );
}
if ( $this->value ) {
$this->value = $visitor->visitObj( $this->value );
}
}
public function isRulesetLike() {
return $this->rules || !$this->isCharset();
}
public function isCharset() {
return $this->name === "@charset";
}
/**
* @see Less_Tree::genCSS
*/
@ -47,7 +65,7 @@ class Less_Tree_Directive extends Less_Tree {
$this->value->genCSS( $output );
}
if ( $this->rules ) {
Less_Tree::outputRuleset( $output, [ $this->rules ] );
Less_Tree::outputRuleset( $output, $this->rules );
} else {
$output->add( ';' );
}
@ -56,37 +74,56 @@ class Less_Tree_Directive extends Less_Tree {
public function compile( $env ) {
$value = $this->value;
$rules = $this->rules;
// Media stored inside other directive should not bubble over it
// backup media bubbling information
$mediaPathBackup = $env->mediaPath;
$mediaPBlocksBackup = $env->mediaBlocks;
// Deleted media bubbling information
$env->mediaPath = [];
$env->mediaBlocks = [];
if ( $value ) {
$value = $value->compile( $env );
}
if ( $rules ) {
$rules = $rules->compile( $env );
// Assuming that there is only one rule at this point - that is how parser constructs the rule
$rules = $rules[0]->compile( $env );
$rules->root = true;
}
return new Less_Tree_Directive( $this->name, $value, $rules, $this->index, $this->currentFileInfo, $this->debugInfo );
// Restore media bubbling information
$env->mediaPath = $mediaPathBackup;
$env->mediaBlocks = $mediaPBlocksBackup;
return new self( $this->name, $value, $rules, $this->index, $this->isRooted, $this->currentFileInfo, $this->debugInfo );
}
public function variable( $name ) {
if ( $this->rules ) {
return $this->rules->variable( $name );
return $this->rules[0]->variable( $name );
}
}
public function find( $selector ) {
if ( $this->rules ) {
return $this->rules->find( $selector, $this );
return $this->rules[0]->find( $selector, $this );
}
}
// rulesets: function () { if (this.rules) return tree.Ruleset.prototype.rulesets.apply(this.rules); },
public function markReferenced() {
$this->isReferenced = true;
if ( $this->rules ) {
Less_Tree::ReferencedArray( $this->rules->rules );
Less_Tree::ReferencedArray( $this->rules );
}
}
public function emptySelectors() {
$el = new Less_Tree_Element( '', '&', $this->index, $this->currentFileInfo );
$sels = [ new Less_Tree_Selector( [ $el ], [], null, $this->index, $this->currentFileInfo ) ];
$sels[0]->mediaEmpty = true;
return $sels;
}
}

View file

@ -2,7 +2,7 @@
/**
* @private
*/
class Less_Tree_Element extends Less_Tree {
class Less_Tree_Element extends Less_Tree implements Less_Tree_HasValueProperty {
/** @var string */
public $combinator;
@ -12,7 +12,6 @@ class Less_Tree_Element extends Less_Tree {
public $value;
public $index;
public $currentFileInfo;
public $type = 'Element';
public $value_is_object = false;
@ -41,7 +40,7 @@ class Less_Tree_Element extends Less_Tree {
}
public function compile( $env ) {
return new Less_Tree_Element(
return new self(
$this->combinator,
( $this->value_is_object ? $this->value->compile( $env ) : $this->value ),
$this->index,
@ -63,7 +62,7 @@ class Less_Tree_Element extends Less_Tree {
$value = $this->value;
}
if ( $value === '' && $this->combinator && $this->combinator === '&' ) {
if ( $value === '' && $this->combinator === '&' ) {
return '';
}

View file

@ -2,11 +2,11 @@
/**
* @private
*/
class Less_Tree_Expression extends Less_Tree {
/** @var array */
class Less_Tree_Expression extends Less_Tree implements Less_Tree_HasValueProperty {
/** @var Less_Tree[] */
public $value = [];
public $parens = false;
public $type = 'Expression';
public function __construct( $value, $parens = null ) {
$this->value = $value;
@ -35,11 +35,11 @@ class Less_Tree_Expression extends Less_Tree {
foreach ( $this->value as $e ) {
$ret[] = $e->compile( $env );
}
$returnValue = new Less_Tree_Expression( $ret );
$returnValue = new self( $ret );
} else {
if ( ( $this->value[0] instanceof Less_Tree_Expression ) && $this->value[0]->parens && !$this->value[0]->parensInOp ) {
if ( ( $this->value[0] instanceof self ) && $this->value[0]->parens && !$this->value[0]->parensInOp ) {
$doubleParen = true;
}

View file

@ -11,13 +11,14 @@ class Less_Tree_Extend extends Less_Tree {
public $allowBefore;
public $allowAfter;
public $firstExtendOnThisSelectorPath;
public $type = 'Extend';
public $ruleset;
public $object_id;
public $parent_ids = [];
/**
* @param Less_Tree_Selector $selector
* @param string $option
* @param int $index
*/
public function __construct( $selector, $option, $index ) {
@ -54,7 +55,11 @@ class Less_Tree_Extend extends Less_Tree {
Less_Parser::$has_extends = true;
$this->selector = $this->selector->compile( $env );
return $this;
// return new Less_Tree_Extend( $this->selector->compile($env), $this->option, $this->index);
// return new self( $this->selector->compile($env), $this->option, $this->index);
}
public function clone() {
return new self( $this->selector, $this->option, $this->index );
}
public function findSelfSelectors( $selectors ) {

View file

@ -0,0 +1,8 @@
<?php
/**
* @private
* @property mixed $value
*/
interface Less_Tree_HasValueProperty {
}

View file

@ -23,7 +23,6 @@ class Less_Tree_Import extends Less_Tree {
public $css;
public $skip;
public $root;
public $type = 'Import';
public function __construct( $path, $features, $options, $index, $currentFileInfo = null ) {
$this->options = $options;
@ -105,10 +104,10 @@ class Less_Tree_Import extends Less_Tree {
$path = $this->path->value;
$path = ( isset( $this->css ) || preg_match( '/(\.[a-z]*$)|([\?;].*)$/', $path ) ) ? $path : $path . '.less';
// During the first pass, Less_Tree_URL may contain a Less_Tree_Variable (not yet expanded),
// During the first pass, Less_Tree_Url may contain a Less_Tree_Variable (not yet expanded),
// and thus has no value property defined yet. Return null until we reach the next phase.
// https://github.com/wikimedia/less.php/issues/29
} elseif ( $this->path instanceof Less_Tree_URL && !( $this->path->value instanceof Less_Tree_Variable ) ) {
} elseif ( $this->path instanceof Less_Tree_Url && !( $this->path->value instanceof Less_Tree_Variable ) ) {
$path = $this->path->value->value;
} else {
return null;
@ -119,7 +118,7 @@ class Less_Tree_Import extends Less_Tree {
}
public function compileForImport( $env ) {
return new Less_Tree_Import( $this->path->compile( $env ), $this->features, $this->options, $this->index, $this->currentFileInfo );
return new self( $this->path->compile( $env ), $this->features, $this->options, $this->index, $this->currentFileInfo );
}
public function compilePath( $env ) {
@ -129,7 +128,7 @@ class Less_Tree_Import extends Less_Tree {
$rootpath = $this->currentFileInfo['rootpath'];
}
if ( !( $path instanceof Less_Tree_URL ) ) {
if ( !( $path instanceof Less_Tree_Url ) ) {
if ( $rootpath ) {
$pathValue = $path->value;
// Add the base path if the import is relative
@ -143,21 +142,23 @@ class Less_Tree_Import extends Less_Tree {
return $path;
}
/**
* @param Less_Environment $env
* @see less-2.5.3.js#Import.prototype.eval
*/
public function compile( $env ) {
$evald = $this->compileForImport( $env );
// get path & uri
$path_and_uri = null;
if ( is_callable( Less_Parser::$options['import_callback'] ) ) {
$path_and_uri = call_user_func( Less_Parser::$options['import_callback'], $evald );
}
$callback = Less_Parser::$options['import_callback'];
$path_and_uri = is_callable( $callback ) ? $callback( $evald ) : null;
if ( !$path_and_uri ) {
$path_and_uri = $evald->PathAndUri();
}
if ( $path_and_uri ) {
list( $full_path, $uri ) = $path_and_uri;
[ $full_path, $uri ] = $path_and_uri;
} else {
$full_path = $uri = $evald->getPath();
}
@ -169,11 +170,8 @@ class Less_Tree_Import extends Less_Tree {
'@phan-var string $full_path';
if ( $this->options['inline'] ) {
// todo needs to reference css file not import
//$contents = new Less_Tree_Anonymous($this->root, 0, array('filename'=>$this->importedFilename), true );
Less_Parser::AddParsedFile( $full_path );
$contents = new Less_Tree_Anonymous( file_get_contents( $full_path ), 0, [], true );
$contents = new Less_Tree_Anonymous( file_get_contents( $full_path ), 0, [], true, true );
if ( $this->features ) {
return new Less_Tree_Media( [ $contents ], $this->features->value );
@ -190,7 +188,7 @@ class Less_Tree_Import extends Less_Tree {
// css ?
if ( $evald->css ) {
$features = ( $evald->features ? $evald->features->compile( $env ) : null );
return new Less_Tree_Import( $this->compilePath( $env ), $features, $this->options, $this->index );
return new self( $this->compilePath( $env ), $features, $this->options, $this->index );
}
return $this->ParseImport( $full_path, $uri, $env );
@ -227,23 +225,26 @@ class Less_Tree_Import extends Less_Tree {
foreach ( $import_dirs as $rootpath => $rooturi ) {
if ( is_callable( $rooturi ) ) {
list( $path, $uri ) = call_user_func( $rooturi, $evald_path );
if ( is_string( $path ) ) {
$full_path = $path;
return [ $full_path, $uri ];
$res = $rooturi( $evald_path );
if ( $res && is_string( $res[0] ) ) {
return [
Less_Environment::normalizePath( $res[0] ),
Less_Environment::normalizePath( $res[1] ?? dirname( $evald_path ) )
];
}
} elseif ( !empty( $rootpath ) ) {
$path = rtrim( $rootpath, '/\\' ) . '/' . ltrim( $evald_path, '/\\' );
if ( file_exists( $path ) ) {
$full_path = Less_Environment::normalizePath( $path );
$uri = Less_Environment::normalizePath( dirname( $rooturi . $evald_path ) );
return [ $full_path, $uri ];
} elseif ( file_exists( $path . '.less' ) ) {
$full_path = Less_Environment::normalizePath( $path . '.less' );
$uri = Less_Environment::normalizePath( dirname( $rooturi . $evald_path . '.less' ) );
return [ $full_path, $uri ];
return [
Less_Environment::normalizePath( $path ),
Less_Environment::normalizePath( dirname( $rooturi . $evald_path ) )
];
}
if ( file_exists( $path . '.less' ) ) {
return [
Less_Environment::normalizePath( $path . '.less' ),
Less_Environment::normalizePath( dirname( $rooturi . $evald_path . '.less' ) )
];
}
}
}

View file

@ -2,15 +2,15 @@
/**
* @private
*/
class Less_Tree_Javascript extends Less_Tree {
class Less_Tree_JavaScript extends Less_Tree {
public $type = 'Javascript';
public $escaped;
public $expression;
public $index;
/**
* @param bool $index
* @param string $string
* @param int $index
* @param bool $escaped
*/
public function __construct( $string, $index, $escaped ) {

View file

@ -2,10 +2,10 @@
/**
* @private
*/
class Less_Tree_Keyword extends Less_Tree {
class Less_Tree_Keyword extends Less_Tree implements Less_Tree_HasValueProperty {
/** @var string */
public $value;
public $type = 'Keyword';
/**
* @param string $value
@ -26,7 +26,7 @@ class Less_Tree_Keyword extends Less_Tree {
}
public function compare( $other ) {
if ( $other instanceof Less_Tree_Keyword ) {
if ( $other instanceof self ) {
return $other->value === $this->value ? 0 : 1;
} else {
return -1;

View file

@ -9,7 +9,6 @@ class Less_Tree_Media extends Less_Tree {
public $index;
public $currentFileInfo;
public $isReferenced;
public $type = 'Media';
public function __construct( $value = [], $features = [], $index = null, $currentFileInfo = null ) {
$this->index = $index;
@ -39,11 +38,11 @@ class Less_Tree_Media extends Less_Tree {
/**
* @param Less_Environment $env
* @return Less_Tree_Media|Less_Tree_Ruleset
* @return self|Less_Tree_Ruleset
* @see less-2.5.3.js#Media.prototype.eval
*/
public function compile( $env ) {
$media = new Less_Tree_Media( [], [], $this->index, $this->currentFileInfo );
$media = new self( [], [], $this->index, $this->currentFileInfo );
$strictMathBypass = false;
if ( Less_Parser::$options['strictMath'] === false ) {
@ -112,7 +111,7 @@ class Less_Tree_Media extends Less_Tree {
*/
public function compileNested( $env ) {
$path = array_merge( $env->mediaPath, [ $this ] );
'@phan-var array<Less_Tree_Media> $path';
'@phan-var self[] $path';
// Extract the media-query conditions separated with `,` (OR).
foreach ( $path as $key => $p ) {
@ -130,6 +129,7 @@ class Less_Tree_Media extends Less_Tree {
// b and c and e
$permuted = $this->permute( $path );
'@phan-var (Less_Tree|string)[][] $permuted';
$expressions = [];
foreach ( $permuted as $path ) {

View file

@ -10,12 +10,7 @@ class Less_Tree_Mixin_Call extends Less_Tree {
public $currentFileInfo;
public $important;
public $type = 'MixinCall';
/**
* less.js: tree.mixin.Call
*
*/
public function __construct( $elements, $args, $index, $currentFileInfo, $important = false ) {
$this->selector = new Less_Tree_Selector( $elements );
$this->arguments = $args;
@ -24,17 +19,14 @@ class Less_Tree_Mixin_Call extends Less_Tree {
$this->important = $important;
}
// function accept($visitor){
// $this->selector = $visitor->visit($this->selector);
// $this->arguments = $visitor->visit($this->arguments);
//}
/**
* @see less-2.5.3.js#MixinCall.prototype.eval
*/
public function compile( $env ) {
$rules = [];
$match = false;
$isOneFound = false;
$candidates = [];
$defaultUsed = false;
$conditionResult = [];
$args = [];
@ -42,18 +34,16 @@ class Less_Tree_Mixin_Call extends Less_Tree {
$args[] = [ 'name' => $a['name'], 'value' => $a['value']->compile( $env ) ];
}
$defNone = 0;
$defTrue = 1;
$defFalse = 2;
foreach ( $env->frames as $frame ) {
$mixins = $frame->find( $this->selector );
if ( !$mixins ) {
continue;
}
$isOneFound = true;
$defNone = 0;
$defTrue = 1;
$defFalse = 2;
// To make `default()` function independent of definition order we have two "subpasses" here.
// At first we evaluate each guard *twice* (with `default() == true` and `default() == false`),
@ -113,20 +103,18 @@ class Less_Tree_Mixin_Call extends Less_Tree {
}
$candidates_length = count( $candidates );
$length_1 = ( $candidates_length == 1 );
for ( $m = 0; $m < $candidates_length; $m++ ) {
$candidate = $candidates[$m]['group'];
if ( ( $candidate === $defNone ) || ( $candidate === $defaultResult ) ) {
try{
try {
$mixin = $candidates[$m]['mixin'];
if ( !( $mixin instanceof Less_Tree_Mixin_Definition ) ) {
$originalRuleset = $mixin instanceof Less_Tree_Ruleset ? $mixin->originalRuleset : $mixin;
$mixin = new Less_Tree_Mixin_Definition( '', [], $mixin->rules, null, false );
$mixin->originalRuleset = $mixins[$m]->originalRuleset;
$mixin->originalRuleset = $originalRuleset;
}
$rules = array_merge( $rules, $mixin->evalCall( $env, $args, $this->important )->rules );
} catch ( Exception $e ) {
// throw new Less_Exception_Compiler($e->getMessage(), $e->index, null, $this->currentFileInfo['filename']);
throw new Less_Exception_Compiler( $e->getMessage(), null, null, $this->currentFileInfo );
}
}
@ -142,7 +130,8 @@ class Less_Tree_Mixin_Call extends Less_Tree {
}
if ( $isOneFound ) {
throw new Less_Exception_Compiler( 'No matching definition was found for `' . $this->Format( $args ) . '`', null, $this->index, $this->currentFileInfo );
$selectorName = $this->selector->toCSS();
throw new Less_Exception_Compiler( 'No matching definition was found for ' . $selectorName . ' with args `' . $this->Format( $args ) . '`', null, $this->index, $this->currentFileInfo );
} else {
throw new Less_Exception_Compiler( trim( $this->selector->toCSS() ) . " is undefined in " . $this->currentFileInfo['filename'], null, $this->index );
@ -151,7 +140,6 @@ class Less_Tree_Mixin_Call extends Less_Tree {
/**
* Format the args for use in exception messages
*
*/
private function Format( $args ) {
$message = [];

View file

@ -13,9 +13,7 @@ class Less_Tree_Mixin_Definition extends Less_Tree_Ruleset {
public $frames = [];
public $condition;
public $variadic;
public $type = 'MixinDefinition';
// less.js : /lib/less/tree/mixin.js : tree.mixin.Definition
public function __construct( $name, $params, $rules, $condition, $variadic = false, $frames = [] ) {
$this->name = $name;
$this->selectors = [ new Less_Tree_Selector( [ new Less_Tree_Element( null, $name ) ] ) ];
@ -38,17 +36,13 @@ class Less_Tree_Mixin_Definition extends Less_Tree_Ruleset {
$this->SetRulesetIndex();
}
// function accept( $visitor ){
// $this->params = $visitor->visit($this->params);
// $this->rules = $visitor->visit($this->rules);
// $this->condition = $visitor->visit($this->condition);
//}
public function toCSS() {
return '';
}
// less.js : /lib/less/tree/mixin.js : tree.mixin.Definition.evalParams
/**
* @see less-2.5.3.js#Definition.prototype.evalParams
*/
public function compileParams( $env, $mixinFrames, $args = [], &$evaldArguments = [] ) {
$frame = new Less_Tree_Ruleset( null, [] );
$params = $this->params;
@ -64,7 +58,7 @@ class Less_Tree_Mixin_Definition extends Less_Tree_Ruleset {
$isNamedFound = false;
foreach ( $params as $j => $param ) {
if ( !isset( $evaldArguments[$j] ) && $arg['name'] === $params[$j]['name'] ) {
if ( !isset( $evaldArguments[$j] ) && $arg['name'] === $param['name'] ) {
$evaldArguments[$j] = $arg['value']->compile( $env );
array_unshift( $frame->rules, new Less_Tree_Rule( $arg['name'], $arg['value']->compile( $env ) ) );
$isNamedFound = true;
@ -75,7 +69,6 @@ class Less_Tree_Mixin_Definition extends Less_Tree_Ruleset {
array_splice( $args, $i, 1 );
$i--;
$argsLength--;
continue;
} else {
throw new Less_Exception_Compiler( "Named argument for " . $this->name . ' ' . $args[$i]['name'] . ' not found' );
}
@ -85,24 +78,21 @@ class Less_Tree_Mixin_Definition extends Less_Tree_Ruleset {
$argIndex = 0;
foreach ( $params as $i => $param ) {
if ( isset( $evaldArguments[$i] ) ) { continue;
if ( isset( $evaldArguments[$i] ) ) {
continue;
}
$arg = null;
if ( isset( $args[$argIndex] ) ) {
$arg = $args[$argIndex];
}
if ( isset( $param['name'] ) && $param['name'] ) {
$arg = $args[$argIndex] ?? null;
$name = $param['name'] ?? null;
if ( $name ) {
if ( isset( $param['variadic'] ) ) {
$varargs = [];
for ( $j = $argIndex; $j < $argsLength; $j++ ) {
$varargs[] = $args[$j]['value']->compile( $env );
}
$expression = new Less_Tree_Expression( $varargs );
array_unshift( $frame->rules, new Less_Tree_Rule( $param['name'], $expression->compile( $env ) ) );
array_unshift( $frame->rules, new Less_Tree_Rule( $name, $expression->compile( $env ) ) );
} else {
$val = ( $arg && $arg['value'] ) ? $arg['value'] : false;
@ -121,7 +111,7 @@ class Less_Tree_Mixin_Definition extends Less_Tree_Ruleset {
throw new Less_Exception_Compiler( "Wrong number of arguments for " . $this->name . " (" . $argsLength . ' for ' . $this->arity . ")" );
}
array_unshift( $frame->rules, new Less_Tree_Rule( $param['name'], $val ) );
array_unshift( $frame->rules, new Less_Tree_Rule( $name, $val ) );
$evaldArguments[$i] = $val;
}
}
@ -142,9 +132,9 @@ class Less_Tree_Mixin_Definition extends Less_Tree_Ruleset {
public function compile( $env ) {
if ( $this->frames ) {
return new Less_Tree_Mixin_Definition( $this->name, $this->params, $this->rules, $this->condition, $this->variadic, $this->frames );
return new self( $this->name, $this->params, $this->rules, $this->condition, $this->variadic, $this->frames );
}
return new Less_Tree_Mixin_Definition( $this->name, $this->params, $this->rules, $this->condition, $this->variadic, $env->frames );
return new self( $this->name, $this->params, $this->rules, $this->condition, $this->variadic, $env->frames );
}
public function evalCall( $env, $args = null, $important = null ) {
@ -194,8 +184,8 @@ class Less_Tree_Mixin_Definition extends Less_Tree_Ruleset {
$compile_env = new Less_Environment();
$compile_env->frames = array_merge(
[ $frame ], // the parameter variables
$this->frames, // the parent namespace/mixin frames
[ $frame ], // the parameter variables
$this->frames, // the parent namespace/mixin frames
$env->frames // the current environment frames
);
@ -204,6 +194,18 @@ class Less_Tree_Mixin_Definition extends Less_Tree_Ruleset {
return (bool)$this->condition->compile( $compile_env );
}
public function makeImportant() {
$important_rules = [];
foreach ( $this->rules as $rule ) {
if ( $rule instanceof Less_Tree_Rule || $rule instanceof self || $rule instanceof Less_Tree_NameValue ) {
$important_rules[] = $rule->makeImportant();
} else {
$important_rules[] = $rule;
}
}
return new self( $this->name, $this->params, $important_rules, $this->condition, $this->variadic, $this->frames );
}
public function matchArgs( $args, $env = null ) {
$argsLength = count( $args );

View file

@ -10,13 +10,12 @@
*
* @private
*/
class Less_Tree_NameValue extends Less_Tree {
class Less_Tree_NameValue extends Less_Tree implements Less_Tree_HasValueProperty {
public $name;
public $value;
public $index;
public $currentFileInfo;
public $type = 'NameValue';
public $important = '';
public function __construct( $name, $value = null, $index = null, $currentFileInfo = null ) {
@ -41,7 +40,7 @@ class Less_Tree_NameValue extends Less_Tree {
}
public function makeImportant() {
$new = new Less_Tree_NameValue( $this->name, $this->value, $this->index, $this->currentFileInfo );
$new = new self( $this->name, $this->value, $this->index, $this->currentFileInfo );
$new->important = ' !important';
return $new;
}

View file

@ -2,10 +2,9 @@
/**
* @private
*/
class Less_Tree_Negative extends Less_Tree {
class Less_Tree_Negative extends Less_Tree implements Less_Tree_HasValueProperty {
public $value;
public $type = 'Negative';
public function __construct( $node ) {
$this->value = $node;
@ -28,6 +27,6 @@ class Less_Tree_Negative extends Less_Tree {
$ret = new Less_Tree_Operation( '*', [ new Less_Tree_Dimension( -1 ), $this->value ] );
return $ret->compile( $env );
}
return new Less_Tree_Negative( $this->value->compile( $env ) );
return new self( $this->value->compile( $env ) );
}
}

View file

@ -7,7 +7,6 @@ class Less_Tree_Operation extends Less_Tree {
public $op;
public $operands;
public $isSpaced;
public $type = 'Operation';
/**
* @param string $op
@ -26,6 +25,10 @@ class Less_Tree_Operation extends Less_Tree {
$a = $this->operands[0]->compile( $env );
$b = $this->operands[1]->compile( $env );
// Skip operation if argument was not compiled down to a non-operable value.
// For example, if one argument is a Less_Tree_Call like 'var(--foo)' then we
// preserve it as literal for native CSS.
// https://phabricator.wikimedia.org/T331688
if ( Less_Environment::isMathOn() ) {
if ( $a instanceof Less_Tree_Dimension && $b instanceof Less_Tree_Color ) {
@ -33,17 +36,18 @@ class Less_Tree_Operation extends Less_Tree {
} elseif ( $b instanceof Less_Tree_Dimension && $a instanceof Less_Tree_Color ) {
$b = $b->toColor();
}
if ( !method_exists( $a, 'operate' ) ) {
if ( !( $a instanceof Less_Tree_Dimension || $a instanceof Less_Tree_Color ) ) {
throw new Less_Exception_Compiler( "Operation on an invalid type" );
}
return $a->operate( $this->op, $b );
if ( $b instanceof Less_Tree_Dimension || $b instanceof Less_Tree_Color ) {
return $a->operate( $this->op, $b );
}
}
return new Less_Tree_Operation( $this->op, [ $a, $b ], $this->isSpaced );
return new self( $this->op, [ $a, $b ], $this->isSpaced );
}
/**

View file

@ -2,11 +2,10 @@
/**
* @private
*/
class Less_Tree_Paren extends Less_Tree {
class Less_Tree_Paren extends Less_Tree implements Less_Tree_HasValueProperty {
/** @var Less_Tree $value */
/** @var Less_Tree */
public $value;
public $type = 'Paren';
/**
* @param Less_Tree $value
@ -29,7 +28,7 @@ class Less_Tree_Paren extends Less_Tree {
}
public function compile( $env ) {
return new Less_Tree_Paren( $this->value->compile( $env ) );
return new self( $this->value->compile( $env ) );
}
}

View file

@ -2,18 +2,18 @@
/**
* @private
*/
class Less_Tree_Quoted extends Less_Tree {
class Less_Tree_Quoted extends Less_Tree implements Less_Tree_HasValueProperty {
public $escaped;
/** @var string */
public $value;
public $quote;
public $index;
public $currentFileInfo;
public $type = 'Quoted';
/**
* @param string $str
*/
public function __construct( $str, $content = '', $escaped = false, $index = false, $currentFileInfo = null ) {
public function __construct( $str, $content = '', $escaped = true, $index = false, $currentFileInfo = null ) {
$this->escaped = $escaped;
$this->value = $content;
if ( $str ) {
@ -39,37 +39,41 @@ class Less_Tree_Quoted extends Less_Tree {
public function compile( $env ) {
$value = $this->value;
if ( preg_match_all( '/`([^`]+)`/', $this->value, $matches ) ) {
foreach ( $matches as $i => $match ) {
$js = new Less_Tree_JavaScript( $matches[1], $this->index, true );
foreach ( $matches[1] as $i => $match ) {
$js = new Less_Tree_JavaScript( $match, $this->index, true );
$js = $js->compile( $env )->value;
$value = str_replace( $matches[0][$i], $js, $value );
}
}
if ( preg_match_all( '/@\{([\w-]+)\}/', $value, $matches ) ) {
foreach ( $matches[1] as $i => $match ) {
$v = new Less_Tree_Variable( '@' . $match, $this->index, $this->currentFileInfo );
$v = $v->compile( $env );
$v = ( $v instanceof Less_Tree_Quoted ) ? $v->value : $v->toCSS();
$value = str_replace( $matches[0][$i], $v, $value );
$r = $value;
do {
$value = $r;
if ( preg_match_all( '/@\{([\w-]+)\}/', $value, $matches ) ) {
foreach ( $matches[1] as $i => $match ) {
$v = new Less_Tree_Variable( '@' . $match, $this->index, $this->currentFileInfo );
$v = $v->compile( $env );
$v = ( $v instanceof self ) ? $v->value : $v->toCSS();
$r = str_replace( $matches[0][$i], $v, $r );
}
}
}
} while ( $r != $value );
return new Less_Tree_Quoted( $this->quote . $value . $this->quote, $value, $this->escaped, $this->index, $this->currentFileInfo );
return new self( $this->quote . $r . $this->quote, $r, $this->escaped, $this->index, $this->currentFileInfo );
}
public function compare( $x ) {
if ( !Less_Parser::is_method( $x, 'toCSS' ) ) {
return -1;
/**
* @param mixed $other
* @return int|null
* @see less-2.5.3.js#Quoted.prototype.compare
*/
public function compare( $other ) {
if ( $other instanceof self && !$this->escaped && !$other->escaped ) {
return Less_Tree::numericCompare( $this->value, $other->value );
} else {
return (
Less_Parser::is_method( $other, 'toCSS' )
&& $this->toCSS() === $other->toCSS()
) ? 0 : null;
}
$left = $this->toCSS();
$right = $x->toCSS();
if ( $left === $right ) {
return 0;
}
return $left < $right ? -1 : 1;
}
}

View file

@ -2,21 +2,27 @@
/**
* @private
*/
class Less_Tree_Rule extends Less_Tree {
class Less_Tree_Rule extends Less_Tree implements Less_Tree_HasValueProperty {
public $name;
/** @var Less_Tree $value */
/** @var Less_Tree */
public $value;
/** @var string */
public $important;
public $merge;
public $index;
public $inline;
public $variable;
public $currentFileInfo;
public $type = 'Rule';
/**
* @param string $important
* @param string|array<Less_Tree_Keyword|Less_Tree_Variable> $name
* @param mixed $value
* @param null|false|string $important
* @param null|false|string $merge
* @param int|null $index
* @param array|null $currentFileInfo
* @param bool $inline
*/
public function __construct( $name, $value = null, $important = null, $merge = null, $index = null, $currentFileInfo = null, $inline = false ) {
$this->name = $name;
@ -40,10 +46,10 @@ class Less_Tree_Rule extends Less_Tree {
*/
public function genCSS( $output ) {
$output->add( $this->name . Less_Environment::$_outputMap[': '], $this->currentFileInfo, $this->index );
try{
try {
$this->value->genCSS( $output );
}catch ( Less_Exception_Parser $e ) {
} catch ( Less_Exception_Parser $e ) {
$e->index = $this->index;
$e->currentFile = $this->currentFileInfo;
throw $e;
@ -53,7 +59,7 @@ class Less_Tree_Rule extends Less_Tree {
/**
* @param Less_Environment $env
* @return Less_Tree_Rule
* @return self
*/
public function compile( $env ) {
$name = $this->name;
@ -75,12 +81,12 @@ class Less_Tree_Rule extends Less_Tree {
try {
$evaldValue = $this->value->compile( $env );
if ( !$this->variable && $evaldValue->type === "DetachedRuleset" ) {
if ( !$this->variable && $evaldValue instanceof Less_Tree_DetachedRuleset ) {
throw new Less_Exception_Compiler( "Rulesets cannot be evaluated on a property.", null, $this->index, $this->currentFileInfo );
}
if ( Less_Environment::$mixin_stack ) {
$return = new Less_Tree_Rule( $name, $evaldValue, $this->important, $this->merge, $this->index, $this->currentFileInfo, $this->inline );
$return = new self( $name, $evaldValue, $this->important, $this->merge, $this->index, $this->currentFileInfo, $this->inline );
} else {
$this->name = $name;
$this->value = $evaldValue;
@ -91,6 +97,7 @@ class Less_Tree_Rule extends Less_Tree {
if ( !is_numeric( $e->index ) ) {
$e->index = $this->index;
$e->currentFile = $this->currentFileInfo;
$e->genMessage();
}
throw $e;
}
@ -109,7 +116,7 @@ class Less_Tree_Rule extends Less_Tree {
}
public function makeImportant() {
return new Less_Tree_Rule( $this->name, $this->value, '!important', $this->merge, $this->index, $this->currentFileInfo, $this->inline );
return new self( $this->name, $this->value, '!important', $this->merge, $this->index, $this->currentFileInfo, $this->inline );
}
}

View file

@ -16,11 +16,12 @@ class Less_Tree_Ruleset extends Less_Tree {
public $allowImports;
public $paths;
public $firstRoot;
public $type = 'Ruleset';
public $multiMedia;
public $allExtends;
/** @var int */
public $ruleset_id;
/** @var int */
public $originalRuleset;
public $first_oelements;
@ -68,7 +69,7 @@ class Less_Tree_Ruleset extends Less_Tree {
/**
* @param Less_Environment $env
* @return Less_Tree_Ruleset
* @return self
* @see less-2.5.3.js#Ruleset.prototype.eval
*/
public function compile( $env ) {
@ -101,7 +102,7 @@ class Less_Tree_Ruleset extends Less_Tree {
$rule = $ruleset->rules[$i];
// for rulesets, check if it is a css guard and can be removed
if ( $rule instanceof Less_Tree_Ruleset && $rule->selectors && count( $rule->selectors ) === 1 ) {
if ( $rule instanceof self && $rule->selectors && count( $rule->selectors ) === 1 ) {
// check if it can be folded in (e.g. & where)
if ( $rule->selectors[0]->isJustParentSelector() ) {
@ -136,8 +137,9 @@ class Less_Tree_Ruleset extends Less_Tree {
/**
* Compile Less_Tree_Mixin_Call objects
*
* @param Less_Tree_Ruleset $ruleset
* @param int $rsRuleCnt
* @param self $ruleset
* @param Less_Environment $env
* @param int &$rsRuleCnt
*/
private function EvalMixinCalls( $ruleset, $env, &$rsRuleCnt ) {
for ( $i = 0; $i < $rsRuleCnt; $i++ ) {
@ -190,7 +192,7 @@ class Less_Tree_Ruleset extends Less_Tree {
* Compile the selectors and create a new ruleset object for the compile() method
*
* @param Less_Environment $env
* @return Less_Tree_Ruleset
* @return self
*/
private function PrepareRuleset( $env ) {
// NOTE: Preserve distinction between null and empty array when compiling
@ -223,7 +225,7 @@ class Less_Tree_Ruleset extends Less_Tree {
$rules = [];
}
$ruleset = new Less_Tree_Ruleset( $selectors, $rules, $this->strictImports );
$ruleset = new self( $selectors, $rules, $this->strictImports );
$ruleset->originalRuleset = $this->ruleset_id;
$ruleset->root = $this->root;
@ -241,7 +243,7 @@ class Less_Tree_Ruleset extends Less_Tree {
return $ruleset;
}
function evalImports( $env ) {
public function evalImports( $env ) {
$rules_len = count( $this->rules );
for ( $i = 0; $i < $rules_len; $i++ ) {
$rule = $this->rules[$i];
@ -262,17 +264,17 @@ class Less_Tree_Ruleset extends Less_Tree {
}
}
function makeImportant() {
public function makeImportant() {
$important_rules = [];
foreach ( $this->rules as $rule ) {
if ( $rule instanceof Less_Tree_Rule || $rule instanceof Less_Tree_Ruleset || $rule instanceof Less_Tree_NameValue ) {
if ( $rule instanceof Less_Tree_Rule || $rule instanceof self || $rule instanceof Less_Tree_NameValue ) {
$important_rules[] = $rule->makeImportant();
} else {
$important_rules[] = $rule;
}
}
return new Less_Tree_Ruleset( $this->selectors, $important_rules, $this->strictImports );
return new self( $this->selectors, $important_rules, $this->strictImports );
}
public function matchArgs( $args, $env = null ) {
@ -292,7 +294,7 @@ class Less_Tree_Ruleset extends Less_Tree {
return true;
}
function resetCache() {
public function resetCache() {
$this->_rulesets = null;
$this->_variables = null;
$this->lookups = [];
@ -332,7 +334,7 @@ class Less_Tree_Ruleset extends Less_Tree {
$first_oelement = $selector->_oelements[0];
foreach ( $this->rules as $rule ) {
if ( $rule instanceof Less_Tree_Ruleset && $rule->ruleset_id != $self ) {
if ( $rule instanceof self && $rule->ruleset_id != $self ) {
if ( isset( $rule->first_oelements[$first_oelement] ) ) {
@ -355,8 +357,23 @@ class Less_Tree_Ruleset extends Less_Tree {
return $this->lookups[$key];
}
private function isRulesetLikeNode( $rule ) {
// if it has nested rules, then it should be treated like a ruleset
// medias and comments do not have nested rules, but should be treated like rulesets anyway
// some directives and anonymous nodes are ruleset like, others are not
if ( $rule instanceof Less_Tree_Media || $rule instanceof Less_Tree_Ruleset ) {
return true;
} elseif ( $rule instanceof Less_Tree_Anonymous || $rule instanceof Less_Tree_Directive ) {
return $rule->isRulesetLike();
}
// anything else is assumed to be a rule
return false;
}
/**
* @see Less_Tree::genCSS
* @param Less_Output $output
* @see less-2.5.3.js#Ruleset.prototype.genCSS
*/
public function genCSS( $output ) {
if ( !$this->root ) {
@ -374,17 +391,21 @@ class Less_Tree_Ruleset extends Less_Tree {
}
$ruleNodes = [];
$rulesetNodes = [];
foreach ( $this->rules as $rule ) {
$class = get_class( $rule );
if (
( $class === 'Less_Tree_Media' ) ||
( $class === 'Less_Tree_Directive' ) ||
( $this->root && $class === 'Less_Tree_Comment' ) ||
( $rule instanceof Less_Tree_Ruleset && $rule->rules )
) {
$rulesetNodes[] = $rule;
$charsetNodeIndex = 0;
$importNodeIndex = 0;
foreach ( $this->rules as $i => $rule ) {
if ( $rule instanceof Less_Tree_Comment ) {
if ( $importNodeIndex === $i ) {
$importNodeIndex++;
}
$ruleNodes[] = $rule;
} elseif ( $rule instanceof Less_Tree_Directive && $rule->isCharset() ) {
array_splice( $ruleNodes, $charsetNodeIndex, 0, [ $rule ] );
$charsetNodeIndex++;
$importNodeIndex++;
} elseif ( $rule instanceof Less_Tree_Import ) {
array_splice( $ruleNodes, $importNodeIndex, 0, [ $rule ] );
$importNodeIndex++;
} else {
$ruleNodes[] = $rule;
}
@ -393,18 +414,25 @@ class Less_Tree_Ruleset extends Less_Tree {
// If this is the root node, we don't render
// a selector, or {}.
if ( !$this->root ) {
$paths_len = count( $this->paths );
for ( $i = 0; $i < $paths_len; $i++ ) {
$path = $this->paths[$i];
$firstSelector = true;
foreach ( $path as $p ) {
$p->genCSS( $output, $firstSelector );
$firstSelector = false;
$sep = ',' . $tabSetStr;
// TODO: Move to Env object
// TODO: Inject Env object to toCSS() and genCSS()
$firstSelector = false;
foreach ( $this->paths as $i => $path ) {
$pathSubCnt = count( $path );
if ( !$pathSubCnt ) {
continue;
}
if ( $i + 1 < $paths_len ) {
$output->add( ',' . $tabSetStr );
if ( $i > 0 ) {
$output->add( $sep );
}
$firstSelector = true;
$path[0]->genCSS( $output, $firstSelector );
$firstSelector = false;
for ( $j = 1; $j < $pathSubCnt; $j++ ) {
$path[$j]->genCSS( $output, $firstSelector );
}
}
@ -412,19 +440,21 @@ class Less_Tree_Ruleset extends Less_Tree {
}
// Compile rules and rulesets
$ruleNodes_len = count( $ruleNodes );
$rulesetNodes_len = count( $rulesetNodes );
for ( $i = 0; $i < $ruleNodes_len; $i++ ) {
$rule = $ruleNodes[$i];
foreach ( $ruleNodes as $i => $rule ) {
// @page{ directive ends up with root elements inside it, a mix of rules and rulesets
// In this instance we do not know whether it is the last property
if ( $i + 1 === $ruleNodes_len && ( !$this->root || $rulesetNodes_len === 0 || $this->firstRoot ) ) {
if ( $i + 1 === count( $ruleNodes ) ) {
Less_Environment::$lastRule = true;
}
$currentLastRule = Less_Environment::$lastRule;
if ( $this->isRulesetLikeNode( $rule ) ) {
Less_Environment::$lastRule = false;
}
$rule->genCSS( $output );
Less_Environment::$lastRule = $currentLastRule;
if ( !Less_Environment::$lastRule ) {
$output->add( $tabRuleStr );
} else {
@ -437,25 +467,12 @@ class Less_Tree_Ruleset extends Less_Tree {
Less_Environment::$tabLevel--;
}
$firstRuleset = true;
$space = ( $this->root ? $tabRuleStr : $tabSetStr );
for ( $i = 0; $i < $rulesetNodes_len; $i++ ) {
if ( $ruleNodes_len && $firstRuleset ) {
$output->add( $space );
} elseif ( !$firstRuleset ) {
$output->add( $space );
}
$firstRuleset = false;
$rulesetNodes[$i]->genCSS( $output );
}
if ( !Less_Parser::$options['compress'] && $this->firstRoot ) {
$output->add( "\n" );
}
}
function markReferenced() {
public function markReferenced() {
if ( !$this->selectors ) {
return;
}
@ -605,9 +622,9 @@ class Less_Tree_Ruleset extends Less_Tree {
foreach ( $newSelectors as &$sel ) {
$length = count( $sel );
if ( $length ) {
$paths[] = $sel;
$lastSelector = $sel[$length - 1];
$sel[$length - 1] = $lastSelector->createDerived( $lastSelector->elements, $inSelector->extendList );
$paths[] = $sel;
}
}
@ -708,7 +725,7 @@ class Less_Tree_Ruleset extends Less_Tree {
return $newSelectorPath;
}
function mergeElementsOnToSelectors( $elements, &$selectors ) {
public function mergeElementsOnToSelectors( $elements, &$selectors ) {
if ( !$elements ) {
return;
}

View file

@ -10,7 +10,6 @@ class Less_Tree_Selector extends Less_Tree {
public $_css;
public $index;
public $evaldCondition = false;
public $type = 'Selector';
public $currentFileInfo = [];
public $isReferenced;
public $mediaEmpty;
@ -23,7 +22,12 @@ class Less_Tree_Selector extends Less_Tree {
public $cacheable = true;
/**
* @param bool $isReferenced
* @param Less_Tree_Element[] $elements
* @param Less_Tree_Element[] $extendList
* @param Less_Tree_Condition|null $condition
* @param int|null $index
* @param array|null $currentFileInfo
* @param bool|null $isReferenced
*/
public function __construct( $elements, $extendList = [], $condition = null, $index = null, $currentFileInfo = null, $isReferenced = null ) {
$this->elements = $elements;
@ -54,7 +58,7 @@ class Less_Tree_Selector extends Less_Tree {
}
public function createDerived( $elements, $extendList = null, $evaldCondition = null ) {
$newSelector = new Less_Tree_Selector(
$newSelector = new self(
$elements,
( $extendList ?: $this->extendList ),
null,
@ -81,6 +85,9 @@ class Less_Tree_Selector extends Less_Tree {
return $other->_oelements_len; // return number of matched elements
}
/**
* @see less-2.5.3.js#Selector.prototype.CacheElements
*/
public function CacheElements() {
$this->_oelements = [];
$this->_oelements_assoc = [];
@ -94,15 +101,16 @@ class Less_Tree_Selector extends Less_Tree {
$css .= $v->value;
continue;
}
if ( !property_exists( $v->value, 'value' ) || !is_string( $v->value->value ) ) {
if ( ( $v->value instanceof Less_Tree_Selector || $v->value instanceof Less_Tree_Variable )
|| !is_string( $v->value->value ) ) {
$this->cacheable = false;
return;
}
$css .= $v->value->value;
if ( isset( $v->value->value ) && !is_object( $v->value->value ) ) {
$css .= $v->value->value;
}
}
$this->_oelements_len = preg_match_all( '/[,&#\.\w-](?:[\w-]|(?:\\\\.))*/', $css, $matches );
$this->_oelements_len = preg_match_all( '/[,&#\*\.\w-](?:[\w-]|(?:\\\\.))*/', $css, $matches );
if ( $this->_oelements_len ) {
$this->_oelements = $matches[0];

View file

@ -2,10 +2,9 @@
/**
* @private
*/
class Less_Tree_UnicodeDescriptor extends Less_Tree {
class Less_Tree_UnicodeDescriptor extends Less_Tree implements Less_Tree_HasValueProperty {
public $value;
public $type = 'UnicodeDescriptor';
public function __construct( $value ) {
$this->value = $value;

View file

@ -4,10 +4,9 @@
*/
class Less_Tree_Unit extends Less_Tree {
var $numerator = [];
var $denominator = [];
public $numerator = [];
public $denominator = [];
public $backupUnit;
public $type = 'Unit';
public function __construct( $numerator = [], $denominator = [], $backupUnit = null ) {
$this->numerator = $numerator;
@ -28,7 +27,6 @@ class Less_Tree_Unit extends Less_Tree {
$output->add( $this->denominator[0] );
} elseif ( !Less_Parser::$options['strictUnits'] && $this->backupUnit ) {
$output->add( $this->backupUnit );
return;
}
}
@ -45,14 +43,14 @@ class Less_Tree_Unit extends Less_Tree {
}
/**
* @param Less_Tree_Unit $other
* @param self $other
*/
public function compare( $other ) {
return $this->is( $other->toString() ) ? 0 : -1;
}
public function is( $unitString ) {
return $this->toString() === $unitString;
return strtoupper( $this->toString() ) === strtoupper( $unitString );
}
public function isLength() {

View file

@ -4,7 +4,7 @@
*/
class Less_Tree_UnitConversions {
public static $groups = [ 'length','duration','angle' ];
public static $groups = [ 'length', 'duration', 'angle' ];
public static $length = [
'm' => 1,
@ -22,9 +22,9 @@ class Less_Tree_UnitConversions {
];
public static $angle = [
'rad' => 0.1591549430919, // 1/(2*M_PI),
'deg' => 0.002777778, // 1/360,
'grad' => 0.0025, // 1/400,
'rad' => 0.1591549430919, // 1/(2*M_PI),
'deg' => 0.002777778, // 1/360,
'grad' => 0.0025, // 1/400,
'turn' => 1
];

View file

@ -2,20 +2,19 @@
/**
* @private
*/
class Less_Tree_Url extends Less_Tree {
class Less_Tree_Url extends Less_Tree implements Less_Tree_HasValueProperty {
public $attrs;
public $value;
public $currentFileInfo;
public $isEvald;
public $type = 'Url';
/**
* @param Less_Tree_Variable|Less_Tree_Quoted|Less_Tree_Anonymous $value
* @param array|null $currentFileInfo
* @param bool|null $isEvald
*/
public function __construct( $value, $currentFileInfo = null, $isEvald = null ) {
public function __construct( Less_Tree $value, $currentFileInfo = null, $isEvald = null ) {
$this->value = $value;
$this->currentFileInfo = $currentFileInfo;
$this->isEvald = $isEvald;
@ -35,10 +34,10 @@ class Less_Tree_Url extends Less_Tree {
}
/**
* @param Less_Environment $ctx
* @param Less_Environment $env
*/
public function compile( $ctx ) {
$val = $this->value->compile( $ctx );
public function compile( $env ) {
$val = $this->value->compile( $env );
if ( !$this->isEvald ) {
// Add the base path if the URL is relative
@ -71,7 +70,7 @@ class Less_Tree_Url extends Less_Tree {
}
}
return new Less_Tree_URL( $val, $this->currentFileInfo, true );
return new self( $val, $this->currentFileInfo, true );
}
}

View file

@ -2,9 +2,9 @@
/**
* @private
*/
class Less_Tree_Value extends Less_Tree {
class Less_Tree_Value extends Less_Tree implements Less_Tree_HasValueProperty {
public $type = 'Value';
/** @var Less_Tree[] */
public $value;
/**
@ -25,7 +25,7 @@ class Less_Tree_Value extends Less_Tree {
$ret[] = $v->compile( $env );
}
if ( $i > 0 ) {
return new Less_Tree_Value( $ret );
return new self( $ret );
}
return $ret[0];
}
@ -33,7 +33,7 @@ class Less_Tree_Value extends Less_Tree {
/**
* @see Less_Tree::genCSS
*/
function genCSS( $output ) {
public function genCSS( $output ) {
$len = count( $this->value );
for ( $i = 0; $i < $len; $i++ ) {
$this->value[$i]->genCSS( $output );

View file

@ -8,7 +8,6 @@ class Less_Tree_Variable extends Less_Tree {
public $index;
public $currentFileInfo;
public $evaluating = false;
public $type = 'Variable';
/**
* @param string $name
@ -21,16 +20,14 @@ class Less_Tree_Variable extends Less_Tree {
/**
* @param Less_Environment $env
* @return Less_Tree
* @return Less_Tree|Less_Tree_Keyword|Less_Tree_Quoted
* @see less-2.5.3.js#Ruleset.prototype.eval
*/
public function compile( $env ) {
if ( $this->name[1] === '@' ) {
$v = new Less_Tree_Variable( substr( $this->name, 1 ), $this->index + 1, $this->currentFileInfo );
// While some Less_Tree nodes have no 'value', we know these can't ocurr after a variable
// assignment (would have been a ParseError).
// TODO: Solve better (https://phabricator.wikimedia.org/T327082).
// @phan-suppress-next-line PhanUndeclaredProperty
$v = new self( substr( $this->name, 1 ), $this->index + 1, $this->currentFileInfo );
// While some Less_Tree nodes have no 'value', we know these can't occur after a
// variable assignment (would have been a ParseError).
$name = '@' . $v->compile( $env )->value;
} else {
$name = $this->name;

View file

@ -1,12 +1,16 @@
<?php
/**
* Release numbers
* Version numbers
*/
class Less_Version {
public const version = '3.2.1'; // The current build number of less.php
public const less_version = '2.5.3'; // The less.js version that this build should be compatible with
public const cache_version = '253'; // The parser cache version
/* Current release version of less.php */
public const version = '4.2.0';
/* Upstream less.js version that this release should be compatible with */
public const less_version = '2.5.3';
/* Parser cache version */
public const cache_version = '253-1';
}

View file

@ -65,9 +65,9 @@ class Less_Visitor_extendFinder extends Less_Visitor {
$this->contexts[] = $rulesetNode->selectors;
}
public function allExtendsStackPush( $rulesetNode, $selectorPath, $extend, &$j ) {
public function allExtendsStackPush( $rulesetNode, $selectorPath, Less_Tree_Extend $extend, &$j ) {
$this->foundExtends = true;
$extend = clone $extend;
$extend = $extend->clone();
$extend->findSelfSelectors( $selectorPath );
$extend->ruleset = $rulesetNode;
if ( $j === 0 ) {

View file

@ -64,4 +64,12 @@ class Less_Visitor_joinSelector extends Less_Visitor {
}
}
public function visitDirective( $directiveNode ) {
$context = end( $this->contexts );
if ( $directiveNode->rules && count( $directiveNode->rules ) > 0 ) {
$directiveNode->rules[0]->root = $directiveNode->isRooted || count( $context ) === 0;
}
}
}

View file

@ -98,10 +98,10 @@ class Less_Visitor_processExtends extends Less_Visitor {
// may no longer be needed. $this->extendChainCount++;
if ( $iterationCount > 100 ) {
try{
try {
$selectorOne = $extendsToAdd[0]->selfSelectors[0]->toCSS();
$selectorTwo = $extendsToAdd[0]->selector->toCSS();
}catch ( Exception $e ) {
} catch ( Exception $e ) {
$selectorOne = "{unable to calculate}";
$selectorTwo = "{unable to calculate}";
}
@ -264,6 +264,9 @@ class Less_Visitor_processExtends extends Less_Visitor {
}
/**
* @param array $potentialMatch
* @param Less_Tree_Element[] $needleElements
* @param Less_Tree_Element $haystackElement
* @param int $hackstackElementIndex
*/
private function PotentialMatch( $potentialMatch, $needleElements, $haystackElement, $hackstackElementIndex ) {
@ -359,8 +362,17 @@ class Less_Visitor_processExtends extends Less_Visitor {
return true;
}
$elementValue1 = ( $elementValue1->value->value ?: $elementValue1->value );
$elementValue2 = ( $elementValue2->value->value ?: $elementValue2->value );
$elementValue1 = $elementValue1->value;
if ( $elementValue1 instanceof Less_Tree_Quoted ) {
$elementValue1 = $elementValue1->value;
}
$elementValue2 = $elementValue2->value;
if ( $elementValue2 instanceof Less_Tree_Quoted ) {
$elementValue2 = $elementValue2->value;
}
return $elementValue1 === $elementValue2;
}
@ -393,7 +405,12 @@ class Less_Visitor_processExtends extends Less_Visitor {
}
$newElements = array_merge(
array_slice( $selector->elements, $currentSelectorPathElementIndex, ( $match['index'] - $currentSelectorPathElementIndex ) ), // last parameter of array_slice is different than the last parameter of javascript's slice
array_slice(
$selector->elements,
$currentSelectorPathElementIndex,
// last parameter of array_slice is different than the last parameter of javascript's slice
$match['index'] - $currentSelectorPathElementIndex
),
[ $firstElement ],
array_slice( $replacementSelector->elements, 1 )
);

View file

@ -82,7 +82,8 @@ class Less_Visitor_toCSS extends Less_VisitorReplacing {
foreach ( $rulesetNode->rules as $ruleNode ) {
if ( $ruleNode instanceof Less_Tree_Rule && !$ruleNode->variable ) {
$msg = "properties must be inside selector blocks, they cannot be in the root. Index " . $ruleNode->index . ( $ruleNode->currentFileInfo ? ( ' Filename: ' . $ruleNode->currentFileInfo['filename'] ) : null );
$msg = "properties must be inside selector blocks, they cannot be in the root. Index " . $ruleNode->index .
( $ruleNode->currentFileInfo ? ' Filename: ' . $ruleNode->currentFileInfo['filename'] : null );
throw new Less_Exception_Compiler( $msg );
}
}
@ -195,7 +196,7 @@ class Less_Visitor_toCSS extends Less_VisitorReplacing {
}
$ruleCSS = $rule->toCSS();
if ( array_search( $ruleCSS, $ruleList ) !== false ) {
if ( in_array( $ruleCSS, $ruleList ) ) {
array_splice( $rules, $i, 1 );
} else {
$ruleList[] = $ruleCSS;

View file

@ -0,0 +1,197 @@
Less.php API
========
## Basic use
#### Parse strings
```php
$parser = new Less_Parser();
$parser->parse( '@color: #36c; .link { color: @color; } a { color: @color; }' );
$css = $parser->getCss();
```
#### Parse files
The `parseFile()` function takes two parameters:
* The absolute path to a `.less` file.
* The base URL for any relative image or CSS references in the `.less` file,
typically the same directory that contains the `.less` file or a public equivalent.
```php
$parser = new Less_Parser();
$parser->parseFile( '/var/www/mysite/bootstrap.less', 'https://example.org/mysite/' );
$css = $parser->getCss();
```
#### Handle invalid syntax
An exception will be thrown if the compiler encounters invalid LESS.
```php
try{
$parser = new Less_Parser();
$parser->parseFile( '/var/www/mysite/bootstrap.less', 'https://example.org/mysite/' );
$css = $parser->getCss();
} catch (Exception $e) {
echo $e->getMessage();
}
```
#### Parse multiple inputs
Less.php can parse multiple input sources (e.g. files and/or strings) and generate a single CSS output.
```php
$parser = new Less_Parser();
$parser->parseFile( '/var/www/mysite/bootstrap.less', '/mysite/' );
$parser->parse( '@color: #36c; .link { color: @color; } a { color: @color; }' );
$css = $parser->getCss();
```
#### Metadata
Less.php keeps track of which `.less` files have been parsed, i.e. the input
file(s) and any direct and indirect imports.
```php
$parser = new Less_Parser();
$parser->parseFile( '/var/www/mysite/bootstrap.less', '/mysite/' );
$css = $parser->getCss();
$files = $parser->AllParsedFiles();
```
#### Compress output
You can tell Less.php to remove comments and whitespace to generate minified CSS.
```php
$options = [ 'compress' => true ];
$parser = new Less_Parser( $options );
$parser->parseFile( '/var/www/mysite/bootstrap.less', '/mysite/' );
$css = $parser->getCss();
```
#### Get variables
You can use the `getVariables()` method to get an all variables defined and
their value in an associative array. Note that the input must be compiled first
by calling `getCss()`.
```php
$parser = new Less_Parser;
$parser->parseFile( '/var/www/mysite/bootstrap.less');
$css = $parser->getCss();
$variables = $parser->getVariables();
```
#### Set variables
Use the `ModifyVars()` method to inject additional variables, i.e. custom values
computed or accessed from your PHP code.
```php
$parser = new Less_Parser();
$parser->parseFile( '/var/www/mysite/bootstrap.less', '/mysite/' );
$parser->ModifyVars( [ 'font-size-base' => '16px' ] );
$css = $parser->getCss();
```
#### Import directories
By default, Less.php will look for imported files in the directory of the file passed to `parseFile()`.
If you use `parse()`, or if need to enable additional import directories, you can specify these by
calling `SetImportDirs()`.
```php
$directories = [ '/var/www/mysite/bootstrap/' => '/mysite/bootstrap/' ];
$parser = new Less_Parser();
$parser->SetImportDirs( $directories );
$parser->parseFile( '/var/www/mysite/theme.less', '/mysite/' );
$css = $parser->getCss();
```
## Caching
Compiling LESS code into CSS can be a time-consuming process. It is recommended to cache your results.
#### Basic cache
Use the `Less_Cache` class to save and reuse the results of compiling LESS files.
This class will check the modified time and size of each LESS file (including imported files) and
either re-use or re-generate the CSS output accordingly.
The cache files are determinstically named, based on the full list of referenced LESS files and the metadata (file path, file mtime, file size) of each file. This means that each time a change is made, a different cache filename is used.
```php
$lessFiles = [ '/var/www/mysite/bootstrap.less' => '/mysite/' ];
$options = [ 'cache_dir' => '/var/www/writable_folder' ];
$cssOutputFile = Less_Cache::Get( $lessFiles, $options );
$css = file_get_contents( '/var/www/writable_folder/' . $cssOutputFile );
```
#### Caching with variables
Passing custom variables to `Less_Cache::Get()`:
```php
$lessFiles = [ '/var/www/mysite/bootstrap.less' => '/mysite/' ];
$options = [ 'cache_dir' => '/var/www/writable_folder' ];
$variables = [ 'width' => '100px' ];
$cssOutputFile = Less_Cache::Get( $lessFiles, $options, $variables );
$css = file_get_contents( '/var/www/writable_folder/' . $cssOutputFile );
```
#### Incremental caching
In addition to the whole-output caching described above, Less.php also has the ability to keep an internal cache which allows re-parses to be faster by effectively only re-compiling portions that have changed.
## Source maps
Less.php supports v3 sourcemaps.
#### Inline
The sourcemap will be appended to the generated CSS file.
```php
$options = [ 'sourceMap' => true ];
$parser = new Less_Parser($options);
$parser->parseFile( '/var/www/mysite/bootstrap.less', '/mysite/' );
$css = $parser->getCss();
```
#### Saving to map file
```php
$options = [
'sourceMap' => true,
'sourceMapWriteTo' => '/var/www/mysite/writable_folder/filename.map',
'sourceMapURL' => '/mysite/writable_folder/filename.map',
];
$parser = new Less_Parser($options);
$parser->parseFile( '/var/www/mysite/bootstrap.less', '/mysite/' );
$css = $parser->getCss();
```
## Command line
An additional script has been included to use the Less.php compiler from the command line.
In its simplest invocation, you specify an input file and the compiled CSS is written to standard out:
```
$ lessc input.less > output.css
```
By using the `-w` flag you can watch a specified input file and have it compile as needed to the output file:
```
$ lessc -w input.less output.css
```
Errors from watch mode are written to standard out.
For more information, run `lessc --help`

View file

@ -0,0 +1,57 @@
<?php
/**
* Autoloader
*/
class Less_Autoloader {
/** @var bool */
protected static $registered = false;
/**
* Register the autoloader in the SPL autoloader
*
* @return void
* @throws Exception If there was an error in registration
*/
public static function register() {
if ( self::$registered ) {
return;
}
if ( !spl_autoload_register( [ 'Less_Autoloader', 'loadClass' ] ) ) {
throw new Exception( 'Unable to register Less_Autoloader::loadClass as an autoloading method.' );
}
self::$registered = true;
}
/**
* Unregister the autoloader
*
* @return void
*/
public static function unregister() {
spl_autoload_unregister( [ 'Less_Autoloader', 'loadClass' ] );
self::$registered = false;
}
/**
* Load the class
*
* @param string $className The class to load
*/
public static function loadClass( $className ) {
// handle only package classes
if ( strpos( $className, 'Less_' ) !== 0 ) {
return;
}
$className = substr( $className, 5 );
$fileName = __DIR__ . DIRECTORY_SEPARATOR . str_replace( '_', DIRECTORY_SEPARATOR, $className ) . '.php';
require $fileName;
return true;
}
}

View file

@ -0,0 +1,91 @@
# Changelog
## 3.2.1
* [All changes](https://gerrit.wikimedia.org/g/mediawiki/libs/less.php/+log/v3.2.1)
* Tree_Ruleset: Fix support for nested parent selectors (Timo Tijhof) [T204816](https://phabricator.wikimedia.org/T204816)
* Fix ParseError when interpolating variable after colon in selector (Timo Tijhof) [T327163](https://phabricator.wikimedia.org/T327163)
* Functions: Fix "Undefined property" warning on bad minmax arg
* Tree_Call: Include previous exception when catching functions (Robert Frunzke)
## 3.2.0
* [All changes](https://github.com/wikimedia/less.php/compare/v3.1.0...v3.2.0)
* Fix "Implicit conversion" PHP 8.1 warnings (Ayokunle Odusan)
* Fix "Creation of dynamic property" PHP 8.2 warnings (Bas Couwenberg)
* Fix "Creation of dynamic property" PHP 8.2 warnings (Rajesh Kumar)
* Tree_Url: Add support for "Url" type to `Parser::getVariables()` (ciroarcadio) [#51](https://github.com/wikimedia/less.php/pull/51)
* Tree_Import: Add support for importing URLs without file extension (Timo Tijhof) [#27](https://github.com/wikimedia/less.php/issues/27)
## 3.1.0
* [All changes](https://github.com/wikimedia/less.php/compare/v3.0.0...v3.1.0)
* Add PHP 8.0 support: Drop use of curly braces for sub-string eval (James D. Forrester)
* Make `Directive::__construct` $rules arg optional (fix PHP 7.4 warning) (Sam Reed)
* ProcessExtends: Improve performance by using a map for selectors and parents (Andrey Legayev)
## 3.0.0
* [All changes](https://github.com/wikimedia/less.php/compare/v2.0.0...v3.0.0)
* Raise PHP requirement from 7.1 to 7.2.9 (James Forrester)
## 2.0.0
* [All changes](https://github.com/wikimedia/less.php/compare/v1.8.2...v2.0.0)
* Relax PHP requirement down to 7.1, from 7.2.9 (Franz Liedke)
* Reflect recent breaking changes properly with the semantic versioning (James Forrester)
## 1.8.2
* [All changes](https://github.com/wikimedia/less.php/compare/v1.8.1...v1.8.2)
* Require PHP 7.2.9+, up from 5.3+ (James Forrester)
* release: Update Version.php with the current release ID (COBadger)
* Fix access array offset on value of type null (Michele Locati)
* Fix test suite on PHP 7.4 (Sergei Morozov)
## 1.8.1
* [All changes](https://github.com/wikimedia/less.php/compare/v1.8.0...v1.8.1)
* Another PHP 7.3 compatibility tweak
## 1.8.0
Library forked by Wikimedia, from [oyejorge/less.php](https://github.com/oyejorge/less.php).
* [All changes](https://github.com/wikimedia/less.php/compare/v1.7.0.13...v1.8.0)
* Supports up to PHP 7.3
* No longer tested against PHP 5, though it's still remains allowed in `composer.json` for HHVM compatibility
* Switched to [semantic versioning](https://semver.org/), hence version numbers now use 3 digits
## 1.7.0.13
* [All changes](https://github.com/wikimedia/less.php/compare/v1.7.0.12...v1.7.0.13)
* Fix composer.json (PSR-4 was invalid)
## 1.7.0.12
* [All changes](https://github.com/wikimedia/less.php/compare/v1.7.0.11...v1.7.0.12)
* set bin/lessc bit executable
* Add `gettingVariables` method to `Less_Parser`
## 1.7.0.11
* [All changes](https://github.com/wikimedia/less.php/compare/v1.7.0.10...v1.7.0.11)
* Fix realpath issue (windows)
* Set Less_Tree_Call property back to public ( Fix 258 266 267 issues from oyejorge/less.php)
## 1.7.0.10
* [All changes](https://github.com/wikimedia/less.php/compare/v1.7.0.9...v1.7.10)
* Add indentation option
* Add `optional` modifier for `@import`
* Fix $color in Exception messages
* take relative-url into account when building the cache filename
* urlArgs should be string no array()
* fix missing on NameValue type [#269](https://github.com/oyejorge/less.php/issues/269)
## 1.7.0.9
* [All changes](https://github.com/wikimedia/less.php/compare/v1.7.0.8...v1.7.0.9)
* Remove space at beginning of Version.php
* Revert require() paths in test interface

View file

@ -0,0 +1 @@
The development of this software is covered by a [Code of Conduct](https://www.mediawiki.org/wiki/Special:MyLanguage/Code_of_Conduct).

View file

@ -0,0 +1,276 @@
<?php
/**
* Utility for handling the generation and caching of css files
*/
class Less_Cache {
// directory less.php can use for storing data
public static $cache_dir = false;
// prefix for the storing data
public static $prefix = 'lessphp_';
// prefix for the storing vars
public static $prefix_vars = 'lessphpvars_';
// specifies the number of seconds after which data created by less.php will be seen as 'garbage' and potentially cleaned up
public static $gc_lifetime = 604800;
/**
* Save and reuse the results of compiled less files.
* The first call to Get() will generate css and save it.
* Subsequent calls to Get() with the same arguments will return the same css filename
*
* @param array $less_files Array of .less files to compile
* @param array $parser_options Array of compiler options
* @param array $modify_vars Array of variables
* @return string|false Name of the css file
*/
public static function Get( $less_files, $parser_options = [], $modify_vars = [] ) {
// check $cache_dir
if ( isset( $parser_options['cache_dir'] ) ) {
self::$cache_dir = $parser_options['cache_dir'];
}
if ( empty( self::$cache_dir ) ) {
throw new Exception( 'cache_dir not set' );
}
if ( isset( $parser_options['prefix'] ) ) {
self::$prefix = $parser_options['prefix'];
}
if ( empty( self::$prefix ) ) {
throw new Exception( 'prefix not set' );
}
if ( isset( $parser_options['prefix_vars'] ) ) {
self::$prefix_vars = $parser_options['prefix_vars'];
}
if ( empty( self::$prefix_vars ) ) {
throw new Exception( 'prefix_vars not set' );
}
self::CheckCacheDir();
$less_files = (array)$less_files;
// create a file for variables
if ( !empty( $modify_vars ) ) {
$lessvars = Less_Parser::serializeVars( $modify_vars );
$vars_file = self::$cache_dir . self::$prefix_vars . sha1( $lessvars ) . '.less';
if ( !file_exists( $vars_file ) ) {
file_put_contents( $vars_file, $lessvars );
}
$less_files += [ $vars_file => '/' ];
}
// generate name for compiled css file
$hash = md5( json_encode( $less_files ) );
$list_file = self::$cache_dir . self::$prefix . $hash . '.list';
// check cached content
if ( !isset( $parser_options['use_cache'] ) || $parser_options['use_cache'] === true ) {
if ( file_exists( $list_file ) ) {
self::ListFiles( $list_file, $list, $cached_name );
$compiled_name = self::CompiledName( $list, $hash );
// if $cached_name is the same as the $compiled name, don't regenerate
if ( !$cached_name || $cached_name === $compiled_name ) {
$output_file = self::OutputFile( $compiled_name, $parser_options );
if ( $output_file && file_exists( $output_file ) ) {
@touch( $list_file );
return basename( $output_file ); // for backwards compatibility, we just return the name of the file
}
}
}
}
$compiled = self::Cache( $less_files, $parser_options );
if ( !$compiled ) {
return false;
}
$compiled_name = self::CompiledName( $less_files, $hash );
$output_file = self::OutputFile( $compiled_name, $parser_options );
// save the file list
$list = $less_files;
$list[] = $compiled_name;
$cache = implode( "\n", $list );
file_put_contents( $list_file, $cache );
// save the css
file_put_contents( $output_file, $compiled );
// clean up
self::CleanCache();
return basename( $output_file );
}
/**
* Force the compiler to regenerate the cached css file
*
* @param array $less_files Array of .less files to compile
* @param array $parser_options Array of compiler options
* @param array $modify_vars Array of variables
* @return string Name of the css file
*/
public static function Regen( $less_files, $parser_options = [], $modify_vars = [] ) {
$parser_options['use_cache'] = false;
return self::Get( $less_files, $parser_options, $modify_vars );
}
public static function Cache( &$less_files, $parser_options = [] ) {
$parser_options['cache_dir'] = self::$cache_dir;
$parser = new Less_Parser( $parser_options );
// combine files
foreach ( $less_files as $file_path => $uri_or_less ) {
// treat as less markup if there are newline characters
if ( strpos( $uri_or_less, "\n" ) !== false ) {
$parser->Parse( $uri_or_less );
continue;
}
$parser->ParseFile( $file_path, $uri_or_less );
}
$compiled = $parser->getCss();
$less_files = $parser->allParsedFiles();
return $compiled;
}
private static function OutputFile( $compiled_name, $parser_options ) {
// custom output file
if ( !empty( $parser_options['output'] ) ) {
// relative to cache directory?
if ( preg_match( '#[\\\\/]#', $parser_options['output'] ) ) {
return $parser_options['output'];
}
return self::$cache_dir . $parser_options['output'];
}
return self::$cache_dir . $compiled_name;
}
private static function CompiledName( $files, $extrahash ) {
// save the file list
$temp = [ Less_Version::cache_version ];
foreach ( $files as $file ) {
$temp[] = filemtime( $file ) . "\t" . filesize( $file ) . "\t" . $file;
}
return self::$prefix . sha1( json_encode( $temp ) . $extrahash ) . '.css';
}
public static function SetCacheDir( $dir ) {
self::$cache_dir = $dir;
self::CheckCacheDir();
}
public static function CheckCacheDir() {
self::$cache_dir = str_replace( '\\', '/', self::$cache_dir );
self::$cache_dir = rtrim( self::$cache_dir, '/' ) . '/';
if ( !file_exists( self::$cache_dir ) ) {
if ( !mkdir( self::$cache_dir ) ) {
throw new Less_Exception_Parser( 'Less.php cache directory couldn\'t be created: ' . self::$cache_dir );
}
} elseif ( !is_dir( self::$cache_dir ) ) {
throw new Less_Exception_Parser( 'Less.php cache directory doesn\'t exist: ' . self::$cache_dir );
} elseif ( !is_writable( self::$cache_dir ) ) {
throw new Less_Exception_Parser( 'Less.php cache directory isn\'t writable: ' . self::$cache_dir );
}
}
/**
* Delete unused less.php files
*/
public static function CleanCache() {
static $clean = false;
if ( $clean || empty( self::$cache_dir ) ) {
return;
}
$clean = true;
// only remove files with extensions created by less.php
// css files removed based on the list files
$remove_types = [ 'lesscache' => 1,'list' => 1,'less' => 1,'map' => 1 ];
$files = scandir( self::$cache_dir );
if ( !$files ) {
return;
}
$check_time = time() - self::$gc_lifetime;
foreach ( $files as $file ) {
// don't delete if the file wasn't created with less.php
if ( strpos( $file, self::$prefix ) !== 0 ) {
continue;
}
$parts = explode( '.', $file );
$type = array_pop( $parts );
if ( !isset( $remove_types[$type] ) ) {
continue;
}
$full_path = self::$cache_dir . $file;
$mtime = filemtime( $full_path );
// don't delete if it's a relatively new file
if ( $mtime > $check_time ) {
continue;
}
// delete the list file and associated css file
if ( $type === 'list' ) {
self::ListFiles( $full_path, $list, $css_file_name );
if ( $css_file_name ) {
$css_file = self::$cache_dir . $css_file_name;
if ( file_exists( $css_file ) ) {
unlink( $css_file );
}
}
}
unlink( $full_path );
}
}
/**
* Get the list of less files and generated css file from a list file
*/
static function ListFiles( $list_file, &$list, &$css_file_name ) {
$list = explode( "\n", file_get_contents( $list_file ) );
// pop the cached name that should match $compiled_name
$css_file_name = array_pop( $list );
if ( !preg_match( '/^' . self::$prefix . '[a-f0-9]+\.css$/', $css_file_name ) ) {
$list[] = $css_file_name;
$css_file_name = false;
}
}
}

View file

@ -0,0 +1,176 @@
<?php
/**
* Utility for css colors
*
* @private
*/
class Less_Colors {
private const COLORS = [
'aliceblue' => '#f0f8ff',
'antiquewhite' => '#faebd7',
'aqua' => '#00ffff',
'aquamarine' => '#7fffd4',
'azure' => '#f0ffff',
'beige' => '#f5f5dc',
'bisque' => '#ffe4c4',
'black' => '#000000',
'blanchedalmond' => '#ffebcd',
'blue' => '#0000ff',
'blueviolet' => '#8a2be2',
'brown' => '#a52a2a',
'burlywood' => '#deb887',
'cadetblue' => '#5f9ea0',
'chartreuse' => '#7fff00',
'chocolate' => '#d2691e',
'coral' => '#ff7f50',
'cornflowerblue' => '#6495ed',
'cornsilk' => '#fff8dc',
'crimson' => '#dc143c',
'cyan' => '#00ffff',
'darkblue' => '#00008b',
'darkcyan' => '#008b8b',
'darkgoldenrod' => '#b8860b',
'darkgray' => '#a9a9a9',
'darkgrey' => '#a9a9a9',
'darkgreen' => '#006400',
'darkkhaki' => '#bdb76b',
'darkmagenta' => '#8b008b',
'darkolivegreen' => '#556b2f',
'darkorange' => '#ff8c00',
'darkorchid' => '#9932cc',
'darkred' => '#8b0000',
'darksalmon' => '#e9967a',
'darkseagreen' => '#8fbc8f',
'darkslateblue' => '#483d8b',
'darkslategray' => '#2f4f4f',
'darkslategrey' => '#2f4f4f',
'darkturquoise' => '#00ced1',
'darkviolet' => '#9400d3',
'deeppink' => '#ff1493',
'deepskyblue' => '#00bfff',
'dimgray' => '#696969',
'dimgrey' => '#696969',
'dodgerblue' => '#1e90ff',
'firebrick' => '#b22222',
'floralwhite' => '#fffaf0',
'forestgreen' => '#228b22',
'fuchsia' => '#ff00ff',
'gainsboro' => '#dcdcdc',
'ghostwhite' => '#f8f8ff',
'gold' => '#ffd700',
'goldenrod' => '#daa520',
'gray' => '#808080',
'grey' => '#808080',
'green' => '#008000',
'greenyellow' => '#adff2f',
'honeydew' => '#f0fff0',
'hotpink' => '#ff69b4',
'indianred' => '#cd5c5c',
'indigo' => '#4b0082',
'ivory' => '#fffff0',
'khaki' => '#f0e68c',
'lavender' => '#e6e6fa',
'lavenderblush' => '#fff0f5',
'lawngreen' => '#7cfc00',
'lemonchiffon' => '#fffacd',
'lightblue' => '#add8e6',
'lightcoral' => '#f08080',
'lightcyan' => '#e0ffff',
'lightgoldenrodyellow' => '#fafad2',
'lightgray' => '#d3d3d3',
'lightgrey' => '#d3d3d3',
'lightgreen' => '#90ee90',
'lightpink' => '#ffb6c1',
'lightsalmon' => '#ffa07a',
'lightseagreen' => '#20b2aa',
'lightskyblue' => '#87cefa',
'lightslategray' => '#778899',
'lightslategrey' => '#778899',
'lightsteelblue' => '#b0c4de',
'lightyellow' => '#ffffe0',
'lime' => '#00ff00',
'limegreen' => '#32cd32',
'linen' => '#faf0e6',
'magenta' => '#ff00ff',
'maroon' => '#800000',
'mediumaquamarine' => '#66cdaa',
'mediumblue' => '#0000cd',
'mediumorchid' => '#ba55d3',
'mediumpurple' => '#9370d8',
'mediumseagreen' => '#3cb371',
'mediumslateblue' => '#7b68ee',
'mediumspringgreen' => '#00fa9a',
'mediumturquoise' => '#48d1cc',
'mediumvioletred' => '#c71585',
'midnightblue' => '#191970',
'mintcream' => '#f5fffa',
'mistyrose' => '#ffe4e1',
'moccasin' => '#ffe4b5',
'navajowhite' => '#ffdead',
'navy' => '#000080',
'oldlace' => '#fdf5e6',
'olive' => '#808000',
'olivedrab' => '#6b8e23',
'orange' => '#ffa500',
'orangered' => '#ff4500',
'orchid' => '#da70d6',
'palegoldenrod' => '#eee8aa',
'palegreen' => '#98fb98',
'paleturquoise' => '#afeeee',
'palevioletred' => '#d87093',
'papayawhip' => '#ffefd5',
'peachpuff' => '#ffdab9',
'peru' => '#cd853f',
'pink' => '#ffc0cb',
'plum' => '#dda0dd',
'powderblue' => '#b0e0e6',
'purple' => '#800080',
'red' => '#ff0000',
'rosybrown' => '#bc8f8f',
'royalblue' => '#4169e1',
'saddlebrown' => '#8b4513',
'salmon' => '#fa8072',
'sandybrown' => '#f4a460',
'seagreen' => '#2e8b57',
'seashell' => '#fff5ee',
'sienna' => '#a0522d',
'silver' => '#c0c0c0',
'skyblue' => '#87ceeb',
'slateblue' => '#6a5acd',
'slategray' => '#708090',
'slategrey' => '#708090',
'snow' => '#fffafa',
'springgreen' => '#00ff7f',
'steelblue' => '#4682b4',
'tan' => '#d2b48c',
'teal' => '#008080',
'thistle' => '#d8bfd8',
'tomato' => '#ff6347',
'turquoise' => '#40e0d0',
'violet' => '#ee82ee',
'wheat' => '#f5deb3',
'white' => '#ffffff',
'whitesmoke' => '#f5f5f5',
'yellow' => '#ffff00',
'yellowgreen' => '#9acd32',
];
/**
* @param string $color
* @return bool
*/
public static function hasOwnProperty( string $color ): bool {
return isset( self::COLORS[$color] );
}
/**
* @param string $color Should be an existing color name,
* checked via hasOwnProperty()
* @return string the corresponding hexadecimal representation
*/
public static function color( string $color ): string {
return self::COLORS[$color];
}
}

View file

@ -0,0 +1,60 @@
<?php
/**
* @private
*/
abstract class Less_Configurable {
/**
* Array of options
*
* @var array
*/
protected $options = [];
/**
* Array of default options
*
* @var array
*/
protected $defaultOptions = [];
/**
* Set options
*
* If $options is an object it will be converted into an array by called
* it's toArray method.
*
* @param array|object $options
*/
public function setOptions( $options ) {
$options = array_intersect_key( $options, $this->defaultOptions );
$this->options = array_merge( $this->defaultOptions, $this->options, $options );
}
/**
* Get an option value by name
*
* If the option is empty or not set a NULL value will be returned.
*
* @param string $name
* @param mixed $default Default value if confiuration of $name is not present
* @return mixed
*/
public function getOption( $name, $default = null ) {
if ( isset( $this->options[$name] ) ) {
return $this->options[$name];
}
return $default;
}
/**
* Set an option
*
* @param string $name
* @param mixed $value
*/
public function setOption( $name, $value ) {
$this->options[$name] = $value;
}
}

View file

@ -0,0 +1,153 @@
<?php
/**
* @private
*/
class Less_Environment {
/**
* Information about the current file - for error reporting and importing and making urls relative etc.
*
* - rootpath: rootpath to append to URLs
*
* @var array|null $currentFileInfo;
*/
public $currentFileInfo;
/* Whether we are currently importing multiple copies */
public $importMultiple = false;
/**
* @var array
*/
public $frames = [];
/**
* @var array
*/
public $mediaBlocks = [];
/**
* @var array
*/
public $mediaPath = [];
public static $parensStack = 0;
public static $tabLevel = 0;
public static $lastRule = false;
public static $_outputMap;
public static $mixin_stack = 0;
/**
* @var array
*/
public $functions = [];
public function Init() {
self::$parensStack = 0;
self::$tabLevel = 0;
self::$lastRule = false;
self::$mixin_stack = 0;
if ( Less_Parser::$options['compress'] ) {
self::$_outputMap = [
',' => ',',
': ' => ':',
'' => '',
' ' => ' ',
':' => ' :',
'+' => '+',
'~' => '~',
'>' => '>',
'|' => '|',
'^' => '^',
'^^' => '^^'
];
} else {
self::$_outputMap = [
',' => ', ',
': ' => ': ',
'' => '',
' ' => ' ',
':' => ' :',
'+' => ' + ',
'~' => ' ~ ',
'>' => ' > ',
'|' => '|',
'^' => ' ^ ',
'^^' => ' ^^ '
];
}
}
public function copyEvalEnv( $frames = [] ) {
$new_env = new Less_Environment();
$new_env->frames = $frames;
return $new_env;
}
public static function isMathOn() {
return !Less_Parser::$options['strictMath'] || self::$parensStack;
}
public static function isPathRelative( $path ) {
return !preg_match( '/^(?:[a-z-]+:|\/)/', $path );
}
/**
* Canonicalize a path by resolving references to '/./', '/../'
* Does not remove leading "../"
* @param string $path or url
* @return string Canonicalized path
*/
public static function normalizePath( $path ) {
$segments = explode( '/', $path );
$segments = array_reverse( $segments );
$path = [];
$path_len = 0;
while ( $segments ) {
$segment = array_pop( $segments );
switch ( $segment ) {
case '.':
break;
case '..':
// @phan-suppress-next-line PhanTypeInvalidDimOffset False positive
if ( !$path_len || ( $path[$path_len - 1] === '..' ) ) {
$path[] = $segment;
$path_len++;
} else {
array_pop( $path );
$path_len--;
}
break;
default:
$path[] = $segment;
$path_len++;
break;
}
}
return implode( '/', $path );
}
public function unshiftFrame( $frame ) {
array_unshift( $this->frames, $frame );
}
public function shiftFrame() {
return array_shift( $this->frames );
}
}

View file

@ -0,0 +1,199 @@
<?php
/**
* @private
*/
class Less_Exception_Chunk extends Less_Exception_Parser {
protected $parserCurrentIndex = 0;
protected $emitFrom = 0;
protected $input_len;
/**
* @param string $input
* @param Exception|null $previous Previous exception
* @param int|null $index The current parser index
* @param array|null $currentFile The file
* @param int $code The exception code
*/
public function __construct( $input, Exception $previous = null, $index = null, $currentFile = null, $code = 0 ) {
$this->message = 'ParseError: Unexpected input'; // default message
$this->index = $index;
$this->currentFile = $currentFile;
$this->input = $input;
$this->input_len = strlen( $input );
$this->Chunks();
$this->genMessage();
}
/**
* See less.js chunks()
* We don't actually need the chunks
*/
protected function Chunks() {
$level = 0;
$parenLevel = 0;
$lastMultiCommentEndBrace = null;
$lastOpening = null;
$lastMultiComment = null;
$lastParen = null;
for ( $this->parserCurrentIndex = 0; $this->parserCurrentIndex < $this->input_len; $this->parserCurrentIndex++ ) {
$cc = $this->CharCode( $this->parserCurrentIndex );
if ( ( ( $cc >= 97 ) && ( $cc <= 122 ) ) || ( $cc < 34 ) ) {
// a-z or whitespace
continue;
}
switch ( $cc ) {
// (
case 40:
$parenLevel++;
$lastParen = $this->parserCurrentIndex;
break;
// )
case 41:
$parenLevel--;
if ( $parenLevel < 0 ) {
return $this->fail( "missing opening `(`" );
}
break;
// ;
case 59:
// if (!$parenLevel) { $this->emitChunk(); }
break;
// {
case 123:
$level++;
$lastOpening = $this->parserCurrentIndex;
break;
// }
case 125:
$level--;
if ( $level < 0 ) {
return $this->fail( "missing opening `{`" );
}
// if (!$level && !$parenLevel) { $this->emitChunk(); }
break;
// \
case 92:
if ( $this->parserCurrentIndex < $this->input_len - 1 ) {
$this->parserCurrentIndex++;
break;
}
return $this->fail( "unescaped `\\`" );
// ", ' and `
case 34:
case 39:
case 96:
$matched = 0;
$currentChunkStartIndex = $this->parserCurrentIndex;
for ( $this->parserCurrentIndex += 1; $this->parserCurrentIndex < $this->input_len; $this->parserCurrentIndex++ ) {
$cc2 = $this->CharCode( $this->parserCurrentIndex );
if ( $cc2 > 96 ) { continue;
}
if ( $cc2 == $cc ) { $matched = 1;
break;
}
if ( $cc2 == 92 ) { // \
if ( $this->parserCurrentIndex == $this->input_len - 1 ) {
return $this->fail( "unescaped `\\`" );
}
$this->parserCurrentIndex++;
}
}
if ( $matched ) { break;
}
return $this->fail( "unmatched `" . chr( $cc ) . "`", $currentChunkStartIndex );
// /, check for comment
case 47:
if ( $parenLevel || ( $this->parserCurrentIndex == $this->input_len - 1 ) ) { break;
}
$cc2 = $this->CharCode( $this->parserCurrentIndex + 1 );
if ( $cc2 == 47 ) {
// //, find lnfeed
for ( $this->parserCurrentIndex += 2; $this->parserCurrentIndex < $this->input_len; $this->parserCurrentIndex++ ) {
$cc2 = $this->CharCode( $this->parserCurrentIndex );
if ( ( $cc2 <= 13 ) && ( ( $cc2 == 10 ) || ( $cc2 == 13 ) ) ) { break;
}
}
} elseif ( $cc2 == 42 ) {
// /*, find */
$lastMultiComment = $currentChunkStartIndex = $this->parserCurrentIndex;
for ( $this->parserCurrentIndex += 2; $this->parserCurrentIndex < $this->input_len - 1; $this->parserCurrentIndex++ ) {
$cc2 = $this->CharCode( $this->parserCurrentIndex );
if ( $cc2 == 125 ) { $lastMultiCommentEndBrace = $this->parserCurrentIndex;
}
if ( $cc2 != 42 ) { continue;
}
if ( $this->CharCode( $this->parserCurrentIndex + 1 ) == 47 ) { break;
}
}
if ( $this->parserCurrentIndex == $this->input_len - 1 ) {
return $this->fail( "missing closing `*/`", $currentChunkStartIndex );
}
}
break;
// *, check for unmatched */
case 42:
if ( ( $this->parserCurrentIndex < $this->input_len - 1 ) && ( $this->CharCode( $this->parserCurrentIndex + 1 ) == 47 ) ) {
return $this->fail( "unmatched `/*`" );
}
break;
}
}
if ( $level !== 0 ) {
if ( ( $lastMultiComment > $lastOpening ) && ( $lastMultiCommentEndBrace > $lastMultiComment ) ) {
return $this->fail( "missing closing `}` or `*/`", $lastOpening );
} else {
return $this->fail( "missing closing `}`", $lastOpening );
}
} elseif ( $parenLevel !== 0 ) {
return $this->fail( "missing closing `)`", $lastParen );
}
// chunk didn't fail
//$this->emitChunk(true);
}
public function CharCode( $pos ) {
return ord( $this->input[$pos] );
}
public function fail( $msg, $index = null ) {
if ( !$index ) {
$this->index = $this->parserCurrentIndex;
} else {
$this->index = $index;
}
$this->message = 'ParseError: ' . $msg;
}
/*
function emitChunk( $force = false ){
$len = $this->parserCurrentIndex - $this->emitFrom;
if ((($len < 512) && !$force) || !$len) {
return;
}
$chunks[] = substr($this->input, $this->emitFrom, $this->parserCurrentIndex + 1 - $this->emitFrom );
$this->emitFrom = $this->parserCurrentIndex + 1;
}
*/
}

View file

@ -0,0 +1,8 @@
<?php
/**
* Compiler Exception
*/
class Less_Exception_Compiler extends Less_Exception_Parser {
}

View file

@ -0,0 +1,103 @@
<?php
/**
* Parser Exception
*/
class Less_Exception_Parser extends Exception {
/**
* The current file
*
* @var array
*/
public $currentFile;
/**
* The current parser index
*
* @var int
*/
public $index;
protected $input;
protected $details = [];
/**
* @param string|null $message
* @param Exception|null $previous Previous exception
* @param int|null $index The current parser index
* @param array|null $currentFile The file
* @param int $code The exception code
*/
public function __construct( $message = null, Exception $previous = null, $index = null, $currentFile = null, $code = 0 ) {
parent::__construct( $message, $code, $previous );
$this->currentFile = $currentFile;
$this->index = $index;
$this->genMessage();
}
protected function getInput() {
if ( !$this->input && $this->currentFile && $this->currentFile['filename'] && file_exists( $this->currentFile['filename'] ) ) {
$this->input = file_get_contents( $this->currentFile['filename'] );
}
}
/**
* Set a message based on the exception info
*/
public function genMessage() {
if ( $this->currentFile && $this->currentFile['filename'] ) {
$this->message .= ' in ' . basename( $this->currentFile['filename'] );
}
if ( $this->index !== null ) {
$this->getInput();
if ( $this->input ) {
$line = self::getLineNumber();
$this->message .= ' on line ' . $line . ', column ' . self::getColumn();
$lines = explode( "\n", $this->input );
$count = count( $lines );
$start_line = max( 0, $line - 3 );
$last_line = min( $count, $start_line + 6 );
$num_len = strlen( $last_line );
for ( $i = $start_line; $i < $last_line; $i++ ) {
$this->message .= "\n" . str_pad( (string)( $i + 1 ), $num_len, '0', STR_PAD_LEFT ) . '| ' . $lines[$i];
}
}
}
}
/**
* Returns the line number the error was encountered
*
* @return int
*/
public function getLineNumber() {
if ( $this->index ) {
// https://bugs.php.net/bug.php?id=49790
if ( ini_get( "mbstring.func_overload" ) ) {
return substr_count( substr( $this->input, 0, $this->index ), "\n" ) + 1;
} else {
return substr_count( $this->input, "\n", 0, $this->index ) + 1;
}
}
return 1;
}
/**
* Returns the column the error was encountered
*
* @return int
*/
public function getColumn() {
$part = substr( $this->input, 0, $this->index );
$pos = strrpos( $part, "\n" );
return $this->index - $pos;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -0,0 +1,17 @@
./Parser.php
./Colors.php
./Environment.php
./Functions.php
./Mime.php
./Tree.php
./Output.php
./Visitor.php
./VisitorReplacing.php
./Configurable.php
./Tree
./Visitor
./Exception/Parser.php
./Exception/
./Output
./SourceMap

View file

@ -0,0 +1,36 @@
<?php
/**
* Mime lookup
*
* @private
*/
class Less_Mime {
// this map is intentionally incomplete
// if you want more, install 'mime' dep
private static $types = [
'.htm' => 'text/html',
'.html' => 'text/html',
'.gif' => 'image/gif',
'.jpg' => 'image/jpeg',
'.jpeg' => 'image/jpeg',
'.png' => 'image/png',
'.ttf' => 'application/x-font-ttf',
'.otf' => 'application/x-font-otf',
'.eot' => 'application/vnd.ms-fontobject',
'.woff' => 'application/x-font-woff',
'.svg' => 'image/svg+xml',
];
public static function lookup( $filepath ) {
$parts = explode( '.', $filepath );
$ext = '.' . strtolower( array_pop( $parts ) );
return self::$types[$ext] ?? null;
}
public static function charsets_lookup( $type = null ) {
// assumes all text types are UTF-8
return $type && preg_match( '/^text\//', $type ) ? 'UTF-8' : '';
}
}

View file

@ -0,0 +1,18 @@
wikimedia/less.php. https://gerrit.wikimedia.org/g/mediawiki/libs/less.php
Copyright Matt Agar <https://github.com/agar>
Copyright Martin Jantošovič <https://github.com/Mordred>
Copyright Josh Schmidt <https://github.com/oyejorge>
Copyright Timo Tijhof <https://timotijhof.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -0,0 +1,46 @@
<?php
/**
* Parser output
*
* @private
*/
class Less_Output {
/**
* Output holder
*
* @var string[]
*/
protected $strs = [];
/**
* Adds a chunk to the stack
*
* @param string $chunk The chunk to output
* @param array|null $fileInfo The file information
* @param int $index The index
* @param mixed $mapLines
*/
public function add( $chunk, $fileInfo = null, $index = 0, $mapLines = null ) {
$this->strs[] = $chunk;
}
/**
* Is the output empty?
*
* @return bool
*/
public function isEmpty() {
return count( $this->strs ) === 0;
}
/**
* Converts the output to string
*
* @return string
*/
public function toString() {
return implode( '', $this->strs );
}
}

View file

@ -0,0 +1,117 @@
<?php
/**
* Parser output with source map
*
* @private
*/
class Less_Output_Mapped extends Less_Output {
/**
* The source map generator
*
* @var Less_SourceMap_Generator
*/
protected $generator;
/**
* Current line
*
* @var int
*/
protected $lineNumber = 0;
/**
* Current column
*
* @var int
*/
protected $column = 0;
/**
* Array of contents map (file and its content)
*
* @var array
*/
protected $contentsMap = [];
/**
* Constructor
*
* @param array $contentsMap Array of filename to contents map
* @param Less_SourceMap_Generator $generator
*/
public function __construct( array $contentsMap, $generator ) {
$this->contentsMap = $contentsMap;
$this->generator = $generator;
}
/**
* Adds a chunk to the stack
* The $index for less.php may be different from less.js since less.php does not chunkify inputs
*
* @param string $chunk
* @param array|null $fileInfo
* @param int $index
* @param mixed $mapLines
*/
public function add( $chunk, $fileInfo = null, $index = 0, $mapLines = null ) {
// ignore adding empty strings
if ( $chunk === '' ) {
return;
}
$sourceLines = [];
$sourceColumns = ' ';
if ( $fileInfo ) {
$url = $fileInfo['currentUri'];
if ( isset( $this->contentsMap[$url] ) ) {
$inputSource = substr( $this->contentsMap[$url], 0, $index );
$sourceLines = explode( "\n", $inputSource );
$sourceColumns = end( $sourceLines );
} else {
throw new Exception( 'Filename ' . $url . ' not in contentsMap' );
}
}
$lines = explode( "\n", $chunk );
$columns = end( $lines );
if ( $fileInfo ) {
if ( !$mapLines ) {
$this->generator->addMapping(
$this->lineNumber + 1, // generated_line
$this->column, // generated_column
count( $sourceLines ), // original_line
strlen( $sourceColumns ), // original_column
$fileInfo
);
} else {
for ( $i = 0, $count = count( $lines ); $i < $count; $i++ ) {
$this->generator->addMapping(
$this->lineNumber + $i + 1, // generated_line
$i === 0 ? $this->column : 0, // generated_column
count( $sourceLines ) + $i, // original_line
$i === 0 ? strlen( $sourceColumns ) : 0, // original_column
$fileInfo
);
}
}
}
if ( count( $lines ) === 1 ) {
$this->column += strlen( $columns );
} else {
$this->lineNumber += count( $lines ) - 1;
$this->column = strlen( $columns );
}
// add only chunk
parent::add( $chunk );
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,77 @@
[![Packagist](https://img.shields.io/packagist/v/wikimedia/less.php.svg?style=flat)](https://packagist.org/packages/wikimedia/less.php)
Less.php
========
This is a PHP port of the [official LESS processor](https://lesscss.org).
## About
The code structure of Less.php mirrors that of upstream Less.js to ensure compatibility and help reduce maintenance. The port is currently compatible with Less.js 2.5.3. Please note that "inline JavaScript expressions" (via eval or backticks) are not supported.
* [API § Caching](./API.md#caching), Less.php includes a file-based cache.
* [API § Source maps](./API.md#source-maps), Less.php supports v3 sourcemaps.
* [API § Command line](./API.md#command-line), the `lessc` command includes a watch mode.
## Installation
You can install the library with Composer or standalone.
If you have [Composer](https://getcomposer.org/download/) installed:
1. Run `composer require wikimedia/less.php`
2. Use `Less_Parser` in your code.
Or standalone:
1. [Download Less.php](https://gerrit.wikimedia.org/g/mediawiki/libs/less.php/+archive/HEAD.tar.gz) and upload the PHP files to your server.
2. Include the library:
```php
require_once '[path to]/less.php/lib/Less/Autoloader.php';
Less_Autoloader::register();
```
3. Use `Less_Parser` in your code.
## Security
The LESS processor language is powerful and includes features that may read or embed arbitrary files that the web server has access to, and features that may be computationally exensive if misused.
In general you should treat LESS files as being in the same trust domain as other server-side executables, such as PHP code. In particular, it is not recommended to allow people that use your web service to provide arbitrary LESS code for server-side processing.
_See also [SECURITY](./SECURITY.md)._
## Who uses Less.php?
* **[Wikipedia](https://en.wikipedia.org/wiki/MediaWiki)** and the MediaWiki platform ([docs](https://www.mediawiki.org/wiki/ResourceLoader/Architecture#Resource:_Styles)).
* **[Matomo](https://en.wikipedia.org/wiki/Matomo_(software))** ([docs](https://devdocs.magento.com/guides/v2.4/frontend-dev-guide/css-topics/custom_preprocess.html)).
* **[Magento](https://en.wikipedia.org/wiki/Magento)** as part of Adobe Commerce ([docs](https://developer.matomo.org/guides/asset-pipeline#vanilla-javascript-css-and-less-files)).
* **[Icinga](https://en.wikipedia.org/wiki/Icinga)** in Icinga Web ([docs](https://github.com/Icinga/icingaweb2)).
* **[Shopware](https://de.wikipedia.org/wiki/Shopware)** ([docs](https://developers.shopware.com/designers-guide/less/)).
## Integrations
Less.php has been integrated with various other projects.
#### Transitioning from Leafo/lessphp
If you're looking to transition from the [Leafo/lessphp](https://github.com/leafo/lessphp) library, use the `lessc.inc.php` adapter file that comes with Less.php.
This allows Less.php to be a drop-in replacement for Leafo/lessphp.
[Download Less.php](https://gerrit.wikimedia.org/g/mediawiki/libs/less.php/+archive/HEAD.tar.gz), unzip the files into your project, and include its `lessc.inc.php` instead.
Note: The `setPreserveComments` option is ignored. Less.php already preserves CSS block comments by default, and removes LESS inline comments.
#### Drupal
Less.php can be used with [Drupal's less module](https://drupal.org/project/less) via the `lessc.inc.php` adapter. [Download Less.php](https://gerrit.wikimedia.org/g/mediawiki/libs/less.php/+archive/HEAD.tar.gz) and unzip it so that `lessc.inc.php` is located at `sites/all/libraries/lessphp/lessc.inc.php`, then install the Drupal less module as usual.
#### WordPress
* [wp_enqueue_less](https://github.com/Ed-ITSolutions/wp_enqueue_less) is a Composer package for use in WordPress themes and plugins. It provides a `wp_enqueue_less()` function to automatically manage caching and compilation on-demand, and loads the compressed CSS on the page.
* [JBST framework](https://github.com/bassjobsen/jamedo-bootstrap-start-theme) bundles a copy of Less.php.
* The [lessphp plugin](https://wordpress.org/plugins/lessphp/) bundles a copy of Less.php for use in other plugins or themes. This dependency can also be combined with the [TGM Library](http://tgmpluginactivation.com/).
## Credits
Less.php was originally ported to PHP in 2011 by [Matt Agar](https://github.com/agar) and then updated by [Martin Jantošovič](https://github.com/Mordred) in 2012. From 2013 to 2017, [Josh Schmidt](https://github.com/oyejorge) lead development of the library. Since 2019, the library is maintained by Wikimedia Foundation.

View file

@ -0,0 +1,5 @@
# Security policy
Wikimedia takes security seriously. If you believe you have found a
security issue, see <https://www.mediawiki.org/wiki/Reporting_security_bugs>
for information on how to responsibly report it.

View file

@ -0,0 +1,185 @@
<?php
/**
* Encode / Decode Base64 VLQ.
*
* @private
*/
class Less_SourceMap_Base64VLQ {
/**
* Shift
*
* @var int
*/
private $shift = 5;
/**
* Mask
*
* @var int
*/
private $mask = 0x1F; // == (1 << shift) == 0b00011111
/**
* Continuation bit
*
* @var int
*/
private $continuationBit = 0x20; // == (mask - 1 ) == 0b00100000
/**
* Char to integer map
*
* @var array
*/
private $charToIntMap = [
'A' => 0, 'B' => 1, 'C' => 2, 'D' => 3, 'E' => 4, 'F' => 5, 'G' => 6,
'H' => 7,'I' => 8, 'J' => 9, 'K' => 10, 'L' => 11, 'M' => 12, 'N' => 13,
'O' => 14, 'P' => 15, 'Q' => 16, 'R' => 17, 'S' => 18, 'T' => 19, 'U' => 20,
'V' => 21, 'W' => 22, 'X' => 23, 'Y' => 24, 'Z' => 25, 'a' => 26, 'b' => 27,
'c' => 28, 'd' => 29, 'e' => 30, 'f' => 31, 'g' => 32, 'h' => 33, 'i' => 34,
'j' => 35, 'k' => 36, 'l' => 37, 'm' => 38, 'n' => 39, 'o' => 40, 'p' => 41,
'q' => 42, 'r' => 43, 's' => 44, 't' => 45, 'u' => 46, 'v' => 47, 'w' => 48,
'x' => 49, 'y' => 50, 'z' => 51, 0 => 52, 1 => 53, 2 => 54, 3 => 55, 4 => 56,
5 => 57, 6 => 58, 7 => 59, 8 => 60, 9 => 61, '+' => 62, '/' => 63,
];
/**
* Integer to char map
*
* @var array
*/
private $intToCharMap = [
0 => 'A', 1 => 'B', 2 => 'C', 3 => 'D', 4 => 'E', 5 => 'F', 6 => 'G',
7 => 'H', 8 => 'I', 9 => 'J', 10 => 'K', 11 => 'L', 12 => 'M', 13 => 'N',
14 => 'O', 15 => 'P', 16 => 'Q', 17 => 'R', 18 => 'S', 19 => 'T', 20 => 'U',
21 => 'V', 22 => 'W', 23 => 'X', 24 => 'Y', 25 => 'Z', 26 => 'a', 27 => 'b',
28 => 'c', 29 => 'd', 30 => 'e', 31 => 'f', 32 => 'g', 33 => 'h', 34 => 'i',
35 => 'j', 36 => 'k', 37 => 'l', 38 => 'm', 39 => 'n', 40 => 'o', 41 => 'p',
42 => 'q', 43 => 'r', 44 => 's', 45 => 't', 46 => 'u', 47 => 'v', 48 => 'w',
49 => 'x', 50 => 'y', 51 => 'z', 52 => '0', 53 => '1', 54 => '2', 55 => '3',
56 => '4', 57 => '5', 58 => '6', 59 => '7', 60 => '8', 61 => '9', 62 => '+',
63 => '/',
];
/**
* Constructor
*/
public function __construct() {
// I leave it here for future reference
// foreach(str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/') as $i => $char)
// {
// $this->charToIntMap[$char] = $i;
// $this->intToCharMap[$i] = $char;
// }
}
/**
* Convert from a two-complement value to a value where the sign bit is
* is placed in the least significant bit. For example, as decimals:
* 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
* 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
* We generate the value for 32 bit machines, hence -2147483648 becomes 1, not 4294967297,
* even on a 64 bit machine.
* @param int $aValue
*/
public function toVLQSigned( $aValue ) {
return 0xffffffff & ( $aValue < 0 ? ( ( -$aValue ) << 1 ) + 1 : ( $aValue << 1 ) + 0 );
}
/**
* Convert to a two-complement value from a value where the sign bit is
* is placed in the least significant bit. For example, as decimals:
* 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
* 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
* We assume that the value was generated with a 32 bit machine in mind.
* Hence
* 1 becomes -2147483648
* even on a 64 bit machine.
* @param int $aValue
*/
public function fromVLQSigned( $aValue ) {
return $aValue & 1 ? $this->zeroFill( ~$aValue + 2, 1 ) | ( -1 - 0x7fffffff ) : $this->zeroFill( $aValue, 1 );
}
/**
* Return the base 64 VLQ encoded value.
*
* @param int $aValue The value to encode
* @return string The encoded value
*/
public function encode( $aValue ) {
$encoded = '';
$vlq = $this->toVLQSigned( $aValue );
do
{
$digit = $vlq & $this->mask;
$vlq = $this->zeroFill( $vlq, $this->shift );
if ( $vlq > 0 ) {
$digit |= $this->continuationBit;
}
$encoded .= $this->base64Encode( $digit );
} while ( $vlq > 0 );
return $encoded;
}
/**
* Return the value decoded from base 64 VLQ.
*
* @param string $encoded The encoded value to decode
* @return int The decoded value
*/
public function decode( $encoded ) {
$vlq = 0;
$i = 0;
do
{
$digit = $this->base64Decode( $encoded[$i] );
$vlq |= ( $digit & $this->mask ) << ( $i * $this->shift );
$i++;
} while ( $digit & $this->continuationBit );
return $this->fromVLQSigned( $vlq );
}
/**
* Right shift with zero fill.
*
* @param int $a number to shift
* @param int $b number of bits to shift
* @return int
*/
public function zeroFill( $a, $b ) {
return ( $a >= 0 ) ? ( $a >> $b ) : ( $a >> $b ) & ( PHP_INT_MAX >> ( $b - 1 ) );
}
/**
* Encode single 6-bit digit as base64.
*
* @param int $number
* @return string
* @throws Exception If the number is invalid
*/
public function base64Encode( $number ) {
if ( $number < 0 || $number > 63 ) {
throw new Exception( sprintf( 'Invalid number "%s" given. Must be between 0 and 63.', (string)$number ) );
}
return $this->intToCharMap[$number];
}
/**
* Decode single 6-bit digit from base64
*
* @param string $char
* @return int
* @throws Exception If the number is invalid
*/
public function base64Decode( $char ) {
if ( !array_key_exists( $char, $this->charToIntMap ) ) {
throw new Exception( sprintf( 'Invalid base 64 digit "%s" given.', $char ) );
}
return $this->charToIntMap[$char];
}
}

View file

@ -0,0 +1,354 @@
<?php
/**
* Source map generator
*
* @private
*/
class Less_SourceMap_Generator extends Less_Configurable {
/**
* What version of source map does the generator generate?
*/
private const VERSION = 3;
/**
* Array of default options
*
* @var array
*/
protected $defaultOptions = [
// an optional source root, useful for relocating source files
// on a server or removing repeated values in the 'sources' entry.
// This value is prepended to the individual entries in the 'source' field.
'sourceRoot' => '',
// an optional name of the generated code that this source map is associated with.
'sourceMapFilename' => null,
// url of the map
'sourceMapURL' => null,
// absolute path to a file to write the map to
'sourceMapWriteTo' => null,
// output source contents?
'outputSourceFiles' => false,
// base path for filename normalization
'sourceMapRootpath' => '',
// base path for filename normalization
'sourceMapBasepath' => ''
];
/**
* The base64 VLQ encoder
*
* @var Less_SourceMap_Base64VLQ
*/
protected $encoder;
/**
* Array of mappings
*
* @var array
*/
protected $mappings = [];
/**
* The root node
*
* @var Less_Tree_Ruleset
*/
protected $root;
/**
* Array of contents map
*
* @var array
*/
protected $contentsMap = [];
/**
* File to content map
*
* @var array
*/
protected $sources = [];
protected $source_keys = [];
/**
* Constructor
*
* @param Less_Tree_Ruleset $root The root node
* @param array $contentsMap
* @param array $options Array of options
*/
public function __construct( Less_Tree_Ruleset $root, $contentsMap, $options = [] ) {
$this->root = $root;
$this->contentsMap = $contentsMap;
$this->encoder = new Less_SourceMap_Base64VLQ();
$this->SetOptions( $options );
$this->options['sourceMapRootpath'] = $this->fixWindowsPath( $this->options['sourceMapRootpath'], true );
$this->options['sourceMapBasepath'] = $this->fixWindowsPath( $this->options['sourceMapBasepath'], true );
}
/**
* Generates the CSS
*
* @return string
*/
public function generateCSS() {
$output = new Less_Output_Mapped( $this->contentsMap, $this );
// catch the output
$this->root->genCSS( $output );
$sourceMapUrl = $this->getOption( 'sourceMapURL' );
$sourceMapFilename = $this->getOption( 'sourceMapFilename' );
$sourceMapContent = $this->generateJson();
$sourceMapWriteTo = $this->getOption( 'sourceMapWriteTo' );
if ( !$sourceMapUrl && $sourceMapFilename ) {
$sourceMapUrl = $this->normalizeFilename( $sourceMapFilename );
}
// write map to a file
if ( $sourceMapWriteTo ) {
$this->saveMap( $sourceMapWriteTo, $sourceMapContent );
}
// inline the map
if ( !$sourceMapUrl ) {
$sourceMapUrl = sprintf( 'data:application/json,%s', Less_Functions::encodeURIComponent( $sourceMapContent ) );
}
if ( $sourceMapUrl ) {
$output->add( sprintf( '/*# sourceMappingURL=%s */', $sourceMapUrl ) );
}
return $output->toString();
}
/**
* Saves the source map to a file
*
* @param string $file The absolute path to a file
* @param string $content The content to write
* @throws Exception If the file could not be saved
*/
protected function saveMap( $file, $content ) {
$dir = dirname( $file );
// directory does not exist
if ( !is_dir( $dir ) ) {
// FIXME: create the dir automatically?
throw new Exception( sprintf( 'The directory "%s" does not exist. Cannot save the source map.', $dir ) );
}
// FIXME: proper saving, with dir write check!
if ( file_put_contents( $file, $content ) === false ) {
throw new Exception( sprintf( 'Cannot save the source map to "%s"', $file ) );
}
return true;
}
/**
* Normalizes the filename
*
* @param string $filename
* @return string
*/
protected function normalizeFilename( $filename ) {
$filename = $this->fixWindowsPath( $filename );
$rootpath = $this->getOption( 'sourceMapRootpath' );
$basePath = $this->getOption( 'sourceMapBasepath' );
// "Trim" the 'sourceMapBasepath' from the output filename.
if ( is_string( $basePath ) && strpos( $filename, $basePath ) === 0 ) {
$filename = substr( $filename, strlen( $basePath ) );
}
// Remove extra leading path separators.
if ( strpos( $filename, '\\' ) === 0 || strpos( $filename, '/' ) === 0 ) {
$filename = substr( $filename, 1 );
}
return $rootpath . $filename;
}
/**
* Adds a mapping
*
* @param int $generatedLine The line number in generated file
* @param int $generatedColumn The column number in generated file
* @param int $originalLine The line number in original file
* @param int $originalColumn The column number in original file
* @param array $fileInfo The original source file
*/
public function addMapping( $generatedLine, $generatedColumn, $originalLine, $originalColumn, $fileInfo ) {
$this->mappings[] = [
'generated_line' => $generatedLine,
'generated_column' => $generatedColumn,
'original_line' => $originalLine,
'original_column' => $originalColumn,
'source_file' => $fileInfo['currentUri']
];
$this->sources[$fileInfo['currentUri']] = $fileInfo['filename'];
}
/**
* Generates the JSON source map
*
* @return string
* @see https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#
*/
protected function generateJson() {
$sourceMap = [];
$mappings = $this->generateMappings();
// File version (always the first entry in the object) and must be a positive integer.
$sourceMap['version'] = self::VERSION;
// An optional name of the generated code that this source map is associated with.
$file = $this->getOption( 'sourceMapFilename' );
if ( $file ) {
$sourceMap['file'] = $file;
}
// An optional source root, useful for relocating source files on a server or removing repeated values in the 'sources' entry. This value is prepended to the individual entries in the 'source' field.
$root = $this->getOption( 'sourceRoot' );
if ( $root ) {
$sourceMap['sourceRoot'] = $root;
}
// A list of original sources used by the 'mappings' entry.
$sourceMap['sources'] = [];
foreach ( $this->sources as $source_uri => $source_filename ) {
$sourceMap['sources'][] = $this->normalizeFilename( $source_filename );
}
// A list of symbol names used by the 'mappings' entry.
$sourceMap['names'] = [];
// A string with the encoded mapping data.
$sourceMap['mappings'] = $mappings;
if ( $this->getOption( 'outputSourceFiles' ) ) {
// An optional list of source content, useful when the 'source' can't be hosted.
// The contents are listed in the same order as the sources above.
// 'null' may be used if some original sources should be retrieved by name.
$sourceMap['sourcesContent'] = $this->getSourcesContent();
}
// less.js compat fixes
if ( count( $sourceMap['sources'] ) && empty( $sourceMap['sourceRoot'] ) ) {
unset( $sourceMap['sourceRoot'] );
}
return json_encode( $sourceMap );
}
/**
* Returns the sources contents
*
* @return array|null
*/
protected function getSourcesContent() {
if ( empty( $this->sources ) ) {
return;
}
$content = [];
foreach ( $this->sources as $sourceFile ) {
$content[] = file_get_contents( $sourceFile );
}
return $content;
}
/**
* Generates the mappings string
*
* @return string
*/
public function generateMappings() {
if ( !count( $this->mappings ) ) {
return '';
}
$this->source_keys = array_flip( array_keys( $this->sources ) );
// group mappings by generated line number.
$groupedMap = $groupedMapEncoded = [];
foreach ( $this->mappings as $m ) {
$groupedMap[$m['generated_line']][] = $m;
}
ksort( $groupedMap );
$lastGeneratedLine = $lastOriginalIndex = $lastOriginalLine = $lastOriginalColumn = 0;
foreach ( $groupedMap as $lineNumber => $line_map ) {
while ( ++$lastGeneratedLine < $lineNumber ) {
$groupedMapEncoded[] = ';';
}
$lineMapEncoded = [];
$lastGeneratedColumn = 0;
foreach ( $line_map as $m ) {
$mapEncoded = $this->encoder->encode( $m['generated_column'] - $lastGeneratedColumn );
$lastGeneratedColumn = $m['generated_column'];
// find the index
if ( $m['source_file'] ) {
$index = $this->findFileIndex( $m['source_file'] );
if ( $index !== false ) {
$mapEncoded .= $this->encoder->encode( $index - $lastOriginalIndex );
$lastOriginalIndex = $index;
// lines are stored 0-based in SourceMap spec version 3
$mapEncoded .= $this->encoder->encode( $m['original_line'] - 1 - $lastOriginalLine );
$lastOriginalLine = $m['original_line'] - 1;
$mapEncoded .= $this->encoder->encode( $m['original_column'] - $lastOriginalColumn );
$lastOriginalColumn = $m['original_column'];
}
}
$lineMapEncoded[] = $mapEncoded;
}
$groupedMapEncoded[] = implode( ',', $lineMapEncoded ) . ';';
}
return rtrim( implode( $groupedMapEncoded ), ';' );
}
/**
* Finds the index for the filename
*
* @param string $filename
* @return int|false
*/
protected function findFileIndex( $filename ) {
return $this->source_keys[$filename];
}
/**
* fix windows paths
* @param string $path
* @param bool $addEndSlash
* @return string
*/
public function fixWindowsPath( $path, $addEndSlash = false ) {
$slash = ( $addEndSlash ) ? '/' : '';
if ( !empty( $path ) ) {
$path = str_replace( '\\', '/', $path );
$path = rtrim( $path, '/' ) . $slash;
}
return $path;
}
}

View file

@ -0,0 +1,95 @@
<?php
/**
* Tree
*
* TODO: Callers often use `property_exists(, 'value')` to distinguish
* tree nodes that are considerd value-holding. Refactor this to move
* the 'value' property that most subclasses implement to there, and use
* something else (special value, method, or intermediate class?) to
* signal whether a subclass is considered value-holding.
*/
class Less_Tree {
public $cache_string;
public $parensInOp = false;
public $extendOnEveryPath;
public $allExtends;
public function toCSS() {
$output = new Less_Output();
$this->genCSS( $output );
return $output->toString();
}
/**
* Generate CSS by adding it to the output object
*
* @param Less_Output $output The output
* @return void
*/
public function genCSS( $output ) {
}
public function compile( $env ) {
return $this;
}
/**
* @param Less_Output $output
* @param Less_Tree_Ruleset[] $rules
*/
public static function outputRuleset( $output, $rules ) {
$ruleCnt = count( $rules );
Less_Environment::$tabLevel++;
// Compressed
if ( Less_Parser::$options['compress'] ) {
$output->add( '{' );
for ( $i = 0; $i < $ruleCnt; $i++ ) {
$rules[$i]->genCSS( $output );
}
$output->add( '}' );
Less_Environment::$tabLevel--;
return;
}
// Non-compressed
$tabSetStr = "\n" . str_repeat( Less_Parser::$options['indentation'], Less_Environment::$tabLevel - 1 );
$tabRuleStr = $tabSetStr . Less_Parser::$options['indentation'];
$output->add( " {" );
for ( $i = 0; $i < $ruleCnt; $i++ ) {
$output->add( $tabRuleStr );
$rules[$i]->genCSS( $output );
}
Less_Environment::$tabLevel--;
$output->add( $tabSetStr . '}' );
}
public function accept( $visitor ) {
}
public static function ReferencedArray( $rules ) {
foreach ( $rules as $rule ) {
if ( method_exists( $rule, 'markReferenced' ) ) {
// @phan-suppress-next-line PhanUndeclaredMethod
$rule->markReferenced();
}
}
}
/**
* Requires php 5.3+
*/
public static function __set_state( $args ) {
$class = get_called_class();
$obj = new $class( null, null, null, null );
foreach ( $args as $key => $val ) {
$obj->$key = $val;
}
return $obj;
}
}

View file

@ -0,0 +1,44 @@
<?php
/**
* @private
*/
class Less_Tree_Alpha extends Less_Tree {
public $value;
public $type = 'Alpha';
public function __construct( $val ) {
$this->value = $val;
}
// function accept( $visitor ){
// $this->value = $visitor->visit( $this->value );
//}
public function compile( $env ) {
if ( is_object( $this->value ) ) {
$this->value = $this->value->compile( $env );
}
return $this;
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ) {
$output->add( "alpha(opacity=" );
if ( is_string( $this->value ) ) {
$output->add( $this->value );
} else {
$this->value->genCSS( $output );
}
$output->add( ')' );
}
public function toCSS() {
return "alpha(opacity=" . ( is_string( $this->value ) ? $this->value : $this->value->toCSS() ) . ")";
}
}

View file

@ -0,0 +1,54 @@
<?php
/**
* @private
*/
class Less_Tree_Anonymous extends Less_Tree {
public $value;
public $quote;
public $index;
public $mapLines;
public $currentFileInfo;
public $type = 'Anonymous';
/**
* @param int $index
* @param bool|null $mapLines
*/
public function __construct( $value, $index = null, $currentFileInfo = null, $mapLines = null ) {
$this->value = $value;
$this->index = $index;
$this->mapLines = $mapLines;
$this->currentFileInfo = $currentFileInfo;
}
public function compile( $env ) {
return new Less_Tree_Anonymous( $this->value, $this->index, $this->currentFileInfo, $this->mapLines );
}
public function compare( $x ) {
if ( !is_object( $x ) ) {
return -1;
}
$left = $this->toCSS();
$right = $x->toCSS();
if ( $left === $right ) {
return 0;
}
return $left < $right ? -1 : 1;
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ) {
$output->add( $this->value, $this->currentFileInfo, $this->index, $this->mapLines );
}
public function toCSS() {
return $this->value;
}
}

View file

@ -0,0 +1,35 @@
<?php
/**
* @private
*/
class Less_Tree_Assignment extends Less_Tree {
public $key;
public $value;
public $type = 'Assignment';
public function __construct( $key, $val ) {
$this->key = $key;
$this->value = $val;
}
public function accept( $visitor ) {
$this->value = $visitor->visitObj( $this->value );
}
public function compile( $env ) {
return new Less_Tree_Assignment( $this->key, $this->value->compile( $env ) );
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ) {
$output->add( $this->key . '=' );
$this->value->genCSS( $output );
}
public function toCss() {
return $this->key . '=' . $this->value->toCSS();
}
}

View file

@ -0,0 +1,49 @@
<?php
/**
* @private
*/
class Less_Tree_Attribute extends Less_Tree {
public $key;
public $op;
public $value;
public $type = 'Attribute';
public function __construct( $key, $op, $value ) {
$this->key = $key;
$this->op = $op;
$this->value = $value;
}
public function compile( $env ) {
$key_obj = is_object( $this->key );
$val_obj = is_object( $this->value );
if ( !$key_obj && !$val_obj ) {
return $this;
}
return new Less_Tree_Attribute(
$key_obj ? $this->key->compile( $env ) : $this->key,
$this->op,
$val_obj ? $this->value->compile( $env ) : $this->value );
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ) {
$output->add( $this->toCSS() );
}
public function toCSS() {
$value = $this->key;
if ( $this->op ) {
$value .= $this->op;
$value .= ( is_object( $this->value ) ? $this->value->toCSS() : $this->value );
}
return '[' . $value . ']';
}
}

View file

@ -0,0 +1,116 @@
<?php
/**
* @private
*/
class Less_Tree_Call extends Less_Tree {
public $value;
public $name;
public $args;
public $index;
public $currentFileInfo;
public $type = 'Call';
public function __construct( $name, $args, $index, $currentFileInfo = null ) {
$this->name = $name;
$this->args = $args;
$this->index = $index;
$this->currentFileInfo = $currentFileInfo;
}
public function accept( $visitor ) {
$this->args = $visitor->visitArray( $this->args );
}
//
// When evaluating a function call,
// we either find the function in `tree.functions` [1],
// in which case we call it, passing the evaluated arguments,
// or we simply print it out as it appeared originally [2].
//
// The *functions.js* file contains the built-in functions.
//
// The reason why we evaluate the arguments, is in the case where
// we try to pass a variable to a function, like: `saturate(@color)`.
// The function should receive the value, not the variable.
//
public function compile( $env = null ) {
$args = [];
foreach ( $this->args as $a ) {
$args[] = $a->compile( $env );
}
$nameLC = strtolower( $this->name );
switch ( $nameLC ) {
case '%':
$nameLC = '_percent';
break;
case 'get-unit':
$nameLC = 'getunit';
break;
case 'data-uri':
$nameLC = 'datauri';
break;
case 'svg-gradient':
$nameLC = 'svggradient';
break;
}
$result = null;
if ( $nameLC === 'default' ) {
$result = Less_Tree_DefaultFunc::compile();
} else {
$func = null;
if ( method_exists( 'Less_Functions', $nameLC ) ) {
$functions = new Less_Functions( $env, $this->currentFileInfo );
$func = [ $functions, $nameLC ];
} elseif ( isset( $env->functions[$nameLC] ) && is_callable( $env->functions[$nameLC] ) ) {
$func = $env->functions[$nameLC];
}
// If the function name isn't known to LESS, output it unchanged as CSS.
if ( $func ) {
try {
$result = call_user_func_array( $func, $args );
} catch ( Exception $e ) {
// Preserve original trace, especially from custom functions.
// https://github.com/wikimedia/less.php/issues/38
throw new Less_Exception_Compiler(
'error evaluating function `' . $this->name . '` ' . $e->getMessage()
. ' index: ' . $this->index,
$e
);
}
}
}
if ( $result !== null ) {
return $result;
}
return new Less_Tree_Call( $this->name, $args, $this->index, $this->currentFileInfo );
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ) {
$output->add( $this->name . '(', $this->currentFileInfo, $this->index );
$args_len = count( $this->args );
for ( $i = 0; $i < $args_len; $i++ ) {
$this->args[$i]->genCSS( $output );
if ( $i + 1 < $args_len ) {
$output->add( ', ' );
}
}
$output->add( ')' );
}
// public function toCSS(){
// return $this->compile()->toCSS();
//}
}

View file

@ -0,0 +1,228 @@
<?php
/**
* @private
*/
class Less_Tree_Color extends Less_Tree {
public $rgb;
public $alpha;
public $isTransparentKeyword;
public $type = 'Color';
public function __construct( $rgb, $a = 1, $isTransparentKeyword = null ) {
if ( $isTransparentKeyword ) {
$this->rgb = $rgb;
$this->alpha = $a;
$this->isTransparentKeyword = true;
return;
}
$this->rgb = [];
if ( is_array( $rgb ) ) {
$this->rgb = $rgb;
} elseif ( strlen( $rgb ) == 6 ) {
foreach ( str_split( $rgb, 2 ) as $c ) {
$this->rgb[] = hexdec( $c );
}
} else {
foreach ( str_split( $rgb, 1 ) as $c ) {
$this->rgb[] = hexdec( $c . $c );
}
}
$this->alpha = is_numeric( $a ) ? $a : 1;
}
public function luma() {
$r = $this->rgb[0] / 255;
$g = $this->rgb[1] / 255;
$b = $this->rgb[2] / 255;
$r = ( $r <= 0.03928 ) ? $r / 12.92 : pow( ( ( $r + 0.055 ) / 1.055 ), 2.4 );
$g = ( $g <= 0.03928 ) ? $g / 12.92 : pow( ( ( $g + 0.055 ) / 1.055 ), 2.4 );
$b = ( $b <= 0.03928 ) ? $b / 12.92 : pow( ( ( $b + 0.055 ) / 1.055 ), 2.4 );
return 0.2126 * $r + 0.7152 * $g + 0.0722 * $b;
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ) {
$output->add( $this->toCSS() );
}
public function toCSS( $doNotCompress = false ) {
$compress = Less_Parser::$options['compress'] && !$doNotCompress;
$alpha = Less_Functions::fround( $this->alpha );
//
// If we have some transparency, the only way to represent it
// is via `rgba`. Otherwise, we use the hex representation,
// which has better compatibility with older browsers.
// Values are capped between `0` and `255`, rounded and zero-padded.
//
if ( $alpha < 1 ) {
if ( ( $alpha === 0 || $alpha === 0.0 ) && isset( $this->isTransparentKeyword ) && $this->isTransparentKeyword ) {
return 'transparent';
}
$values = [];
foreach ( $this->rgb as $c ) {
$values[] = Less_Functions::clamp( round( $c ), 255 );
}
$values[] = $alpha;
$glue = ( $compress ? ',' : ', ' );
return "rgba(" . implode( $glue, $values ) . ")";
} else {
$color = $this->toRGB();
if ( $compress ) {
// Convert color to short format
if ( $color[1] === $color[2] && $color[3] === $color[4] && $color[5] === $color[6] ) {
$color = '#' . $color[1] . $color[3] . $color[5];
}
}
return $color;
}
}
//
// Operations have to be done per-channel, if not,
// channels will spill onto each other. Once we have
// our result, in the form of an integer triplet,
// we create a new Color node to hold the result.
//
/**
* @param string $op
*/
public function operate( $op, $other ) {
$rgb = [];
$alpha = $this->alpha * ( 1 - $other->alpha ) + $other->alpha;
for ( $c = 0; $c < 3; $c++ ) {
$rgb[$c] = Less_Functions::operate( $op, $this->rgb[$c], $other->rgb[$c] );
}
return new Less_Tree_Color( $rgb, $alpha );
}
public function toRGB() {
return $this->toHex( $this->rgb );
}
public function toHSL() {
$r = $this->rgb[0] / 255;
$g = $this->rgb[1] / 255;
$b = $this->rgb[2] / 255;
$a = $this->alpha;
$max = max( $r, $g, $b );
$min = min( $r, $g, $b );
$l = ( $max + $min ) / 2;
$d = $max - $min;
$h = $s = 0;
if ( $max !== $min ) {
$s = $l > 0.5 ? $d / ( 2 - $max - $min ) : $d / ( $max + $min );
switch ( $max ) {
case $r:
$h = ( $g - $b ) / $d + ( $g < $b ? 6 : 0 );
break;
case $g:
$h = ( $b - $r ) / $d + 2;
break;
case $b:
$h = ( $r - $g ) / $d + 4;
break;
}
$h /= 6;
}
return [ 'h' => $h * 360, 's' => $s, 'l' => $l, 'a' => $a ];
}
// Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
public function toHSV() {
$r = $this->rgb[0] / 255;
$g = $this->rgb[1] / 255;
$b = $this->rgb[2] / 255;
$a = $this->alpha;
$max = max( $r, $g, $b );
$min = min( $r, $g, $b );
$v = $max;
$d = $max - $min;
if ( $max === 0 ) {
$s = 0;
} else {
$s = $d / $max;
}
$h = 0;
if ( $max !== $min ) {
switch ( $max ) {
case $r:
$h = ( $g - $b ) / $d + ( $g < $b ? 6 : 0 );
break;
case $g:
$h = ( $b - $r ) / $d + 2;
break;
case $b:
$h = ( $r - $g ) / $d + 4;
break;
}
$h /= 6;
}
return [ 'h' => $h * 360, 's' => $s, 'v' => $v, 'a' => $a ];
}
public function toARGB() {
$argb = array_merge( (array)Less_Parser::round( $this->alpha * 255 ), $this->rgb );
return $this->toHex( $argb );
}
public function compare( $x ) {
if ( !property_exists( $x, 'rgb' ) ) {
return -1;
}
return ( $x->rgb[0] === $this->rgb[0] &&
$x->rgb[1] === $this->rgb[1] &&
$x->rgb[2] === $this->rgb[2] &&
$x->alpha === $this->alpha ) ? 0 : -1;
}
public function toHex( $v ) {
$ret = '#';
foreach ( $v as $c ) {
$c = Less_Functions::clamp( Less_Parser::round( $c ), 255 );
if ( $c < 16 ) {
$ret .= '0';
}
$ret .= dechex( $c );
}
return $ret;
}
/**
* @param string $keyword
*/
public static function fromKeyword( $keyword ) {
$keyword = strtolower( $keyword );
if ( Less_Colors::hasOwnProperty( $keyword ) ) {
// detect named color
return new Less_Tree_Color( substr( Less_Colors::color( $keyword ), 1 ) );
}
if ( $keyword === 'transparent' ) {
return new Less_Tree_Color( [ 0, 0, 0 ], 0, true );
}
}
}

View file

@ -0,0 +1,43 @@
<?php
/**
* @private
*/
class Less_Tree_Comment extends Less_Tree {
public $value;
public $silent;
public $isReferenced;
public $currentFileInfo;
public $type = 'Comment';
public function __construct( $value, $silent, $index = null, $currentFileInfo = null ) {
$this->value = $value;
$this->silent = (bool)$silent;
$this->currentFileInfo = $currentFileInfo;
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ) {
// if( $this->debugInfo ){
//$output->add( tree.debugInfo($env, $this), $this->currentFileInfo, $this->index);
//}
$output->add( trim( $this->value ) );// TODO shouldn't need to trim, we shouldn't grab the \n
}
public function toCSS() {
return Less_Parser::$options['compress'] ? '' : $this->value;
}
public function isSilent() {
$isReference = ( $this->currentFileInfo && isset( $this->currentFileInfo['reference'] ) && ( !isset( $this->isReferenced ) || !$this->isReferenced ) );
$isCompressed = Less_Parser::$options['compress'] && !preg_match( '/^\/\*!/', $this->value );
return $this->silent || $isReference || $isCompressed;
}
public function markReferenced() {
$this->isReferenced = true;
}
}

View file

@ -0,0 +1,68 @@
<?php
/**
* @private
*/
class Less_Tree_Condition extends Less_Tree {
public $op;
public $lvalue;
public $rvalue;
public $index;
public $negate;
public $type = 'Condition';
public function __construct( $op, $l, $r, $i = 0, $negate = false ) {
$this->op = trim( $op );
$this->lvalue = $l;
$this->rvalue = $r;
$this->index = $i;
$this->negate = $negate;
}
public function accept( $visitor ) {
$this->lvalue = $visitor->visitObj( $this->lvalue );
$this->rvalue = $visitor->visitObj( $this->rvalue );
}
public function compile( $env ) {
$a = $this->lvalue->compile( $env );
$b = $this->rvalue->compile( $env );
switch ( $this->op ) {
case 'and':
$result = $a && $b;
break;
case 'or':
$result = $a || $b;
break;
default:
if ( Less_Parser::is_method( $a, 'compare' ) ) {
$result = $a->compare( $b );
} elseif ( Less_Parser::is_method( $b, 'compare' ) ) {
$result = $b->compare( $a );
} else {
throw new Less_Exception_Compiler( 'Unable to perform comparison', null, $this->index );
}
switch ( $result ) {
case -1:
$result = $this->op === '<' || $this->op === '=<' || $this->op === '<=';
break;
case 0:
$result = $this->op === '=' || $this->op === '>=' || $this->op === '=<' || $this->op === '<=';
break;
case 1:
$result = $this->op === '>' || $this->op === '>=';
break;
}
break;
}
return $this->negate ? !$result : $result;
}
}

View file

@ -0,0 +1,30 @@
<?php
/**
* @private
*/
class Less_Tree_DefaultFunc {
static $error_;
static $value_;
public static function compile() {
if ( self::$error_ ) {
throw new Exception( self::$error_ );
}
if ( self::$value_ !== null ) {
return self::$value_ ? new Less_Tree_Keyword( 'true' ) : new Less_Tree_Keyword( 'false' );
}
}
public static function value( $v ) {
self::$value_ = $v;
}
public static function error( $e ) {
self::$error_ = $e;
}
public static function reset() {
self::$value_ = self::$error_ = null;
}
}

View file

@ -0,0 +1,35 @@
<?php
/**
* @private
*/
class Less_Tree_DetachedRuleset extends Less_Tree {
public $ruleset;
public $frames;
public $type = 'DetachedRuleset';
public function __construct( $ruleset, $frames = null ) {
$this->ruleset = $ruleset;
$this->frames = $frames;
}
public function accept( $visitor ) {
$this->ruleset = $visitor->visitObj( $this->ruleset );
}
public function compile( $env ) {
if ( $this->frames ) {
$frames = $this->frames;
} else {
$frames = $env->frames;
}
return new Less_Tree_DetachedRuleset( $this->ruleset, $frames );
}
public function callEval( $env ) {
if ( $this->frames ) {
return $this->ruleset->compile( $env->copyEvalEnv( array_merge( $this->frames, $env->frames ) ) );
}
return $this->ruleset->compile( $env );
}
}

View file

@ -0,0 +1,190 @@
<?php
/**
* @private
*/
class Less_Tree_Dimension extends Less_Tree {
public $value;
public $unit;
public $type = 'Dimension';
public function __construct( $value, $unit = null ) {
$this->value = floatval( $value );
if ( $unit && ( $unit instanceof Less_Tree_Unit ) ) {
$this->unit = $unit;
} elseif ( $unit ) {
$this->unit = new Less_Tree_Unit( [ $unit ] );
} else {
$this->unit = new Less_Tree_Unit();
}
}
public function accept( $visitor ) {
$this->unit = $visitor->visitObj( $this->unit );
}
public function toColor() {
return new Less_Tree_Color( [ $this->value, $this->value, $this->value ] );
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ) {
if ( Less_Parser::$options['strictUnits'] && !$this->unit->isSingular() ) {
throw new Less_Exception_Compiler( "Multiple units in dimension. Correct the units or use the unit function. Bad unit: " . $this->unit->toString() );
}
$value = Less_Functions::fround( $this->value );
$strValue = (string)$value;
if ( $value !== 0 && $value < 0.000001 && $value > -0.000001 ) {
// would be output 1e-6 etc.
$strValue = number_format( (float)$strValue, 10 );
$strValue = preg_replace( '/\.?0+$/', '', $strValue );
}
if ( Less_Parser::$options['compress'] ) {
// Zero values doesn't need a unit
if ( $value === 0 && $this->unit->isLength() ) {
$output->add( $strValue );
return;
}
// Float values doesn't need a leading zero
if ( $value > 0 && $value < 1 && $strValue[0] === '0' ) {
$strValue = substr( $strValue, 1 );
}
}
$output->add( $strValue );
$this->unit->genCSS( $output );
}
public function __toString() {
return $this->toCSS();
}
// In an operation between two Dimensions,
// we default to the first Dimension's unit,
// so `1px + 2em` will yield `3px`.
/**
* @param string $op
*/
public function operate( $op, $other ) {
$value = Less_Functions::operate( $op, $this->value, $other->value );
$unit = clone $this->unit;
if ( $op === '+' || $op === '-' ) {
if ( !$unit->numerator && !$unit->denominator ) {
$unit->numerator = $other->unit->numerator;
$unit->denominator = $other->unit->denominator;
} elseif ( !$other->unit->numerator && !$other->unit->denominator ) {
// do nothing
} else {
$other = $other->convertTo( $this->unit->usedUnits() );
if ( Less_Parser::$options['strictUnits'] && $other->unit->toString() !== $unit->toCSS() ) {
throw new Less_Exception_Compiler( "Incompatible units. Change the units or use the unit function. Bad units: '" . $unit->toString() . "' and " . $other->unit->toString() . "'." );
}
$value = Less_Functions::operate( $op, $this->value, $other->value );
}
} elseif ( $op === '*' ) {
$unit->numerator = array_merge( $unit->numerator, $other->unit->numerator );
$unit->denominator = array_merge( $unit->denominator, $other->unit->denominator );
sort( $unit->numerator );
sort( $unit->denominator );
$unit->cancel();
} elseif ( $op === '/' ) {
$unit->numerator = array_merge( $unit->numerator, $other->unit->denominator );
$unit->denominator = array_merge( $unit->denominator, $other->unit->numerator );
sort( $unit->numerator );
sort( $unit->denominator );
$unit->cancel();
}
return new Less_Tree_Dimension( $value, $unit );
}
public function compare( $other ) {
if ( $other instanceof Less_Tree_Dimension ) {
if ( $this->unit->isEmpty() || $other->unit->isEmpty() ) {
$a = $this;
$b = $other;
} else {
$a = $this->unify();
$b = $other->unify();
if ( $a->unit->compare( $b->unit ) !== 0 ) {
return -1;
}
}
$aValue = $a->value;
$bValue = $b->value;
if ( $bValue > $aValue ) {
return -1;
} elseif ( $bValue < $aValue ) {
return 1;
} else {
return 0;
}
} else {
return -1;
}
}
public function unify() {
return $this->convertTo( [ 'length' => 'px', 'duration' => 's', 'angle' => 'rad' ] );
}
public function convertTo( $conversions ) {
$value = $this->value;
$unit = clone $this->unit;
if ( is_string( $conversions ) ) {
$derivedConversions = [];
foreach ( Less_Tree_UnitConversions::$groups as $i ) {
if ( isset( Less_Tree_UnitConversions::${$i}[$conversions] ) ) {
$derivedConversions = [ $i => $conversions ];
}
}
$conversions = $derivedConversions;
}
foreach ( $conversions as $groupName => $targetUnit ) {
$group = Less_Tree_UnitConversions::${$groupName};
// numerator
foreach ( $unit->numerator as $i => $atomicUnit ) {
$atomicUnit = $unit->numerator[$i];
if ( !isset( $group[$atomicUnit] ) ) {
continue;
}
$value = $value * ( $group[$atomicUnit] / $group[$targetUnit] );
$unit->numerator[$i] = $targetUnit;
}
// denominator
foreach ( $unit->denominator as $i => $atomicUnit ) {
$atomicUnit = $unit->denominator[$i];
if ( !isset( $group[$atomicUnit] ) ) {
continue;
}
$value = $value / ( $group[$atomicUnit] / $group[$targetUnit] );
$unit->denominator[$i] = $targetUnit;
}
}
$unit->cancel();
return new Less_Tree_Dimension( $value, $unit );
}
}

View file

@ -0,0 +1,92 @@
<?php
/**
* @private
*/
class Less_Tree_Directive extends Less_Tree {
public $name;
public $value;
public $rules;
public $index;
public $isReferenced;
public $currentFileInfo;
public $debugInfo;
public $type = 'Directive';
public function __construct( $name, $value = null, $rules = null, $index = null, $currentFileInfo = null, $debugInfo = null ) {
$this->name = $name;
$this->value = $value;
if ( $rules ) {
$this->rules = $rules;
$this->rules->allowImports = true;
}
$this->index = $index;
$this->currentFileInfo = $currentFileInfo;
$this->debugInfo = $debugInfo;
}
public function accept( $visitor ) {
if ( $this->rules ) {
$this->rules = $visitor->visitObj( $this->rules );
}
if ( $this->value ) {
$this->value = $visitor->visitObj( $this->value );
}
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ) {
$value = $this->value;
$rules = $this->rules;
$output->add( $this->name, $this->currentFileInfo, $this->index );
if ( $this->value ) {
$output->add( ' ' );
$this->value->genCSS( $output );
}
if ( $this->rules ) {
Less_Tree::outputRuleset( $output, [ $this->rules ] );
} else {
$output->add( ';' );
}
}
public function compile( $env ) {
$value = $this->value;
$rules = $this->rules;
if ( $value ) {
$value = $value->compile( $env );
}
if ( $rules ) {
$rules = $rules->compile( $env );
$rules->root = true;
}
return new Less_Tree_Directive( $this->name, $value, $rules, $this->index, $this->currentFileInfo, $this->debugInfo );
}
public function variable( $name ) {
if ( $this->rules ) {
return $this->rules->variable( $name );
}
}
public function find( $selector ) {
if ( $this->rules ) {
return $this->rules->find( $selector, $this );
}
}
// rulesets: function () { if (this.rules) return tree.Ruleset.prototype.rulesets.apply(this.rules); },
public function markReferenced() {
$this->isReferenced = true;
if ( $this->rules ) {
Less_Tree::ReferencedArray( $this->rules->rules );
}
}
}

View file

@ -0,0 +1,73 @@
<?php
/**
* @private
*/
class Less_Tree_Element extends Less_Tree {
/** @var string */
public $combinator;
/** @var bool Whether combinator is null (represented by empty string) or child (single space) */
public $combinatorIsEmptyOrWhitespace;
/** @var string|Less_Tree */
public $value;
public $index;
public $currentFileInfo;
public $type = 'Element';
public $value_is_object = false;
/**
* @param null|string $combinator
* @param string|Less_Tree $value
* @param int|null $index
* @param array|null $currentFileInfo
*/
public function __construct( $combinator, $value, $index = null, $currentFileInfo = null ) {
$this->value = $value;
$this->value_is_object = is_object( $value );
// see less-2.5.3.js#Combinator
$this->combinator = $combinator ?? '';
$this->combinatorIsEmptyOrWhitespace = ( $combinator === null || trim( $combinator ) === '' );
$this->index = $index;
$this->currentFileInfo = $currentFileInfo;
}
public function accept( $visitor ) {
if ( $this->value_is_object ) { // object or string
$this->value = $visitor->visitObj( $this->value );
}
}
public function compile( $env ) {
return new Less_Tree_Element(
$this->combinator,
( $this->value_is_object ? $this->value->compile( $env ) : $this->value ),
$this->index,
$this->currentFileInfo
);
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ) {
$output->add( $this->toCSS(), $this->currentFileInfo, $this->index );
}
public function toCSS() {
if ( $this->value_is_object ) {
$value = $this->value->toCSS();
} else {
$value = $this->value;
}
if ( $value === '' && $this->combinator && $this->combinator === '&' ) {
return '';
}
return Less_Environment::$_outputMap[$this->combinator] . $value;
}
}

View file

@ -0,0 +1,90 @@
<?php
/**
* @private
*/
class Less_Tree_Expression extends Less_Tree {
/** @var array */
public $value = [];
public $parens = false;
public $type = 'Expression';
public function __construct( $value, $parens = null ) {
$this->value = $value;
$this->parens = $parens;
}
public function accept( $visitor ) {
$this->value = $visitor->visitArray( $this->value );
}
public function compile( $env ) {
$doubleParen = false;
if ( $this->parens && !$this->parensInOp ) {
Less_Environment::$parensStack++;
}
$returnValue = null;
if ( $this->value ) {
$count = count( $this->value );
if ( $count > 1 ) {
$ret = [];
foreach ( $this->value as $e ) {
$ret[] = $e->compile( $env );
}
$returnValue = new Less_Tree_Expression( $ret );
} else {
if ( ( $this->value[0] instanceof Less_Tree_Expression ) && $this->value[0]->parens && !$this->value[0]->parensInOp ) {
$doubleParen = true;
}
$returnValue = $this->value[0]->compile( $env );
}
} else {
$returnValue = $this;
}
if ( $this->parens ) {
if ( !$this->parensInOp ) {
Less_Environment::$parensStack--;
} elseif ( !Less_Environment::isMathOn() && !$doubleParen ) {
$returnValue = new Less_Tree_Paren( $returnValue );
}
}
return $returnValue;
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ) {
$val_len = count( $this->value );
for ( $i = 0; $i < $val_len; $i++ ) {
$this->value[$i]->genCSS( $output );
if ( $i + 1 < $val_len ) {
$output->add( ' ' );
}
}
}
public function throwAwayComments() {
if ( is_array( $this->value ) ) {
$new_value = [];
foreach ( $this->value as $v ) {
if ( $v instanceof Less_Tree_Comment ) {
continue;
}
$new_value[] = $v;
}
$this->value = $new_value;
}
}
}

View file

@ -0,0 +1,76 @@
<?php
/**
* @private
*/
class Less_Tree_Extend extends Less_Tree {
public $selector;
public $option;
public $index;
public $selfSelectors = [];
public $allowBefore;
public $allowAfter;
public $firstExtendOnThisSelectorPath;
public $type = 'Extend';
public $ruleset;
public $object_id;
public $parent_ids = [];
/**
* @param int $index
*/
public function __construct( $selector, $option, $index ) {
static $i = 0;
$this->selector = $selector;
$this->option = $option;
$this->index = $index;
switch ( $option ) {
case "all":
$this->allowBefore = true;
$this->allowAfter = true;
break;
default:
$this->allowBefore = false;
$this->allowAfter = false;
break;
}
// This must use a string (instead of int) so that array_merge()
// preserves keys on arrays that use IDs in their keys.
$this->object_id = 'id_' . $i++;
$this->parent_ids = [
$this->object_id => true
];
}
public function accept( $visitor ) {
$this->selector = $visitor->visitObj( $this->selector );
}
public function compile( $env ) {
Less_Parser::$has_extends = true;
$this->selector = $this->selector->compile( $env );
return $this;
// return new Less_Tree_Extend( $this->selector->compile($env), $this->option, $this->index);
}
public function findSelfSelectors( $selectors ) {
$selfElements = [];
for ( $i = 0, $selectors_len = count( $selectors ); $i < $selectors_len; $i++ ) {
$selectorElements = $selectors[$i]->elements;
// duplicate the logic in genCSS function inside the selector node.
// future TODO - move both logics into the selector joiner visitor
if ( $i && $selectorElements && $selectorElements[0]->combinator === "" ) {
$selectorElements[0]->combinator = ' ';
}
$selfElements = array_merge( $selfElements, $selectors[$i]->elements );
}
$this->selfSelectors = [ new Less_Tree_Selector( $selfElements ) ];
}
}

View file

@ -0,0 +1,299 @@
<?php
/**
* CSS `@import` node
*
* The general strategy here is that we don't want to wait
* for the parsing to be completed, before we start importing
* the file. That's because in the context of a browser,
* most of the time will be spent waiting for the server to respond.
*
* On creation, we push the import path to our import queue, though
* `import,push`, we also pass it a callback, which it'll call once
* the file has been fetched, and parsed.
*
* @private
*/
class Less_Tree_Import extends Less_Tree {
public $options;
public $index;
public $path;
public $features;
public $currentFileInfo;
public $css;
public $skip;
public $root;
public $type = 'Import';
public function __construct( $path, $features, $options, $index, $currentFileInfo = null ) {
$this->options = $options;
$this->index = $index;
$this->path = $path;
$this->features = $features;
$this->currentFileInfo = $currentFileInfo;
if ( is_array( $options ) ) {
$this->options += [ 'inline' => false ];
if ( isset( $this->options['less'] ) || $this->options['inline'] ) {
$this->css = !isset( $this->options['less'] ) || !$this->options['less'] || $this->options['inline'];
} else {
$pathValue = $this->getPath();
// Leave any ".css" file imports as literals for the browser.
// Also leave any remote HTTP resources as literals regardless of whether
// they contain ".css" in their filename.
if ( $pathValue && preg_match( '/^(https?:)?\/\/|\.css$/i', $pathValue ) ) {
$this->css = true;
}
}
}
}
//
// The actual import node doesn't return anything, when converted to CSS.
// The reason is that it's used at the evaluation stage, so that the rules
// it imports can be treated like any other rules.
//
// In `eval`, we make sure all Import nodes get evaluated, recursively, so
// we end up with a flat structure, which can easily be imported in the parent
// ruleset.
//
public function accept( $visitor ) {
if ( $this->features ) {
$this->features = $visitor->visitObj( $this->features );
}
$this->path = $visitor->visitObj( $this->path );
if ( !$this->options['inline'] && $this->root ) {
$this->root = $visitor->visit( $this->root );
}
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ) {
if ( $this->css ) {
$output->add( '@import ', $this->currentFileInfo, $this->index );
$this->path->genCSS( $output );
if ( $this->features ) {
$output->add( ' ' );
$this->features->genCSS( $output );
}
$output->add( ';' );
}
}
public function toCSS() {
$features = $this->features ? ' ' . $this->features->toCSS() : '';
if ( $this->css ) {
return "@import " . $this->path->toCSS() . $features . ";\n";
} else {
return "";
}
}
/**
* @return string|null
*/
public function getPath() {
if ( $this->path instanceof Less_Tree_Quoted ) {
$path = $this->path->value;
$path = ( isset( $this->css ) || preg_match( '/(\.[a-z]*$)|([\?;].*)$/', $path ) ) ? $path : $path . '.less';
// During the first pass, Less_Tree_URL may contain a Less_Tree_Variable (not yet expanded),
// and thus has no value property defined yet. Return null until we reach the next phase.
// https://github.com/wikimedia/less.php/issues/29
} elseif ( $this->path instanceof Less_Tree_URL && !( $this->path->value instanceof Less_Tree_Variable ) ) {
$path = $this->path->value->value;
} else {
return null;
}
// remove query string and fragment
return preg_replace( '/[\?#][^\?]*$/', '', $path );
}
public function compileForImport( $env ) {
return new Less_Tree_Import( $this->path->compile( $env ), $this->features, $this->options, $this->index, $this->currentFileInfo );
}
public function compilePath( $env ) {
$path = $this->path->compile( $env );
$rootpath = '';
if ( $this->currentFileInfo && $this->currentFileInfo['rootpath'] ) {
$rootpath = $this->currentFileInfo['rootpath'];
}
if ( !( $path instanceof Less_Tree_URL ) ) {
if ( $rootpath ) {
$pathValue = $path->value;
// Add the base path if the import is relative
if ( $pathValue && Less_Environment::isPathRelative( $pathValue ) ) {
$path->value = $this->currentFileInfo['uri_root'] . $pathValue;
}
}
$path->value = Less_Environment::normalizePath( $path->value );
}
return $path;
}
public function compile( $env ) {
$evald = $this->compileForImport( $env );
// get path & uri
$path_and_uri = null;
if ( is_callable( Less_Parser::$options['import_callback'] ) ) {
$path_and_uri = call_user_func( Less_Parser::$options['import_callback'], $evald );
}
if ( !$path_and_uri ) {
$path_and_uri = $evald->PathAndUri();
}
if ( $path_and_uri ) {
list( $full_path, $uri ) = $path_and_uri;
} else {
$full_path = $uri = $evald->getPath();
}
// import once
if ( $evald->skip( $full_path, $env ) ) {
return [];
}
'@phan-var string $full_path';
if ( $this->options['inline'] ) {
// todo needs to reference css file not import
//$contents = new Less_Tree_Anonymous($this->root, 0, array('filename'=>$this->importedFilename), true );
Less_Parser::AddParsedFile( $full_path );
$contents = new Less_Tree_Anonymous( file_get_contents( $full_path ), 0, [], true );
if ( $this->features ) {
return new Less_Tree_Media( [ $contents ], $this->features->value );
}
return [ $contents ];
}
// optional (need to be before "CSS" to support optional CSS imports. CSS should be checked only if empty($this->currentFileInfo))
if ( isset( $this->options['optional'] ) && $this->options['optional'] && !file_exists( $full_path ) && ( !$evald->css || !empty( $this->currentFileInfo ) ) ) {
return [];
}
// css ?
if ( $evald->css ) {
$features = ( $evald->features ? $evald->features->compile( $env ) : null );
return new Less_Tree_Import( $this->compilePath( $env ), $features, $this->options, $this->index );
}
return $this->ParseImport( $full_path, $uri, $env );
}
/**
* Using the import directories, get the full absolute path and uri of the import
*/
public function PathAndUri() {
$evald_path = $this->getPath();
if ( $evald_path ) {
$import_dirs = [];
if ( Less_Environment::isPathRelative( $evald_path ) ) {
// if the path is relative, the file should be in the current directory
if ( $this->currentFileInfo ) {
$import_dirs[ $this->currentFileInfo['currentDirectory'] ] = $this->currentFileInfo['uri_root'];
}
} else {
// otherwise, the file should be relative to the server root
if ( $this->currentFileInfo ) {
$import_dirs[ $this->currentFileInfo['entryPath'] ] = $this->currentFileInfo['entryUri'];
}
// if the user supplied entryPath isn't the actual root
$import_dirs[ $_SERVER['DOCUMENT_ROOT'] ] = '';
}
// always look in user supplied import directories
$import_dirs = array_merge( $import_dirs, Less_Parser::$options['import_dirs'] );
foreach ( $import_dirs as $rootpath => $rooturi ) {
if ( is_callable( $rooturi ) ) {
list( $path, $uri ) = call_user_func( $rooturi, $evald_path );
if ( is_string( $path ) ) {
$full_path = $path;
return [ $full_path, $uri ];
}
} elseif ( !empty( $rootpath ) ) {
$path = rtrim( $rootpath, '/\\' ) . '/' . ltrim( $evald_path, '/\\' );
if ( file_exists( $path ) ) {
$full_path = Less_Environment::normalizePath( $path );
$uri = Less_Environment::normalizePath( dirname( $rooturi . $evald_path ) );
return [ $full_path, $uri ];
} elseif ( file_exists( $path . '.less' ) ) {
$full_path = Less_Environment::normalizePath( $path . '.less' );
$uri = Less_Environment::normalizePath( dirname( $rooturi . $evald_path . '.less' ) );
return [ $full_path, $uri ];
}
}
}
}
}
/**
* Parse the import url and return the rules
*
* @param string $full_path
* @param string|null $uri
* @param mixed $env
* @return Less_Tree_Media|array
*/
public function ParseImport( $full_path, $uri, $env ) {
$import_env = clone $env;
if ( ( isset( $this->options['reference'] ) && $this->options['reference'] ) || isset( $this->currentFileInfo['reference'] ) ) {
$import_env->currentFileInfo['reference'] = true;
}
if ( ( isset( $this->options['multiple'] ) && $this->options['multiple'] ) ) {
$import_env->importMultiple = true;
}
$parser = new Less_Parser( $import_env );
$root = $parser->parseFile( $full_path, $uri, true );
$ruleset = new Less_Tree_Ruleset( null, $root->rules );
$ruleset->evalImports( $import_env );
return $this->features ? new Less_Tree_Media( $ruleset->rules, $this->features->value ) : $ruleset->rules;
}
/**
* Should the import be skipped?
*
* @param string|null $path
* @param Less_Environment $env
* @return bool|null
*/
private function skip( $path, $env ) {
$path = Less_Parser::AbsPath( $path, true );
if ( $path && Less_Parser::FileParsed( $path ) ) {
if ( isset( $this->currentFileInfo['reference'] ) ) {
return true;
}
return !isset( $this->options['multiple'] ) && !$env->importMultiple;
}
}
}

View file

@ -0,0 +1,26 @@
<?php
/**
* @private
*/
class Less_Tree_Javascript extends Less_Tree {
public $type = 'Javascript';
public $escaped;
public $expression;
public $index;
/**
* @param bool $index
* @param bool $escaped
*/
public function __construct( $string, $index, $escaped ) {
$this->escaped = $escaped;
$this->expression = $string;
$this->index = $index;
}
public function compile( $env ) {
return new Less_Tree_Anonymous( '/* Sorry, can not do JavaScript evaluation in PHP... :( */' );
}
}

View file

@ -0,0 +1,35 @@
<?php
/**
* @private
*/
class Less_Tree_Keyword extends Less_Tree {
public $value;
public $type = 'Keyword';
/**
* @param string $value
*/
public function __construct( $value ) {
$this->value = $value;
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ) {
if ( $this->value === '%' ) {
throw new Less_Exception_Compiler( "Invalid % without number" );
}
$output->add( $this->value );
}
public function compare( $other ) {
if ( $other instanceof Less_Tree_Keyword ) {
return $other->value === $this->value ? 0 : 1;
} else {
return -1;
}
}
}

View file

@ -0,0 +1,183 @@
<?php
/**
* @private
*/
class Less_Tree_Media extends Less_Tree {
public $features;
public $rules;
public $index;
public $currentFileInfo;
public $isReferenced;
public $type = 'Media';
public function __construct( $value = [], $features = [], $index = null, $currentFileInfo = null ) {
$this->index = $index;
$this->currentFileInfo = $currentFileInfo;
$selectors = $this->emptySelectors();
$this->features = new Less_Tree_Value( $features );
$this->rules = [ new Less_Tree_Ruleset( $selectors, $value ) ];
$this->rules[0]->allowImports = true;
}
public function accept( $visitor ) {
$this->features = $visitor->visitObj( $this->features );
$this->rules = $visitor->visitArray( $this->rules );
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ) {
$output->add( '@media ', $this->currentFileInfo, $this->index );
$this->features->genCSS( $output );
Less_Tree::outputRuleset( $output, $this->rules );
}
/**
* @param Less_Environment $env
* @return Less_Tree_Media|Less_Tree_Ruleset
* @see less-2.5.3.js#Media.prototype.eval
*/
public function compile( $env ) {
$media = new Less_Tree_Media( [], [], $this->index, $this->currentFileInfo );
$strictMathBypass = false;
if ( Less_Parser::$options['strictMath'] === false ) {
$strictMathBypass = true;
Less_Parser::$options['strictMath'] = true;
}
$media->features = $this->features->compile( $env );
if ( $strictMathBypass ) {
Less_Parser::$options['strictMath'] = false;
}
$env->mediaPath[] = $media;
$env->mediaBlocks[] = $media;
array_unshift( $env->frames, $this->rules[0] );
$media->rules = [ $this->rules[0]->compile( $env ) ];
array_shift( $env->frames );
array_pop( $env->mediaPath );
return !$env->mediaPath ? $media->compileTop( $env ) : $media->compileNested( $env );
}
public function variable( $name ) {
return $this->rules[0]->variable( $name );
}
public function find( $selector ) {
return $this->rules[0]->find( $selector, $this );
}
public function emptySelectors() {
$el = new Less_Tree_Element( '', '&', $this->index, $this->currentFileInfo );
$sels = [ new Less_Tree_Selector( [ $el ], [], null, $this->index, $this->currentFileInfo ) ];
$sels[0]->mediaEmpty = true;
return $sels;
}
public function markReferenced() {
$this->rules[0]->markReferenced();
$this->isReferenced = true;
Less_Tree::ReferencedArray( $this->rules[0]->rules );
}
// evaltop
public function compileTop( $env ) {
$result = $this;
if ( count( $env->mediaBlocks ) > 1 ) {
$selectors = $this->emptySelectors();
$result = new Less_Tree_Ruleset( $selectors, $env->mediaBlocks );
$result->multiMedia = true;
}
$env->mediaBlocks = [];
$env->mediaPath = [];
return $result;
}
/**
* @param Less_Environment $env
* @return Less_Tree_Ruleset
*/
public function compileNested( $env ) {
$path = array_merge( $env->mediaPath, [ $this ] );
'@phan-var array<Less_Tree_Media> $path';
// Extract the media-query conditions separated with `,` (OR).
foreach ( $path as $key => $p ) {
$value = $p->features instanceof Less_Tree_Value ? $p->features->value : $p->features;
$path[$key] = is_array( $value ) ? $value : [ $value ];
}
'@phan-var array<array<Less_Tree>> $path';
// Trace all permutations to generate the resulting media-query.
//
// (a, b and c) with nested (d, e) ->
// a and d
// a and e
// b and c and d
// b and c and e
$permuted = $this->permute( $path );
$expressions = [];
foreach ( $permuted as $path ) {
for ( $i = 0, $len = count( $path ); $i < $len; $i++ ) {
$path[$i] = Less_Parser::is_method( $path[$i], 'toCSS' ) ? $path[$i] : new Less_Tree_Anonymous( $path[$i] );
}
for ( $i = count( $path ) - 1; $i > 0; $i-- ) {
array_splice( $path, $i, 0, [ new Less_Tree_Anonymous( 'and' ) ] );
}
$expressions[] = new Less_Tree_Expression( $path );
}
$this->features = new Less_Tree_Value( $expressions );
// Fake a tree-node that doesn't output anything.
return new Less_Tree_Ruleset( [], [] );
}
public function permute( $arr ) {
if ( !$arr ) {
return [];
}
if ( count( $arr ) == 1 ) {
return $arr[0];
}
$result = [];
$rest = $this->permute( array_slice( $arr, 1 ) );
foreach ( $rest as $r ) {
foreach ( $arr[0] as $a ) {
$result[] = array_merge(
is_array( $a ) ? $a : [ $a ],
is_array( $r ) ? $r : [ $r ]
);
}
}
return $result;
}
public function bubbleSelectors( $selectors ) {
if ( !$selectors ) {
return;
}
$this->rules = [ new Less_Tree_Ruleset( $selectors, [ $this->rules[0] ] ) ];
}
}

View file

@ -0,0 +1,197 @@
<?php
/**
* @private
*/
class Less_Tree_Mixin_Call extends Less_Tree {
public $selector;
public $arguments;
public $index;
public $currentFileInfo;
public $important;
public $type = 'MixinCall';
/**
* less.js: tree.mixin.Call
*
*/
public function __construct( $elements, $args, $index, $currentFileInfo, $important = false ) {
$this->selector = new Less_Tree_Selector( $elements );
$this->arguments = $args;
$this->index = $index;
$this->currentFileInfo = $currentFileInfo;
$this->important = $important;
}
// function accept($visitor){
// $this->selector = $visitor->visit($this->selector);
// $this->arguments = $visitor->visit($this->arguments);
//}
public function compile( $env ) {
$rules = [];
$match = false;
$isOneFound = false;
$candidates = [];
$defaultUsed = false;
$conditionResult = [];
$args = [];
foreach ( $this->arguments as $a ) {
$args[] = [ 'name' => $a['name'], 'value' => $a['value']->compile( $env ) ];
}
foreach ( $env->frames as $frame ) {
$mixins = $frame->find( $this->selector );
if ( !$mixins ) {
continue;
}
$isOneFound = true;
$defNone = 0;
$defTrue = 1;
$defFalse = 2;
// To make `default()` function independent of definition order we have two "subpasses" here.
// At first we evaluate each guard *twice* (with `default() == true` and `default() == false`),
// and build candidate list with corresponding flags. Then, when we know all possible matches,
// we make a final decision.
$mixins_len = count( $mixins );
for ( $m = 0; $m < $mixins_len; $m++ ) {
$mixin = $mixins[$m];
if ( $this->IsRecursive( $env, $mixin ) ) {
continue;
}
if ( $mixin->matchArgs( $args, $env ) ) {
$candidate = [ 'mixin' => $mixin, 'group' => $defNone ];
if ( $mixin instanceof Less_Tree_Ruleset ) {
for ( $f = 0; $f < 2; $f++ ) {
Less_Tree_DefaultFunc::value( $f );
$conditionResult[$f] = $mixin->matchCondition( $args, $env );
}
// PhanTypeInvalidDimOffset -- False positive
'@phan-var array{0:bool,1:bool} $conditionResult';
if ( $conditionResult[0] || $conditionResult[1] ) {
if ( $conditionResult[0] != $conditionResult[1] ) {
$candidate['group'] = $conditionResult[1] ? $defTrue : $defFalse;
}
$candidates[] = $candidate;
}
} else {
$candidates[] = $candidate;
}
$match = true;
}
}
Less_Tree_DefaultFunc::reset();
$count = [ 0, 0, 0 ];
for ( $m = 0; $m < count( $candidates ); $m++ ) {
$count[ $candidates[$m]['group'] ]++;
}
if ( $count[$defNone] > 0 ) {
$defaultResult = $defFalse;
} else {
$defaultResult = $defTrue;
if ( ( $count[$defTrue] + $count[$defFalse] ) > 1 ) {
throw new Exception( 'Ambiguous use of `default()` found when matching for `' . $this->format( $args ) . '`' );
}
}
$candidates_length = count( $candidates );
$length_1 = ( $candidates_length == 1 );
for ( $m = 0; $m < $candidates_length; $m++ ) {
$candidate = $candidates[$m]['group'];
if ( ( $candidate === $defNone ) || ( $candidate === $defaultResult ) ) {
try{
$mixin = $candidates[$m]['mixin'];
if ( !( $mixin instanceof Less_Tree_Mixin_Definition ) ) {
$mixin = new Less_Tree_Mixin_Definition( '', [], $mixin->rules, null, false );
$mixin->originalRuleset = $mixins[$m]->originalRuleset;
}
$rules = array_merge( $rules, $mixin->evalCall( $env, $args, $this->important )->rules );
} catch ( Exception $e ) {
// throw new Less_Exception_Compiler($e->getMessage(), $e->index, null, $this->currentFileInfo['filename']);
throw new Less_Exception_Compiler( $e->getMessage(), null, null, $this->currentFileInfo );
}
}
}
if ( $match ) {
if ( !$this->currentFileInfo || !isset( $this->currentFileInfo['reference'] ) || !$this->currentFileInfo['reference'] ) {
Less_Tree::ReferencedArray( $rules );
}
return $rules;
}
}
if ( $isOneFound ) {
throw new Less_Exception_Compiler( 'No matching definition was found for `' . $this->Format( $args ) . '`', null, $this->index, $this->currentFileInfo );
} else {
throw new Less_Exception_Compiler( trim( $this->selector->toCSS() ) . " is undefined in " . $this->currentFileInfo['filename'], null, $this->index );
}
}
/**
* Format the args for use in exception messages
*
*/
private function Format( $args ) {
$message = [];
if ( $args ) {
foreach ( $args as $a ) {
$argValue = '';
if ( $a['name'] ) {
$argValue .= $a['name'] . ':';
}
if ( is_object( $a['value'] ) ) {
$argValue .= $a['value']->toCSS();
} else {
$argValue .= '???';
}
$message[] = $argValue;
}
}
return implode( ', ', $message );
}
/**
* Are we in a recursive mixin call?
*
* @return bool
*/
private function IsRecursive( $env, $mixin ) {
foreach ( $env->frames as $recur_frame ) {
if ( !( $mixin instanceof Less_Tree_Mixin_Definition ) ) {
if ( $mixin === $recur_frame ) {
return true;
}
if ( isset( $recur_frame->originalRuleset ) && $mixin->ruleset_id === $recur_frame->originalRuleset ) {
return true;
}
}
}
return false;
}
}

Some files were not shown because too many files have changed in this diff Show more