This function will rewrite the MoufComponents.php file and the MoufRequire.php file (or their "admin" counterpart)
according to parameters stored in the MoufManager
493565
public function rewriteMouf() {
		//require_once('MoufPackageManager.php');

		if ((file_exists(dirname(__FILE__)."/".$this->componentsFileName) && !is_writable(dirname(__FILE__)."/".$this->componentsFileName)) || (!file_exists(dirname(__FILE__)."/".$this->componentsFileName) && !is_writable(dirname(dirname(__FILE__)."/".$this->componentsFileName)))) {
			$dirname = realpath(dirname(dirname(__FILE__)."/".$this->componentsFileName));
			$filename = basename(dirname(__FILE__)."/".$this->componentsFileName);
			throw new MoufContainerException("Error, unable to write file ".$dirname."/".$filename);
		}

		// Let's start by garbage collecting weak instances.
		$this->purgeUnreachableWeakInstances();

		$fp = fopen(dirname(__FILE__)."/".$this->componentsFileName, "w");
		fwrite($fp, "<?php\n");
		fwrite($fp, "/**\n");
		fwrite($fp, " * This is a file automatically generated by the Mouf framework. Do not modify it, as it could be overwritten.\n");
		fwrite($fp, " */\n");
		fwrite($fp, "use Mouf\MoufManager;\n");
		fwrite($fp, "use Interop\Container\ContainerInterface;\n");
		fwrite($fp, "MoufManager::initMoufManager();\n");
		fwrite($fp, "\$moufManager = MoufManager::getMoufManager();\n");
		fwrite($fp, "\n");
		fwrite($fp, "\$moufManager->getConfigManager()->setConstantsDefinitionArray(".var_export($this->getConfigManager()->getConstantsDefinitionArray(), true).");\n");
		fwrite($fp, "\n");

		// Import all variables
		fwrite($fp, "\$moufManager->setAllVariables(".var_export($this->variables, true).");\n");
		fwrite($fp, "\n");

		// Sort all instances by key. This way, new instances are not added at the end of the array,
		// and this reduces the number of conflicts when working in team with a version control system.
		ksort($this->declaredInstances);

		// Declare all components in one instruction
		$internalDeclaredInstances = array();
		foreach ($this->declaredInstances as $name=>$declaredInstance) {
			if (!isset($declaredInstance["external"]) || !$declaredInstance["external"]) {
				$internalDeclaredInstances[$name] = $declaredInstance;
			}
		}

		fwrite($fp, "\$moufManager->addComponentInstances(".var_export($internalDeclaredInstances, true).");\n");
		fwrite($fp, "\n");

		fwrite($fp, "\n");

		fwrite($fp, "unset(\$moufManager);\n");
		fwrite($fp, "\n");

		fwrite($fp, "/**\n");
		fwrite($fp, " * This is the base class of the Manage Object User Friendly or Modular object user framework (MOUF) framework.\n");
		fwrite($fp, " * This object can be used to get the objects manage by MOUF.\n");
		fwrite($fp, " *\n");
		fwrite($fp, " */\n");
		fwrite($fp, "class $this->mainClassName {\n");
		fwrite($fp, "	");
		
		// Now, let's export the closures!
		/***** closures Start ******/
		fwrite($fp, "public function getClosures() {\n");
		fwrite($fp, "		return [\n");
		
		$targetArray = [];
		foreach ($internalDeclaredInstances as $instanceName=>$instanceDesc) {
			if (isset($instanceDesc['constructor'])) {
				foreach ($instanceDesc['constructor'] as $key=>$param) {
					if ($param['type'] == 'php') {
						try {
							CodeValidatorService::validateCode($param['value']);
							$targetArray[$instanceName]['constructor'][$key] = $param['value'];
						} catch (\PhpParser\Error $ex) {
							error_log("Error in callback declared code for instance '$instanceName', constructor argument '$key': ".$ex->getMessage());
							$targetArray[$instanceName]['constructor'][$key] = $ex;
						}
					}
				}
			}
			if (isset($instanceDesc['fieldProperties'])) {
				foreach ($instanceDesc['fieldProperties'] as $key=>$param) {
					if ($param['type'] == 'php') {
						try {
							CodeValidatorService::validateCode($param['value']);
							$targetArray[$instanceName]['fieldProperties'][$key] = $param['value'];
						} catch (\PhpParser\Error $ex) {
							error_log("Error in callback declared code for instance '$instanceName', public property '$key': ".$ex->getMessage());
							$targetArray[$instanceName]['fieldProperties'][$key] = $ex;
						}
					}
				}
			}
			if (isset($instanceDesc['setterProperties'])) {
				foreach ($instanceDesc['setterProperties'] as $key=>$param) {
					if ($param['type'] == 'php') {
						try {
							CodeValidatorService::validateCode($param['value']);
							$targetArray[$instanceName]['setterProperties'][$key] = $param['value'];
						} catch (\PhpParser\Error $ex) {
							error_log("Error in callback declared code for instance '$instanceName', setter '$key': ".$ex->getMessage());
							$targetArray[$instanceName]['fieldProperties'][$key] = $ex;
						}
					}
				}
			}
			if (isset($instanceDesc['code']) && !isset($instanceDesc['error'])) {
				$targetArray[$instanceName] = $instanceDesc['code'];
			}
		}
		foreach ($targetArray as $instanceName=>$instanceDesc) {
			// If the whole instance is a PHP declaration
			if (is_string($instanceDesc)) {
				fwrite($fp, "			".var_export($instanceName, true)." => function(ContainerInterface \$container) {\n				");
				fwrite($fp, $instanceDesc);
				fwrite($fp, "\n			},\n");
			} else {
				// If properties are a PHP declaration
				fwrite($fp, "			".var_export($instanceName, true)." => [\n");
				if (isset($instanceDesc['constructor'])) {
					fwrite($fp, "				'constructor' => [\n");
					foreach ($instanceDesc['constructor'] as $key=>$code) {
						fwrite($fp, "					".var_export($key, true)." => ");
						if (!$code instanceof \PhpParser\Error) {
							fwrite($fp, "function(ContainerInterface \$container) {\n						");
							fwrite($fp, $code);
							fwrite($fp, "\n					},\n");
						} else {
							// If the code is an exception we put the error message instead of a callback in the closures array
							fwrite($fp, var_export($code->getMessage(), true).",\n");
						}
					}
					fwrite($fp, "				],\n");
				}
				if (isset($instanceDesc['fieldProperties'])) {
					fwrite($fp, "				'fieldProperties' => [\n");
					foreach ($instanceDesc['fieldProperties'] as $key=>$code) {
						fwrite($fp, "					".var_export($key, true)." => ");
						if (!$code instanceof \PhpParser\Error) {
							fwrite($fp, "function(ContainerInterface \$container) {\n						");
							fwrite($fp, $code);
							fwrite($fp, "\n					},\n");
						} else {
							// If the code is an exception we put the error message instead of a callback in the closures array
							fwrite($fp, var_export($code->getMessage(), true).",\n");
						}
					}
					fwrite($fp, "				],\n");
				}
				if (isset($instanceDesc['setterProperties'])) {
					fwrite($fp, "				'setterProperties' => [\n");
					foreach ($instanceDesc['setterProperties'] as $key=>$code) {
						fwrite($fp, "					".var_export($key, true)." => ");
						if (!$code instanceof \PhpParser\Error) {
							fwrite($fp, "function(ContainerInterface \$container) {\n						");
							fwrite($fp, $code);
							fwrite($fp, "\n					},\n");
						} else {
							// If the code is an exception we put the error message instead of a callback in the closures array
							fwrite($fp, var_export($code->getMessage(), true).",\n");
						}
					}
					fwrite($fp, "				],\n");
				}
				fwrite($fp, "			],\n");
			}
		}
		
		fwrite($fp, "		];\n");
		fwrite($fp, "	}\n");
		/***** closures end ******/
		
		
		$getters = array();
		foreach ($this->declaredInstances as $name=>$classDesc) {
			if (!isset($classDesc['class'])) {
				if (isset($classDesc['code'])) {
					continue;
				}
				throw new MoufContainerException("No class for instance '$name'");
			}
			if (isset($classDesc['anonymous']) && $classDesc['anonymous']) {
				continue;
			}
			$className = $classDesc['class'];
			$getter = self::generateGetterString($name);
			if (isset($getters[strtolower($getter)])){
				$i = 0;
				while (isset($getters[strtolower($getter."_$i")])) {
					$i++;
				}
				$getter = $getter."_$i";
			}
			$getters[strtolower($getter)] = true;
			fwrite($fp, "	/**\n");
			fwrite($fp, "	 * @return $className\n");
			fwrite($fp, "	 */\n");
			fwrite($fp, "	 public static function ".$getter."() {\n");
			fwrite($fp, "	 	return MoufManager::getMoufManager()->get(".var_export($name,true).");\n");
			fwrite($fp, "	 }\n\n");
		}
		fwrite($fp, "}\n");


		fclose($fp);
		if (function_exists("opcache_invalidate")) {
			opcache_invalidate(dirname(__FILE__)."/".$this->componentsFileName);
		}

		// Note: rewriting MoufUI here is useless, since it is only modified on update or install of packages.
		$selfEdit = ($this->scope == MoufManager::SCOPE_ADMIN);
		$composerService = new ComposerService($selfEdit);
		$composerService->rewriteMoufUi();

	}
