Skip to content

Commit

Permalink
Merge pull request consolidation#305 from Codegyre/text-if-match
Browse files Browse the repository at this point in the history
Add Write::appendIfMatches() and appendUnlessMatches() for taskWriteToFile.
  • Loading branch information
DavertMik committed Mar 31, 2016
2 parents e64df1f + 94392bf commit c660a93
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/Task/File/Write.php
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,32 @@ public function regexReplace($pattern, $replacement)
return $this;
}

/**
* Append the provided text to the end of the buffer if the provided
* regex pattern matches any text already in the buffer.
*
* @param string $pattern
* @param string
*/
public function appendIfMatches($pattern, $text)
{
$this->stack[] = array_merge(['appendIfMatchesCollect'], [$pattern, $text, true]);
return $this;
}

/**
* Append the provided text to the end of the buffer unless the provided
* regex pattern matches any text already in the buffer.
*
* @param string $pattern
* @param string
*/
public function appendUnlessMatches($pattern, $text)
{
$this->stack[] = array_merge(['appendIfMatchesCollect'], [$pattern, $text, false]);
return $this;
}

protected function textFromFileCollect($contents, $filename)
{
return $contents . file_get_contents($filename);
Expand All @@ -163,6 +189,14 @@ protected function textCollect($contents, $text)
return $contents . $text;
}

protected function appendIfMatchesCollect($contents, $pattern, $text, $shouldMatch)
{
if (preg_match($pattern, $contents) == $shouldMatch) {
$contents .= $text;
}
return $contents;
}

protected function getContents()
{
$contents = "";
Expand Down
23 changes: 23 additions & 0 deletions tests/cli/WriteFileCest.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,29 @@ public function insertFile(CliGuy $I)
****
BC
HERE
);
}

public function appendIfMatch(CliGuy $I)
{
$I->wantTo('append lines with WriteToFile task, but only if pattern does not match');
$I->taskWriteToFile('blogpost.md')
->line('****')
->line('hello world')
->line('****')
->appendUnlessMatches('/hello/', 'Should not add this')
->appendUnlessMatches('/goodbye/', 'Should add this')
->appendIfMatches('/hello/', ' and should also add this')
->appendIfMatches('/goodbye/', ' but should not add this')
->appendIfMatches('/should/', '!')
->run();
$I->seeFileFound('blogpost.md');
$I->seeFileContentsEqual(<<<HERE
****
hello world
****
Should add this and should also add this!
HERE
);
}
Expand Down

0 comments on commit c660a93

Please sign in to comment.