Ejemplo n.º 1
0
 /**
  * Normalizes a path by removing any trailing slashes, any redundant slashes, any references to the current
  * directory, and any references to the parent directory where possible, and returns the new path.
  *
  * For example, "/path//./dir-a/.././to//../dir-b/" is normalized to "/path/dir-b".
  *
  * @param  string $path The path to be normalized (can be absolute or relative).
  * @param  bool $targetIsExecutable **OPTIONAL. Default is** `false`. Tells whether the path's target should be
  * treated as an executable so that, if the path starts with ".", the resulting path will start with "." too and
  * the "." will not be removed as a reference to the current directory.
  *
  * @return CUStringObject The normalized path.
  */
 public static function normalize($path, $targetIsExecutable = false)
 {
     assert('is_cstring($path) && is_bool($targetIsExecutable)', vs(isset($this), get_defined_vars()));
     assert('!CString::isEmpty($path)', vs(isset($this), get_defined_vars()));
     $path = CRegex::replace($path, "/\\/{2,}/", "/");
     // normalize consecutive slashes
     $path = CString::stripEnd($path, "/");
     // remove the trailing slash, if any
     if (CString::isEmpty($path)) {
         return "/";
     }
     $path = CRegex::remove($path, "/\\/\\.(?=\\/|\\z)/");
     // remove any "/." followed by a slash or at the end
     if (CString::isEmpty($path)) {
         return "/";
     }
     if (!$targetIsExecutable) {
         $path = CString::stripStart($path, "./");
     }
     $pathIsAbsolute;
     if (!CString::startsWith($path, "/")) {
         $pathIsAbsolute = false;
     } else {
         $pathIsAbsolute = true;
         $path = CString::substr($path, 1);
     }
     if (!CString::find($path, "/")) {
         if ($pathIsAbsolute) {
             if (!CString::equals($path, "..")) {
                 $path = "/{$path}";
             } else {
                 $path = "/";
             }
         }
         return $path;
     }
     // Recompose the path.
     $components = CString::split($path, "/");
     $newComponents = CArray::make();
     $len = CArray::length($components);
     for ($i = 0; $i < $len; $i++) {
         $comp = $components[$i];
         $lastAddedComp = "";
         $noCompsAddedYet = CArray::isEmpty($newComponents);
         if (!$noCompsAddedYet) {
             $lastAddedComp = CArray::last($newComponents);
         }
         if (CString::equals($comp, "..")) {
             if ($noCompsAddedYet || CString::equals($lastAddedComp, "..") || CString::equals($lastAddedComp, ".")) {
                 if (!($noCompsAddedYet && $pathIsAbsolute)) {
                     CArray::push($newComponents, $comp);
                 }
             } else {
                 CArray::pop($newComponents);
             }
         } else {
             CArray::push($newComponents, $comp);
         }
     }
     $path = CArray::join($newComponents, "/");
     if ($pathIsAbsolute) {
         $path = "/{$path}";
     } else {
         if (CString::isEmpty($path)) {
             $path = ".";
         }
     }
     return $path;
 }
Ejemplo n.º 2
0
 /**
  * Adds a keyword-value pair to a locale.
  *
  * @param  string $keyword The keyword.
  * @param  string $value The value.
  *
  * @return void
  */
 public function addKeyword($keyword, $value)
 {
     assert('is_cstring($keyword) && is_cstring($value)', vs(isset($this), get_defined_vars()));
     assert('CRegex::find($keyword, "/^\\\\w+\\\\z/")', vs(isset($this), get_defined_vars()));
     assert('CRegex::find($value, "/^\\\\w+\\\\z/")', vs(isset($this), get_defined_vars()));
     $this->m_name .= (!CString::find($this->m_name, "@") ? "@" : ";") . CString::toLowerCase($keyword) . "=" . $value;
 }
