ispim-1.0.x-dev/src/Commands/PreviewImageCommands.php
src/Commands/PreviewImageCommands.php
<?php
declare(strict_types=1);
namespace Drupal\ispim\Commands;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\file\FileInterface;
use Drupal\file\FileRepositoryInterface;
use Drupal\ispim\Entity\IspimPreviewImageInterface;
use Drush\Attributes\Argument as CliArgument;
use Drush\Attributes\Bootstrap as CliBootstrap;
use Drush\Attributes\Command as CliCommand;
use Drush\Attributes\Help as CliHelp;
use Drush\Attributes\Usage as CliUsage;
use Drush\Boot\DrupalBootLevels;
use Drush\Commands\DrushCommands;
use Robo\Collection\CollectionBuilder;
use Robo\Collection\Tasks as CollectionTaskLoader;
use Robo\Common\BuilderAwareTrait;
use Robo\Contract\BuilderAwareInterface;
use Robo\Contract\TaskInterface;
use Robo\TaskAccessor;
class PreviewImageCommands extends DrushCommands implements BuilderAwareInterface {
use TaskAccessor;
use BuilderAwareTrait;
use CollectionTaskLoader;
public function __construct(
protected EntityTypeManagerInterface $entityTypeManager,
protected EntityFieldManagerInterface $entityFieldManager,
protected FileRepositoryInterface $fileRepository,
) {
parent::__construct();
}
/**
* @param array<string> $images
*/
#[CliCommand(name: 'ispim:preview-image:import')]
#[CliHelp(
description: 'Import images.',
)]
#[CliBootstrap(level: DrupalBootLevels::FULL)]
#[CliArgument(
name: 'images',
description: 'Variadic arguments. Image file paths',
)]
#[CliUsage(
name: 'Import all images from a directory in one go with ZSH shell',
description: <<< 'SHELL'
images=$(find /path/to/images/ -type f) ; drush ispim:preview-image:import "${(f)images}"
SHELL
)]
#[CliUsage(
name: 'Import all images from a directory one-by-one with xargs',
description: <<< 'SHELL'
find /path/to/images/ -type f | xargs -I{} drush ispim:preview-image:import {}"
SHELL
)]
public function cmdImportExecute(array $images): TaskInterface {
$valuesList = [];
foreach ($images as $weight => $imagePathName) {
$valuesList[$imagePathName] = [
'label' => pathinfo($imagePathName, \PATHINFO_BASENAME),
'weight' => $weight,
'image' => $imagePathName,
'uid' => 1,
];
}
// @phpstan-ignore-next-line
$taskForEach = $this
->taskForEach()
->setIterable($valuesList)
->iterationMessage('Import {key} as ispim_preview_image')
->withBuilder(
function (CollectionBuilder $builder, string $imagePathName, $values): void {
$builder
->addCode(function () use ($imagePathName, $values): int {
try {
$previewImage = $this->createIspimPreviewImage($values);
$violation = $previewImage->validate();
if ($violation->count() > 0) {
$this->logger()->error(
'Validation failed for image: @image',
[
'@image' => $imagePathName,
],
);
return 1;
}
$previewImage->save();
}
catch (\Exception $exception) {
$this->logger()->error($exception->getMessage());
return 1;
}
return 0;
});
}
);
return $this
->collectionBuilder()
->addTask($taskForEach);
}
/**
* @param array<string, mixed> $values
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
* @throws \Drupal\Core\Entity\EntityStorageException
*/
protected function createIspimPreviewImage(array $values): IspimPreviewImageInterface {
$image = $this->createFile(
$values['image'],
$this
->entityFieldManager
->getBaseFieldDefinitions('ispim_preview_image')['image'],
);
$values['image'] = [
'target_id' => $image->id(),
'alt' => $values['label'] ?? $image->getFilename(),
'title' => $values['label'] ?? $image->getFilename(),
];
/** @var \Drupal\ispim\Entity\IspimPreviewImageInterface $previewImage */
$previewImage = $this
->entityTypeManager
->getStorage('ispim_preview_image')
->create($values);
return $previewImage;
}
/**
* @throws \Drupal\Core\Entity\EntityStorageException
*/
protected function createFile(string $pathName, FieldDefinitionInterface $field): FileInterface {
// @todo Token replace.
return $this->fileRepository->writeData(
file_get_contents($pathName) ?: '',
sprintf(
'%s://%s/%s',
$field->getSetting('uri_scheme'),
$field->getSetting('file_directory'),
pathinfo($pathName, \PATHINFO_BASENAME),
),
);
}
}
