generate-default.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. /**
  3. * @param string $directory
  4. *
  5. * @return array
  6. */
  7. function getRules($directory): array
  8. {
  9. $rules = [];
  10. $iterator = new DirectoryIterator($directory);
  11. foreach ($iterator as $file) {
  12. if ($file->isFile() && $file->getExtension() === 'json') {
  13. $rules[$file->getBasename('.json')] = json_decode(file_get_contents($file->getRealPath()), true);
  14. }
  15. }
  16. return $rules;
  17. }
  18. /**
  19. * @param string $fileName
  20. * @param array $rules
  21. *
  22. * @return bool
  23. */
  24. function insertRules($fileName, array $rules = []): bool
  25. {
  26. $startTag = '/*INSERT_START*/';
  27. $endTag = '/*INSERT_END*/';
  28. $content = file_get_contents($fileName);
  29. $content = preg_replace(
  30. $regexp = sprintf('#%s(.*)%s#s', quotemeta($startTag), quotemeta($endTag)),
  31. $startTag.var_export($rules, true).$endTag,
  32. $content
  33. );
  34. return false !== file_put_contents($fileName, $content);
  35. }
  36. $directory = __DIR__.'/../Resources/rules';
  37. $fileName = __DIR__.'/../src/RuleProvider/DefaultRuleProvider.php';
  38. $rules = getRules($directory);
  39. ksort($rules);
  40. $result = insertRules($fileName, $rules);
  41. $ruleCount = array_reduce($rules, function ($count, $rules) {
  42. return $count + count($rules);
  43. }, 0);
  44. if ($result) {
  45. printf("Written %d rules into '%s'.\n", $ruleCount, $fileName);
  46. } else {
  47. printf("Error writing rules into '%s'.\n", $fileName);
  48. }