FilePostDump.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. namespace Drupal\reinstall\EventSubscriber;
  3. use Drupal\reinstall\Dumper;
  4. use Drupal\reinstall\DumperEvent;
  5. use Drupal\reinstall\DumperEvents;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. class FilePostDump implements EventSubscriberInterface {
  8. protected $importPath = Dumper::IMPORT_PATH;
  9. public function __construct(string $importPath) {
  10. $this->importPath = $importPath;
  11. }
  12. public static function getSubscribedEvents() {
  13. return [
  14. DumperEvents::POST_DUMP => 'onDumpPost',
  15. ];
  16. }
  17. public function onDumpPost(DumperEvent $event) {
  18. $args = func_get_args();
  19. if ($event->storage->getEntityTypeId() !== 'file') {
  20. return;
  21. }
  22. echo "coucou" . $event->bundleName . "\n";
  23. static::dumpFiles($event->bundleName, $event->entities);
  24. }
  25. public function dumpFiles(string $bundle, array $files) {
  26. $importPath = $this->importPath;
  27. $dir = "$importPath/file";
  28. $usedNamespaces = array_keys(array_reduce($files, [__CLASS__, 'namespacesReducer'], []));
  29. $lists = [];
  30. foreach ($usedNamespaces as $ns) {
  31. // XXX Consider using \0 to support xargs: file names MAY contain spaces.
  32. $path = "$dir/$ns.list.txt";
  33. $nsDir = "$dir/$ns";
  34. if (!is_dir($nsDir)) {
  35. echo "Creating $nsDir\n";
  36. mkdir($nsDir, 0777, TRUE);
  37. }
  38. // fopen() is in text mode by default.
  39. $lists[$ns] = [
  40. 'dir' => $nsDir,
  41. 'handle' => fopen($path, 'w'),
  42. ];
  43. }
  44. /**
  45. * @var int $fid
  46. * @var \Drupal\file\Entity\File $file
  47. */
  48. foreach ($files as $fid => $file) {
  49. $uri = $file->getFileUri();
  50. $target = file_uri_target($uri);
  51. fputs($lists[$ns]['handle'], $target . "\n");
  52. $dest = $lists[$ns]['dir'] . '/' . $target;
  53. $dir = dirname($dest);
  54. if (!is_dir($dir)) {
  55. mkdir($dir, 0777, TRUE);
  56. }
  57. file_unmanaged_copy($uri, $dest, FILE_EXISTS_REPLACE);
  58. }
  59. foreach ($lists as $list) {
  60. fclose($list['handle']);
  61. }
  62. }
  63. /**
  64. * array_reduce() callback to collect namespaces from file entities.
  65. *
  66. * @param string[] $accu
  67. * @param \Drupal\file\Entity\File $fileItem
  68. *
  69. * @return string[]
  70. *
  71. * @see \Drupal\reinstall\Dumper::dumpFiles()
  72. */
  73. protected static function namespacesReducer(array $accu, File $fileItem) {
  74. $uri = $fileItem->getFileUri();
  75. // Plain filenames without a namespace. Should not happen, but...
  76. if (FALSE === ($len = Unicode::strpos($uri, '://'))) {
  77. return $accu;
  78. };
  79. $namespace = Unicode::substr($uri, 0, $len);
  80. $accu[$namespace] = TRUE;
  81. return $accu;
  82. }
  83. }