Snippets

mason.malone replace controllers urls with calls to PageController::url()

Created by mason.malone last modified Mason Malone
<?php

# composer require "riimu/kit-phpencoder:2.*"

require 'vendor/autoload.php';
$encoder = new \Riimu\Kit\PHPEncoder\PHPEncoder();

$files = explode("\n", `grep -Rl '/controllers.*php' app`);
//$files = ['app/templates/editor/supervisor_subordinate_decisions.tpl.php'];
foreach ($files as $file) {
   if (empty($file)) continue;
   print "Handling $file\n";
   $fileContents = file_get_contents($file);
   $newFileContents = preg_replace_callback('@^(\s*)(.*)(["\'])/controllers/([^/]+)\.php(\?[^\1]*?)?\3@m', function ($matches) use ($encoder) {
      $new_string = $matches[1] . $matches[2] . $matches[3] . '<?= ' . $matches[4] . '::url(';
      echo "\nMATCHES {$matches[0]}\n";
      if (!empty($matches[5])) {
         $queryString = htmlspecialchars_decode(substr($matches[5], 1));
         parse_str($queryString, $query);
         if (!isset($query['action'])) {
            $new_string .= 'null';
         } else {
            $new_string .= "'{$query['action']}'";
         }
         unset($query['action']);
         if (!empty($query)) {
            $queryArrayString = $encoder->encode($query, [
               'array.base' => $matches[1],
               'array.indent' => "\t",
               'array.inline' => 100,
            ]);
            $queryArrayString = preg_replace('/\'<\?=?(.*)\?>\'/', '\1', $queryArrayString);
            $new_string .= ', ' . $queryArrayString;
         }
      }
      $new_string .= ') ?>' . $matches[2];
      var_dump($matches); var_dump($new_string);
      return $new_string;
   }, $fileContents);
   file_put_contents($file, $newFileContents);
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.