Generate.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. /**
  3. * This file is part of the ForkBB <https://github.com/forkbb>.
  4. *
  5. * @copyright (c) Visman <mio.visman@yandex.ru, https://github.com/MioVisman>
  6. * @license The MIT License (MIT)
  7. */
  8. declare(strict_types=1);
  9. namespace ForkBB\Models\BBCodeList;
  10. use ForkBB\Models\Method;
  11. use ForkBB\Models\BBCodeList\BBCodeList;
  12. use RuntimeException;
  13. class Generate extends Method
  14. {
  15. /**
  16. * Создает файл с массивом сгенерированных bbcode
  17. */
  18. public function generate(): BBCodeList
  19. {
  20. $query = 'SELECT bb_structure
  21. FROM ::bbcode';
  22. $content = "<?php\n\nuse function \\ForkBB\\{__, url};\n\nreturn [\n";
  23. $stmt = $this->c->DB->query($query);
  24. while ($row = $stmt->fetch()) {
  25. $content .= " [\n"
  26. . $this->addArray(\json_decode($row['bb_structure'], true, 512, \JSON_THROW_ON_ERROR))
  27. . " ],\n";
  28. }
  29. $content .= "];\n";
  30. if (false === \file_put_contents($this->model->fileCache, $content, \LOCK_EX)) {
  31. throw new RuntimeException('The generated bbcode file cannot be created');
  32. } else {
  33. return $this->model->invalidate();
  34. }
  35. }
  36. /**
  37. * Преобразует массив по аналогии с var_export()
  38. */
  39. protected function addArray(array $array, int $level = 0): string
  40. {
  41. $space = \str_repeat(' ', $level + 2);
  42. $result = '';
  43. foreach ($array as $key => $value) {
  44. $type = \gettype($value);
  45. switch ($type) {
  46. case 'NULL':
  47. $value = 'null';
  48. break;
  49. case 'boolean':
  50. $value = $value ? 'true' : 'false';
  51. break;
  52. case 'array':
  53. $value = "[\n" . $this->addArray($value, $level + 1) . "{$space}]";
  54. break;
  55. case 'double':
  56. case 'integer':
  57. break;
  58. case 'string':
  59. if (
  60. 0 === $level
  61. && (
  62. 'handler' === $key
  63. || 'text_handler' === $key
  64. )
  65. ) {
  66. $value = "function (\$body, \$attrs, \$parser) {\n{$value}\n{$space}}";
  67. } else {
  68. $value = '\'' . \addslashes($value) . '\'';
  69. }
  70. break;
  71. default:
  72. throw new RuntimeException("Invalid data type ({$type})");
  73. break;
  74. }
  75. if (\is_string($key)) {
  76. $key = "'{$key}'";
  77. }
  78. $result .= "{$space}{$key} => {$value},\n";
  79. }
  80. return $result;
  81. }
  82. }