Example #1
0
 /**
  * Returns a number between 0 and 1 inclusive that indicates the percentage
  * of characters in the string which are covered by glyphs in this font.
  *
  * Since no one font will contain glyphs for the entire Unicode character
  * range, this method can be used to help locate a suitable font when the
  * actual contents of the string are not known.
  *
  * Note that some fonts lie about the characters they support. Additionally,
  * fonts don't usually contain glyphs for control characters such as tabs
  * and line breaks, so it is rare that you will get back a full 1.0 score.
  * The resulting value should be considered informational only.
  *
  * @param string $string
  * @param string $charEncoding (optional) Character encoding of source text.
  *   If omitted, uses 'current locale'.
  * @return float
  */
 public function getCoveredPercentage($string, $charEncoding = '')
 {
     /* Convert the string to UTF-16BE encoding so we can match the string's
      * character codes to those found in the cmap.
      */
     if ($charEncoding != 'UTF-16BE') {
         if (PHP_OS != 'AIX') {
             // AIX doesnt know what UTF-16BE is
             $string = iconv($charEncoding, 'UTF-16BE', $string);
         }
     }
     $charCount = PHP_OS != 'AIX' ? iconv_strlen($string, 'UTF-16BE') : strlen($string);
     if ($charCount == 0) {
         return 0;
     }
     /* Fetch the covered character code list from the font's cmap.
      */
     $coveredCharacters = $this->_cmap->getCoveredCharacters();
     /* Calculate the score by doing a lookup for each character.
      */
     $score = 0;
     $maxIndex = strlen($string);
     for ($i = 0; $i < $maxIndex; $i++) {
         /**
          * @todo Properly handle characters encoded as surrogate pairs.
          */
         $charCode = ord($string[$i]) << 8 | ord($string[++$i]);
         /* This could probably be optimized a bit with a binary search...
          */
         if (in_array($charCode, $coveredCharacters)) {
             $score++;
         }
     }
     return $score / $charCount;
 }