BuildDirTrait.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. declare(strict_types=1);
  11. namespace chillerlan\QRCodeTest;
  12. use RuntimeException;
  13. use function dirname, file_exists, file_get_contents, is_file, mkdir, realpath, sprintf, trim;
  14. /**
  15. * Trait BuildDirTrait
  16. */
  17. trait BuildDirTrait{
  18. private const _buildDir = __DIR__.'/../.build/';
  19. /**
  20. * returns the full raw path to the build dir
  21. */
  22. protected function getBuildPath(string $subPath):string{
  23. return self::_buildDir.trim($subPath, '\\/');
  24. }
  25. /**
  26. * attempts to create the build dir
  27. *
  28. * @throws \RuntimeException
  29. */
  30. protected function createBuildDir(string $subPath):void{
  31. $dir = $this->getBuildPath($subPath);
  32. // attempt to write
  33. if(!file_exists($dir)){
  34. $created = mkdir($dir, 0777, true);
  35. if(!$created){
  36. throw new RuntimeException('could not create build dir');
  37. }
  38. }
  39. }
  40. /**
  41. * returns the full (real) path to the given build path
  42. *
  43. * @throws \RuntimeException
  44. */
  45. protected function getBuildDir(string $subPath = ''):string{
  46. $dir = realpath($this->getBuildPath($subPath));
  47. if(empty($dir)){
  48. throw new RuntimeException('invalid build dir');
  49. }
  50. return dirname($dir);
  51. }
  52. /**
  53. * returns the full (real) path to the given build file
  54. *
  55. * @throws \RuntimeException
  56. */
  57. protected function getBuildFilePath(string $fileSubPath):string{
  58. $file = realpath($this->getBuildPath($fileSubPath));
  59. if(empty($file)){
  60. throw new RuntimeException('invalid build dir/file');
  61. }
  62. if(!is_file($file)){
  63. throw new RuntimeException(sprintf('the given path "%s" found in "%s" is not a file', $fileSubPath, $file));
  64. }
  65. return $file;
  66. }
  67. /**
  68. * returns the contents of the given build file
  69. *
  70. * @throws \RuntimeException
  71. */
  72. protected function getBuildFileContent(string $fileSubPath):string{
  73. $content = file_get_contents($this->getBuildFilePath($fileSubPath));
  74. if($content === false){
  75. throw new RuntimeException('file_get_contents() error while reading build file');
  76. }
  77. return $content;
  78. }
  79. }