|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace PatrickMaynard\AuditClassGenerator; |
| 4 | + |
| 5 | +class Applier |
| 6 | +{ |
| 7 | + public function getDirContents($dir){ |
| 8 | + $results = array(); |
| 9 | + $files = scandir($dir); |
| 10 | + |
| 11 | + foreach($files as $key => $value){ |
| 12 | + if(!is_dir($dir. DIRECTORY_SEPARATOR .$value)){ |
| 13 | + $results[] = $dir. DIRECTORY_SEPARATOR . $value; |
| 14 | + } else if( |
| 15 | + is_dir($dir. DIRECTORY_SEPARATOR .$value) && |
| 16 | + !str_contains($value, '..') && |
| 17 | + $value !== '.' |
| 18 | + ) { |
| 19 | + $results[] = $value; |
| 20 | + $results = array_merge($results, $this->getDirContents($dir. DIRECTORY_SEPARATOR .$value)); |
| 21 | + } |
| 22 | + } |
| 23 | + return $results; |
| 24 | + |
| 25 | + } |
| 26 | + |
| 27 | + //TODO: Allow blade as well. |
| 28 | + public function filterAllFilesForTwigExtension() |
| 29 | + { |
| 30 | + $directoryToParse = getcwd() . '..' . DIRECTORY_SEPARATOR . ' .. '; |
| 31 | + echo PHP_EOL . 'We will be looking recursively in ' . $directoryToParse . ' for Twig files .. ' . PHP_EOL; |
| 32 | + $files = $this->getDirContents($directoryToParse); |
| 33 | + $output = []; |
| 34 | + foreach ($files as $file) { |
| 35 | + if (str_ends_with($file, '.html.twig')) { |
| 36 | + $output[] = $file; |
| 37 | + } |
| 38 | + } |
| 39 | + return $output; |
| 40 | + } |
| 41 | + |
| 42 | + |
| 43 | + function applyAllAuditTags() |
| 44 | + { |
| 45 | + //First, we need to be on a safe git branch, since this set of changes will mess with lots of files |
| 46 | + exec('git checkout -b temporary-template-audit-branch-remove-me-soon'); |
| 47 | + |
| 48 | + echo PHP_EOL; |
| 49 | + echo "Temporary git branch created. Iterating through templates ... "; |
| 50 | + echo PHP_EOL; |
| 51 | + |
| 52 | + $files = $this->filterAllFilesForTwigExtension(); |
| 53 | + |
| 54 | + foreach ($files as $index => $file) { |
| 55 | + $contents = file_get_contents($file); |
| 56 | + preg_match_all('/class="[^"]+"/', $contents, $matches); |
| 57 | + foreach ($matches as $index => $match) { |
| 58 | + if ( $index = 0 ) { |
| 59 | + continue; |
| 60 | + } |
| 61 | + |
| 62 | + if (is_array($match)) { |
| 63 | + foreach ($match as $matchingString) { |
| 64 | + $hash = md5(rand(0,1000000000) . "This will provide a nice, long, randomish string."); |
| 65 | + $shorterFingerprint = 'audit_' . substr($hash, 0, 6); |
| 66 | + $withSpace = ' ' . $shorterFingerprint . ' '; |
| 67 | + |
| 68 | + //Now just do a simple string replacement |
| 69 | + $contents = str_replace( |
| 70 | + $matchingString, substr($matchingString, 0, -1) . $withSpace . '"', $contents |
| 71 | + ); |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + } |
| 76 | + file_put_contents($file, $contents); |
| 77 | + } |
| 78 | + echo "Done!"; |
| 79 | + echo PHP_EOL; |
| 80 | + } |
| 81 | +} |
0 commit comments