From cb396c8fe0175c4258726dda142ccf1c4aa2c5c4 Mon Sep 17 00:00:00 2001 From: Yeni Atencio Date: Tue, 22 Oct 2024 10:08:58 +1100 Subject: [PATCH] moving from content-vic and adding drush services file --- drush.services.yml | 7 ++ src/Commands/TideDeleteOrphanedParagraphs.php | 74 +++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 drush.services.yml create mode 100644 src/Commands/TideDeleteOrphanedParagraphs.php diff --git a/drush.services.yml b/drush.services.yml new file mode 100644 index 00000000..3cd5a78e --- /dev/null +++ b/drush.services.yml @@ -0,0 +1,7 @@ +services: + delete_orphaned_paragraphs_test.commands: + class: Drupal\tide_core\Commands\TideDeleteOrphanedParagraphsTest + arguments: ['@keyvalue'] + tags: + - { name: drush.command } + diff --git a/src/Commands/TideDeleteOrphanedParagraphs.php b/src/Commands/TideDeleteOrphanedParagraphs.php new file mode 100644 index 00000000..24252746 --- /dev/null +++ b/src/Commands/TideDeleteOrphanedParagraphs.php @@ -0,0 +1,74 @@ +keyValue = $keyValue; + } + + /** + * Delete orphaned paragraphs. + * + * @param int $limit + * The maximum number of paragraphs to process. + * + * @param string $number_days_ago + * The number of days to purge the data. + * @command tide_core:delete-orphaned-paragraphs-test + * @aliases dop + * @usage tide_core:delete-orphaned-paragraphs-test 5 + */ + public function deleteOrphanedParagraphsTest($limit = 5, $number_days_ago = '-90 days') + { + $kv = $this->keyValue->get('delete-orphaned-paragraphs-test'); + $last_checked_p_id = $kv->get('last_checked_p_id', 0); + $thirty_days_ago = strtotime($number_days_ago); + $database = \Drupal::database() + ->select('paragraphs_item_field_data', 'p') + ->fields('p', ['id']) + ->where("p.id > :last_checked_p_id", [':last_checked_p_id' => $last_checked_p_id]) + ->where("p.created < :thirty_days_ago", [':thirty_days_ago' => $thirty_days_ago]) + ->orderBy("p.id") + ->range(0, $limit); + $results = $database->execute(); + $paragraph_ids = $results->fetchCol(); + if (empty($paragraph_ids)) { + $this->output()->writeln('No paragraphs found.'); + return; + } + + foreach ($paragraph_ids as $paragraph_id) { + $paragraph_entity = Paragraph::load($paragraph_id); + if ($paragraph_entity instanceof Paragraph && $paragraph_entity->getParentEntity() === NULL) { + $paragraph_entity->delete(); + $this->output()->writeln('Paragraphs deleted.'); + } + } + $kv->set('last_checked_p_id', max($paragraph_ids)); + } +}