Neos\Flow\Core\Migrations\Tools::searchAndReplace PHP Метод

searchAndReplace() публичный статический Метод

A simple str_replace is used, unless $regularExpression is set to TRUE. In that case preg_replace is used. The given patterns are used as given, no quoting is applied! In case $regularExpression is TRUE, a closure can be given for the $replace variable. It should return a string and is given an array of matches as parameter.
public static searchAndReplace ( string $search, string | Closure $replace, string $pathAndFilename, boolean $regularExpression = false ) : boolean | null
$search string
$replace string | Closure
$pathAndFilename string
$regularExpression boolean
Результат boolean | null FALSE on errors, NULL on skip, TRUE on success
    public static function searchAndReplace($search, $replace, $pathAndFilename, $regularExpression = false)
    {
        $pathInfo = pathinfo($pathAndFilename);
        if (!isset($pathInfo['filename']) || $pathAndFilename === __FILE__) {
            return false;
        }
        $file = file_get_contents($pathAndFilename);
        $fileBackup = $file;
        if ($regularExpression === true) {
            if ($replace instanceof \Closure) {
                $file = preg_replace_callback($search, $replace, $file);
            } else {
                $file = preg_replace($search, $replace, $file);
            }
        } else {
            $file = str_replace($search, $replace, $file);
        }
        if ($file !== $fileBackup) {
            file_put_contents($pathAndFilename, $file);
            return true;
        }
        return null;
    }

Usage Example

 /**
  * Applies all registered searchAndReplace operations.
  *
  * @return void
  */
 protected function applySearchAndReplaceOperations()
 {
     foreach (Files::getRecursiveDirectoryGenerator($this->targetPackageData['path'], null, true) as $pathAndFilename) {
         $pathInfo = pathinfo($pathAndFilename);
         if (!isset($pathInfo['filename'])) {
             continue;
         }
         if (strpos($pathAndFilename, 'Migrations/Code') !== false) {
             continue;
         }
         foreach ($this->operations['searchAndReplace'] as $operation) {
             list($search, $replacement, $filter, $regularExpression) = $operation;
             if (is_array($filter)) {
                 if ($filter !== array() && (!isset($pathInfo['extension']) || !in_array($pathInfo['extension'], $filter, true))) {
                     continue;
                 }
             } elseif (substr($pathAndFilename, -strlen($filter)) !== $filter) {
                 continue;
             }
             Tools::searchAndReplace($search, $replacement, $pathAndFilename, $regularExpression);
         }
     }
 }