1241113
public static function install(MoufManager $moufManager)
    {
        $cascadingTranslator = InstallUtils::getOrCreateInstance("defaultTranslationService", "Mouf\\Utils\\I18n\\Fine\\Common\\FineCascadingTranslator", $moufManager);

        if ($moufManager->has('twigEnvironment') && !$moufManager->has('fineTwigExtension')) {
            $fineTwigExtension = $moufManager->createInstance(FineTwigExtension::class);

            $fineTwigExtension->getConstructorArgumentProperty('translator')->setValue($cascadingTranslator);

            $twigEnvironment = $moufManager->getInstanceDescriptor('twigEnvironment');
            $extensions = $twigEnvironment->getSetterProperty('setExtensions')->getValue();
            $extensions[] = $fineTwigExtension;
            $twigEnvironment->getSetterProperty('setExtensions')->setValue($extensions);
        }

        // Let's rewrite the MoufComponents.php file to save the component
        $moufManager->rewriteMouf();
    }
854061
public function admin_init(){
        if( !AjaxBase::is_ajax() && current_user_can('manage_options') ){
            if( !empty($this->classes) ){
                $rewrites = '';
                foreach( $this->classes as $class_name ){
                   $rewrites .= $this->get_prefix($class_name);
                }
                $rewrites = md5($rewrites);
                if( get_option('rewrite_rules') && $this->rewrite_md5 != $rewrites ){
                    flush_rewrite_rules();
                    $last_updated = current_time('timestamp');
                    update_option($this->option_name, $last_updated);
                    update_option($this->rewrite_md5_name, $rewrites);
                    $message = sprintf($this->__('Rewrite rules updated. Last modified date is %s'), date_i18n(get_option('date_format').' '.get_option('time_format'), $last_updated));
                    add_action('admin_notices', function() use ($message){
                        printf('<div class="updated"><p>%s</p></div>', $message);
                    });
                }
            }
        }
    }
