MDL-30995 Completion Fixedup some more PHP DOC issues
[moodle.git] / lib / textlib.class.php
blob9f95a489507d00305505f10514dba91c50930caf
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 * Defines string apis
20 * @package core
21 * @copyright (C) 2001-3001 Eloy Lafuente (stronk7) {@link http://contiento.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') || die();
27 /**
28 * defines string api's for manipulating strings
30 * This class is used to manipulate strings under Moodle 1.6 an later. As
31 * utf-8 text become mandatory a pool of safe functions under this encoding
32 * become necessary. The name of the methods is exactly the
33 * same than their PHP originals.
35 * A big part of this class acts as a wrapper over the Typo3 charset library,
36 * really a cool group of utilities to handle texts and encoding conversion.
38 * Take a look to its own copyright and license details.
40 * IMPORTANT Note: Typo3 libraries always expect lowercase charsets to use 100%
41 * its capabilities so, don't forget to make the conversion
42 * from every wrapper function!
44 * @package core
45 * @category string
46 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
47 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 class textlib {
51 /**
52 * Return t3lib helper class, which is used for conversion between charsets
54 * @return t3lib_cs
56 protected static function typo3() {
57 static $typo3cs = null;
59 if (isset($typo3cs)) {
60 return $typo3cs;
63 global $CFG;
65 // Required files
66 require_once($CFG->libdir.'/typo3/class.t3lib_cs.php');
67 require_once($CFG->libdir.'/typo3/class.t3lib_div.php');
69 // do not use mbstring or recode because it may return invalid results in some corner cases
70 $GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_convMethod'] = 'iconv';
71 $GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] = 'iconv';
73 // Tell Typo3 we are curl enabled always (mandatory since 2.0)
74 $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] = '1';
76 // And this directory must exist to allow Typo to cache conversion
77 // tables when using internal functions
78 make_temp_directory('typo3temp/cs');
80 // Make sure typo is using our dir permissions
81 $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'] = decoct($CFG->directorypermissions);
83 // Default mask for Typo
84 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = $CFG->directorypermissions;
86 // This full path constants must be defined too, transforming backslashes
87 // to forward slashed because Typo3 requires it.
88 define ('PATH_t3lib', str_replace('\\','/',$CFG->libdir.'/typo3/'));
89 define ('PATH_typo3', str_replace('\\','/',$CFG->libdir.'/typo3/'));
90 define ('PATH_site', str_replace('\\','/',$CFG->tempdir.'/'));
91 define ('TYPO3_OS', stristr(PHP_OS,'win')&&!stristr(PHP_OS,'darwin')?'WIN':'');
93 $typo3cs = new t3lib_cs();
95 return $typo3cs;
98 /**
99 * Standardise charset name
101 * Please note it does not mean the returned charset is actually supported.
103 * @static
104 * @param string $charset raw charset name
105 * @return string normalised lowercase charset name
107 public static function parse_charset($charset) {
108 $charset = strtolower($charset);
110 // shortcuts so that we do not have to load typo3 on every page
112 if ($charset === 'utf8' or $charset === 'utf-8') {
113 return 'utf-8';
116 if (preg_match('/^(cp|win|windows)-?(12[0-9]{2})$/', $charset, $matches)) {
117 return 'windows-'.$matches[2];
120 if (preg_match('/^iso-8859-[0-9]+$/', $charset, $matches)) {
121 return $charset;
124 if ($charset === 'euc-jp') {
125 return 'euc-jp';
127 if ($charset === 'iso-2022-jp') {
128 return 'iso-2022-jp';
130 if ($charset === 'shift-jis' or $charset === 'shift_jis') {
131 return 'shift_jis';
133 if ($charset === 'gb2312') {
134 return 'gb2312';
136 if ($charset === 'gb18030') {
137 return 'gb18030';
140 // fallback to typo3
141 return self::typo3()->parse_charset($charset);
145 * Converts the text between different encodings. It uses iconv extension with //TRANSLIT parameter,
146 * falls back to typo3.
147 * Returns false if fails.
149 * @param string $text
150 * @param string $fromCS source encoding
151 * @param string $toCS result encoding
152 * @return string|bool converted string or false on error
154 public static function convert($text, $fromCS, $toCS='utf-8') {
155 $fromCS = self::parse_charset($fromCS);
156 $toCS = self::parse_charset($toCS);
158 $text = (string)$text; // we can work only with strings
160 if ($text === '') {
161 return '';
164 $result = iconv($fromCS, $toCS.'//TRANSLIT', $text);
166 if ($result === false or $result === '') {
167 // note: iconv is prone to return empty string when invalid char encountered, or false if encoding unsupported
168 $oldlevel = error_reporting(E_PARSE);
169 $result = self::typo3()->conv($text, $fromCS, $toCS);
170 error_reporting($oldlevel);
173 return $result;
177 * Multibyte safe substr() function, uses mbstring or iconv for UTF-8, falls back to typo3.
179 * @param string $text string to truncate
180 * @param int $start negative value means from end
181 * @param int $len maximum length of characters beginning from start
182 * @param string $charset encoding of the text
183 * @return string portion of string specified by the $start and $len
185 public static function substr($text, $start, $len=null, $charset='utf-8') {
186 $charset = self::parse_charset($charset);
188 if ($charset === 'utf-8') {
189 if (function_exists('mb_substr')) {
190 // this is much faster than iconv - see MDL-31142
191 if ($len === null) {
192 $oldcharset = mb_internal_encoding();
193 mb_internal_encoding('UTF-8');
194 $result = mb_substr($text, $start);
195 mb_internal_encoding($oldcharset);
196 return $result;
197 } else {
198 return mb_substr($text, $start, $len, 'UTF-8');
201 } else {
202 if ($len === null) {
203 $len = iconv_strlen($text, 'UTF-8');
205 return iconv_substr($text, $start, $len, 'UTF-8');
209 $oldlevel = error_reporting(E_PARSE);
210 if ($len === null) {
211 $result = self::typo3()->substr($charset, $text, $start);
212 } else {
213 $result = self::typo3()->substr($charset, $text, $start, $len);
215 error_reporting($oldlevel);
217 return $result;
221 * Multibyte safe strlen() function, uses mbstring or iconv for UTF-8, falls back to typo3.
223 * @param string $text input string
224 * @param string $charset encoding of the text
225 * @return int number of characters
227 public static function strlen($text, $charset='utf-8') {
228 $charset = self::parse_charset($charset);
230 if ($charset === 'utf-8') {
231 if (function_exists('mb_strlen')) {
232 return mb_strlen($text, 'UTF-8');
233 } else {
234 return iconv_strlen($text, 'UTF-8');
238 $oldlevel = error_reporting(E_PARSE);
239 $result = self::typo3()->strlen($charset, $text);
240 error_reporting($oldlevel);
242 return $result;
246 * Multibyte safe strtolower() function, uses mbstring, falls back to typo3.
248 * @param string $text input string
249 * @param string $charset encoding of the text (may not work for all encodings)
250 * @return string lower case text
252 public static function strtolower($text, $charset='utf-8') {
253 $charset = self::parse_charset($charset);
255 if ($charset === 'utf-8' and function_exists('mb_strtolower')) {
256 return mb_strtolower($text, 'UTF-8');
259 $oldlevel = error_reporting(E_PARSE);
260 $result = self::typo3()->conv_case($charset, $text, 'toLower');
261 error_reporting($oldlevel);
263 return $result;
267 * Multibyte safe strtoupper() function, uses mbstring, falls back to typo3.
269 * @param string $text input string
270 * @param string $charset encoding of the text (may not work for all encodings)
271 * @return string upper case text
273 public static function strtoupper($text, $charset='utf-8') {
274 $charset = self::parse_charset($charset);
276 if ($charset === 'utf-8' and function_exists('mb_strtoupper')) {
277 return mb_strtoupper($text, 'UTF-8');
280 $oldlevel = error_reporting(E_PARSE);
281 $result = self::typo3()->conv_case($charset, $text, 'toUpper');
282 error_reporting($oldlevel);
284 return $result;
288 * Find the position of the first occurrence of a substring in a string.
289 * UTF-8 ONLY safe strpos(), uses mbstring, falls back to iconv.
291 * @param string $haystack the string to search in
292 * @param string $needle one or more charachters to search for
293 * @param int $offset offset from begining of string
294 * @return int the numeric position of the first occurrence of needle in haystack.
296 public static function strpos($haystack, $needle, $offset=0) {
297 if (function_exists('mb_strpos')) {
298 return mb_strpos($haystack, $needle, $offset, 'UTF-8');
299 } else {
300 return iconv_strpos($haystack, $needle, $offset, 'UTF-8');
305 * Find the position of the last occurrence of a substring in a string
306 * UTF-8 ONLY safe strrpos(), uses mbstring, falls back to iconv.
308 * @param string $haystack the string to search in
309 * @param string $needle one or more charachters to search for
310 * @return int the numeric position of the last occurrence of needle in haystack
312 public static function strrpos($haystack, $needle) {
313 if (function_exists('mb_strpos')) {
314 return mb_strrpos($haystack, $needle, null, 'UTF-8');
315 } else {
316 return iconv_strrpos($haystack, $needle, 'UTF-8');
321 * Try to convert upper unicode characters to plain ascii,
322 * the returned string may contain unconverted unicode characters.
324 * @param string $text input string
325 * @param string $charset encoding of the text
326 * @return string converted ascii string
328 public static function specialtoascii($text, $charset='utf-8') {
329 $charset = self::parse_charset($charset);
330 $oldlevel = error_reporting(E_PARSE);
331 $result = self::typo3()->specCharsToASCII($charset, $text);
332 error_reporting($oldlevel);
333 return $result;
337 * Generate a correct base64 encoded header to be used in MIME mail messages.
338 * This function seems to be 100% compliant with RFC1342. Credits go to:
339 * paravoid (http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283).
341 * @param string $text input string
342 * @param string $charset encoding of the text
343 * @return string base64 encoded header
345 public static function encode_mimeheader($text, $charset='utf-8') {
346 if (empty($text)) {
347 return (string)$text;
349 // Normalize charset
350 $charset = self::parse_charset($charset);
351 // If the text is pure ASCII, we don't need to encode it
352 if (self::convert($text, $charset, 'ascii') == $text) {
353 return $text;
355 // Although RFC says that line feed should be \r\n, it seems that
356 // some mailers double convert \r, so we are going to use \n alone
357 $linefeed="\n";
358 // Define start and end of every chunk
359 $start = "=?$charset?B?";
360 $end = "?=";
361 // Accumulate results
362 $encoded = '';
363 // Max line length is 75 (including start and end)
364 $length = 75 - strlen($start) - strlen($end);
365 // Multi-byte ratio
366 $multilength = self::strlen($text, $charset);
367 // Detect if strlen and friends supported
368 if ($multilength === false) {
369 if ($charset == 'GB18030' or $charset == 'gb18030') {
370 while (strlen($text)) {
371 // try to encode first 22 chars - we expect most chars are two bytes long
372 if (preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,22}/m', $text, $matches)) {
373 $chunk = $matches[0];
374 $encchunk = base64_encode($chunk);
375 if (strlen($encchunk) > $length) {
376 // find first 11 chars - each char in 4 bytes - worst case scenario
377 preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,11}/m', $text, $matches);
378 $chunk = $matches[0];
379 $encchunk = base64_encode($chunk);
381 $text = substr($text, strlen($chunk));
382 $encoded .= ' '.$start.$encchunk.$end.$linefeed;
383 } else {
384 break;
387 $encoded = trim($encoded);
388 return $encoded;
389 } else {
390 return false;
393 $ratio = $multilength / strlen($text);
394 // Base64 ratio
395 $magic = $avglength = floor(3 * $length * $ratio / 4);
396 // basic infinite loop protection
397 $maxiterations = strlen($text)*2;
398 $iteration = 0;
399 // Iterate over the string in magic chunks
400 for ($i=0; $i <= $multilength; $i+=$magic) {
401 if ($iteration++ > $maxiterations) {
402 return false; // probably infinite loop
404 $magic = $avglength;
405 $offset = 0;
406 // Ensure the chunk fits in length, reducing magic if necessary
407 do {
408 $magic -= $offset;
409 $chunk = self::substr($text, $i, $magic, $charset);
410 $chunk = base64_encode($chunk);
411 $offset++;
412 } while (strlen($chunk) > $length);
413 // This chunk doesn't break any multi-byte char. Use it.
414 if ($chunk)
415 $encoded .= ' '.$start.$chunk.$end.$linefeed;
417 // Strip the first space and the last linefeed
418 $encoded = substr($encoded, 1, -strlen($linefeed));
420 return $encoded;
424 * Converts all the numeric entities &#nnnn; or &#xnnn; to UTF-8
425 * Original from laurynas dot butkus at gmail at:
426 * http://php.net/manual/en/function.html-entity-decode.php#75153
427 * with some custom mods to provide more functionality
429 * @param string $str input string
430 * @param boolean $htmlent convert also html entities (defaults to true)
431 * @return string encoded UTF-8 string
433 * NOTE: we could have used typo3 entities_to_utf8() here
434 * but the direct alternative used runs 400% quicker
435 * and uses 0.5Mb less memory, so, let's use it
436 * (tested against 10^6 conversions)
438 public static function entities_to_utf8($str, $htmlent=true) {
439 static $trans_tbl; // Going to use static transliteration table
441 // Replace numeric entities
442 $result = preg_replace('~&#x([0-9a-f]+);~ei', 'textlib::code2utf8(hexdec("\\1"))', $str);
443 $result = preg_replace('~&#([0-9]+);~e', 'textlib::code2utf8(\\1)', $result);
445 // Replace literal entities (if desired)
446 if ($htmlent) {
447 // Generate/create $trans_tbl
448 if (!isset($trans_tbl)) {
449 $trans_tbl = array();
450 foreach (get_html_translation_table(HTML_ENTITIES) as $val=>$key) {
451 $trans_tbl[$key] = utf8_encode($val);
454 $result = strtr($result, $trans_tbl);
456 // Return utf8-ised string
457 return $result;
461 * Converts all Unicode chars > 127 to numeric entities &#nnnn; or &#xnnn;.
463 * @param string $str input string
464 * @param boolean $dec output decadic only number entities
465 * @param boolean $nonnum remove all non-numeric entities
466 * @return string converted string
468 public static function utf8_to_entities($str, $dec=false, $nonnum=false) {
469 // Avoid some notices from Typo3 code
470 $oldlevel = error_reporting(E_PARSE);
471 if ($nonnum) {
472 $str = self::typo3()->entities_to_utf8($str, true);
474 $result = self::typo3()->utf8_to_entities($str);
475 if ($dec) {
476 $result = preg_replace('/&#x([0-9a-f]+);/ie', "'&#'.hexdec('$1').';'", $result);
478 // Restore original debug level
479 error_reporting($oldlevel);
480 return $result;
484 * Removes the BOM from unicode string {@link http://unicode.org/faq/utf_bom.html}
486 * @param string $str input string
487 * @return string
489 public static function trim_utf8_bom($str) {
490 $bom = "\xef\xbb\xbf";
491 if (strpos($str, $bom) === 0) {
492 return substr($str, strlen($bom));
494 return $str;
498 * Returns encoding options for select boxes, utf-8 and platform encoding first
500 * @return array encodings
502 public static function get_encodings() {
503 $encodings = array();
504 $encodings['UTF-8'] = 'UTF-8';
505 $winenc = strtoupper(get_string('localewincharset', 'langconfig'));
506 if ($winenc != '') {
507 $encodings[$winenc] = $winenc;
509 $nixenc = strtoupper(get_string('oldcharset', 'langconfig'));
510 $encodings[$nixenc] = $nixenc;
512 foreach (self::typo3()->synonyms as $enc) {
513 $enc = strtoupper($enc);
514 $encodings[$enc] = $enc;
516 return $encodings;
520 * Returns the utf8 string corresponding to the unicode value
521 * (from php.net, courtesy - romans@void.lv)
523 * @param int $num one unicode value
524 * @return string the UTF-8 char corresponding to the unicode value
526 public static function code2utf8($num) {
527 if ($num < 128) {
528 return chr($num);
530 if ($num < 2048) {
531 return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
533 if ($num < 65536) {
534 return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
536 if ($num < 2097152) {
537 return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
539 return '';
543 * Makes first letter of each word capital - words must be separated by spaces.
544 * Use with care, this function does not work properly in many locales!!!
546 * @param string $text input string
547 * @return string
549 public static function strtotitle($text) {
550 if (empty($text)) {
551 return $text;
554 if (function_exists('mb_convert_case')) {
555 return mb_convert_case($text, MB_CASE_TITLE, 'UTF-8');
558 $text = self::strtolower($text);
559 $words = explode(' ', $text);
560 foreach ($words as $i=>$word) {
561 $length = self::strlen($word);
562 if (!$length) {
563 continue;
565 } else if ($length == 1) {
566 $words[$i] = self::strtoupper($word);
568 } else {
569 $letter = self::substr($word, 0, 1);
570 $letter = self::strtoupper($letter);
571 $rest = self::substr($word, 1);
572 $words[$i] = $letter.$rest;
575 return implode(' ', $words);
579 * Locale aware sorting, the key associations are kept, values are sorted alphabetically.
581 * @param array $arr array to be sorted (reference)
582 * @param int $sortflag One of Collator::SORT_REGULAR, Collator::SORT_NUMERIC, Collator::SORT_STRING
583 * @return void modifies parameter
585 public static function asort(array &$arr, $sortflag = null) {
586 debugging('textlib::asort has been superseeded by collatorlib::asort please upgrade your code to use that', DEBUG_DEVELOPER);
587 collatorlib::asort($arr, $sortflag);
592 * A collator class with static methods that can be used for sorting.
594 * @package core
595 * @copyright 2011 Sam Hemelryk
596 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
598 abstract class collatorlib {
600 /** @var Collator|false|null **/
601 protected static $collator = null;
603 /** @var string|null The locale that was used in instantiating the current collator **/
604 protected static $locale = null;
607 * Ensures that a collator is available and created
609 * @return bool Returns true if collation is available and ready
611 protected static function ensure_collator_available() {
612 global $CFG;
614 $locale = get_string('locale', 'langconfig');
615 if (is_null(self::$collator) || $locale != self::$locale) {
616 self::$collator = false;
617 self::$locale = $locale;
618 if (class_exists('Collator', false)) {
619 $collator = new Collator($locale);
620 if (!empty($collator) && $collator instanceof Collator) {
621 // Check for non fatal error messages. This has to be done immediately
622 // after instantiation as any further calls to collation will cause
623 // it to reset to 0 again (or another error code if one occurred)
624 $errorcode = $collator->getErrorCode();
625 $errormessage = $collator->getErrorMessage();
626 // Check for an error code, 0 means no error occurred
627 if ($errorcode !== 0) {
628 // Get the actual locale being used, e.g. en, he, zh
629 $localeinuse = $collator->getLocale(Locale::ACTUAL_LOCALE);
630 // Check for the common fallback warning error codes. If this occurred
631 // there is normally little to worry about:
632 // - U_USING_DEFAULT_WARNING (127) - default fallback locale used (pt => UCA)
633 // - U_USING_FALLBACK_WARNING (128) - fallback locale used (de_CH => de)
634 // (UCA: Unicode Collation Algorithm http://unicode.org/reports/tr10/)
635 if ($errorcode === -127 || $errorcode === -128) {
636 // Check if the locale in use is UCA default one ('root') or
637 // if it is anything like the locale we asked for
638 if ($localeinuse !== 'root' && strpos($locale, $localeinuse) !== 0) {
639 // The locale we asked for is completely different to the locale
640 // we have received, let the user know via debugging
641 debugging('Invalid locale: "' . $locale . '", with warning (not fatal) "' . $errormessage .
642 '", falling back to "' . $collator->getLocale(Locale::VALID_LOCALE) . '"');
643 } else {
644 // Nothing to do here, this is expected!
645 // The Moodle locale setting isn't what the collator expected but
646 // it is smart enough to match the first characters of our locale
647 // to find the correct locale or to use UCA collation
649 } else {
650 // We've recieved some other sort of non fatal warning - let the
651 // user know about it via debugging.
652 debugging('Problem with locale: "' . $locale . '", with message "' . $errormessage .
653 '", falling back to "' . $collator->getLocale(Locale::VALID_LOCALE) . '"');
656 // Store the collator object now that we can be sure it is in a workable condition
657 self::$collator = $collator;
658 } else {
659 // Fatal error while trying to instantiate the collator... something went wrong
660 debugging('Error instantiating collator for locale: "' . $locale . '", with error [' .
661 intl_get_error_code() . '] ' . intl_get_error_message($collator));
665 return (self::$collator instanceof Collator);
669 * Locale aware sorting, the key associations are kept, values are sorted alphabetically.
671 * @param array $arr array to be sorted (reference)
672 * @param int $sortflag One of Collator::SORT_REGULAR, Collator::SORT_NUMERIC, Collator::SORT_STRING
673 * @return void modifies parameter
675 public static function asort(array &$arr, $sortflag = null) {
676 if (self::ensure_collator_available()) {
677 if (!isset($sortflag)) {
678 $sortflag = Collator::SORT_REGULAR;
680 self::$collator->asort($arr, $sortflag);
681 return;
683 asort($arr, SORT_LOCALE_STRING);
687 * Locale aware comparison of two strings.
689 * Returns:
690 * 1 if str1 is greater than str2
691 * 0 if str1 is equal to str2
692 * -1 if str1 is less than str2
694 * @param string $str1 first string to compare
695 * @param string $str2 second string to compare
696 * @return int
698 public static function compare($str1, $str2) {
699 if (self::ensure_collator_available()) {
700 return self::$collator->compare($str1, $str2);
702 return strcmp($str1, $str2);
706 * Locale aware sort of objects by a property in common to all objects
708 * @param array $objects An array of objects to sort (handled by reference)
709 * @param string $property The property to use for comparison
710 * @return bool True on success
712 public static function asort_objects_by_property(array &$objects, $property) {
713 $comparison = new collatorlib_property_comparison($property);
714 return uasort($objects, array($comparison, 'compare'));
718 * Locale aware sort of objects by a method in common to all objects
720 * @param array $objects An array of objects to sort (handled by reference)
721 * @param string $method The method to call to generate a value for comparison
722 * @return bool True on success
724 public static function asort_objects_by_method(array &$objects, $method) {
725 $comparison = new collatorlib_method_comparison($method);
726 return uasort($objects, array($comparison, 'compare'));
731 * Object comparison using collator
733 * Abstract class to aid the sorting of objects with respect to proper language
734 * comparison using collator
736 * @package core
737 * @copyright 2011 Sam Hemelryk
738 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
740 abstract class collatorlib_comparison {
742 * This function will perform the actual comparison of values
743 * It must be overridden by the deriving class.
745 * Returns:
746 * 1 if str1 is greater than str2
747 * 0 if str1 is equal to str2
748 * -1 if str1 is less than str2
750 * @param mixed $a The first something to compare
751 * @param mixed $b The second something to compare
752 * @return int
754 public abstract function compare($a, $b);
758 * Compare properties of two objects
760 * A comparison helper for comparing properties of two objects
762 * @package core
763 * @category string
764 * @copyright 2011 Sam Hemelryk
765 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
767 class collatorlib_property_comparison extends collatorlib_comparison {
769 /** @var string The property to sort by **/
770 protected $property;
773 * Constructor
775 * @param string $property
777 public function __construct($property) {
778 $this->property = $property;
782 * Returns:
783 * 1 if str1 is greater than str2
784 * 0 if str1 is equal to str2
785 * -1 if str1 is less than str2
787 * @param mixed $obja The first object to compare
788 * @param mixed $objb The second object to compare
789 * @return int
791 public function compare($obja, $objb) {
792 $resulta = $obja->{$this->property};
793 $resultb = $objb->{$this->property};
794 return collatorlib::compare($resulta, $resultb);
799 * Compare method of two objects
801 * A comparison helper for comparing the result of a method on two objects
803 * @package core
804 * @copyright 2011 Sam Hemelryk
805 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
807 class collatorlib_method_comparison extends collatorlib_comparison {
809 /** @var string The method to use for comparison **/
810 protected $method;
813 * Constructor
815 * @param string $method The method to call against each object
817 public function __construct($method) {
818 $this->method = $method;
822 * Returns:
823 * 1 if str1 is greater than str2
824 * 0 if str1 is equal to str2
825 * -1 if str1 is less than str2
827 * @param mixed $obja The first object to compare
828 * @param mixed $objb The second object to compare
829 * @return int
831 public function compare($obja, $objb) {
832 $resulta = $obja->{$this->method}();
833 $resultb = $objb->{$this->method}();
834 return collatorlib::compare($resulta, $resultb);