fox-1.1.2/src/Plugin/FoxCommand/FoxCommandDelete.php
src/Plugin/FoxCommand/FoxCommandDelete.php
<?php
namespace Drupal\fox\Plugin\FoxCommand;
use Drupal\fox\FoxCommandsHelper as Helper;
/**
* DELETE fox command.
*
* @FoxCommand(
* id = "delete",
* label = @Translation("Delete context record. Usage: DELETE")
* )
*/
class FoxCommandDelete extends FoxCommandBaseClass {
/**
* {@inheritdoc}
*/
public function execute(array $params, array $variables, array $options): array {
$entity_type = $variables['entity_type'] ?? NULL;
if (empty($entity_type)) {
return $this->errorReturn($this->t('Empty entity type. Use USE command.'));
}
$helper = $this->foxCommandsHelper();
[, $additional_params] = Helper::parseParameters('loop', $params);
if (!empty($additional_params)) {
$data = reset($additional_params);
$data = Helper::prepareValue($data);
$data = $helper->stringRender($data, $variables);
if (is_array($data)) {
$entities = $helper->getEntities($data, $variables);
if (isset($entities['error'])) {
return $this->errorReturn($entities['error']);
}
foreach ($entities as $entity) {
$this->delete($entity);
}
$deleted = count($entities);
}
else {
return $this->errorReturn($this->t('Loop data is not array'));
}
}
else {
$entity = $helper->getEntity($variables);
if (is_array($entity) and isset($entity['error'])) {
return $entity;
}
if (empty($entity)) {
return $this->errorReturn($this->t('Empty entity'));
}
$this->delete($entity);
$deleted = 1;
}
// Get count.
$query = $helper->getEntityQuery($entity_type);
$count = $query
->count()
->execute();
return [
'message' => $this->t('Deleted entities: @cnt', [
'@cnt' => $deleted,
]),
'variables' => [
'id' => NULL,
'recno' => NULL,
'count' => $count,
],
];
}
/**
* Delete entity.
*
* @param object $entity
* Entity for deleting.
*/
protected function delete($entity) {
try {
$entity->delete();
}
catch (\Exception $e) {
return $this->errorReturn($e->getMessage());
}
}
}