439557
private function rewrite()
    {
        // Current positional parameter.
        $positionalParameter = 1;

        // TRUE if we are in a literal section else FALSE.
        $literal = false;

        // The statement length.
        $statementLength = strlen($this->statement);

        // Iterate each statement char.
        for ($placeholderPos = 0; $placeholderPos < $statementLength; $placeholderPos++) {

            // Switch the literal flag if the current statement char is a literal delimiter.
            if (in_array($this->statement[$placeholderPos], array('\'', '"'))) {
                $literal = !$literal;
            }

            // Check if we are not in a literal section and the current statement char is a double colon.
            if (!$literal && $this->statement[$placeholderPos] === ':') {

                // Determine placeholder length.
                $placeholderLength = 1;
                while (isset($this->statement[$placeholderPos + $placeholderLength])
                    && $this->isValidPlaceholderCharacter($this->statement[$placeholderPos + $placeholderLength])) {
                    $placeholderLength++;
                }

                // Extract placeholder from the statement.
                $placeholder = substr($this->statement, $placeholderPos, $placeholderLength);

                // Initialize rewrites parameters.
                if (!isset($this->parameters[$placeholder])) {
                    $this->parameters[$placeholder] = array();
                }

                // Rewrites parameter.
                $this->parameters[$placeholder][] = $positionalParameter;

                // Rewrite statement.
                $this->statement = substr($this->statement, 0, $placeholderPos).
                    '?'.
                    substr($this->statement, $placeholderPos + $placeholderLength);

                // Decrement statement length.
                $statementLength = $statementLength - $placeholderLength + 1;

                // Increment position parameter.
                $positionalParameter++;
            }
        }
    }
