Merge branch 'MDL-34171_22' of git://github.com/timhunt/moodle into MOODLE_22_STABLE
[moodle.git] / lib / textlib.class.php
blob970273893081ae9da90c738ab8bbb049595a2682
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 mbstring or 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 if (function_exists('mb_substr')) {
198 // this is much faster than iconv - see MDL-31142
199 if ($len === null) {
200 $oldcharset = mb_internal_encoding();
201 mb_internal_encoding('UTF-8');
202 $result = mb_substr($text, $start);
203 mb_internal_encoding($oldcharset);
204 return $result;
205 } else {
206 return mb_substr($text, $start, $len, 'UTF-8');
209 } else {
210 if ($len === null) {
211 $len = iconv_strlen($text, 'UTF-8');
213 return iconv_substr($text, $start, $len, 'UTF-8');
217 $oldlevel = error_reporting(E_PARSE);
218 if ($len === null) {
219 $result = self::typo3()->substr($charset, $text, $start);
220 } else {
221 $result = self::typo3()->substr($charset, $text, $start, $len);
223 error_reporting($oldlevel);
225 return $result;
229 * Multibyte safe strlen() function, uses mbstring or iconv for UTF-8, falls back to typo3.
231 * @param string $text
232 * @param string $charset encoding of the text
233 * @return int number of characters
235 public static function strlen($text, $charset='utf-8') {
236 $charset = self::parse_charset($charset);
238 if ($charset === 'utf-8') {
239 if (function_exists('mb_strlen')) {
240 return mb_strlen($text, 'UTF-8');
241 } else {
242 return iconv_strlen($text, 'UTF-8');
246 $oldlevel = error_reporting(E_PARSE);
247 $result = self::typo3()->strlen($charset, $text);
248 error_reporting($oldlevel);
250 return $result;
254 * Multibyte safe strtolower() function, uses mbstring, falls back to typo3.
256 * @param string $text
257 * @param string $charset encoding of the text (may not work for all encodings)
258 * @return string lower case text
260 public static function strtolower($text, $charset='utf-8') {
261 $charset = self::parse_charset($charset);
263 if ($charset === 'utf-8' and function_exists('mb_strtolower')) {
264 return mb_strtolower($text, 'UTF-8');
267 $oldlevel = error_reporting(E_PARSE);
268 $result = self::typo3()->conv_case($charset, $text, 'toLower');
269 error_reporting($oldlevel);
271 return $result;
275 * Multibyte safe strtoupper() function, uses mbstring, falls back to typo3.
277 * @param string $text
278 * @param string $charset encoding of the text (may not work for all encodings)
279 * @return string upper case text
281 public static function strtoupper($text, $charset='utf-8') {
282 $charset = self::parse_charset($charset);
284 if ($charset === 'utf-8' and function_exists('mb_strtoupper')) {
285 return mb_strtoupper($text, 'UTF-8');
288 $oldlevel = error_reporting(E_PARSE);
289 $result = self::typo3()->conv_case($charset, $text, 'toUpper');
290 error_reporting($oldlevel);
292 return $result;
296 * UTF-8 ONLY safe strpos(), uses mbstring, falls back to iconv.
298 * @param string $haystack
299 * @param string $needle
300 * @param int $offset
301 * @return string
303 public static function strpos($haystack, $needle, $offset=0) {
304 if (function_exists('mb_strpos')) {
305 return mb_strpos($haystack, $needle, $offset, 'UTF-8');
306 } else {
307 return iconv_strpos($haystack, $needle, $offset, 'UTF-8');
312 * UTF-8 ONLY safe strrpos(), uses mbstring, falls back to iconv.
314 * @param string $haystack
315 * @param string $needle
316 * @return string
318 public static function strrpos($haystack, $needle) {
319 if (function_exists('mb_strpos')) {
320 return mb_strrpos($haystack, $needle, null, 'UTF-8');
321 } else {
322 return iconv_strrpos($haystack, $needle, 'UTF-8');
327 * Try to convert upper unicode characters to plain ascii,
328 * the returned string may contain unconverted unicode characters.
330 * @param string $text
331 * @param string $charset encoding of the text
332 * @return string
334 public static function specialtoascii($text, $charset='utf-8') {
335 $charset = self::parse_charset($charset);
336 $oldlevel = error_reporting(E_PARSE);
337 $result = self::typo3()->specCharsToASCII($charset, $text);
338 error_reporting($oldlevel);
339 return $result;
343 * Generate a correct base64 encoded header to be used in MIME mail messages.
344 * This function seems to be 100% compliant with RFC1342. Credits go to:
345 * paravoid (http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283).
347 * @param string $text
348 * @param string $charset encoding of the text
349 * @return string
351 public static function encode_mimeheader($text, $charset='utf-8') {
352 if (empty($text)) {
353 return (string)$text;
355 // Normalize charset
356 $charset = self::parse_charset($charset);
357 // If the text is pure ASCII, we don't need to encode it
358 if (self::convert($text, $charset, 'ascii') == $text) {
359 return $text;
361 // Although RFC says that line feed should be \r\n, it seems that
362 // some mailers double convert \r, so we are going to use \n alone
363 $linefeed="\n";
364 // Define start and end of every chunk
365 $start = "=?$charset?B?";
366 $end = "?=";
367 // Accumulate results
368 $encoded = '';
369 // Max line length is 75 (including start and end)
370 $length = 75 - strlen($start) - strlen($end);
371 // Multi-byte ratio
372 $multilength = self::strlen($text, $charset);
373 // Detect if strlen and friends supported
374 if ($multilength === false) {
375 if ($charset == 'GB18030' or $charset == 'gb18030') {
376 while (strlen($text)) {
377 // try to encode first 22 chars - we expect most chars are two bytes long
378 if (preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,22}/m', $text, $matches)) {
379 $chunk = $matches[0];
380 $encchunk = base64_encode($chunk);
381 if (strlen($encchunk) > $length) {
382 // find first 11 chars - each char in 4 bytes - worst case scenario
383 preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,11}/m', $text, $matches);
384 $chunk = $matches[0];
385 $encchunk = base64_encode($chunk);
387 $text = substr($text, strlen($chunk));
388 $encoded .= ' '.$start.$encchunk.$end.$linefeed;
389 } else {
390 break;
393 $encoded = trim($encoded);
394 return $encoded;
395 } else {
396 return false;
399 $ratio = $multilength / strlen($text);
400 // Base64 ratio
401 $magic = $avglength = floor(3 * $length * $ratio / 4);
402 // basic infinite loop protection
403 $maxiterations = strlen($text)*2;
404 $iteration = 0;
405 // Iterate over the string in magic chunks
406 for ($i=0; $i <= $multilength; $i+=$magic) {
407 if ($iteration++ > $maxiterations) {
408 return false; // probably infinite loop
410 $magic = $avglength;
411 $offset = 0;
412 // Ensure the chunk fits in length, reducing magic if necessary
413 do {
414 $magic -= $offset;
415 $chunk = self::substr($text, $i, $magic, $charset);
416 $chunk = base64_encode($chunk);
417 $offset++;
418 } while (strlen($chunk) > $length);
419 // This chunk doesn't break any multi-byte char. Use it.
420 if ($chunk)
421 $encoded .= ' '.$start.$chunk.$end.$linefeed;
423 // Strip the first space and the last linefeed
424 $encoded = substr($encoded, 1, -strlen($linefeed));
426 return $encoded;
430 * Converts all the numeric entities &#nnnn; or &#xnnn; to UTF-8
431 * Original from laurynas dot butkus at gmail at:
432 * http://php.net/manual/en/function.html-entity-decode.php#75153
433 * with some custom mods to provide more functionality
435 * @param string $str input string
436 * @param boolean $htmlent convert also html entities (defaults to true)
437 * @return string
439 * NOTE: we could have used typo3 entities_to_utf8() here
440 * but the direct alternative used runs 400% quicker
441 * and uses 0.5Mb less memory, so, let's use it
442 * (tested against 10^6 conversions)
444 public static function entities_to_utf8($str, $htmlent=true) {
445 static $trans_tbl; // Going to use static transliteration table
447 // Replace numeric entities
448 $result = preg_replace('~&#x([0-9a-f]+);~ei', 'textlib::code2utf8(hexdec("\\1"))', $str);
449 $result = preg_replace('~&#([0-9]+);~e', 'textlib::code2utf8(\\1)', $result);
451 // Replace literal entities (if desired)
452 if ($htmlent) {
453 // Generate/create $trans_tbl
454 if (!isset($trans_tbl)) {
455 $trans_tbl = array();
456 foreach (get_html_translation_table(HTML_ENTITIES) as $val=>$key) {
457 $trans_tbl[$key] = utf8_encode($val);
460 $result = strtr($result, $trans_tbl);
462 // Return utf8-ised string
463 return $result;
467 * Converts all Unicode chars > 127 to numeric entities &#nnnn; or &#xnnn;.
469 * @param string $str input string
470 * @param boolean $dec output decadic only number entities
471 * @param boolean $nonnum remove all non-numeric entities
472 * @return string converted string
474 public static function utf8_to_entities($str, $dec=false, $nonnum=false) {
475 // Avoid some notices from Typo3 code
476 $oldlevel = error_reporting(E_PARSE);
477 if ($nonnum) {
478 $str = self::typo3()->entities_to_utf8($str, true);
480 $result = self::typo3()->utf8_to_entities($str);
481 if ($dec) {
482 $result = preg_replace('/&#x([0-9a-f]+);/ie', "'&#'.hexdec('$1').';'", $result);
484 // Restore original debug level
485 error_reporting($oldlevel);
486 return $result;
490 * Removes the BOM from unicode string - see http://unicode.org/faq/utf_bom.html
492 * @param string $str
493 * @return string
495 public static function trim_utf8_bom($str) {
496 $bom = "\xef\xbb\xbf";
497 if (strpos($str, $bom) === 0) {
498 return substr($str, strlen($bom));
500 return $str;
504 * Returns encoding options for select boxes, utf-8 and platform encoding first
505 * @return array encodings
507 public static function get_encodings() {
508 $encodings = array();
509 $encodings['UTF-8'] = 'UTF-8';
510 $winenc = strtoupper(get_string('localewincharset', 'langconfig'));
511 if ($winenc != '') {
512 $encodings[$winenc] = $winenc;
514 $nixenc = strtoupper(get_string('oldcharset', 'langconfig'));
515 $encodings[$nixenc] = $nixenc;
517 foreach (self::typo3()->synonyms as $enc) {
518 $enc = strtoupper($enc);
519 $encodings[$enc] = $enc;
521 return $encodings;
525 * Returns the utf8 string corresponding to the unicode value
526 * (from php.net, courtesy - romans@void.lv)
528 * @param int $num one unicode value
529 * @return string the UTF-8 char corresponding to the unicode value
531 public static function code2utf8($num) {
532 if ($num < 128) {
533 return chr($num);
535 if ($num < 2048) {
536 return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
538 if ($num < 65536) {
539 return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
541 if ($num < 2097152) {
542 return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
544 return '';
548 * Makes first letter of each word capital - words must be separated by spaces.
549 * Use with care, this function does not work properly in many locales!!!
551 * @param string $text
552 * @return string
554 public static function strtotitle($text) {
555 if (empty($text)) {
556 return $text;
559 if (function_exists('mb_convert_case')) {
560 return mb_convert_case($text, MB_CASE_TITLE, 'UTF-8');
563 $text = self::strtolower($text);
564 $words = explode(' ', $text);
565 foreach ($words as $i=>$word) {
566 $length = self::strlen($word);
567 if (!$length) {
568 continue;
570 } else if ($length == 1) {
571 $words[$i] = self::strtoupper($word);
573 } else {
574 $letter = self::substr($word, 0, 1);
575 $letter = self::strtoupper($letter);
576 $rest = self::substr($word, 1);
577 $words[$i] = $letter.$rest;
580 return implode(' ', $words);
584 * Locale aware sorting, the key associations are kept, values are sorted alphabetically.
586 * @param array $arr array to be sorted (reference)
587 * @param int $sortflag One of Collator::SORT_REGULAR, Collator::SORT_NUMERIC, Collator::SORT_STRING
588 * @return void modifies parameter
590 public static function asort(array &$arr, $sortflag = null) {
591 debugging('textlib::asort has been superseeded by collatorlib::asort please upgrade your code to use that', DEBUG_DEVELOPER);
592 collatorlib::asort($arr, $sortflag);
597 * A collator class with static methods that can be used for sorting.
599 * @package core
600 * @subpackage lib
601 * @copyright 2011 Sam Hemelryk
602 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
604 abstract class collatorlib {
606 /** @var Collator|false|null **/
607 protected static $collator = null;
609 /** @var string|null The locale that was used in instantiating the current collator **/
610 protected static $locale = null;
613 * Ensures that a collator is available and created
615 * @return bool Returns true if collation is available and ready
617 protected static function ensure_collator_available() {
618 global $CFG;
620 $locale = get_string('locale', 'langconfig');
621 if (is_null(self::$collator) || $locale != self::$locale) {
622 self::$collator = false;
623 self::$locale = $locale;
624 if (class_exists('Collator', false)) {
625 $collator = new Collator($locale);
626 if (!empty($collator) && $collator instanceof Collator) {
627 // Check for non fatal error messages. This has to be done immediately
628 // after instantiation as any further calls to collation will cause
629 // it to reset to 0 again (or another error code if one occurred)
630 $errorcode = $collator->getErrorCode();
631 $errormessage = $collator->getErrorMessage();
632 // Check for an error code, 0 means no error occurred
633 if ($errorcode !== 0) {
634 // Get the actual locale being used, e.g. en, he, zh
635 $localeinuse = $collator->getLocale(Locale::ACTUAL_LOCALE);
636 // Check for the common fallback warning error codes. If this occurred
637 // there is normally little to worry about:
638 // - U_USING_DEFAULT_WARNING (127) - default fallback locale used (pt => UCA)
639 // - U_USING_FALLBACK_WARNING (128) - fallback locale used (de_CH => de)
640 // (UCA: Unicode Collation Algorithm http://unicode.org/reports/tr10/)
641 if ($errorcode === -127 || $errorcode === -128) {
642 // Check if the locale in use is UCA default one ('root') or
643 // if it is anything like the locale we asked for
644 if ($localeinuse !== 'root' && strpos($locale, $localeinuse) !== 0) {
645 // The locale we asked for is completely different to the locale
646 // we have received, let the user know via debugging
647 debugging('Invalid locale: "' . $locale . '", with warning (not fatal) "' . $errormessage .
648 '", falling back to "' . $collator->getLocale(Locale::VALID_LOCALE) . '"');
649 } else {
650 // Nothing to do here, this is expected!
651 // The Moodle locale setting isn't what the collator expected but
652 // it is smart enough to match the first characters of our locale
653 // to find the correct locale or to use UCA collation
655 } else {
656 // We've recieved some other sort of non fatal warning - let the
657 // user know about it via debugging.
658 debugging('Problem with locale: "' . $locale . '", with message "' . $errormessage .
659 '", falling back to "' . $collator->getLocale(Locale::VALID_LOCALE) . '"');
662 // Store the collator object now that we can be sure it is in a workable condition
663 self::$collator = $collator;
664 } else {
665 // Fatal error while trying to instantiate the collator... something went wrong
666 debugging('Error instantiating collator for locale: "' . $locale . '", with error [' .
667 intl_get_error_code() . '] ' . intl_get_error_message($collator));
671 return (self::$collator instanceof Collator);
675 * Locale aware sorting, the key associations are kept, values are sorted alphabetically.
677 * @param array $arr array to be sorted (reference)
678 * @param int $sortflag One of Collator::SORT_REGULAR, Collator::SORT_NUMERIC, Collator::SORT_STRING
679 * @return void modifies parameter
681 public static function asort(array &$arr, $sortflag = null) {
682 if (self::ensure_collator_available()) {
683 if (!isset($sortflag)) {
684 $sortflag = Collator::SORT_REGULAR;
686 self::$collator->asort($arr, $sortflag);
687 return;
689 asort($arr, SORT_LOCALE_STRING);
693 * Locale aware comparison of two strings.
695 * Returns:
696 * 1 if str1 is greater than str2
697 * 0 if str1 is equal to str2
698 * -1 if str1 is less than str2
700 * @return int
702 public static function compare($str1, $str2) {
703 if (self::ensure_collator_available()) {
704 return self::$collator->compare($str1, $str2);
706 return strcmp($str1, $str2);
710 * Locale aware sort of objects by a property in common to all objects
712 * @param array $objects An array of objects to sort (handled by reference)
713 * @param string $property The property to use for comparison
714 * @return bool True on success
716 public static function asort_objects_by_property(array &$objects, $property) {
717 $comparison = new collatorlib_property_comparison($property);
718 return uasort($objects, array($comparison, 'compare'));
722 * Locale aware sort of objects by a method in common to all objects
724 * @param array $objects An array of objects to sort (handled by reference)
725 * @param string $method The method to call to generate a value for comparison
726 * @return bool True on success
728 public static function asort_objects_by_method(array &$objects, $method) {
729 $comparison = new collatorlib_method_comparison($method);
730 return uasort($objects, array($comparison, 'compare'));
735 * Abstract class to aid the sorting of objects with respect to proper language
736 * comparison using collator
738 * @package core
739 * @subpackage lib
740 * @copyright 2011 Sam Hemelryk
741 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
743 abstract class collatorlib_comparison {
745 * This function will perform the actual comparison of values
746 * It must be overridden by the deriving class.
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 $a The first something to compare
754 * @param mixed $b The second something to compare
755 * @return int
757 public abstract function compare($a, $b);
761 * A comparison helper for comparing properties of two objects
763 * @package core
764 * @subpackage lib
765 * @copyright 2011 Sam Hemelryk
766 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
768 class collatorlib_property_comparison extends collatorlib_comparison {
770 /** @var string The property to sort by **/
771 protected $property;
774 * @param string $property
776 public function __construct($property) {
777 $this->property = $property;
781 * Returns:
782 * 1 if str1 is greater than str2
783 * 0 if str1 is equal to str2
784 * -1 if str1 is less than str2
786 * @param mixed $obja The first object to compare
787 * @param mixed $objb The second object to compare
788 * @return int
790 public function compare($obja, $objb) {
791 $resulta = $obja->{$this->property};
792 $resultb = $objb->{$this->property};
793 return collatorlib::compare($resulta, $resultb);
798 * A comparison helper for comparing the result of a method on two objects
800 * @package core
801 * @subpackage lib
802 * @copyright 2011 Sam Hemelryk
803 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
805 class collatorlib_method_comparison extends collatorlib_comparison {
807 /** @var string The method to use for comparison **/
808 protected $method;
811 * @param string $method The method to call against each object
813 public function __construct($method) {
814 $this->method = $method;
818 * Returns:
819 * 1 if str1 is greater than str2
820 * 0 if str1 is equal to str2
821 * -1 if str1 is less than str2
823 * @param mixed $obja The first object to compare
824 * @param mixed $objb The second object to compare
825 * @return int
827 public function compare($obja, $objb) {
828 $resulta = $obja->{$this->method}();
829 $resultb = $objb->{$this->method}();
830 return collatorlib::compare($resulta, $resultb);