Ejemplo n.º 3
0
 /**
  * @ignore
  */
 public static function onError($exit = true, $message)
 {
     if ($exit) {
         if (!CString::isEmpty($message)) {
             $message .= !CString::find($message, "\n") ? " " : "\n";
         }
         $message .= "Exiting.";
     }
     if (!CString::isEmpty($message)) {
         self::say($message);
     }
     if (isset(self::$ms_mail)) {
         self::sendMail($message);
     }
     if ($exit) {
         self::exitScript(false);
     }
 }
Ejemplo n.º 4
0
 /**
  * @ignore
  */
 public static function onThirdPartyUpdateByPackageManager()
 {
     if (!self::isInCliMode()) {
         // This method can be run in CLI mode only.
         assert('false', vs(isset($this), get_defined_vars()));
     }
     $timeoutPause = new CTimeoutPause();
     CShell::speak("Processing third-party components ...");
     $tpDps = CFile::listDirectories(CFilePath::absolute($GLOBALS["PHRED_PATH_TO_THIRD_PARTY"]));
     $ignorePackages = CConfiguration::option("upd.thirdPartyOopWrappingIgnorePackages");
     $ignorePackagesL2 = CArray::filter($ignorePackages, function ($package) {
         return CString::find($package, "/");
     });
     $newTpDps = CArray::make();
     $len = CArray::length($tpDps);
     for ($i = 0; $i < $len; $i++) {
         $tpDp = $tpDps[$i];
         $dirName = CFilePath::name($tpDp);
         if (!CArray::find($ignorePackages, $dirName)) {
             $dpHasL2DirsToIgnore = CArray::find($ignorePackagesL2, $dirName, function ($packageL2, $dirName) {
                 return CString::equals(CFilePath::directory($packageL2), $dirName);
             });
             if (!$dpHasL2DirsToIgnore) {
                 CArray::push($newTpDps, $tpDp);
             } else {
                 $tpSubDps = CFile::listDirectories($tpDp);
                 $tpSubDps = CArray::filter($tpSubDps, function ($subDp) use($ignorePackagesL2) {
                     return !CArray::find($ignorePackagesL2, $subDp, function ($packageL2, $subDp) {
                         return CString::endsWith($subDp, $packageL2);
                     });
                 });
                 CArray::pushArray($newTpDps, $tpSubDps);
             }
         }
     }
     $tpDps = $newTpDps;
     $wrapProtectedMethods = CConfiguration::option("upd.thirdPartyOopWrappingInProtectedMethods");
     $wrapPrivateMethods = CConfiguration::option("upd.thirdPartyOopWrappingInPrivateMethods");
     static $s_stdPhpTag = "<?php";
     static $s_progressResolution = 0.05;
     $prevProgressDivR = 0;
     $tpDpsLen = CArray::length($tpDps);
     for ($i0 = 0; $i0 < $tpDpsLen; $i0++) {
         $tpFps = CFile::reFindFilesRecursive($tpDps[$i0], "/\\.php\\d?\\z/");
         $tpFpsLen = CArray::length($tpFps);
         for ($i1 = 0; $i1 < $tpFpsLen; $i1++) {
             $fileCode = CFile::read($tpFps[$i1]);
             if (!CString::find($fileCode, self::$ms_thirdPartyAlreadyOopWrappedMark)) {
                 $parser = new PhpParser\Parser(new PhpParser\Lexer());
                 try {
                     // Parse the code.
                     $statements = $parser->parse($fileCode);
                     // Wrap the code into OOP.
                     $traverser = new PhpParser\NodeTraverser();
                     $mainVisitor = new CMainVisitor($wrapProtectedMethods, $wrapPrivateMethods);
                     $traverser->addVisitor($mainVisitor);
                     $statements = $traverser->traverse($statements);
                     $wrappedCode = (new PhpParser\PrettyPrinter\Standard())->prettyPrint($statements);
                     $phpTagPos = CString::indexOf($wrappedCode, $s_stdPhpTag);
                     if ($phpTagPos == -1) {
                         $wrappedCode = "{$s_stdPhpTag}\n\n{$wrappedCode}";
                         $phpTagPos = 0;
                     }
                     $wrappedCode = CString::insert($wrappedCode, $phpTagPos + CString::length($s_stdPhpTag), "\n\n" . self::$ms_thirdPartyAlreadyOopWrappedMark);
                     // Save.
                     CFile::write($tpFps[$i1], $wrappedCode);
                 } catch (PhpParser\Error $parserError) {
                     CShell::say("\nPhpParser: " . $tpFps[$i1] . ", at line " . $parserError->getRawLine() . ": " . $parserError->getRawMessage());
                 }
             }
             $progress = (double) ($i0 / $tpDpsLen + 1 / $tpDpsLen * $i1 / $tpFpsLen);
             $progressDivR = CMathi::floor($progress / $s_progressResolution);
             if ($progressDivR != $prevProgressDivR) {
                 $perc = CMathi::round($progressDivR * $s_progressResolution * 100);
                 CShell::speak("{$perc}%");
             }
             $prevProgressDivR = $progressDivR;
         }
     }
     CShell::speak("100%");
     CShell::say("Done.");
     $timeoutPause->end();
 }