535602
private static void rewriteOptions(String[] args, String option, String new_option) {
        for (int i=0; i<args.length; ++i) {
            if (args[i].equals(option)) {
                args[i] = new_option;
            }
        }
    }
1006856
private function prepareReplacements()
    {
        $usesString = '';
        foreach ($this->modelReplacements[':uses'] as $use) {
            $usesString .= 'use '.$use.';'.PHP_EOL;
        }
        $this->modelReplacements[':uses'] = $usesString;

        $this->modelReplacements[':implementations'] = ! empty($this->modelReplacements[':implementations']) ?
            'implements '.implode(', ', $this->modelReplacements[':implementations']) : '';

        $this->modelReplacements[':traits'] = ! empty($this->modelReplacements[':traits']) ?
            'use '.implode(', ', $this->modelReplacements[':traits']).';' : '';
    }
192729
public function write()
    {
        foreach ($this->parameters as $prop => $value) {
            $placeHolders[] = sprintf('<%s>', $prop);
            $replacements[] = $value;
        }

        $content = str_replace($placeHolders, $replacements, self::$template);

        fwrite($this->file, $this->addHeaders($content));
    }
957203
function rewriteLink(href, renderOpts) {
    var imgRoute = renderOpts.fqImages && (renderOpts.fqImages.route || '/images/');
    var imgPrefix = renderOpts.fqImages && renderOpts.fqImages.url;
    var linkPrefix = renderOpts.fqLinks || renderOpts.relPath;

    if (imgPrefix && u.startsWith(href, imgRoute)) { href = imgPrefix + href; }
    else if (linkPrefix && /^\/([^/]|$)/.test(href)) { href = linkPrefix + href; }

    return href;
  }
549486
private static function applyRewrites(string $requestedUri, array $rewrites): string
    {
        foreach ($rewrites as $route) {
            $pattern      = $route['pattern'];
            $replacement  = $route['replacement'];
            $requestedUri = preg_replace($pattern, $replacement, $requestedUri);

            if (isset($route['last'])) {
                break;
            }
        }

        return $requestedUri;
    }
503955
void rewriteProvidesAndRequires(Node externs, Node root) {
    checkState(!hasRewritingOccurred, "Cannot call rewriteProvidesAndRequires twice per instance");
    hasRewritingOccurred = true;

    collectProvidedNames(externs, root);

    for (ProvidedName pn : providedNames.values()) {
      pn.replace();
    }
    deleteNamespaceInitializationsFromPreviousProvides();

    if (requiresLevel.isOn()) {
      for (UnrecognizedRequire r : unrecognizedRequires) {
        checkForLateOrMissingProvide(r);
      }
    }

    for (Node closureRequire : requiresToBeRemoved) {
      compiler.reportChangeToEnclosingScope(closureRequire);
      closureRequire.detach();
    }
    for (Node forwardDeclare : forwardDeclaresToRemove) {
      NodeUtil.deleteNode(forwardDeclare, compiler);
    }
  }
880998
def _apply_rewrites(date_classes, rules):
    
    for rule in rules:
        date_classes = rule.execute(date_classes)

    return date_classes
1000368
protected function writePipelineFile() {
		if(!$this->config()->get('allow_web_editing')) return;
		$path = $this->getPipelineFilename();
		if($this->PipelineConfig) {
			// Update file
			file_put_contents($path, $this->PipelineConfig);
		} elseif($this->isChanged('PipelineConfig') && file_exists($path)) {
			// Remove file if deleted
			unlink($path);
		}
	}
