|
| 1 | +<?php |
| 2 | +namespace PhpBrew\Patch; |
| 3 | + |
| 4 | +use PhpBrew\Patch\Patch; |
| 5 | +use PhpBrew\Buildable; |
| 6 | +use CLIFramework\Logger; |
| 7 | + |
| 8 | +/** |
| 9 | + * Applies patches to a file using regexp. |
| 10 | + * You can customize replacement rules of a patch by passing |
| 11 | + * RegexpPatchRule objects to this class. |
| 12 | + */ |
| 13 | +class RegexpPatch implements Patch |
| 14 | +{ |
| 15 | + /** |
| 16 | + * @var Logger |
| 17 | + */ |
| 18 | + private $logger; |
| 19 | + |
| 20 | + /** |
| 21 | + * @var Buildable |
| 22 | + */ |
| 23 | + private $build; |
| 24 | + |
| 25 | + /** |
| 26 | + * @var array |
| 27 | + */ |
| 28 | + private $paths; |
| 29 | + |
| 30 | + /** |
| 31 | + * @var array |
| 32 | + */ |
| 33 | + private $rules; |
| 34 | + |
| 35 | + /** |
| 36 | + * @var string |
| 37 | + */ |
| 38 | + private $backupFileSuffix; |
| 39 | + |
| 40 | + public function __construct(Logger $logger, Buildable $build, array $paths, array $rules) |
| 41 | + { |
| 42 | + $this->logger = $logger; |
| 43 | + $this->build = $build; |
| 44 | + $this->paths = $paths; |
| 45 | + $this->rules = $rules; |
| 46 | + } |
| 47 | + |
| 48 | + public function enableBackup() |
| 49 | + { |
| 50 | + $this->backupFileSuffix = '.bak'; |
| 51 | + } |
| 52 | + |
| 53 | + public function apply() |
| 54 | + { |
| 55 | + foreach ($this->paths as $relativePath) { |
| 56 | + $absolutePath = $this->build->getSourceDirectory() . DIRECTORY_SEPARATOR . $relativePath; |
| 57 | + $contents = $this->read($absolutePath); |
| 58 | + $this->backup($absolutePath, $contents); |
| 59 | + $newContents = $this->applyRules($contents); |
| 60 | + $this->write($absolutePath, $newContents); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + private function read($path) |
| 65 | + { |
| 66 | + $contents = file_get_contents($path); |
| 67 | + |
| 68 | + if ($contents === false) { |
| 69 | + throw new \RuntimeException('Failed to read '. $path); |
| 70 | + } |
| 71 | + |
| 72 | + return $contents; |
| 73 | + } |
| 74 | + |
| 75 | + protected function backup($path, $contents) |
| 76 | + { |
| 77 | + if ($this->backupFileSuffix && file_put_contents($path . $this->backupFileSuffix, $contents) === false) { |
| 78 | + throw new \RuntimeException('Failed to write ' . $path); |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + private function applyRules($contents) |
| 83 | + { |
| 84 | + foreach ($this->rules as $rule) { |
| 85 | + $contents = $rule->apply($contents); |
| 86 | + } |
| 87 | + return $contents; |
| 88 | + } |
| 89 | + |
| 90 | + private function write($path, $contents) |
| 91 | + { |
| 92 | + if (file_put_contents($path, $contents) === false) { |
| 93 | + throw new \RuntimeException('Failed to write ' . $path); |
| 94 | + } |
| 95 | + } |
| 96 | +} |
| 97 | + |
0 commit comments