-
-
Save briantully/86090ca31918fa85e24c22ed0c864c0e 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