<?php

//
// This example demonstrates how to write a drush
// script. These scripts are run with the php:script command.
//
use Drush\Drush;

// $this->output()->writeln("Hello world!");
// $this->output()->writeln("The extra options/arguments to this command were:");
// $this->output()->writeln(print_r($extra, true));

//
// We can check which site was bootstrapped via
// the '@self' alias, which is defined only if
// there is a bootstrapped site.
//
$self = Drush::aliasManager()->getSelf();;
if (!$self->hasRoot()) {
  $this->output()->writeln('No bootstrapped site.');
}
else {
  $this->output()->writeln('The following site is bootstrapped:');
  $this->output()->writeln(print_r($self->legacyRecord(), true));
  
  // $nids = \Drupal::entityQuery('node')->condition('type','projet')->execute();
  $nodes = \Drupal::entityTypeManager()->getStorage('node')
    ->loadByProperties(['type' => 'projet']);
  
  foreach ($nodes as $nid => $node) {
    /** @var Drupal\file\Plugin\Field\FieldType\FileFieldItemList $field_photo */
    $field_photo = $node->get('field_photo');
    $itemlist = $field_photo->getValue();
    /** @var Drupal\image_field_caption\ImageCaptionItem $field_item */
    foreach ($itemlist as $key => $field_item) {
      if (!empty($field_item['alt']) && (!isset($field_item['caption']) || empty($field_item['caption']))) {
        $field_item['image_field_caption']['value'] = $field_item['alt'];
        $field_item['image_field_caption']['format'] = 'plain_text';
        $itemlist[$key] = $field_item;
      }
    }
    // $field_photo->setValue($itemlist);
    $node->set('field_photo', $itemlist);
    $node->save();
  }
}

