/**
* Apply the patches
*
* @return integer The number of files patched
*
* @since 3.0.0
* @throws \RuntimeException
*/
public function apply()
{
foreach ($this->patches as $patch) {
// Separate the input into lines
$lines = self::splitLines($patch['udiff']);
// Loop for each header
while (self::findHeader($lines, $src, $dst)) {
$done = false;
$regex = '#^([^/]*/)*#';
if ($patch['strip'] !== null) {
$regex = '#^([^/]*/){' . (int) $patch['strip'] . '}#';
}
$src = $patch['root'] . preg_replace($regex, '', $src);
$dst = $patch['root'] . preg_replace($regex, '', $dst);
// Loop for each hunk of differences
while (self::findHunk($lines, $src_line, $src_size, $dst_line, $dst_size)) {
$done = true;
// Apply the hunk of differences
$this->applyHunk($lines, $src, $dst, $src_line, $src_size, $dst_line, $dst_size);
}
// If no modifications were found, throw an exception
if (!$done) {
throw new \RuntimeException('Invalid Diff');
}
}
}
// Initialize the counter
$done = 0;
// Patch each destination file
foreach ($this->destinations as $file => $content) {
$buffer = implode("\n", $content);
if (File::write($file, $buffer)) {
if (isset($this->sources[$file])) {
$this->sources[$file] = $content;
}
$done++;
}
}
// Remove each removed file
foreach ($this->removals as $file) {
if (File::delete($file)) {
if (isset($this->sources[$file])) {
unset($this->sources[$file]);
}
$done++;
}
}
// Clear the destinations cache
$this->destinations = array();
// Clear the removals
$this->removals = array();
// Clear the patches
$this->patches = array();
return $done;
}