From b2a229ddf4422aa804de688f02d539b68aae7bee Mon Sep 17 00:00:00 2001 From: Alan Stanley Date: Tue, 4 Feb 2020 14:16:36 -0400 Subject: [PATCH] added dir creation --- .../src/Controller/MediaSourceController.php | 43 ++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/modules/islandora_text_extraction/src/Controller/MediaSourceController.php b/modules/islandora_text_extraction/src/Controller/MediaSourceController.php index 5c16e4f5..f716dd0c 100644 --- a/modules/islandora_text_extraction/src/Controller/MediaSourceController.php +++ b/modules/islandora_text_extraction/src/Controller/MediaSourceController.php @@ -3,9 +3,11 @@ namespace Drupal\islandora_text_extraction\Controller; use Drupal\Core\Controller\ControllerBase; +use Symfony\Component\DependencyInjection\ContainerInterface; use Drupal\media\Entity\Media; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Drupal\Core\File\FileSystem; /** * Class MediaSourceController. @@ -30,6 +32,41 @@ class MediaSourceController extends ControllerBase { * @throws \Drupal\Core\Entity\EntityStorageException * @throws \Drupal\Core\TypedData\Exception\ReadOnlyException */ + + /** + * File system service. + * + * @var \Drupal\Core\File\FileSystem + */ + protected $fileSystem; + + /** + * MediaSourceController constructor. + * + * @param \Drupal\Core\File\FileSystem + * Filesystem service. + */ + + + public function __construct(FileSystem $fileSystem) { + $this->fileSystem = $fileSystem; + } + + /** + * Controller's create method for dependency injection. + * + * @param \Symfony\Component\DependencyInjection\ContainerInterface $container + * The App Container. + * + * @return \Drupal\islandora\Controller\MediaSourceController + * Controller instance. + */ + public static function create(ContainerInterface $container) { + return new static( + $container->get('file_system') + ); + } + public function attachToMedia( Media $media, string $destination_field, @@ -39,6 +76,10 @@ class MediaSourceController extends ControllerBase { $contents = $request->getContent(); if ($contents) { + $directory = $this->fileSystem->dirname($content_location); + if (!file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) { + throw new HttpException(500, "The destination directory does not exist, could not be created, or is not writable"); + } $file = file_save_data($contents, $content_location, FILE_EXISTS_REPLACE); if ($media->hasField($destination_field)) { $media->{$destination_field}->setValue([ @@ -51,7 +92,7 @@ class MediaSourceController extends ControllerBase { if ($media->hasField($destination_text_field)) { $media->{$destination_text_field}->setValue(nl2br($contents)); } - else{ + else { $this->getLogger('islandora')->warning("Field $destination_text_field is not defined in Media Type {$media->bundle()}"); } $media->save();