PageRenderTime 26ms CodeModel.GetById 7ms RepoModel.GetById 0ms app.codeStats 0ms

/build/Burgomaster.php

https://gitlab.com/github-cloud-corp/aws-sdk-php
PHP | 394 lines | 252 code | 40 blank | 102 comment | 29 complexity | 7f96dfb3275fdf869754fec0fb6ad24e MD5 | raw file
  1. <?php
  2. /**
  3. * Packages the zip and phar file using a staging directory.
  4. *
  5. * @license MIT, Michael Dowling https://github.com/mtdowling
  6. * @license https://github.com/mtdowling/Burgomaster/LICENSE
  7. */
  8. class Burgomaster
  9. {
  10. /** @var string Base staging directory of the project */
  11. public $stageDir;
  12. /** @var string Root directory of the project */
  13. public $projectRoot;
  14. /** @var array stack of sections */
  15. private $sections = array();
  16. /**
  17. * @param string $stageDir Staging base directory where your packaging
  18. * takes place. This folder will be created for
  19. * you if it does not exist. If it exists, it
  20. * will be deleted and recreated to start fresh.
  21. * @param string $projectRoot Root directory of the project.
  22. *
  23. * @throws \InvalidArgumentException
  24. * @throws \RuntimeException
  25. */
  26. public function __construct($stageDir, $projectRoot = null)
  27. {
  28. $this->startSection('setting_up');
  29. $this->stageDir = $stageDir;
  30. $this->projectRoot = $projectRoot;
  31. if (!$this->stageDir || $this->stageDir == '/') {
  32. throw new \InvalidArgumentException('Invalid base directory');
  33. }
  34. if (is_dir($this->stageDir)) {
  35. $this->debug("Removing existing directory: $this->stageDir");
  36. echo $this->exec("rm -rf $this->stageDir");
  37. }
  38. $this->debug("Creating staging directory: $this->stageDir");
  39. if (!mkdir($this->stageDir, 0777, true)) {
  40. throw new \RuntimeException("Could not create {$this->stageDir}");
  41. }
  42. $this->stageDir = realpath($this->stageDir);
  43. $this->debug("Creating staging directory at: {$this->stageDir}");
  44. if (!is_dir($this->projectRoot)) {
  45. throw new \InvalidArgumentException(
  46. "Project root not found: $this->projectRoot"
  47. );
  48. }
  49. $this->endSection();
  50. $this->startSection('staging');
  51. chdir($this->projectRoot);
  52. }
  53. /**
  54. * Cleanup if the last section was not already closed.
  55. */
  56. public function __destruct()
  57. {
  58. if ($this->sections) {
  59. $this->endSection();
  60. }
  61. }
  62. /**
  63. * Call this method when starting a specific section of the packager.
  64. *
  65. * This makes the debug messages used in your script more meaningful and
  66. * adds context when things go wrong. Be sure to call endSection() when
  67. * you have finished a section of your packaging script.
  68. *
  69. * @param string $section Part of the packager that is running
  70. */
  71. public function startSection($section)
  72. {
  73. $this->sections[] = $section;
  74. $this->debug('Starting');
  75. }
  76. /**
  77. * Call this method when leaving the last pushed section of the packager.
  78. */
  79. public function endSection()
  80. {
  81. if ($this->sections) {
  82. $this->debug('Completed');
  83. array_pop($this->sections);
  84. }
  85. }
  86. /**
  87. * Prints a debug message to STDERR bound to the current section.
  88. *
  89. * @param string $message Message to echo to STDERR
  90. */
  91. public function debug($message)
  92. {
  93. $prefix = date('c') . ': ';
  94. if ($this->sections) {
  95. $prefix .= '[' . end($this->sections) . '] ';
  96. }
  97. fwrite(STDERR, $prefix . $message . "\n");
  98. }
  99. /**
  100. * Copies a file and creates the destination directory if needed.
  101. *
  102. * @param string $from File to copy
  103. * @param string $to Destination to copy the file to, relative to the
  104. * base staging directory.
  105. * @throws \InvalidArgumentException if the file cannot be found
  106. * @throws \RuntimeException if the directory cannot be created.
  107. * @throws \RuntimeException if the file cannot be copied.
  108. */
  109. public function deepCopy($from, $to)
  110. {
  111. if (!is_file($from)) {
  112. throw new \InvalidArgumentException("File not found: {$from}");
  113. }
  114. $to = str_replace('//', '/', $this->stageDir . '/' . $to);
  115. $dir = dirname($to);
  116. if (!is_dir($dir)) {
  117. if (!mkdir($dir, 0777, true)) {
  118. throw new \RuntimeException("Unable to create directory: $dir");
  119. }
  120. }
  121. if (!copy($from, $to)) {
  122. throw new \RuntimeException("Unable to copy $from to $to");
  123. }
  124. }
  125. /**
  126. * Recursively copy one folder to another.
  127. *
  128. * Any LICENSE file is automatically copied.
  129. *
  130. * @param string $sourceDir Source directory to copy from
  131. * @param string $destDir Directory to copy the files to that is relative
  132. * to the the stage base directory.
  133. * @param array $extensions File extensions to copy from the $sourceDir.
  134. * Defaults to "php" files only (e.g., ['php']).
  135. * @param Iterator|null $files Files to copy from the source directory, each
  136. * yielded out as an SplFileInfo object.
  137. * Defaults to a recursive iterator of $sourceDir
  138. * @throws \InvalidArgumentException if the source directory is invalid.
  139. */
  140. function recursiveCopy(
  141. $sourceDir,
  142. $destDir,
  143. $extensions = array('php'),
  144. Iterator $files = null
  145. ) {
  146. if (!realpath($sourceDir)) {
  147. throw new \InvalidArgumentException("$sourceDir not found");
  148. }
  149. if (!$extensions) {
  150. throw new \InvalidArgumentException('$extensions is empty!');
  151. }
  152. $sourceDir = realpath($sourceDir);
  153. $exts = array_fill_keys($extensions, true);
  154. if (empty($files)) {
  155. $files = new \RecursiveIteratorIterator(
  156. new \RecursiveDirectoryIterator($sourceDir)
  157. );
  158. }
  159. $total = 0;
  160. $this->startSection('copy');
  161. $this->debug("Starting to copy files from $sourceDir");
  162. foreach ($files as $file) {
  163. if (isset($exts[$file->getExtension()])
  164. || $file->getBaseName() == 'LICENSE'
  165. ) {
  166. // Remove the source directory from the destination path
  167. $toPath = str_replace($sourceDir, '', (string) $file);
  168. $toPath = $destDir . '/' . $toPath;
  169. $toPath = str_replace('//', '/', $toPath);
  170. $this->deepCopy((string) $file, $toPath);
  171. $total++;
  172. }
  173. }
  174. $this->debug("Copied $total files from $sourceDir");
  175. $this->endSection();
  176. }
  177. /**
  178. * Execute a command and throw an exception if the return code is not 0.
  179. *
  180. * @param string $command Command to execute
  181. *
  182. * @return string Returns the output of the command as a string
  183. * @throws \RuntimeException on error.
  184. */
  185. public function exec($command)
  186. {
  187. $this->debug("Executing: $command");
  188. $output = $returnValue = null;
  189. exec($command, $output, $returnValue);
  190. if ($returnValue != 0) {
  191. throw new \RuntimeException('Error executing command: '
  192. . $command . ' : ' . implode("\n", $output));
  193. }
  194. return implode("\n", $output);
  195. }
  196. /**
  197. * Creates a class-map autoloader to the staging directory in a file
  198. * named autoloader.php
  199. *
  200. * @param array $files Files to explicitly require in the autoloader. This
  201. * is similar to Composer's "files" "autoload" section.
  202. * @param string $filename Name of the autoloader file.
  203. * @throws \RuntimeException if the file cannot be written
  204. */
  205. function createAutoloader($files = array(), $filename = 'autoloader.php') {
  206. $sourceDir = realpath($this->stageDir);
  207. $iter = new \RecursiveDirectoryIterator($sourceDir);
  208. $iter = new \RecursiveIteratorIterator($iter);
  209. $this->startSection('autoloader');
  210. $this->debug('Creating classmap autoloader');
  211. $this->debug("Collecting valid PHP files from {$this->stageDir}");
  212. $classMap = array();
  213. foreach ($iter as $file) {
  214. if ($file->getExtension() == 'php') {
  215. $location = str_replace($this->stageDir . '/', '', (string) $file);
  216. $className = str_replace('/', '\\', $location);
  217. $className = substr($className, 0, -4);
  218. // Remove "src\" or "lib\"
  219. if (strpos($className, 'src\\') === 0
  220. || strpos($className, 'lib\\') === 0
  221. ) {
  222. $className = substr($className, 4);
  223. }
  224. $classMap[$className] = "__DIR__ . '/$location'";
  225. $this->debug("Found $className");
  226. }
  227. }
  228. $destFile = $this->stageDir . '/' . $filename;
  229. $this->debug("Writing autoloader to {$destFile}");
  230. if (!($h = fopen($destFile, 'w'))) {
  231. throw new \RuntimeException('Unable to open file for writing');
  232. }
  233. $this->debug('Writing classmap files');
  234. fwrite($h, "<?php\n\n");
  235. fwrite($h, "\$mapping = array(\n");
  236. foreach ($classMap as $c => $f) {
  237. fwrite($h, " '$c' => $f,\n");
  238. }
  239. fwrite($h, ");\n\n");
  240. fwrite($h, <<<EOT
  241. spl_autoload_register(function (\$class) use (\$mapping) {
  242. if (isset(\$mapping[\$class])) {
  243. require \$mapping[\$class];
  244. }
  245. }, true);
  246. EOT
  247. );
  248. fwrite($h, "\n");
  249. $this->debug('Writing automatically included files');
  250. foreach ($files as $file) {
  251. fwrite($h, "require __DIR__ . '/$file';\n");
  252. }
  253. fclose($h);
  254. $this->endSection();
  255. }
  256. /**
  257. * Creates a default stub for the phar that includeds the generated
  258. * autoloader.
  259. *
  260. * This phar also registers a constant that can be used to check if you
  261. * are running the phar. The constant is the basename of the $dest variable
  262. * without the extension, with "_PHAR" appended, then converted to all
  263. * caps (e.g., "/foo/guzzle.phar" gets a contant defined as GUZZLE_PHAR.
  264. *
  265. * @param $dest
  266. * @param string $autoloaderFilename Name of the autoloader file.
  267. * @param string $alias The phar alias to use
  268. *
  269. * @return string
  270. */
  271. private function createStub($dest, $autoloaderFilename = 'autoloader.php', $alias = null)
  272. {
  273. $this->startSection('stub');
  274. $this->debug("Creating phar stub at $dest");
  275. $alias = $alias ?: basename($dest);
  276. $constName = str_replace('.phar', '', strtoupper($alias)) . '_PHAR';
  277. $stub = "<?php\n";
  278. $stub .= "define('$constName', true);\n";
  279. $stub .= "Phar::mapPhar('$alias');\n";
  280. $stub .= "require 'phar://$alias/{$autoloaderFilename}';\n";
  281. $stub .= "__HALT_COMPILER();\n";
  282. $this->endSection();
  283. return $stub;
  284. }
  285. /**
  286. * Creates a phar that automatically registers an autoloader.
  287. *
  288. * Call this only after your staging directory is built.
  289. *
  290. * @param string $dest Where to save the file. The basename of the file
  291. * is also used as the alias name in the phar
  292. * (e.g., /path/to/guzzle.phar => guzzle.phar).
  293. * @param string|bool|null $stub The path to the phar stub file. Pass or
  294. * leave null to automatically have one created for you. Pass false
  295. * to no use a stub in the generated phar.
  296. * @param string $autoloaderFilename Name of the autoloader filename.
  297. */
  298. public function createPhar(
  299. $dest,
  300. $stub = null,
  301. $autoloaderFilename = 'autoloader.php',
  302. $alias = null
  303. ) {
  304. $this->startSection('phar');
  305. $this->debug("Creating phar file at $dest");
  306. $this->createDirIfNeeded(dirname($dest));
  307. $phar = new \Phar($dest, 0, $alias ?: basename($dest));
  308. $phar->buildFromDirectory($this->stageDir);
  309. if ($stub !== false) {
  310. if (!$stub) {
  311. $stub = $this->createStub($dest, $autoloaderFilename, $alias);
  312. }
  313. $phar->setStub($stub);
  314. }
  315. $this->debug("Created phar at $dest");
  316. $this->endSection();
  317. }
  318. /**
  319. * Creates a zip file containing the staged files of your project.
  320. *
  321. * Call this only after your staging directory is built.
  322. *
  323. * @param string $dest Where to save the zip file
  324. */
  325. public function createZip($dest)
  326. {
  327. $this->startSection('zip');
  328. $this->debug("Creating a zip file at $dest");
  329. $this->createDirIfNeeded(dirname($dest));
  330. chdir($this->stageDir);
  331. $this->exec("zip -r $dest ./");
  332. $this->debug(" > Created at $dest");
  333. chdir(__DIR__);
  334. $this->endSection();
  335. }
  336. private function createDirIfNeeded($dir)
  337. {
  338. if (!is_dir($dir) && !mkdir($dir, 0755, true)) {
  339. throw new \RuntimeException("Could not create dir: $dir");
  340. }
  341. }
  342. }