FileAccessHelper.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Lukas Reschke <lukas@statuscode.ch>
  8. * @author Roeland Jago Douma <roeland@famdouma.nl>
  9. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  10. *
  11. * @license AGPL-3.0
  12. *
  13. * This code is free software: you can redistribute it and/or modify
  14. * it under the terms of the GNU Affero General Public License, version 3,
  15. * as published by the Free Software Foundation.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License, version 3,
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>
  24. *
  25. */
  26. namespace OC\IntegrityCheck\Helpers;
  27. /**
  28. * Class FileAccessHelper provides a helper around file_get_contents and
  29. * file_put_contents
  30. *
  31. * @package OC\IntegrityCheck\Helpers
  32. */
  33. class FileAccessHelper {
  34. /**
  35. * Wrapper around file_get_contents($filename, $data)
  36. *
  37. * @param string $filename
  38. * @return string|false
  39. */
  40. public function file_get_contents(string $filename) {
  41. return file_get_contents($filename);
  42. }
  43. /**
  44. * Wrapper around file_exists($filename)
  45. *
  46. * @param string $filename
  47. * @return bool
  48. */
  49. public function file_exists(string $filename): bool {
  50. return file_exists($filename);
  51. }
  52. /**
  53. * Wrapper around file_put_contents($filename, $data)
  54. *
  55. * @param string $filename
  56. * @param string $data
  57. * @return int
  58. * @throws \Exception
  59. */
  60. public function file_put_contents(string $filename, string $data): int {
  61. $bytesWritten = @file_put_contents($filename, $data);
  62. if ($bytesWritten === false || $bytesWritten !== \strlen($data)) {
  63. throw new \Exception('Failed to write into ' . $filename);
  64. }
  65. return $bytesWritten;
  66. }
  67. /**
  68. * @param string $path
  69. * @return bool
  70. */
  71. public function is_writable(string $path): bool {
  72. return is_writable($path);
  73. }
  74. /**
  75. * @param string $path
  76. * @throws \Exception
  77. */
  78. public function assertDirectoryExists(string $path) {
  79. if (!is_dir($path)) {
  80. throw new \Exception('Directory ' . $path . ' does not exist.');
  81. }
  82. }
  83. }