mercredi 1 juillet 2015

PHP: Parse CSS file, find quoted font-family value, copy rules/selectors without that quoted font, add class to all selectors with that font name

Here's a simple example showing what I would like to do with CSS.

Example Input:

html {
  font-family: "PT Sans", Helvetica, Arial, sans-serif;
  color: #222222;
}

Desired Output:

html {
  font-family: Helvetica, Arial, sans-serif;
  color: #222222;
}
.pt-sans html {
  font-family: "PT Sans", Helvetica, Arial, sans-serif;
  color: #222222;
}

I've been using http://ift.tt/1mGBIIC but the examples are not detailed enough for me to figure this out.

This is what I have so far:

<?php
$css_string = '
    html {
      font-family: "PT Sans", Helvetica, Arial, sans-serif;
      color: #222222;
    }';

// Create parser.
$oSettings = Sabberworm\CSS\Settings::create()->withMultibyteSupport(false);
$oCssParser = new Sabberworm\CSS\Parser($subject, $oSettings);
$oCssDocument = $oCssParser->parse();

// Get font-family rules.
foreach($oCssDocument->getAllRuleSets() as $key0 => $oRuleSet) {
  $rules = $oRuleSet->getRules('font-family');
  if (!empty($rules)) {
    foreach ($rules as $key1 => $values) {
      var_dump(array($key0, $key1));
      var_dump($values->getValue());
    }
  }
}

Which outputs this

array (size=2)
  0 => int 0
  1 => int 0

object(Sabberworm\CSS\Value\RuleValueList)[91]
  protected 'aComponents' => 
    array (size=4)
      0 => 
        object(Sabberworm\CSS\Value\String)[85]
          private 'sString' => string 'PT Sans' (length=7)
      1 => string 'Helvetica' (length=9)
      2 => string 'Arial' (length=5)
      3 => string 'sans-serif' (length=10)
  protected 'sSeparator' => string ',' (length=1)

The reason why I want to do this is for async font loading http://ift.tt/1LVYHbC Where I would run some js code like this.

<script src="//cdn.rawgit.com/bramstein/fontfaceobserver/master/fontfaceobserver.js"></script>
<script>
var observer = new FontFaceObserver("PT Sans", {});
observer.check(null, 5000).then(function () {
  w.document.documentElement.className += " pt-sans";
});
</script>

Aucun commentaire:

Enregistrer un commentaire