@@ -684,14 +684,22 @@ protected function stripWhitespace($content)
684
684
*/
685
685
protected function extractMath ()
686
686
{
687
+ $ functions = array ('calc ' , 'clamp ' , 'min ' , 'max ' );
688
+ $ pattern = '/( ' . implode ($ functions , '| ' ) .')(\(.+?)(?=$|;|})/m ' ;
689
+
687
690
// PHP only supports $this inside anonymous functions since 5.4
688
691
$ minifier = $ this ;
689
- $ callback = function ($ match ) use ($ minifier ) {
692
+ $ callback = function ($ match ) use ($ minifier, $ pattern , & $ callback ) {
690
693
$ function = $ match [1 ];
691
694
$ length = strlen ($ match [2 ]);
692
695
$ expr = '' ;
693
696
$ opened = 0 ;
694
697
698
+ // the regular expression for extracting math has 1 significant problem:
699
+ // it can't determine the correct closing parenthesis...
700
+ // instead, it'll match a larger portion of code to where it's certain that
701
+ // the calc() musts have ended, and we'll figure out which is the correct
702
+ // closing parenthesis here, by counting how many have opened
695
703
for ($ i = 0 ; $ i < $ length ; $ i ++) {
696
704
$ char = $ match [2 ][$ i ];
697
705
$ expr .= $ char ;
@@ -701,25 +709,22 @@ protected function extractMath()
701
709
break ;
702
710
}
703
711
}
704
- $ rest = str_replace ($ expr , '' , $ match [2 ]);
705
- $ expr = trim (substr ($ expr , 1 , -1 ));
706
712
713
+ // now that we've figured out where the calc() starts and ends, extract it
707
714
$ count = count ($ minifier ->extracted );
708
715
$ placeholder = 'math( ' .$ count .') ' ;
709
- $ minifier ->extracted [$ placeholder ] = $ function .'( ' .$ expr .') ' ;
716
+ $ minifier ->extracted [$ placeholder ] = $ function .'( ' .trim (substr ($ expr , 1 , -1 )).') ' ;
717
+
718
+ // and since we've captured more code than required, we may have some leftover
719
+ // calc() in here too - go recursive on the remaining but of code to go figure
720
+ // that out and extract what is needed
721
+ $ rest = str_replace ($ function .$ expr , '' , $ match [0 ]);
722
+ $ rest = preg_replace_callback ($ pattern , $ callback , $ rest );
710
723
711
724
return $ placeholder .$ rest ;
712
725
};
713
726
714
- $ functions = array ('calc ' , 'clamp ' , 'min ' , 'max ' );
715
- $ this ->registerPattern (
716
- '/( ' . implode ($ functions , '| ' ) .')(\(.+?)(?=$|;|}|( ' . implode ($ functions , '| ' ) .')\()/ ' ,
717
- $ callback
718
- );
719
- $ this ->registerPattern (
720
- '/( ' . implode ($ functions , '| ' ) .')(\(.+?)(?=$|;|}|( ' . implode ($ functions , '| ' ) .')\()/m ' ,
721
- $ callback
722
- );
727
+ $ this ->registerPattern ($ pattern , $ callback );
723
728
}
724
729
725
730
/**
0 commit comments