From 985a4ceaddae0e5391629de228b201948080cd99 Mon Sep 17 00:00:00 2001 From: Ashley Rich Date: Sun, 12 Nov 2017 21:07:48 +0000 Subject: [PATCH] Lock an attachment to prevent multiple queue jobs being created --- src/Image_Processing_Queue/Queue.php | 42 +++++++++++++++++++++++ src/Image_Processing_Queue/Resize_Job.php | 2 ++ 2 files changed, 44 insertions(+) diff --git a/src/Image_Processing_Queue/Queue.php b/src/Image_Processing_Queue/Queue.php index cff812e..3e0dd57 100644 --- a/src/Image_Processing_Queue/Queue.php +++ b/src/Image_Processing_Queue/Queue.php @@ -100,6 +100,12 @@ public function filter_update_post_metadata( $check, $object_id, $meta_key, $met * @param array $sizes */ protected function process_image( $post_id, $sizes ) { + if ( self::is_attachment_locked( $post_id ) ) { + return; + } + + $lock_attachment = false; + foreach ( $sizes as $size ) { if ( self::does_size_already_exist_for_image( $post_id, $size ) ) { continue; @@ -117,6 +123,12 @@ protected function process_image( $post_id, $sizes ) { ); wp_queue()->push( new Resize_Job( $item ) ); + + $lock_attachment = true; + } + + if ( $lock_attachment ) { + self::lock_attachment( $post_id ); } } @@ -250,4 +262,34 @@ public static function is_size_larger_than_original( $post_id, $size ) { return false; } + + /** + * Is an attachment locked? + * + * @param int $post_id + * + * @return bool + */ + public static function is_attachment_locked( $post_id ) { + $image_meta = self::get_image_meta( $post_id ); + + if ( isset( $image_meta['ipq_locked'] ) && $image_meta['ipq_locked'] ) { + return true; + } + + return false; + } + + /** + * Lock an attachment to prevent multiple queue jobs being created. + * + * @param int $post_id + */ + public static function lock_attachment( $post_id ) { + $image_meta = self::get_image_meta( $post_id ); + + $image_meta['ipq_locked'] = true; + + wp_update_attachment_metadata( $post_id, $image_meta ); + } } diff --git a/src/Image_Processing_Queue/Resize_Job.php b/src/Image_Processing_Queue/Resize_Job.php index f740f27..5adcf07 100644 --- a/src/Image_Processing_Queue/Resize_Job.php +++ b/src/Image_Processing_Queue/Resize_Job.php @@ -80,6 +80,8 @@ public function handle() { 'height' => $resized_file['height'], 'mime-type' => $resized_file['mime-type'], ); + + unset( $image_meta['ipq_locked'] ); wp_update_attachment_metadata( $post_id, $image_meta ); }