Fermer

novembre 28, 2022

Utilisez la commande Drush avec Batch pour mettre à jour Node


Dans ce tutoriel, nous allons apprendre à créer/mettre à jour des nœuds à l’aide de la commande Drush en utilisant l’API Batch dans Drupal. Pour cela, nous devons créer un module personnalisé. La structure du fichier sera comme ci-dessous :

Exemple : Dans l’exemple ci-dessous, nous mettons à jour le type de contenu de l’article Titre champ avec une valeur fictive en le divisant en morceaux de 100, vous pouvez également ajouter votre propre logique.

Pour créer un module personnalisé, suivez les étapes ci-dessous, ce qui vous aidera à créer une commande Drush personnalisée. mise à jour : article sur le nœud.

  1. Créer BatchDrushCommand.php fichier sous le dossier module personnalisé/commandes.
    <?php
    
    namespace Drupal\module_name\Commands;
    
    use Drupal\Core\Entity\EntityTypeManagerInterface;
    
    use Drupal\Core\Logger\LoggerChannelFactoryInterface;
    
    use Drush\Commands\DrushCommands;
    
    /**
    
    * A Drush commandfile for defining the command and callback method to it.
    
    */
    
    class BatchDrushCommand extends DrushCommands {
    
    /**
    
    * Entity type service.
    
    *
    
    * @var \Drupal\Core\Entity\EntityTypeManagerInterface
    
    */
    
    private $entityTypeManager;
    
    /**
    
    * Logger service.
    
    *
    
    * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
    
    */
    
    private $loggerChannelFactory;
    
    /**
    
    *
    
    * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
    
    * Entity type service.
    
    * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $loggerChannelFactory
    
    * Logger service.
    
    */
    
    public function__construct(EntityTypeManagerInterface$entityTypeManager, LoggerChannelFactoryInterface$loggerChannelFactory) {
    
    $this->entityTypeManager = $entityTypeManager;
    
    $this->loggerChannelFactory = $loggerChannelFactory;
    
    }
    
    /**
    
    * Update Node.
    
    *
    
    * @param string $type
    
    * Type of node to update
    
    * Argument provided to the drush command.
    
    *
    
    * @command update:node
    
    * @aliases update-node
    
    *
    
    * @usage update:node article
    
    */
    
    public functionupdateNode($type="") {
    
    // 1. Log the start of the script.
    
    $this->loggerChannelFactory->get('module_name')->info('node update started');
    
    // Check the type of node given as argument, if not, set article as default.
    
    if (strlen($type) == 0) {
    
    $type="article";
    
    }
    
    // 2. Retrieve all nodes of this type.
    
    try {
    
    $storage = $this->entityTypeManager->getStorage('node');
    
    $query = $storage->getQuery()
    
    ->condition('type', $type)
    
    ->condition('status', '1');
    
    $nidsCount = $query->execute();
    
    $nidsCount = count($nidsCount);
    
    }
    
    catch (\Exception$e) {
    
    $this->output()->writeln($e);
    
    $this->loggerChannelFactory->get('module_name')->warning('Error found @e', ['@e' => $e]);
    
    }
    
    // 3. Create the operations array for the batch.
    
    $operations = [];
    
    $numOperations = 0;
    
    $batchId = 1;
    
    if ($nidsCount > 0) {
    
    for ($i = 0; $i < $nidsCount;) {
    
    $query = $storage->getQuery()
    
    ->condition('type', $type)
    
    ->range($i, 100)
    
    ->condition('status', '1');
    
    $nids = $query->execute();
    
    $articleId = array_keys($nids);
    
    $operations[] = [
    
    '\Drupal\module_name\UpdateNode::articleUpdate',
    
    [
    
    $batchId, $articleId,
    
    ],
    
    ];
    
    $batchId++;
    
    $numOperations++;
    
    $i = $i + 100;
    
    }
    
    }
    
    else {
    
    $this->logger()->warning('No nodes of this type @type', ['@type' => $type]);
    
    }
    
    // 4. Create the batch.
    
    $batch = [
    
    'title' => t('Updating @num node(s)', ['@num' => $numOperations]),
    
    'operations' => $operations,
    
    'finished' => '\Drupal\module_name\UpdateNode::articleUpdateFinished',
    
    ];
    
    // 5. Add batch operations as new batch sets.
    
    batch_set($batch);
    
    // 6. Process the batch sets.
    
    drush_backend_batch_process();
    
    }
    
    }
  2.  Create a Helper File named UpdateNode.php in which we will write the articleUpdate and articleUpdateFinished function 
    <?php
    
    namespace Drupal\module_name;
    
    /**
    
    * Class RevisionBatchProcess.
    
    */
    
    class UpdateNode {
    
    /**
    
    * articleUpdate callback.
    
    */
    
    public function articleUpdate($id, $articleId, &$context) {
    
    foreach ($articleId as $nid) {
    
    // Simulate long process by waiting 100 microseconds.
    
    usleep(100);
    
    $entityService = \Drupal::entityTypeManager();
    
    $articleObject = $entityService->getStorage('node')->loadRevision($nid);
    
    $articleObject->set('title', 'update-title');
    
    $articleObject->save();
    
    $context['results'][] = $id;
    
    $context['message'] = t('processing "@id" @response',
    
    ['@id' => $id, '@response' => $nid]
    
    );
    
    }
    
    }
    
    /**
    
    * articleUpdateFinished callback.
    
    */
    
    public function articleUpdateFinished($success, array $results, array $operations) {
    
    $messenger = \Drupal::messenger();
    
    if ($success) {
    
    $messenger->addMessage(t('@count results processed.', ['@count' => count($results)]));
    
    }
    
    }
    
    }

    Une fois le code ajouté au module, activez le module ou si vous utilisez le module existant, puis videz le cache Drupal et exécutez le mise à jour drush : article sur les nœuds
    commande.

    Veuillez ajouter des commentaires si vous avez des questions ou des doutes.

TROUVÉ CELA UTILE ? PARTAGEZ-LE




Source link

novembre 28, 2022