OsPath.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. class Application_Common_OsPath{
  3. // this function is from http://stackoverflow.com/questions/2670299/is-there-a-php-equivalent-function-to-the-python-os-path-normpath
  4. public static function normpath($path)
  5. {
  6. if (empty($path))
  7. return '.';
  8. if (strpos($path, '/') === 0)
  9. $initial_slashes = true;
  10. else
  11. $initial_slashes = false;
  12. if (
  13. ($initial_slashes) &&
  14. (strpos($path, '//') === 0) &&
  15. (strpos($path, '///') === false)
  16. )
  17. $initial_slashes = 2;
  18. $initial_slashes = (int) $initial_slashes;
  19. $comps = explode('/', $path);
  20. $new_comps = array();
  21. foreach ($comps as $comp)
  22. {
  23. if (in_array($comp, array('', '.')))
  24. continue;
  25. if (
  26. ($comp != '..') ||
  27. (!$initial_slashes && !$new_comps) ||
  28. ($new_comps && (end($new_comps) == '..'))
  29. )
  30. array_push($new_comps, $comp);
  31. elseif ($new_comps)
  32. array_pop($new_comps);
  33. }
  34. $comps = $new_comps;
  35. $path = implode('/', $comps);
  36. if ($initial_slashes)
  37. $path = str_repeat('/', $initial_slashes) . $path;
  38. if ($path)
  39. return $path;
  40. else
  41. return '.';
  42. }
  43. /* Similar to the os.path.join python method
  44. * http://stackoverflow.com/a/1782990/276949 */
  45. public static function join() {
  46. $args = func_get_args();
  47. $paths = array();
  48. foreach($args as $arg) {
  49. $paths = array_merge($paths, (array)$arg);
  50. }
  51. foreach($paths as &$path) {
  52. $path = trim($path, DIRECTORY_SEPARATOR);
  53. }
  54. if (substr($args[0], 0, 1) == DIRECTORY_SEPARATOR) {
  55. $paths[0] = DIRECTORY_SEPARATOR . $paths[0];
  56. }
  57. return join(DIRECTORY_SEPARATOR, $paths);
  58. }
  59. public static function getBaseDir() {
  60. $CC_CONFIG = Config::getConfig();
  61. $baseUrl = $CC_CONFIG['baseDir'];
  62. if ($baseUrl[0] != "/") {
  63. $baseUrl = "/".$baseUrl;
  64. }
  65. if ($baseUrl[strlen($baseUrl) -1] != "/") {
  66. $baseUrl = $baseUrl."/";
  67. }
  68. return $baseUrl;
  69. }
  70. public static function formatDirectoryWithDirectorySeparators($dir)
  71. {
  72. if ($dir[0] != "/") {
  73. $dir = "/".$dir;
  74. }
  75. if ($dir[strlen($dir) -1] != "/") {
  76. $dir = $dir."/";
  77. }
  78. return $dir;
  79. }
  80. }