Last active
January 21, 2021 18:44
-
-
Save alexku/e418c11276fa893b47808f2f10c95cba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Implements hook_ENTITY_TYPE_presave(). | |
*/ | |
function [modulename]_media_media_presave(EntityInterface $entity) { | |
if ($entity->bundle() == 'document') { | |
foreach ($entity->field_media_file as $file_reference) { | |
$file = File::load($file_reference->target_id); | |
switch ($entity->status->value) { | |
// Unpublish, set to private. | |
case 0: | |
$old_fs = 'public://'; | |
$new_fs = 'private://'; | |
break; | |
// Publish, set to public. | |
case 1: | |
$old_fs = 'private://'; | |
$new_fs = 'public://'; | |
break; | |
} | |
$new_uri = str_replace($old_fs, $new_fs, $file->getFileUri()); | |
// Ensure directory exists. | |
$directory = substr($new_uri, 0, strrpos($new_uri, '/')); | |
if (!is_dir($directory)) { | |
\Drupal::service('file_system')->mkdir($directory, NULL, TRUE); | |
} | |
// Move the file to the proper directory. | |
file_move($file, $new_uri); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment