Skip to content

Instantly share code, notes, and snippets.

@briantully
Forked from alexku/media_publish_unpublish
Created January 21, 2021 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save briantully/86090ca31918fa85e24c22ed0c864c0e to your computer and use it in GitHub Desktop.
Save briantully/86090ca31918fa85e24c22ed0c864c0e to your computer and use it in GitHub Desktop.
/**
* 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