PathValidator.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace ThurData\Servers\KerioEmail\Core\FileReader;
  3. /**
  4. * Wrapper for files and directories validation methods
  5. *
  6. * @author Sławomir Miśkowicz <slawomir@thurdata.com>
  7. */
  8. class PathValidator
  9. {
  10. /**
  11. * @param string $path -a a path to be validated, can be a file path or a dir path
  12. * @param bool $isReadable - states if path should be readable
  13. * @param bool $isWritable - states if path should be writable
  14. * @param bool $create - states if should try to create a directory if not exists
  15. * @return bool
  16. */
  17. public function validatePath($path = "", $isReadable = true, $isWritable = false, $create = true)
  18. {
  19. //try to create a dir if does not exist
  20. if ($create)
  21. {
  22. $this->createDirIfNotExists($path);
  23. }
  24. //if path does not exists
  25. if (!$this->pathExists($path))
  26. {
  27. return false;
  28. }
  29. //if should be readable and it is not
  30. if ($isReadable && !$this->isPathReadable($path))
  31. {
  32. return false;
  33. }
  34. //if should be writable and it is not
  35. if ($isWritable && !$this->isPathWritable($path))
  36. {
  37. return false;
  38. }
  39. return true;
  40. }
  41. /**
  42. * @param string $path - if provided path does not exist, a dir will be created
  43. */
  44. public function createDirIfNotExists($path)
  45. {
  46. if (!$this->pathExists($path))
  47. {
  48. mkdir($path);
  49. }
  50. }
  51. /**
  52. * @param string $path -a a path to be validated, can be a file path or a dir path
  53. * @return bool
  54. */
  55. public function pathExists($path)
  56. {
  57. return file_exists($path);
  58. }
  59. /**
  60. * @param $path -a a path to be validated, can be a file path or a dir path
  61. * @return bool
  62. */
  63. public function isPathReadable($path)
  64. {
  65. return is_readable($path);
  66. }
  67. /**
  68. * @param $path -a a path to be validated, can be a file path or a dir path
  69. * @return bool
  70. */
  71. public function isPathWritable($path)
  72. {
  73. return is_writable($path);
  74. }
  75. }