Merge branch 'wip-MDL-25454-master' of git://github.com/marinaglancy/moodle
[moodle.git] / lib / textlib.class.php
blob558be5c52822229ded09a0fb37a766213c59fc6c
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * @package core
19 * @subpackage lib
20 * @copyright (C) 2001-3001 Eloy Lafuente (stronk7) {@link http://contiento.com}
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 defined('MOODLE_INTERNAL') || die();
26 /**
27 * Original singleton helper function, please use static methods instead,
28 * ex: textlib::convert()
30 * @deprecated
31 * @return textlib instance
33 function textlib_get_instance() {
34 return new textlib();
38 /**
39 * This class is used to manipulate strings under Moodle 1.6 an later. As
40 * utf-8 text become mandatory a pool of safe functions under this encoding
41 * become necessary. The name of the methods is exactly the
42 * same than their PHP originals.
44 * A big part of this class acts as a wrapper over the Typo3 charset library,
45 * really a cool group of utilities to handle texts and encoding conversion.
47 * Take a look to its own copyright and license details.
49 * IMPORTANT Note: Typo3 libraries always expect lowercase charsets to use 100%
50 * its capabilities so, don't forget to make the conversion
51 * from every wrapper function!
53 * @package core
54 * @subpackage lib
55 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
56 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
58 class textlib {
60 /**
61 * Return t3lib helper class
62 * @return t3lib_cs
64 protected static function typo3() {
65 static $typo3cs = null;
67 if (isset($typo3cs)) {
68 return $typo3cs;
71 global $CFG;
73 // Required files
74 require_once($CFG->libdir.'/typo3/class.t3lib_cs.php');
75 require_once($CFG->libdir.'/typo3/class.t3lib_div.php');
77 // do not use mbstring or recode because it may return invalid results in some corner cases
78 $GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_convMethod'] = 'iconv';
79 $GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] = 'iconv';
81 // Tell Typo3 we are curl enabled always (mandatory since 2.0)
82 $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] = '1';
84 // And this directory must exist to allow Typo to cache conversion
85 // tables when using internal functions
86 make_temp_directory('typo3temp/cs');
88 // Make sure typo is using our dir permissions
89 $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'] = decoct($CFG->directorypermissions);
91 // Default mask for Typo
92 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = $CFG->directorypermissions;
94 // This full path constants must be defined too, transforming backslashes
95 // to forward slashed because Typo3 requires it.
96 define ('PATH_t3lib', str_replace('\\','/',$CFG->libdir.'/typo3/'));
97 define ('PATH_typo3', str_replace('\\','/',$CFG->libdir.'/typo3/'));
98 define ('PATH_site', str_replace('\\','/',$CFG->tempdir.'/'));
99 define ('TYPO3_OS', stristr(PHP_OS,'win')&&!stristr(PHP_OS,'darwin')?'WIN':'');
101 $typo3cs = new t3lib_cs();
103 return $typo3cs;
107 * Standardise charset name
109 * Please note it does not mean the returned charset is actually supported.
111 * @static
112 * @param string $charset raw charset name
113 * @return string normalised lowercase charset name
115 public static function parse_charset($charset) {
116 $charset = strtolower($charset);
118 // shortcuts so that we do not have to load typo3 on every page
120 if ($charset === 'utf8' or $charset === 'utf-8') {
121 return 'utf-8';
124 if (preg_match('/^(cp|win|windows)-?(12[0-9]{2})$/', $charset, $matches)) {
125 return 'windows-'.$matches[2];
128 if (preg_match('/^iso-8859-[0-9]+$/', $charset, $matches)) {
129 return $charset;
132 if ($charset === 'euc-jp') {
133 return 'euc-jp';
135 if ($charset === 'iso-2022-jp') {
136 return 'iso-2022-jp';
138 if ($charset === 'shift-jis' or $charset === 'shift_jis') {
139 return 'shift_jis';
141 if ($charset === 'gb2312') {
142 return 'gb2312';
144 if ($charset === 'gb18030') {
145 return 'gb18030';
148 // fallback to typo3
149 return self::typo3()->parse_charset($charset);
153 * Converts the text between different encodings. It uses iconv extension with //TRANSLIT parameter,
154 * falls back to typo3.
155 * Returns false if fails.
157 * @param string $text
158 * @param string $fromCS source encoding
159 * @param string $toCS result encoding
160 * @return string|bool converted string or false on error
162 public static function convert($text, $fromCS, $toCS='utf-8') {
163 $fromCS = self::parse_charset($fromCS);
164 $toCS = self::parse_charset($toCS);
166 $text = (string)$text; // we can work only with strings
168 if ($text === '') {
169 return '';
172 $result = iconv($fromCS, $toCS.'//TRANSLIT', $text);
174 if ($result === false or $result === '') {
175 // note: iconv is prone to return empty string when invalid char encountered, or false if encoding unsupported
176 $oldlevel = error_reporting(E_PARSE);
177 $result = self::typo3()->conv($text, $fromCS, $toCS);
178 error_reporting($oldlevel);
181 return $result;
185 * Multibyte safe substr() function, uses iconv for utf-8, falls back to typo3.
187 * @param string $text
188 * @param int $start negative value means from end
189 * @param int $len
190 * @param string $charset encoding of the text
191 * @return string
193 public static function substr($text, $start, $len=null, $charset='utf-8') {
194 $charset = self::parse_charset($charset);
196 if ($charset === 'utf-8') {
197 return iconv_substr($text, $start, $len, $charset);
200 $oldlevel = error_reporting(E_PARSE);
201 $result = self::typo3()->substr($charset, $text, $start, $len);
202 error_reporting($oldlevel);
204 return $result;
208 * Multibyte safe strlen() function, uses iconv for utf-8, falls back to typo3.
210 * @param string $text
211 * @param string $charset encoding of the text
212 * @return int number of characters
214 public static function strlen($text, $charset='utf-8') {
215 $charset = self::parse_charset($charset);
217 if ($charset === 'utf-8') {
218 return iconv_strlen($text, $charset);
221 $oldlevel = error_reporting(E_PARSE);
222 $result = self::typo3()->strlen($charset, $text);
223 error_reporting($oldlevel);
225 return $result;
229 * Multibyte safe strtolower() function, uses mbstring, falls back to typo3.
231 * @param string $text
232 * @param string $charset encoding of the text (may not work for all encodings)
233 * @return string lower case text
235 public static function strtolower($text, $charset='utf-8') {
236 $charset = self::parse_charset($charset);
238 if ($charset === 'utf-8' and function_exists('mb_strtolower')) {
239 return mb_strtolower($text, $charset);
242 $oldlevel = error_reporting(E_PARSE);
243 $result = self::typo3()->conv_case($charset, $text, 'toLower');
244 error_reporting($oldlevel);
246 return $result;
250 * Multibyte safe strtoupper() function, uses mbstring, falls back to typo3.
252 * @param string $text
253 * @param string $charset encoding of the text (may not work for all encodings)
254 * @return string upper case text
256 public static function strtoupper($text, $charset='utf-8') {
257 $charset = self::parse_charset($charset);
259 if ($charset === 'utf-8' and function_exists('mb_strtoupper')) {
260 return mb_strtoupper($text, $charset);
263 $oldlevel = error_reporting(E_PARSE);
264 $result = self::typo3()->conv_case($charset, $text, 'toUpper');
265 error_reporting($oldlevel);
267 return $result;
271 * UTF-8 ONLY safe strpos(), uses iconv..
273 * @param string $haystack
274 * @param string $needle
275 * @param int $offset
276 * @return string
278 public static function strpos($haystack, $needle, $offset=0) {
279 return iconv_strpos($haystack, $needle, $offset, 'utf-8');
283 * UTF-8 ONLY safe strrpos(), uses iconv.
285 * @param string $haystack
286 * @param string $needle
287 * @return string
289 public static function strrpos($haystack, $needle) {
290 return iconv_strrpos($haystack, $needle, 'utf-8');
294 * Try to convert upper unicode characters to plain ascii,
295 * the returned string may contain unconverted unicode characters.
297 * @param string $text
298 * @param string $charset encoding of the text
299 * @return string
301 public static function specialtoascii($text, $charset='utf-8') {
302 $charset = self::parse_charset($charset);
303 $oldlevel = error_reporting(E_PARSE);
304 $result = self::typo3()->specCharsToASCII($charset, $text);
305 error_reporting($oldlevel);
306 return $result;
310 * Generate a correct base64 encoded header to be used in MIME mail messages.
311 * This function seems to be 100% compliant with RFC1342. Credits go to:
312 * paravoid (http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283).
314 * @param string $text
315 * @param string $charset encoding of the text
316 * @return string
318 public static function encode_mimeheader($text, $charset='utf-8') {
319 if (empty($text)) {
320 return (string)$text;
322 // Normalize charset
323 $charset = self::parse_charset($charset);
324 // If the text is pure ASCII, we don't need to encode it
325 if (self::convert($text, $charset, 'ascii') == $text) {
326 return $text;
328 // Although RFC says that line feed should be \r\n, it seems that
329 // some mailers double convert \r, so we are going to use \n alone
330 $linefeed="\n";
331 // Define start and end of every chunk
332 $start = "=?$charset?B?";
333 $end = "?=";
334 // Accumulate results
335 $encoded = '';
336 // Max line length is 75 (including start and end)
337 $length = 75 - strlen($start) - strlen($end);
338 // Multi-byte ratio
339 $multilength = self::strlen($text, $charset);
340 // Detect if strlen and friends supported
341 if ($multilength === false) {
342 if ($charset == 'GB18030' or $charset == 'gb18030') {
343 while (strlen($text)) {
344 // try to encode first 22 chars - we expect most chars are two bytes long
345 if (preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,22}/m', $text, $matches)) {
346 $chunk = $matches[0];
347 $encchunk = base64_encode($chunk);
348 if (strlen($encchunk) > $length) {
349 // find first 11 chars - each char in 4 bytes - worst case scenario
350 preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,11}/m', $text, $matches);
351 $chunk = $matches[0];
352 $encchunk = base64_encode($chunk);
354 $text = substr($text, strlen($chunk));
355 $encoded .= ' '.$start.$encchunk.$end.$linefeed;
356 } else {
357 break;
360 $encoded = trim($encoded);
361 return $encoded;
362 } else {
363 return false;
366 $ratio = $multilength / strlen($text);
367 // Base64 ratio
368 $magic = $avglength = floor(3 * $length * $ratio / 4);
369 // basic infinite loop protection
370 $maxiterations = strlen($text)*2;
371 $iteration = 0;
372 // Iterate over the string in magic chunks
373 for ($i=0; $i <= $multilength; $i+=$magic) {
374 if ($iteration++ > $maxiterations) {
375 return false; // probably infinite loop
377 $magic = $avglength;
378 $offset = 0;
379 // Ensure the chunk fits in length, reducing magic if necessary
380 do {
381 $magic -= $offset;
382 $chunk = self::substr($text, $i, $magic, $charset);
383 $chunk = base64_encode($chunk);
384 $offset++;
385 } while (strlen($chunk) > $length);
386 // This chunk doesn't break any multi-byte char. Use it.
387 if ($chunk)
388 $encoded .= ' '.$start.$chunk.$end.$linefeed;
390 // Strip the first space and the last linefeed
391 $encoded = substr($encoded, 1, -strlen($linefeed));
393 return $encoded;
397 * Converts all the numeric entities &#nnnn; or &#xnnn; to UTF-8
398 * Original from laurynas dot butkus at gmail at:
399 * http://php.net/manual/en/function.html-entity-decode.php#75153
400 * with some custom mods to provide more functionality
402 * @param string $str input string
403 * @param boolean $htmlent convert also html entities (defaults to true)
404 * @return string
406 * NOTE: we could have used typo3 entities_to_utf8() here
407 * but the direct alternative used runs 400% quicker
408 * and uses 0.5Mb less memory, so, let's use it
409 * (tested against 10^6 conversions)
411 public static function entities_to_utf8($str, $htmlent=true) {
412 static $trans_tbl; // Going to use static transliteration table
414 // Replace numeric entities
415 $result = preg_replace('~&#x([0-9a-f]+);~ei', 'textlib::code2utf8(hexdec("\\1"))', $str);
416 $result = preg_replace('~&#([0-9]+);~e', 'textlib::code2utf8(\\1)', $result);
418 // Replace literal entities (if desired)
419 if ($htmlent) {
420 // Generate/create $trans_tbl
421 if (!isset($trans_tbl)) {
422 $trans_tbl = array();
423 foreach (get_html_translation_table(HTML_ENTITIES) as $val=>$key) {
424 $trans_tbl[$key] = utf8_encode($val);
427 $result = strtr($result, $trans_tbl);
429 // Return utf8-ised string
430 return $result;
434 * Converts all Unicode chars > 127 to numeric entities &#nnnn; or &#xnnn;.
436 * @param string $str input string
437 * @param boolean $dec output decadic only number entities
438 * @param boolean $nonnum remove all non-numeric entities
439 * @return string converted string
441 public static function utf8_to_entities($str, $dec=false, $nonnum=false) {
442 // Avoid some notices from Typo3 code
443 $oldlevel = error_reporting(E_PARSE);
444 if ($nonnum) {
445 $str = self::typo3()->entities_to_utf8($str, true);
447 $result = self::typo3()->utf8_to_entities($str);
448 if ($dec) {
449 $result = preg_replace('/&#x([0-9a-f]+);/ie', "'&#'.hexdec('$1').';'", $result);
451 // Restore original debug level
452 error_reporting($oldlevel);
453 return $result;
457 * Removes the BOM from unicode string - see http://unicode.org/faq/utf_bom.html
459 * @param string $str
460 * @return string
462 public static function trim_utf8_bom($str) {
463 $bom = "\xef\xbb\xbf";
464 if (strpos($str, $bom) === 0) {
465 return substr($str, strlen($bom));
467 return $str;
471 * Returns encoding options for select boxes, utf-8 and platform encoding first
472 * @return array encodings
474 public static function get_encodings() {
475 $encodings = array();
476 $encodings['UTF-8'] = 'UTF-8';
477 $winenc = strtoupper(get_string('localewincharset', 'langconfig'));
478 if ($winenc != '') {
479 $encodings[$winenc] = $winenc;
481 $nixenc = strtoupper(get_string('oldcharset', 'langconfig'));
482 $encodings[$nixenc] = $nixenc;
484 foreach (self::typo3()->synonyms as $enc) {
485 $enc = strtoupper($enc);
486 $encodings[$enc] = $enc;
488 return $encodings;
492 * Returns the utf8 string corresponding to the unicode value
493 * (from php.net, courtesy - romans@void.lv)
495 * @param int $num one unicode value
496 * @return string the UTF-8 char corresponding to the unicode value
498 public static function code2utf8($num) {
499 if ($num < 128) {
500 return chr($num);
502 if ($num < 2048) {
503 return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
505 if ($num < 65536) {
506 return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
508 if ($num < 2097152) {
509 return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
511 return '';
515 * Makes first letter of each word capital - words must be separated by spaces.
516 * Use with care, this function does not work properly in many locales!!!
518 * @param string $text
519 * @return string
521 public static function strtotitle($text) {
522 if (empty($text)) {
523 return $text;
526 if (function_exists('mb_convert_case')) {
527 return mb_convert_case($text, MB_CASE_TITLE, 'UTF-8');
530 $text = self::strtolower($text);
531 $words = explode(' ', $text);
532 foreach ($words as $i=>$word) {
533 $length = self::strlen($word);
534 if (!$length) {
535 continue;
537 } else if ($length == 1) {
538 $words[$i] = self::strtoupper($word);
540 } else {
541 $letter = self::substr($word, 0, 1);
542 $letter = self::strtoupper($letter);
543 $rest = self::substr($word, 1);
544 $words[$i] = $letter.$rest;
547 return implode(' ', $words);
551 * Locale aware sorting, the key associations are kept, values are sorted alphabetically.
553 * @param array $arr array to be sorted (reference)
554 * @param int $sortflag One of Collator::SORT_REGULAR, Collator::SORT_NUMERIC, Collator::SORT_STRING
555 * @return void modifies parameter
557 public static function asort(array &$arr, $sortflag = null) {
558 debugging('textlib::asort has been superseeded by collatorlib::asort please upgrade your code to use that', DEBUG_DEVELOPER);
559 collatorlib::asort($arr, $sortflag);
564 * A collator class with static methods that can be used for sorting.
566 * @package core
567 * @subpackage lib
568 * @copyright 2011 Sam Hemelryk
569 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
571 abstract class collatorlib {
573 /** @var Collator|false|null **/
574 protected static $collator = null;
576 /** @var string|null The locale that was used in instantiating the current collator **/
577 protected static $locale = null;
580 * Ensures that a collator is available and created
582 * @return bool Returns true if collation is available and ready
584 protected static function ensure_collator_available() {
585 global $CFG;
587 $locale = get_string('locale', 'langconfig');
588 if (is_null(self::$collator) || $locale != self::$locale) {
589 self::$collator = false;
590 self::$locale = $locale;
591 if (class_exists('Collator', false)) {
592 $collator = new Collator($locale);
593 if (!empty($collator) && $collator instanceof Collator) {
594 // Check for non fatal error messages. This has to be done immediately
595 // after instantiation as any further calls to collation will cause
596 // it to reset to 0 again (or another error code if one occurred)
597 $errorcode = $collator->getErrorCode();
598 $errormessage = $collator->getErrorMessage();
599 // Check for an error code, 0 means no error occurred
600 if ($errorcode !== 0) {
601 // Get the actual locale being used, e.g. en, he, zh
602 $localeinuse = $collator->getLocale(Locale::ACTUAL_LOCALE);
603 // Check for the common fallback warning error codes. If this occurred
604 // there is normally little to worry about:
605 // - U_USING_DEFAULT_WARNING (127) - default fallback locale used (pt => UCA)
606 // - U_USING_FALLBACK_WARNING (128) - fallback locale used (de_CH => de)
607 // (UCA: Unicode Collation Algorithm http://unicode.org/reports/tr10/)
608 if ($errorcode === -127 || $errorcode === -128) {
609 // Check if the locale in use is UCA default one ('root') or
610 // if it is anything like the locale we asked for
611 if ($localeinuse !== 'root' && strpos($locale, $localeinuse) !== 0) {
612 // The locale we asked for is completely different to the locale
613 // we have received, let the user know via debugging
614 debugging('Invalid locale: "' . $locale . '", with warning (not fatal) "' . $errormessage .
615 '", falling back to "' . $collator->getLocale(Locale::VALID_LOCALE) . '"');
616 } else {
617 // Nothing to do here, this is expected!
618 // The Moodle locale setting isn't what the collator expected but
619 // it is smart enough to match the first characters of our locale
620 // to find the correct locale or to use UCA collation
622 } else {
623 // We've recieved some other sort of non fatal warning - let the
624 // user know about it via debugging.
625 debugging('Problem with locale: "' . $locale . '", with message "' . $errormessage .
626 '", falling back to "' . $collator->getLocale(Locale::VALID_LOCALE) . '"');
629 // Store the collator object now that we can be sure it is in a workable condition
630 self::$collator = $collator;
631 } else {
632 // Fatal error while trying to instantiate the collator... something went wrong
633 debugging('Error instantiating collator for locale: "' . $locale . '", with error [' .
634 intl_get_error_code() . '] ' . intl_get_error_message($collator));
638 return (self::$collator instanceof Collator);
642 * Locale aware sorting, the key associations are kept, values are sorted alphabetically.
644 * @param array $arr array to be sorted (reference)
645 * @param int $sortflag One of Collator::SORT_REGULAR, Collator::SORT_NUMERIC, Collator::SORT_STRING
646 * @return void modifies parameter
648 public static function asort(array &$arr, $sortflag = null) {
649 if (self::ensure_collator_available()) {
650 if (!isset($sortflag)) {
651 $sortflag = Collator::SORT_REGULAR;
653 self::$collator->asort($arr, $sortflag);
654 return;
656 asort($arr, SORT_LOCALE_STRING);
660 * Locale aware comparison of two strings.
662 * Returns:
663 * 1 if str1 is greater than str2
664 * 0 if str1 is equal to str2
665 * -1 if str1 is less than str2
667 * @return int
669 public static function compare($str1, $str2) {
670 if (self::ensure_collator_available()) {
671 return self::$collator->compare($str1, $str2);
673 return strcmp($str1, $str2);
677 * Locale aware sort of objects by a property in common to all objects
679 * @param array $objects An array of objects to sort (handled by reference)
680 * @param string $property The property to use for comparison
681 * @return bool True on success
683 public static function asort_objects_by_property(array &$objects, $property) {
684 $comparison = new collatorlib_property_comparison($property);
685 return uasort($objects, array($comparison, 'compare'));
689 * Locale aware sort of objects by a method in common to all objects
691 * @param array $objects An array of objects to sort (handled by reference)
692 * @param string $method The method to call to generate a value for comparison
693 * @return bool True on success
695 public static function asort_objects_by_method(array &$objects, $method) {
696 $comparison = new collatorlib_method_comparison($method);
697 return uasort($objects, array($comparison, 'compare'));
702 * Abstract class to aid the sorting of objects with respect to proper language
703 * comparison using collator
705 * @package core
706 * @subpackage lib
707 * @copyright 2011 Sam Hemelryk
708 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
710 abstract class collatorlib_comparison {
712 * This function will perform the actual comparison of values
713 * It must be overridden by the deriving class.
715 * Returns:
716 * 1 if str1 is greater than str2
717 * 0 if str1 is equal to str2
718 * -1 if str1 is less than str2
720 * @param mixed $a The first something to compare
721 * @param mixed $b The second something to compare
722 * @return int
724 public abstract function compare($a, $b);
728 * A comparison helper for comparing properties of two objects
730 * @package core
731 * @subpackage lib
732 * @copyright 2011 Sam Hemelryk
733 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
735 class collatorlib_property_comparison extends collatorlib_comparison {
737 /** @var string The property to sort by **/
738 protected $property;
741 * @param string $property
743 public function __construct($property) {
744 $this->property = $property;
748 * Returns:
749 * 1 if str1 is greater than str2
750 * 0 if str1 is equal to str2
751 * -1 if str1 is less than str2
753 * @param mixed $obja The first object to compare
754 * @param mixed $objb The second object to compare
755 * @return int
757 public function compare($obja, $objb) {
758 $resulta = $obja->{$this->property};
759 $resultb = $objb->{$this->property};
760 return collatorlib::compare($resulta, $resultb);
765 * A comparison helper for comparing the result of a method on two objects
767 * @package core
768 * @subpackage lib
769 * @copyright 2011 Sam Hemelryk
770 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
772 class collatorlib_method_comparison extends collatorlib_comparison {
774 /** @var string The method to use for comparison **/
775 protected $method;
778 * @param string $method The method to call against each object
780 public function __construct($method) {
781 $this->method = $method;
785 * Returns:
786 * 1 if str1 is greater than str2
787 * 0 if str1 is equal to str2
788 * -1 if str1 is less than str2
790 * @param mixed $obja The first object to compare
791 * @param mixed $objb The second object to compare
792 * @return int
794 public function compare($obja, $objb) {
795 $resulta = $obja->{$this->method}();
796 $resultb = $objb->{$this->method}();
797 return collatorlib::compare($resulta, $resultb);