BuildDirTrait.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 const _buildDir = __DIR__.'/../.build/';
  18. /**
  19. * returns the full raw path to the build dir
  20. */
  21. protected function getBuildPath(string $subPath):string{
  22. return self::_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. * @throws \RuntimeException
  70. */
  71. protected function getBuildFileContent(string $fileSubPath):string{
  72. $content = file_get_contents($this->getBuildFilePath($fileSubPath));
  73. if($content === false){
  74. throw new RuntimeException('file_get_contents() error while reading build file');
  75. }
  76. return $content;
  77. }
  78. }