Gush\Helper\MetaHelper::updateContent PHP Method

updateContent() public method

Note. We only support comments in the beginning of the file. If there is already a comment its replaced, if its missing its added.
public updateContent ( Gush\Meta\Meta $meta, string $header, string $fileContent ) : string
$meta Gush\Meta\Meta
$header string
$fileContent string
return string
    public function updateContent(Meta $meta, $header, $fileContent)
    {
        if (!$this->isUpdatable($meta, $fileContent)) {
            return $fileContent;
        }
        $startContent = '';
        $fileContent = ltrim($fileContent);
        if (null !== $meta->getStartTokenRegex()) {
            // When no start token is found just ignore the content to prevent corrupting
            if (!preg_match($meta->getStartTokenRegex(), $fileContent, $startMatch)) {
                return $fileContent;
            }
            $startToken = $startMatch[0];
            $startContent = trim($startToken) . "\n\n";
            $fileContent = substr($fileContent, strlen($startMatch[0]));
        }
        if (preg_match('&^' . preg_quote($meta->getStartDelimiter()) . '+&', $fileContent)) {
            $lines = preg_split("/\r\n|\n|\r/", $fileContent);
            $lineNum = 0;
            $linesCount = count($lines);
            $line = $lines[$lineNum];
            // Skip the comment lines till the end delimiter
            while ($lineNum < $linesCount && !preg_match('&^\\h*' . preg_quote($meta->getEndDelimiter()) . '&', $line)) {
                $line = $lines[$lineNum];
                unset($lines[$lineNum]);
                ++$lineNum;
            }
            $fileContent = implode("\n", $lines);
        }
        return $startContent . $header . ltrim($fileContent);
    }

Usage Example

Example #1
0
    public function testUpdateContentPhpFileWithPreservedHeader()
    {
        $meta = $this->getMetaForPhp();
        $input = <<<'EOT'
<?php

/*!
 * This file is part of Your Package package.
 */

namespace Test;

class MetaTest
{
    private $test;

    public function __construct($test)
    {
        $this->test = $test;
    }
}

EOT;
        $expected = <<<'EOT'
<?php

/*!
 * This file is part of Your Package package.
 */

namespace Test;

class MetaTest
{
    private $test;

    public function __construct($test)
    {
        $this->test = $test;
    }
}

EOT;
        $this->assertEquals(ltrim($expected), $this->helper->updateContent($meta, self::$header, $input));
    }