BuildDirTrait.php 2.1 KB

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