3 namespace Drupal\drupalmoduleupgrader\Plugin\DMU\Converter;
5 use Drupal\Core\StringTranslation\TranslationInterface;
6 use Drupal\drupalmoduleupgrader\ConverterBase;
7 use Drupal\drupalmoduleupgrader\TargetInterface;
9 use Psr\Log\LoggerInterface;
10 use Symfony\Component\DependencyInjection\ContainerInterface;
15 * description = @Translation("Searches for and replaces commonly-used code that has changed in Drupal 8.")
18 class Grep extends ConverterBase {
23 private $targets = [];
25 public function __construct(array $configuration, $plugin_id, $plugin_definition, TranslationInterface $translator, LoggerInterface $log) {
26 parent::__construct($configuration, $plugin_id, $plugin_definition, $translator, $log);
28 foreach ($configuration['globals'] as $variable => $replacement) {
29 $this->targets['global $' . $variable . ';'] = '$' . $variable . ' = ' . $replacement . ';';
30 $this->targets['$GLOBALS[\'' . $variable . '\']'] = $replacement;
31 $this->targets['$GLOBALS["' . $variable . '"]'] = $replacement;
33 foreach ($configuration['constants'] as $constant => $replacement) {
34 $this->targets[$constant] = $replacement;
41 public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
43 $container->get('config.factory')->get('drupalmoduleupgrader.grep')->get('definitions'),
46 $container->get('string_translation'),
47 $container->get('logger.factory')->get('drupalmoduleupgrader')
54 public function convert(TargetInterface $target) {
55 foreach ($this->configuration['function_calls'] as $function => $replace_with) {
56 $function_calls = $target->getIndexer('function_call')->get($function);
57 foreach ($function_calls as $function_call) {
58 $rewritten = str_ireplace($function, $replace_with, $function_call->getText());
59 $node = Parser::parseExpression($rewritten);
60 $function_call->replaceWith($node);
65 // Flush other open syntax trees to ensure that other plugins don't clobber
69 foreach ($target->getFinder() as $file) {
70 // Load in the entire contents of the module. This is criminally inefficient
71 // and wasteful of memory and should eventually be refactored into something
72 // a little more...I dunno, sustainable.
73 /** @var \Symfony\Component\Finder\SplFileInfo $file */
74 $search = array_keys($this->targets);
75 $replace = array_values($this->targets);
76 file_put_contents($file->getPathname(), str_replace($search, $replace, $file->getContents()));