1
0

FileAccessHelper.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OC\IntegrityCheck\Helpers;
  9. /**
  10. * Class FileAccessHelper provides a helper around file_get_contents and
  11. * file_put_contents
  12. *
  13. * @package OC\IntegrityCheck\Helpers
  14. */
  15. class FileAccessHelper {
  16. /**
  17. * Wrapper around file_get_contents($filename, $data)
  18. *
  19. * @param string $filename
  20. * @return string|false
  21. */
  22. public function file_get_contents(string $filename) {
  23. return file_get_contents($filename);
  24. }
  25. /**
  26. * Wrapper around file_exists($filename)
  27. *
  28. * @param string $filename
  29. * @return bool
  30. */
  31. public function file_exists(string $filename): bool {
  32. return file_exists($filename);
  33. }
  34. /**
  35. * Wrapper around file_put_contents($filename, $data)
  36. *
  37. * @param string $filename
  38. * @param string $data
  39. * @return int
  40. * @throws \Exception
  41. */
  42. public function file_put_contents(string $filename, string $data): int {
  43. $bytesWritten = @file_put_contents($filename, $data);
  44. if ($bytesWritten === false || $bytesWritten !== \strlen($data)) {
  45. throw new \Exception('Failed to write into ' . $filename);
  46. }
  47. return $bytesWritten;
  48. }
  49. /**
  50. * @param string $path
  51. * @return bool
  52. */
  53. public function is_writable(string $path): bool {
  54. return is_writable($path);
  55. }
  56. /**
  57. * @param string $path
  58. * @throws \Exception
  59. */
  60. public function assertDirectoryExists(string $path) {
  61. if (!is_dir($path)) {
  62. throw new \Exception('Directory ' . $path . ' does not exist.');
  63. }
  64. }
  65. }