fox-1.1.2/src/Plugin/FoxCommand/FoxCommandAppend.php
src/Plugin/FoxCommand/FoxCommandAppend.php
<?php
namespace Drupal\fox\Plugin\FoxCommand;
use Drupal\Component\Serialization\Json;
use Drupal\fox\FoxCommandsHelper as Helper;
/**
* APPEND fox command.
*
* @FoxCommand(
* id = "append",
* label = @Translation("Append record with fields. Usage: APPEND [uField1 WITH eExpr1 [, uField2 WITH eExpr2]]")
* )
*/
class FoxCommandAppend 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();
// Create entity.
$entity_param = [];
$bundle_key = $helper->entityKey($entity_type, 'bundle');
if (!empty($bundle_key)) {
$bundle = $variables['bundle'] ?? NULL;
if (empty($bundle)) {
return $this->errorReturn($this->t('Empty bundle. Use USE command.'));
}
$entity_param[$bundle_key] = $bundle;
}
$entity = $helper->entityTypeManager()
->getStorage($entity_type)
->create($entity_param);
// Set fields.
if (!empty($params)) {
$bundle = $variables['bundle'] ?? NULL;
$fields = $helper->getFields($entity);
$items = Helper::prepareParameters($params);
foreach ($items as $item) {
$value = explode(' ', trim($item));
if (count($value) < 3) {
return $this->errorReturn($this->t('Bad APPEND format'));
}
$field = array_shift($value);
if (empty($fields[$field])) {
return $this->errorReturn($this->t('Wrong field @field', ['@field' => $field]));
}
$with = array_shift($value);
$with = strtolower($with);
if ($with !== 'with') {
return $this->errorReturn($this->t('There is no WITH part'));
}
try {
$value = Helper::prepareValue($value);
$replace = Json::decode($value) ?? $value;
$replace = $helper->stringRender($replace, $variables);
$entity->set($field, $replace);
}
catch (\Exception $e) {
return $this->errorReturn($e->getMessage());
}
}
}
try {
$entity->save();
}
catch (\Exception $e) {
return $this->errorReturn($e->getMessage());
}
// Get count.
$query = $helper->getEntityQuery($entity_type, $bundle ?? NULL);
$count = $query
->count()
->execute();
return [
'message' => $this->t('Appended'),
'variables' => [
'id' => $entity->id(),
'recno' => NULL,
'count' => $count,
],
];
}
}
