BuildDirTrait.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /**
  3. * BuildDirTrait.php
  4. *
  5. * @created 07.01.2024
  6. * @author smiley <smiley@chillerlan.net>
  7. * @copyright 2024 smiley
  8. * @license MIT
  9. */
  10. namespace chillerlan\QRCodeTest;
  11. use RuntimeException;
  12. use function dirname, file_exists, file_get_contents, is_file, mkdir, realpath, sprintf, trim;
  13. /**
  14. * Trait BuildDirTrait
  15. */
  16. trait BuildDirTrait{
  17. private static string $buildDir = __DIR__.'/../.build/';
  18. /**
  19. * returns the full raw path to the build dir
  20. */
  21. protected function getBuildPath(string $subPath):string{
  22. return static::$buildDir.trim($subPath, '\\/');
  23. }
  24. /**
  25. * attempts to create the build dir
  26. *
  27. * @throws \RuntimeException
  28. */
  29. protected function createBuildDir(string $subPath):void{
  30. $dir = $this->getBuildPath($subPath);
  31. // attempt to write
  32. if(!file_exists($dir)){
  33. $created = mkdir($dir, 0777, true);
  34. if(!$created){
  35. throw new RuntimeException('could not create build dir');
  36. }
  37. }
  38. }
  39. /**
  40. * returns the full (real) path to the given build path
  41. *
  42. * @throws \RuntimeException
  43. */
  44. protected function getBuildDir(string $subPath = ''):string{
  45. $dir = realpath($this->getBuildPath($subPath));
  46. if(empty($dir)){
  47. throw new RuntimeException('invalid build dir');
  48. }
  49. return dirname($dir);
  50. }
  51. /**
  52. * returns the full (real) path to the given build file
  53. *
  54. * @throws \RuntimeException
  55. */
  56. protected function getBuildFilePath(string $fileSubPath):string{
  57. $file = realpath($this->getBuildPath($fileSubPath));
  58. if(empty($file)){
  59. throw new RuntimeException('invalid build dir/file');
  60. }
  61. if(!is_file($file)){
  62. throw new RuntimeException(sprintf('the given path "%s" found in "%s" is not a file', $fileSubPath, $file));
  63. }
  64. return $file;
  65. }
  66. /**
  67. * returns the contents of the given build file
  68. */
  69. protected function getBuildFileContent(string $fileSubPath):string{
  70. return file_get_contents($this->getBuildFilePath($fileSubPath));
  71. }
  72. }