123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- <?php
- namespace Drupal\reinstall\EventSubscriber;
- use Drupal\reinstall\Dumper;
- use Drupal\reinstall\DumperEvent;
- use Drupal\reinstall\DumperEvents;
- use Symfony\Component\EventDispatcher\EventSubscriberInterface;
- class FilePostDump implements EventSubscriberInterface {
- protected $importPath = Dumper::IMPORT_PATH;
- public function __construct(string $importPath) {
- $this->importPath = $importPath;
- }
- public static function getSubscribedEvents() {
- return [
- DumperEvents::POST_DUMP => 'onDumpPost',
- ];
- }
- public function onDumpPost(DumperEvent $event) {
- $args = func_get_args();
- if ($event->storage->getEntityTypeId() !== 'file') {
- return;
- }
- echo "coucou" . $event->bundleName . "\n";
- static::dumpFiles($event->bundleName, $event->entities);
- }
- public function dumpFiles(string $bundle, array $files) {
- $importPath = $this->importPath;
- $dir = "$importPath/file";
- $usedNamespaces = array_keys(array_reduce($files, [__CLASS__, 'namespacesReducer'], []));
- $lists = [];
- foreach ($usedNamespaces as $ns) {
- // XXX Consider using \0 to support xargs: file names MAY contain spaces.
- $path = "$dir/$ns.list.txt";
- $nsDir = "$dir/$ns";
- if (!is_dir($nsDir)) {
- echo "Creating $nsDir\n";
- mkdir($nsDir, 0777, TRUE);
- }
- // fopen() is in text mode by default.
- $lists[$ns] = [
- 'dir' => $nsDir,
- 'handle' => fopen($path, 'w'),
- ];
- }
- /**
- * @var int $fid
- * @var \Drupal\file\Entity\File $file
- */
- foreach ($files as $fid => $file) {
- $uri = $file->getFileUri();
- $target = file_uri_target($uri);
- fputs($lists[$ns]['handle'], $target . "\n");
- $dest = $lists[$ns]['dir'] . '/' . $target;
- $dir = dirname($dest);
- if (!is_dir($dir)) {
- mkdir($dir, 0777, TRUE);
- }
- file_unmanaged_copy($uri, $dest, FILE_EXISTS_REPLACE);
- }
- foreach ($lists as $list) {
- fclose($list['handle']);
- }
- }
- /**
- * array_reduce() callback to collect namespaces from file entities.
- *
- * @param string[] $accu
- * @param \Drupal\file\Entity\File $fileItem
- *
- * @return string[]
- *
- * @see \Drupal\reinstall\Dumper::dumpFiles()
- */
- protected static function namespacesReducer(array $accu, File $fileItem) {
- $uri = $fileItem->getFileUri();
- // Plain filenames without a namespace. Should not happen, but...
- if (FALSE === ($len = Unicode::strpos($uri, '://'))) {
- return $accu;
- };
- $namespace = Unicode::substr($uri, 0, $len);
- $accu[$namespace] = TRUE;
- return $accu;
- }
- }
|