/** * Splits a string into substrings using a specified substring or substrings as the delimiter(s) and returns the * resulting strings as an array. * * If no delimiter substrings were found, the resulting array contains just one element, which is the original * string. If a delimiter is located at the very start or at the very end of the string or next to another * delimiter, it will accordingly cause some string(s) in the resulting array to be empty. * * As a special case, the delimiter substring can be empty, which will split the string into its constituting * characters. * * @param string $string The string to be split. * @param string|array|map $delimiterOrDelimiters The substring or array of substrings to be recognized as the * delimiter(s). * * @return CArray The resulting strings. */ public static function split($string, $delimiterOrDelimiters) { assert('is_cstring($string) && ' . '(is_cstring($delimiterOrDelimiters) || is_collection($delimiterOrDelimiters))', vs(isset($this), get_defined_vars())); if (is_cstring($delimiterOrDelimiters)) { if (self::isEmpty($delimiterOrDelimiters)) { // Special case. if (self::isEmpty($string)) { $resStrings = CArray::fromElements(""); return $resStrings; } else { $resStrings = CArray::make(strlen($string)); for ($i = 0; $i < strlen($string); $i++) { $resStrings[$i] = $string[$i]; } return $resStrings; } } $resStrings = CArray::make(self::numSubstrings($string, $delimiterOrDelimiters) + 1); $startPos = 0; $i = 0; while (true) { $endPos = self::indexOf($string, $delimiterOrDelimiters, $startPos); if ($endPos != -1) { $resStrings[$i++] = self::substring($string, $startPos, $endPos); $startPos = $endPos + strlen($delimiterOrDelimiters); } else { $resStrings[$i] = self::substr($string, $startPos); break; } } return $resStrings; } else { $resStrings = CArray::fromElements($string); foreach ($delimiterOrDelimiters as $delimiter) { assert('is_cstring($delimiter)', vs(isset($this), get_defined_vars())); $resStringsNew = CArray::make(); $len = CArray::length($resStrings); for ($i = 0; $i < $len; $i++) { CArray::pushArray($resStringsNew, self::split($resStrings[$i], $delimiter)); } $resStrings = $resStringsNew; } return $resStrings; } }
public function testSplit() { // ASCII. $res = CRegex::split("He,llo;th,ere!", "/[,;]/"); $this->assertTrue(CArray::length($res) == 4 && CString::equals($res[0], "He") && CString::equals($res[1], "llo") && CString::equals($res[2], "th") && CString::equals($res[3], "ere!")); $res = CRegex::split("He,llo;th.ere!", CArray::fromElements("/[,;]/", "/\\./")); $this->assertTrue(CArray::length($res) == 4 && CString::equals($res[0], "He") && CString::equals($res[1], "llo") && CString::equals($res[2], "th") && CString::equals($res[3], "ere!")); // Special cases. $res = CRegex::split("", "/[,;]/"); $this->assertTrue(CArray::length($res) == 1 && CString::equals($res[0], "")); $res = CRegex::split("Hey", "//"); $this->assertTrue(CArray::length($res) == 3 && CString::equals($res[0], "H") && CString::equals($res[1], "e") && CString::equals($res[2], "y")); $res = CRegex::split("", "//"); $this->assertTrue(CArray::length($res) == 1 && CString::equals($res[0], "")); // Unicode. $res = CRegex::split("¡He,llo·se,ñor!", "/[,·]/u"); $this->assertTrue(CArray::length($res) == 4 && CUString::equals($res[0], "¡He") && CUString::equals($res[1], "llo") && CUString::equals($res[2], "se") && CUString::equals($res[3], "ñor!")); $res = CRegex::split("¡He,llo·se.ñor!", CArray::fromElements("/[,·]/u", "/\\./u")); $this->assertTrue(CArray::length($res) == 4 && CUString::equals($res[0], "¡He") && CUString::equals($res[1], "llo") && CUString::equals($res[2], "se") && CUString::equals($res[3], "ñor!")); // Special cases. $res = CRegex::split("", "/[,·]/u"); $this->assertTrue(CArray::length($res) == 1 && CUString::equals($res[0], "")); $res = CRegex::split("Héy", "//u"); $this->assertTrue(CArray::length($res) == 3 && CUString::equals($res[0], "H") && CUString::equals($res[1], "é") && CUString::equals($res[2], "y")); $res = CRegex::split("", "//u"); $this->assertTrue(CArray::length($res) == 1 && CUString::equals($res[0], "")); }
public function testRepeat() { $array = CArray::repeat("a", 5); $this->assertTrue(CArray::equals($array, CArray::fromElements("a", "a", "a", "a", "a"))); }
/** * @ignore */ public static function initializeFramework() { $currEnv; if (!$GLOBALS["PHRED_TESTS"]) { // Try to get the name of the environment in which the application is currently running without the risk of // encountering an error or triggering an assertion, which could otherwise reveal sensitive debugging // information if "display_errors" happens to be enabled in php.ini. $appConfigFp = $GLOBALS["PHRED_PATH_TO_APP"] . "/Configuration" . "/Application.json"; if (file_exists($appConfigFp)) { $appConfig = file_get_contents($appConfigFp); if (is_string($appConfig)) { $matches; $res = preg_match("/^\\h*\"environment\"\\s*:\\s*\"(\\w+)\"/m", $appConfig, $matches); if ($res === 1) { $currEnv = $matches[1]; } } } } else { $currEnv = "tst"; } if (isset($currEnv)) { // Based on the current environment, set some debugging options to temporary values for the time while the // configuration is not yet read. if (strcasecmp($currEnv, "dev") == 0) { // Development. ini_set("display_errors", "On"); CDebug::setAssertionsLevel1(true); CDebug::setAssertionsLevel2(false); } else { if (strcasecmp($currEnv, "pro") == 0) { // Production. ini_set("display_errors", "Off"); CDebug::setAssertionsLevel1(false); CDebug::setAssertionsLevel2(false); } else { if (strcasecmp($currEnv, "tst") == 0) { // Testing. ini_set("display_errors", "On"); CDebug::setAssertionsLevel1(true); CDebug::setAssertionsLevel2(true); } else { // Unknown environment. error_reporting(E_ALL); ini_set("display_errors", "On"); } } } } else { error_reporting(E_ALL); ini_set("display_errors", "On"); trigger_error("Could not read the name of the current environment.", E_USER_ERROR); } // Read all the configuration options. CConfiguration::initialize(); // Set whether error messages should be shown is the output. if (CConfiguration::option("debug.displayErrors")) { ini_set("display_errors", "On"); } else { ini_set("display_errors", "Off"); } // Set the error reporting level. $errorReportingLevel = constant(CConfiguration::option("debug.errorReportingLevel")); error_reporting($errorReportingLevel); // Process the configuration options that are related to debugging. $debug = CConfiguration::option("debug"); // Assertions and the conditions on which they get active. $assertionsAreActive = false; $assertionsAreEnabled = $debug["enableAssertions"]; if ($assertionsAreEnabled) { $assertionsAreActiveBasedOn = $debug["assertionsAreActiveBasedOn"]; if (CString::equalsCi($assertionsAreActiveBasedOn, "always")) { // Always. $assertionsAreActive = true; } else { // Reference time zone. $refTimeZone; $timeZoneName = $debug["referenceTimeZone"]; if (!CString::isEmpty($timeZoneName)) { $refTimeZone = new CTimeZone($timeZoneName); } else { $refTimeZone = CTimeZone::makeUtc(); } if (CString::equalsCi($assertionsAreActiveBasedOn, "hour")) { // Current time. $currTime = CTime::now(); // Hour. $hourRanges = $debug["assertionsAreActiveWithinHourRange"]; $currHour = $currTime->hourInTimeZone($refTimeZone); if (!is_carray($hourRanges[0])) { $hourRanges = CArray::fromElements($hourRanges); } $len = CArray::length($hourRanges); for ($i = 0; $i < $len; $i++) { $range = $hourRanges[$i]; assert('is_int($range[0]) && is_int($range[1])', vs(isset($this), get_defined_vars())); if ($range[0] <= $currHour && $currHour <= $range[1]) { $assertionsAreActive = true; break; } } } else { if (CString::equalsCi($assertionsAreActiveBasedOn, "dayOfWeek")) { // Current time. $currTime = CTime::now(); // Day of week. $daysOfWeek = $debug["assertionsAreActiveOnDaysOfWeek"]; if (!is_carray($daysOfWeek)) { $daysOfWeek = CArray::fromElements($daysOfWeek); } $currDayOfWeek = $currTime->dayOfWeekInTimeZone($refTimeZone); $currDayOfWeekShort; switch ($currDayOfWeek) { case CTime::SUNDAY: $currDayOfWeekShort = "sun"; break; case CTime::MONDAY: $currDayOfWeekShort = "mon"; break; case CTime::TUESDAY: $currDayOfWeekShort = "tue"; break; case CTime::WEDNESDAY: $currDayOfWeekShort = "wed"; break; case CTime::THURSDAY: $currDayOfWeekShort = "thu"; break; case CTime::FRIDAY: $currDayOfWeekShort = "fri"; break; case CTime::SATURDAY: $currDayOfWeekShort = "sat"; break; } $len = CArray::length($daysOfWeek); for ($i = 0; $i < $len; $i++) { $dow = $daysOfWeek[$i]; assert('!CString::isEmpty($dow)', vs(isset($this), get_defined_vars())); if (CString::equalsCi($currDayOfWeekShort, $dow)) { $assertionsAreActive = true; break; } } } else { if (CString::equalsCi($assertionsAreActiveBasedOn, "dayOfYear")) { // Day of year. $multiplier = $debug["assertionsAreActiveOnEveryDayOfYearMultipleOf"]; assert('is_int($multiplier)', vs(isset($this), get_defined_vars())); $currDayOfYear = CTime::currentDayOfYearInTimeZone($refTimeZone); if ($currDayOfYear % $multiplier == 0) { $assertionsAreActive = true; } } else { assert('false', vs(isset($this), get_defined_vars())); } } } } } if ($assertionsAreActive) { // Enable level 1 assertions. CDebug::setAssertionsLevel1(true); $enableAssertionsLevel2 = $debug["enableAssertionsLevel2"]; if ($enableAssertionsLevel2) { // Enable level 2 assertions. CDebug::setAssertionsLevel2(true); } } else { CDebug::setAssertionsLevel1(false); CDebug::setAssertionsLevel2(false); } // Logging. $logging = $debug["logging"]; $loggingIsEnabled = $logging["enable"]; if ($loggingIsEnabled) { $logFp = $logging["logFilePath"]; assert('!CString::isEmpty($logFp)', vs(isset($this), get_defined_vars())); $logFp = CFilePath::frameworkPath($logFp); CDebug::setLogging($logFp); } // Mailing. $mailing = $debug["mailing"]; $mailingIsEnabled = $mailing["enable"]; if ($mailingIsEnabled) { $adminMail = CConfiguration::option("admin.mail"); $to = $adminMail["to"]; $from = $adminMail["from"]; $transport = $adminMail["transport"]; assert('!CString::isEmpty($to) && !CString::isEmpty($from) && !CString::isEmpty($transport)', vs(isset($this), get_defined_vars())); $minTimeBetweenSendMailHours = $mailing["minTimeBetweenSendMailHours"]; assert('is_int($minTimeBetweenSendMailHours)', vs(isset($this), get_defined_vars())); $mail; if (CString::equalsCi($transport, "smtp")) { $smtpOutgoingServer = $adminMail["smtpOutgoingServer"]; $smtpUsername = $adminMail["smtpUsername"]; $smtpPassword = $adminMail["smtpPassword"]; assert('!CString::isEmpty($smtpOutgoingServer) && !CString::isEmpty($smtpUsername) && ' . '!CString::isEmpty($smtpPassword)', vs(isset($this), get_defined_vars())); $mail = CMail::makeSmtp($smtpOutgoingServer, $smtpUsername, $smtpPassword, $from, $to); } else { if (CString::equalsCi($transport, "system")) { $mail = CMail::makeSystem($from, $to); } else { assert('false', vs(isset($this), get_defined_vars())); } } CDebug::setMailing($mail, $minTimeBetweenSendMailHours); } }
/** * Sets the alternative body of a message to be used if the primary body cannot be displayed. * * @param string $body The alternative body of the message. * @param string $type **OPTIONAL. Default is** `CMimeType::PLAIN_TEXT`. The MIME type of the alternative body. * * @return void */ public function addAltBody($body, $type = CMimeType::PLAIN_TEXT) { assert('is_cstring($body) && is_cstring($type)', vs(isset($this), get_defined_vars())); if (!isset($this->m_altBodiesAndTypes)) { $this->m_altBodiesAndTypes = CArray::make(); } $bodyAndType = CArray::fromElements($body, $type); CArray::push($this->m_altBodiesAndTypes, $bodyAndType); }
public function testFindScalar() { $array = CArrayObject::fromSplArray(CArray::fromElements("a", "b", "c", "d", "e")); $found = $array->findScalar("c"); $this->assertTrue($found); $foundAtPos; $found = $array->findScalar("d", $foundAtPos); $this->assertTrue($found); $this->assertTrue($foundAtPos == 3); $found = $array->findScalar("C"); $this->assertFalse($found); $found = $array->findScalar("f"); $this->assertFalse($found); // Special case. $array = new CArrayObject(); $found = $array->findScalar("a"); $this->assertFalse($found); }
/** * Adds a request to a session. * * @param CInetRequest $request The request to be added. * @param callable $onCompleteCallback **OPTIONAL.** The callback function or method to be called by the session * when the request completes. The function is expected to take four parameters: a flag of type `bool` that tells * whether the request was successful, the response of type `CUStringObject` that was received for the request, an * object of type `CInetRequest` that represents the request, and an object of type `CInetSession` that represents * the session to which the request belongs, in this order. You can use the session's object to add more requests * to the request queue of the session depending on the response or any other factors. * @param bool $newCookieSession **OPTIONAL. Default is** `false`. Tells whether to delete all previously stored * cookies that were set by the remote server(s) to expire when the "browsing session" during which those cookies * were received comes to an end (you can have as much of such "browsing sessions" as you like). If this parameter * is `true`, the "browsing session" cookies are deleted before the request is sent. * * @return void */ public function addRequest(CInetRequest $request, $onCompleteCallback = null, $newCookieSession = false) { assert('(!isset($onCompleteCallback) || is_callable($onCompleteCallback)) && is_bool($newCookieSession)', vs(isset($this), get_defined_vars())); $requestRecord = CArray::fromElements($request, $onCompleteCallback, $newCookieSession); CArray::push($this->m_requestRecordsQueue, $requestRecord); }
/** * Returns all the values assigned to a specified long option with which the script was run, * e.g. "--option=value1 --option=value2". * * @param string $optionName The name of the option, excluding "-". * * @return CArrayObject The values of the option specified, where each value is of type `CUStringObject`. */ public static function valuesForLongOption($optionName) { assert('is_cstring($optionName)', vs(isset($this), get_defined_vars())); assert('self::hasLongOptionWithValue($optionName)', vs(isset($this), get_defined_vars())); $opt = getopt("", ["{$optionName}:"]); $values = $opt[$optionName]; return oop_a(is_cmap($values) ? CArray::fromPArray($values) : CArray::fromElements($values)); }
/** * Splits a string into substrings using a specified pattern or patterns as the delimiter(s) and returns the * resulting strings as an array. * * If no delimiter patterns were found, the resulting array contains just one element, which is the original * string. If a delimiter is located at the very start or at the very end of the string or next to another * delimiter, it will accordingly cause some string(s) in the resulting array to be empty. * * As a special case, the delimiter pattern can be empty, which will split the string into its constituting * characters. * * @param string $string The string to be split. * @param string|array|map $delimiterPatternOrPatterns The pattern or array of patterns to be recognized as the * delimiter(s). * * @return CArray The resulting strings. */ public static function split($string, $delimiterPatternOrPatterns) { assert('is_cstring($string) && (is_cstring($delimiterPatternOrPatterns) || ' . 'is_collection($delimiterPatternOrPatterns))', vs(isset($this), get_defined_vars())); if (is_cstring($delimiterPatternOrPatterns)) { $numIdt = self::findGroups($delimiterPatternOrPatterns, "/^([^0-9A-Za-z\\s\\\\])(.*)\\1/", $foundGroups); assert('$numIdt == 2', vs(isset($this), get_defined_vars())); $idt = $foundGroups[1]; if (CString::isEmpty($idt)) { // Special case. if (CString::isEmpty($string)) { $resStrings = CArray::fromElements(""); return $resStrings; } else { if (preg_match("/^([^0-9A-Za-z\\s\\\\])\\1[A-Za-z]*u[A-Za-z]*\\z/", $delimiterPatternOrPatterns) !== 1) { $resStrings = CArray::make(strlen($string)); for ($i = 0; $i < strlen($string); $i++) { $resStrings[$i] = $string[$i]; } return $resStrings; } else { return CUString::splitIntoChars($string); } } } $paResStrings = preg_split($delimiterPatternOrPatterns, $string); $qty = count($paResStrings); $resStrings = CArray::make($qty); for ($i = 0; $i < $qty; $i++) { $resStrings[$i] = $paResStrings[$i]; } return $resStrings; } else { $resStrings = CArray::fromElements($string); foreach ($delimiterPatternOrPatterns as $delimiterPattern) { assert('is_cstring($delimiterPattern)', vs(isset($this), get_defined_vars())); $resStringsNew = CArray::make(); $len = CArray::length($resStrings); for ($i = 0; $i < $len; $i++) { CArray::pushArray($resStringsNew, self::split($resStrings[$i], $delimiterPattern)); } $resStrings = $resStringsNew; } return $resStrings; } }
/** * Returns the known time zone regions. * * @return CArrayObject The known time zone regions of type `enum` (see [Summary](#summary)). */ public static function knownRegions() { return oop_a(CArray::fromElements(self::REGION_AFRICA, self::REGION_AMERICA, self::REGION_ANTARCTICA, self::REGION_ARCTIC, self::REGION_ASIA, self::REGION_ATLANTIC, self::REGION_AUSTRALIA, self::REGION_EUROPE, self::REGION_INDIAN, self::REGION_PACIFIC)); }
public function testValues() { $map = ["one" => "a", "two" => "b", "three" => "c"]; $values = CMap::values($map); $this->assertTrue(CArray::equals($values, CArray::fromElements("a", "b", "c"))); }
/** * Formats a point in time as a string in a specified time zone and according to the formatting rules used in the * default or some other locale, displaying the date and time parts to the extent of specified predefined styles, * and returns the formatted string. * * @param CTime $time The point in time to be formatted. * @param CTimeZone $timeZone The time zone in which the components in the resulting string are to appear. * @param enum $dateStyle The display style of the date part in the formatted string. Can be `STYLE_SHORT`, * `STYLE_MEDIUM`, `STYLE_LONG`, or `STYLE_FULL`. * @param enum $timeStyle The display style of the time part in the formatted string. Can be `STYLE_SHORT`, * `STYLE_MEDIUM`, `STYLE_LONG`, or `STYLE_FULL`. * @param CULocale $inLocale **OPTIONAL. Default is** *the application's default locale*. The locale in which the * point in time is to be formatted. * * @return CUStringObject A string with the formatted point in time. */ public static function timeWithStyles(CTime $time, CTimeZone $timeZone, $dateStyle, $timeStyle, CULocale $inLocale = null) { assert('is_enum($dateStyle) && is_enum($timeStyle)', vs(isset($this), get_defined_vars())); $styles = CArray::fromElements($dateStyle, $timeStyle); for ($i = 0; $i < 2; $i++) { switch ($styles[$i]) { case self::STYLE_SHORT: $styles[$i] = IntlDateFormatter::SHORT; break; case self::STYLE_MEDIUM: $styles[$i] = IntlDateFormatter::MEDIUM; break; case self::STYLE_LONG: $styles[$i] = IntlDateFormatter::LONG; break; case self::STYLE_FULL: $styles[$i] = IntlDateFormatter::FULL; break; default: assert('false', vs(isset($this), get_defined_vars())); break; } } $idfDateStyle = $styles[0]; $idfTimeStyle = $styles[1]; $locale = isset($inLocale) ? $inLocale->name() : CULocale::defaultLocaleName(); $intlDateFormatter = new IntlDateFormatter($locale, $idfDateStyle, $idfTimeStyle, $timeZone->ITimeZone()); $strTime = $intlDateFormatter->format($time->UTime()); if (is_cstring($strTime)) { return $strTime; } else { assert('false', vs(isset($this), get_defined_vars())); return ""; } }
public function testOrderDesc() { $this->assertTrue(CComparator::orderDesc(u("Hello there!"), u("Hello there!")) == 0); $this->assertTrue(CComparator::orderDesc(u("A"), u("B")) > 0); $this->assertTrue(CComparator::orderDesc(u("C"), u("B")) < 0); $this->assertTrue(CComparator::orderDesc(u("¡Hola señor!"), u("¡Hola señor!")) == 0); $this->assertTrue(CComparator::orderDesc(u("A"), u("B")) > 0); $this->assertTrue(CComparator::orderDesc(u("C"), u("B")) < 0); $this->assertTrue(CComparator::orderDesc(a("a", "b", "c"), a("a", "b", "c")) == 0); $this->assertTrue(CComparator::orderDesc(a("b", "b", "c"), a("a", "b", "c")) < 0); $this->assertTrue(CComparator::orderDesc(m(["one" => "a", "two" => "b", "three" => "c"]), m(["one" => "a", "two" => "b", "three" => "c"])) == 0); $this->assertTrue(CComparator::orderDesc(m(["one" => "b", "two" => "b", "three" => "c"]), m(["one" => "a", "two" => "b", "three" => "c"])) < 0); $this->assertTrue(CComparator::orderDesc(CTime::fromString("11/5/1955 12:00:00 PST"), CTime::fromString("11/5/1955 12:00:00 PST")) == 0); $this->assertTrue(CComparator::orderDesc(CTime::fromString("11/5/1955 12:00:00 PST"), CTime::fromString("11/5/1985 12:00:00 PST")) > 0); $this->assertTrue(CComparator::orderDesc(CTime::fromString("11/5/1985 12:00:01 PST"), CTime::fromString("11/5/1985 12:00:00 PST")) < 0); $this->assertTrue(CComparator::orderDesc(true, true) == 0); $this->assertTrue(CComparator::orderDesc(false, true) > 0); $this->assertTrue(CComparator::orderDesc(true, false) < 0); $this->assertTrue(CComparator::orderDesc(1234, 1234) == 0); $this->assertTrue(CComparator::orderDesc(1234, 5678) > 0); $this->assertTrue(CComparator::orderDesc(5678, 1234) < 0); $this->assertTrue(CComparator::orderDesc(12.34, 12.34) == 0); $this->assertTrue(CComparator::orderDesc(12.34, 56.78) > 0); $this->assertTrue(CComparator::orderDesc(56.78, 12.34) < 0); $this->assertTrue(CComparator::orderDesc(null, null) == 0); $this->assertTrue(CComparator::orderDesc("Hello there!", "Hello there!") == 0); $this->assertTrue(CComparator::orderDesc("A", "B") > 0); $this->assertTrue(CComparator::orderDesc("C", "B") < 0); $this->assertTrue(CComparator::orderDesc(CArray::fromElements("a", "b", "c"), CArray::fromElements("a", "b", "c")) == 0); $this->assertTrue(CComparator::orderDesc(CArray::fromElements("a", "b", "c"), CArray::fromElements("b", "b", "c")) > 0); $this->assertTrue(CComparator::orderDesc(CArray::fromElements("b", "b", "c"), CArray::fromElements("a", "b", "c")) < 0); $this->assertTrue(CComparator::orderDesc(["one" => "a", "two" => "b", "three" => "c"], ["one" => "a", "two" => "b", "three" => "c"]) == 0); $this->assertTrue(CComparator::orderDesc(["one" => "a", "two" => "b", "three" => "c"], ["one" => "b", "two" => "b", "three" => "c"]) > 0); $this->assertTrue(CComparator::orderDesc(["one" => "b", "two" => "b", "three" => "c"], ["one" => "a", "two" => "b", "three" => "c"]) < 0); }