750696
public static function installRequiredFiles()
    {
        $htaccess = [
            __DIR__ . '/../../../../../../app/.htaccess',
            __DIR__ . '/../../../../../../src/.htaccess',
            __DIR__ . '/../../../../../../web/.htaccess',
        ];
        $fileSystem = new Filesystem();

        try {
            if (false === $fileSystem->exists($htaccess)) {
                $fileSystem->copy($htaccess[0] . '.dist', $htaccess[0]);
                $fileSystem->copy($htaccess[1] . '.dist', $htaccess[1]);
                $fileSystem->copy($htaccess[2] . '.dist', $htaccess[2]);
            }
        } catch (\Exception $exception) {
            echo sprintf("Something wrong happens during process: \n%s\n", $exception->getMessage());
        }
    }
337283
protected function writeFile()
    {
        //  Routes are writable, apparently, give it a bash
        $sData = '<?php' . "\n\n";
        $sData .= '/**' . "\n";
        $sData .= ' * THIS FILE IS CREATED/MODIFIED AUTOMATICALLY' . "\n";
        $sData .= ' * ===========================================' . "\n";
        $sData .= ' *' . "\n";
        $sData .= ' * Any changes you make in this file will be overwritten the' . "\n";
        $sData .= ' * next time the app routes are generated.' . "\n";
        $sData .= ' *' . "\n";
        $sData .= ' * See Nails docs for instructions on how to utilise the' . "\n";
        $sData .= ' * routes_app.php file' . "\n";
        $sData .= ' *' . "\n";
        $sData .= ' **/' . "\n\n";

        // --------------------------------------------------------------------------

        foreach ($this->aRoutes as $sKey => $sValue) {
            if (preg_match('#^//.*$#', $sKey)) {
                //  This is a comment
                $sData .= $sKey . "\n";
            } else {
                //  This is a route
                $sData .= '$route[\'' . $sKey . '\']=\'' . $sValue . '\';' . "\n";
            }
        }

        $oDate = Factory::factory('DateTime');
        $sData .= "\n" . '//LAST GENERATED: ' . $oDate->format('Y-m-d H:i:s');
        $sData .= "\n";

        // --------------------------------------------------------------------------

        $fHandle = @fopen(static::ROUTES_DIR . static::ROUTES_FILE, 'w');

        if (!$fHandle) {
            $this->setError('Unable to open routes file for writing.');
            return false;
        }

        if (!fwrite($fHandle, $sData)) {
            fclose($fHandle);
            $this->setError('Unable to write data to routes file.');
            return false;
        }

        fclose($fHandle);
        return true;
    }
1221005
function createPathRewriter(rewriteConfig) {
    let rulesCache;
    if (!isValidRewriteConfig(rewriteConfig)) {
        return;
    }
    if (_.isFunction(rewriteConfig)) {
        const customRewriteFn = rewriteConfig;
        return customRewriteFn;
    }
    else {
        rulesCache = parsePathRewriteRules(rewriteConfig);
        return rewritePath;
    }
    function rewritePath(path) {
        let result = path;
        _.forEach(rulesCache, rule => {
            if (rule.regex.test(path)) {
                result = result.replace(rule.regex, rule.value);
                logger.debug('[HPM] Rewriting path from "%s" to "%s"', path, result);
                return false;
            }
        });
        return result;
    }
}
586234
function rewrite(req, res) {

  /* istanbul ignore next: tough to mock fs write error */
  function onError(err) {
    this.conf.removeAllListeners('error');
    this.conf.removeAllListeners('write');
    res.send(err);
  }

  function onWrite() {
    this.conf.removeAllListeners('error');
    this.conf.removeAllListeners('write');
    res.send(null, Constants.OK);
  }

  this.conf.once('error', onError.bind(this));
  this.conf.write(this.conf.getFile(), onWrite.bind(this));
}
304569
public function format_answer($answer, $context, $answerformat, $options = []) {
        $answer = file_rewrite_pluginfile_urls($answer, 'pluginfile.php', $context->id,
            'mod_lesson', 'essay_answers', $options->attemptid);
        return parent::format_answer($answer, $context, $answerformat, $options);
    }