Ejemplo n.º 5
0
 /**
  * Composes a URL query into a query string ready to be used as a part of a URL and returns it.
  *
  * Any characters that cannot be represented literally in a valid query string come out percent-encoded. The
  * resulting query string never starts with "?".
  *
  * Because the characters in field named and field values are stored in their literal representations, the
  * resulting query string is always normalized, with only those characters appearing percent-encoded that really
  * require it for the query string to be valid and with the hexadecimal letters in percent-encoded characters
  * appearing uppercased. Also, no duplicate fields are produced in the resulting query string (even if the object
  * was constructed from a query string with duplicate fields in it) and "=" is added after any field name that goes
  * without a value and is not followed by "=".
  *
  * @param  bool $sortFields **OPTIONAL. Default is** `false`. Tells whether the fields in the query string should
  * appear sorted in the ascending order, case-insensitively, and with natural order comparison used for sorting.
  *
  * @return CUStringObject The query string.
  */
 public function queryString($sortFields = false)
 {
     assert('is_bool($sortFields)', vs(isset($this), get_defined_vars()));
     if (!CMap::isEmpty($this->m_query)) {
         $useQuery = CMap::makeCopy($this->m_query);
         // Recursively convert any CArray into a CMap for `http_build_query` function to accept the query.
         $useQuery = self::recurseQueryValueBeforeComposingQs($useQuery, 0);
         // Compose a preliminary query string.
         $queryString = http_build_query($useQuery, "", self::$ms_fieldDelimiters[0], PHP_QUERY_RFC1738);
         if (!is_cstring($queryString)) {
             return "";
         }
         // Break the string into fields.
         $fields = CString::split($queryString, self::$ms_fieldDelimiters[0]);
         // Adjust the result of `http_build_query` function.
         $len = CArray::length($fields);
         for ($i = 0; $i < $len; $i++) {
             if (CString::find($fields[$i], "=")) {
                 // Revert excessive percent-encoding of the square brackets next to the identifiers of
                 // multidimensional data.
                 $fields[$i] = CRegex::replaceWithCallback($fields[$i], "/(?:%5B(?:[^%]++|%(?!5B|5D))*+%5D)+?=/i", function ($matches) {
                     $value = $matches[0];
                     $value = CString::replace($value, "%5B", "[");
                     $value = CString::replace($value, "%5D", "]");
                     return $value;
                 });
                 // Remove redundant indexing next to the identifiers of simple arrays.
                 $fields[$i] = CRegex::replaceWithCallback($fields[$i], "/^.+?=/", function ($matches) {
                     return CRegex::replace($matches[0], "/\\[\\d+\\]/", "[]");
                 });
             }
         }
         if ($sortFields) {
             // Normalize the order of fields.
             CArray::sortStringsNatCi($fields);
         }
         $queryString = CArray::join($fields, self::$ms_fieldDelimiters[0]);
         return $queryString;
     } else {
         return "";
     }
 }