mass update actions

This commit is contained in:
Yuri Kuznetsov
2022-05-10 14:53:21 +03:00
parent 9e047650e8
commit f511553ff1
18 changed files with 1411 additions and 394 deletions
@@ -29,40 +29,54 @@
namespace Espo\Classes\MassAction\User;
use Espo\Core\{
MassAction\Actions\MassUpdate as MassUpdateOriginal,
MassAction\QueryBuilder,
MassAction\Params,
MassAction\Result,
MassAction\Data,
MassAction\MassAction,
Utils\File\Manager as FileManager,
DataManager,
Acl,
ORM\EntityManager,
Exceptions\Forbidden,
};
use Espo\Core\MassAction\Actions\MassUpdate as MassUpdateOriginal;
use Espo\Core\MassAction\QueryBuilder;
use Espo\Core\MassAction\Params;
use Espo\Core\MassAction\Result;
use Espo\Core\MassAction\Data;
use Espo\Core\MassAction\MassAction;
use Espo\Core\Utils\File\Manager as FileManager;
use Espo\Core\DataManager;
use Espo\Core\Acl;
use Espo\Core\Acl\Table;
use Espo\{
Entities\User,
ORM\Entity,
};
use Espo\Core\Exceptions\Forbidden;
use Espo\Entities\User;
use Espo\ORM\Entity;
use Espo\ORM\EntityManager;
use Espo\Tools\MassUpdate\Data as MassUpdateData;
class MassUpdate implements MassAction
{
private $massUpdateOriginal;
private MassUpdateOriginal $massUpdateOriginal;
private $queryBuilder;
private QueryBuilder $queryBuilder;
private $entityManager;
private EntityManager $entityManager;
private $acl;
private Acl $acl;
private $user;
private User $user;
private $fileManager;
private FileManager $fileManager;
private $dataManager;
private DataManager $dataManager;
private const PERMISSION = 'massUpdatePermission';
private const SYSTEM_USER_ID = 'system';
/** @var string[] */
private array $notAllowedAttributeList = [
'type',
'password',
'emailAddress',
'isAdmin',
'isSuperAdmin',
'isPortalUser',
];
public function __construct(
MassUpdateOriginal $massUpdateOriginal,
@@ -86,48 +100,54 @@ class MassUpdate implements MassAction
{
$entityType = $params->getEntityType();
if (!$this->acl->check($entityType, 'edit')) {
if (!$this->user->isAdmin()) {
throw new Forbidden("Only admin can mass-update users.");
}
if (!$this->acl->check($entityType, Table::ACTION_EDIT)) {
throw new Forbidden("No edit access for '{$entityType}'.");
}
if ($this->acl->get('massUpdatePermission') !== 'yes') {
if ($this->acl->get(self::PERMISSION) !== Table::LEVEL_YES) {
throw new Forbidden("No mass-update permission.");
}
if (
$data->has('type') ||
$data->has('password') ||
$data->has('emailAddress') ||
$data->has('isAdmin') ||
$data->has('isSuperAdmin') ||
$data->has('isPortalUser')
) {
throw new Forbidden("Not allowed fields.");
}
$massUpdateData = MassUpdateData::fromMassActionData($data);
$this->checkAccess($massUpdateData);
$query = $this->queryBuilder->build($params);
$collection = $this->entityManager
->getRDBRepository('User')
->getRDBRepository(User::ENTITY_TYPE)
->clone($query)
->sth()
->select(['id'])
->find();
foreach ($collection as $entity) {
$this->checkEntity($entity, $data);
$this->checkEntity($entity, $massUpdateData);
}
$result = $this->massUpdateOriginal->process($params, $data);
$this->afterProcess($result, $data);
$this->afterProcess($result, $massUpdateData);
return $result;
}
protected function checkEntity(Entity $entity, Data $data): void
private function checkAccess(MassUpdateData $data): void
{
if ($entity->getId() === 'system') {
foreach ($this->notAllowedAttributeList as $attribute) {
if ($data->has($attribute)) {
throw new Forbidden("Attribute '{$attribute}' not allowed for mass-update.");
}
}
}
private function checkEntity(Entity $entity, MassUpdateData $data): void
{
if ($entity->getId() === self::SYSTEM_USER_ID) {
throw new Forbidden("Can't update 'system' user.");
}
@@ -138,9 +158,9 @@ class MassUpdate implements MassAction
}
}
protected function afterProcess(Result $result, Data $dataWrapped): void
private function afterProcess(Result $result, MassUpdateData $dataWrapped): void
{
$data = $dataWrapped->getRaw();
$data = $dataWrapped->getValues();
if (
property_exists($data, 'rolesIds') ||
@@ -168,12 +188,12 @@ class MassUpdate implements MassAction
}
}
protected function clearRoleCache(string $id): void
private function clearRoleCache(string $id): void
{
$this->fileManager->removeFile('data/cache/application/acl/' . $id . '.php');
}
protected function clearPortalRolesCache(): void
private function clearPortalRolesCache(): void
{
$this->fileManager->removeInDir('data/cache/application/aclPortal');
}
@@ -29,278 +29,27 @@
namespace Espo\Core\MassAction\Actions;
use Espo\Repositories\Attachment as AttachmentRepository;
use Espo\Tools\MassUpdate\Processor;
use Espo\Tools\MassUpdate\Data as MassUpdateData;
use Espo\Entities\User;
use Espo\Core\{
MassAction\QueryBuilder,
MassAction\Params,
MassAction\Result,
MassAction\Data,
MassAction\MassAction,
Acl,
Record\ServiceFactory as RecordServiceFactory,
ORM\EntityManager,
Utils\FieldUtil,
Utils\ObjectUtil,
Exceptions\Forbidden,
};
use Exception;
use stdClass;
use Espo\Core\MassAction\Params;
use Espo\Core\MassAction\Result;
use Espo\Core\MassAction\Data;
use Espo\Core\MassAction\MassAction;
class MassUpdate implements MassAction
{
/**
* @var QueryBuilder
*/
protected $queryBuilder;
private Processor $processor;
/**
* @var Acl
*/
protected $acl;
/**
* @var RecordServiceFactory
*/
protected $recordServiceFactory;
/**
* @var EntityManager
*/
protected $entityManager;
/**
* @var FieldUtil
*/
protected $fieldUtil;
/**
* @var User
*/
private $user;
public function __construct(
QueryBuilder $queryBuilder,
Acl $acl,
RecordServiceFactory $recordServiceFactory,
EntityManager $entityManager,
FieldUtil $fieldUtil,
User $user
) {
$this->queryBuilder = $queryBuilder;
$this->acl = $acl;
$this->recordServiceFactory = $recordServiceFactory;
$this->entityManager = $entityManager;
$this->fieldUtil = $fieldUtil;
$this->user = $user;
public function __construct(Processor $processor)
{
$this->processor = $processor;
}
public function process(Params $params, Data $data): Result
{
$entityType = $params->getEntityType();
$massUpdateData = MassUpdateData::fromMassActionData($data);
if (!$this->acl->check($entityType, 'edit')) {
throw new Forbidden("No edit access for '{$entityType}'.");
}
if ($this->acl->get('massUpdatePermission') !== 'yes') {
throw new Forbidden("No mass-update permission.");
}
$valueMap = $data->getRaw();
$service = $this->recordServiceFactory->create($entityType);
$repository = $this->entityManager->getRDBRepository($entityType);
$service->filterUpdateInput($valueMap);
$fieldToCopyList = $this->detectFieldToCopyList($entityType, $valueMap);
$query = $this->queryBuilder->build($params);
$collection = $repository
->clone($query)
->sth()
->find();
$ids = [];
$count = 0;
foreach ($collection as $i => $entity) {
if (!$this->acl->check($entity, 'edit')) {
continue;
}
$itemValueMap = $this->prepareItemValueMap($entityType, $valueMap, $i, $fieldToCopyList);
$entity->set($itemValueMap);
try {
$service->processValidation($entity, $itemValueMap);
}
catch (Exception $e) {
continue;
}
if (!$service->checkAssignment($entity)) {
continue;
}
$repository->save($entity, [
'massUpdate' => true,
'skipStreamNotesAcl' => true,
'modifiedById' => $this->user->getId(),
]);
/** @var string */
$id = $entity->getId();
$ids[] = $id;
$count++;
$service->processActionHistoryRecord('update', $entity);
}
$result = [
'count' => $count,
'ids' => $ids,
];
return Result::fromArray($result);
}
/**
* @param string[] $fieldToCopyList
*/
protected function prepareItemValueMap(
string $entityType,
stdClass $valueMap,
int $i,
array $fieldToCopyList
): stdClass {
$clonedValueMap = ObjectUtil::clone($valueMap);
if (!count($fieldToCopyList)) {
return $clonedValueMap;
}
if ($i === 0) {
return $clonedValueMap;
}
foreach ($fieldToCopyList as $field) {
$type = $this->fieldUtil->getEntityTypeFieldParam($entityType, $field, 'type');
if ($type === 'file' || $type === 'image') {
$this->copyFileField($field, $clonedValueMap);
continue;
}
if ($type === 'attachmentMultiple') {
$this->copyAttachmentMultipleField($field, $clonedValueMap);
continue;
}
}
return $clonedValueMap;
}
protected function copyFileField(string $field, stdClass $valueMap): void
{
$idAttribute = $field . 'Id';
$id = $valueMap->$idAttribute ?? null;
if (!$id) {
return;
}
$attachment = $this->entityManager->getEntity('Attachment', $id);
if (!$attachment) {
$valueMap->$idAttribute = null;
return;
}
/** @var AttachmentRepository $attachmentRepository */
$attachmentRepository = $this->entityManager->getRepository('Attachment');
$copiedAttachment = $attachmentRepository->getCopiedAttachment($attachment);
$valueMap->$idAttribute = $copiedAttachment->getId();
}
protected function copyAttachmentMultipleField(string $field, stdClass $valueMap): void
{
$idsAttribute = $field . 'Ids';
$ids = $valueMap->$idsAttribute ?? [];
if (!count($ids)) {
return;
}
/** @var AttachmentRepository $attachmentRepository */
$attachmentRepository = $this->entityManager->getRepository('Attachment');
$copiedIds = [];
foreach ($ids as $id) {
$attachment = $this->entityManager->getEntity('Attachment', $id);
if (!$attachment) {
continue;
}
$copiedAttachment = $attachmentRepository->getCopiedAttachment($attachment);
$copiedIds[] = $copiedAttachment->getId();
}
$valueMap->$idsAttribute = $copiedIds;
}
/**
* @return string[]
*/
protected function detectFieldToCopyList(string $entityType, stdClass $valueMap): array
{
$resultFieldList = [];
$fieldList = array_merge(
$this->fieldUtil->getFieldByTypeList($entityType, 'file'),
$this->fieldUtil->getFieldByTypeList($entityType, 'image'),
$this->fieldUtil->getFieldByTypeList($entityType, 'attachmentMultiple')
);
foreach ($fieldList as $field) {
$actualAttributeList = $this->fieldUtil->getActualAttributeList($entityType, $field);
$met = false;
foreach ($actualAttributeList as $attribute) {
$value = $valueMap->$attribute ?? null;
if ($value) {
$met = true;
}
}
if ($met) {
$resultFieldList[] = $field;
}
}
return $resultFieldList;
return $this->processor->process($params, $massUpdateData);
}
}
@@ -90,6 +90,7 @@ class Result
}
/**
* @deprecated
* @param array{
* count?: ?int,
* ids?: ?string[],
@@ -35,38 +35,39 @@ use Espo\Core\MassAction\Result;
use Espo\Core\MassAction\Data;
use Espo\Core\MassAction\MassAction;
use Espo\Tools\MassUpdate\Data as MassUpdateData;
use Espo\Core\Utils\Metadata;
class MassUpdate implements MassAction
{
private $massUpdateOriginal;
private MassUpdateOriginal $massUpdateOriginal;
private $metadata;
private Metadata $metadata;
public function __construct(
MassUpdateOriginal $massUpdateOriginal,
Metadata $metadata
) {
public function __construct(MassUpdateOriginal $massUpdateOriginal, Metadata $metadata)
{
$this->massUpdateOriginal = $massUpdateOriginal;
$this->metadata = $metadata;
}
public function process(Params $params, Data $data): Result
{
$massUpdateData = MassUpdateData::fromMassActionData($data);
$probability = null;
if (
$data->get('stage') &&
!$data->has('probability')
) {
$stage = $massUpdateData->getValue('stage');
if ($stage && !$massUpdateData->has('probability')) {
$probability = $this->metadata
->get(['entityDefs', 'Opportunity', 'fields', 'stage', 'probabilityMap', $data->get('stage')]);
->get(['entityDefs', 'Opportunity', 'fields', 'stage', 'probabilityMap', $stage]);
}
if ($probability !== null) {
$data = $data->with('probability', $probability);
$massUpdateData = $massUpdateData->with('probability', $probability);
}
return $this->massUpdateOriginal->process($params, $data);
return $this->massUpdateOriginal->process($params, $massUpdateData->toMassActionData());
}
}
@@ -60,5 +60,6 @@
},
"translatedOptions": true,
"dynamicLogicOptions": true,
"personalData": true
"personalData": true,
"massUpdateActionList": ["update", "add", "remove"]
}
@@ -54,5 +54,6 @@
"notSortable": true,
"filter": true,
"personalData": true,
"duplicatorClassName": "Espo\\Classes\\FieldDuplicators\\AttachmentMultiple"
"duplicatorClassName": "Espo\\Classes\\FieldDuplicators\\AttachmentMultiple",
"massUpdateActionList": ["update", "add"]
}
@@ -35,5 +35,6 @@
"filter": true,
"valueFactoryClassName": "Espo\\Core\\Field\\LinkMultiple\\LinkMultipleFactory",
"attributeExtractorClassName": "Espo\\Core\\Field\\LinkMultiple\\LinkMultipleAttributeExtractor",
"duplicatorClassName": "Espo\\Classes\\FieldDuplicators\\LinkMultiple"
"duplicatorClassName": "Espo\\Classes\\FieldDuplicators\\LinkMultiple",
"massUpdateActionList": ["update", "add", "remove"]
}
@@ -67,5 +67,6 @@
},
"translatedOptions": true,
"dynamicLogicOptions": true,
"personalData": true
"personalData": true,
"massUpdateActionList": ["update", "add", "remove"]
}
@@ -0,0 +1,39 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM - Open Source CRM application.
* Copyright (C) 2014-2022 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko
* Website: https://www.espocrm.com
*
* EspoCRM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* EspoCRM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\MassUpdate;
class Action
{
public const UPDATE = 'update';
public const ADD = 'add';
public const REMOVE = 'remove';
}
+166
View File
@@ -0,0 +1,166 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM - Open Source CRM application.
* Copyright (C) 2014-2022 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko
* Website: https://www.espocrm.com
*
* EspoCRM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* EspoCRM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\MassUpdate;
use Espo\Core\MassAction\Data as ActionData;
use Espo\Core\Utils\ObjectUtil;
use RuntimeException;
use stdClass;
class Data
{
private stdClass $values;
/**
* @var array<string,Action::*>
*/
private array $actions;
/**
* @param array<string,Action::*> $actions
*/
private function __construct(stdClass $values, array $actions)
{
$this->values = $values;
$this->actions = $actions;
}
public function has(string $attribute): bool
{
return property_exists($this->values, $attribute);
}
/**
* @return string[]
*/
public function getAttributeList(): array
{
return array_keys(get_object_vars($this->values));
}
/**
* @return mixed
*/
public function getValue(string $attribute)
{
return $this->getValues()->$attribute ?? null;
}
public function getValues(): stdClass
{
return ObjectUtil::clone($this->values);
}
/**
* @return Action::*|null
*/
public function getAction(string $attribute): ?string
{
if (!$this->has($attribute)) {
return null;
}
return $this->actions[$attribute] ?? Action::UPDATE;
}
public static function create(): self
{
return new self((object) [], []);
}
public static function fromMassActionData(ActionData $data): self
{
$values = $data->get('values');
$rawActions = $data->get('actions');
// Backward compatibility.
if (!$data->has('values')) {
return new self($data->getRaw(), []);
}
if (!$values instanceof stdClass) {
throw new RuntimeException("No `values` in mass-action data.");
}
if ($rawActions !== null && !$rawActions instanceof stdClass) {
throw new RuntimeException("Bad `actions` in mass-action data.");
}
if ($rawActions === null) {
$rawActions = (object) [];
}
return new self($values, get_object_vars($rawActions));
}
/**
* @param mixed $value
* @param Action::*|null $action If NULL, the current action will be used. If no current, then 'update'.
*/
public function with(string $attribute, $value, ?string $action = null): self
{
if ($action === null) {
$action = $this->getAction($attribute) ?? Action::UPDATE;
}
$values = $this->getValues();
$actions = $this->actions;
$values->$attribute = $value;
$actions[$attribute] = $action;
return new self($values, $actions);
}
public function without(string $attribute): self
{
$values = $this->getValues();
$actions = $this->actions;
unset($values->$attribute);
unset($actions[$attribute]);
return new self($values, $actions);
}
public function toMassActionData(): ActionData
{
return ActionData::fromRaw((object) [
'values' => $this->getValues(),
'actions' => (object) $this->actions,
]);
}
public function __clone()
{
$this->values = ObjectUtil::clone($this->values);
}
}
@@ -0,0 +1,80 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM - Open Source CRM application.
* Copyright (C) 2014-2022 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko
* Website: https://www.espocrm.com
*
* EspoCRM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* EspoCRM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\MassUpdate;
use Espo\Core\MassAction\Params;
use Espo\Core\MassAction\Result;
use Espo\Core\MassAction\MassActionFactory;
use Espo\ORM\EntityManager;
use Espo\Entities\User;
use RuntimeException;
/**
* Entry point for the mass-update tool.
*/
class MassUpdate
{
private MassActionFactory $massActionFactory;
private EntityManager $entityManager;
private const ACTION = 'massUpdate';
private const DEFAULT_USER_ID = 'system';
public function __construct(MassActionFactory $massActionFactory, EntityManager $entityManager)
{
$this->massActionFactory = $massActionFactory;
$this->entityManager = $entityManager;
}
/**
* @param ?User $user Under what user to perform mass-update. If not specified, the system user will be used.
* Access control is applied for the user.
*/
public function process(Params $params, Data $data, ?User $user = null): Result
{
$entityType = $params->getEntityType();
if (!$user) {
$user = $this->entityManager->getEntityById(User::ENTITY_TYPE, self::DEFAULT_USER_ID);
}
if (!$user) {
throw new RuntimeException("No user.");
}
$action = $this->massActionFactory->createForUser(self::ACTION, $entityType, $user);
return $action->process($params, $data->toMassActionData());
}
}
@@ -0,0 +1,332 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM - Open Source CRM application.
* Copyright (C) 2014-2022 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko
* Website: https://www.espocrm.com
*
* EspoCRM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* EspoCRM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\MassUpdate;
use Espo\Core\MassAction\QueryBuilder;
use Espo\Core\MassAction\Params;
use Espo\Core\MassAction\Result;
use Espo\Core\Acl;
use Espo\Core\Acl\Table;
use Espo\Core\Record\ServiceFactory;
use Espo\Core\Record\Service;
use Espo\Core\Utils\FieldUtil;
use Espo\Core\Exceptions\Forbidden;
use Espo\ORM\EntityManager;
use Espo\ORM\Entity;
use Espo\Repositories\Attachment as AttachmentRepository;
use Espo\Entities\User;
use Espo\Entities\Attachment;
use Exception;
use RuntimeException;
use stdClass;
class Processor
{
private ValueMapPreparator $valueMapPreparator;
private QueryBuilder $queryBuilder;
private Acl $acl;
private ServiceFactory $serviceFactory;
private EntityManager $entityManager;
private FieldUtil $fieldUtil;
private User $user;
private const PERMISSION = 'massUpdatePermission';
public function __construct(
ValueMapPreparator $valueMapPreparator,
QueryBuilder $queryBuilder,
Acl $acl,
ServiceFactory $serviceFactory,
EntityManager $entityManager,
FieldUtil $fieldUtil,
User $user
) {
$this->valueMapPreparator = $valueMapPreparator;
$this->queryBuilder = $queryBuilder;
$this->acl = $acl;
$this->serviceFactory = $serviceFactory;
$this->entityManager = $entityManager;
$this->fieldUtil = $fieldUtil;
$this->user = $user;
}
public function process(Params $params, Data $data): Result
{
$entityType = $params->getEntityType();
if (!$this->acl->check($entityType, Table::ACTION_EDIT)) {
throw new Forbidden("No edit access for '{$entityType}'.");
}
if ($this->acl->get(self::PERMISSION) !== Table::LEVEL_YES) {
throw new Forbidden("No mass-update permission.");
}
$service = $this->serviceFactory->create($entityType);
$filteredData = $this->filterData($data, $service);
if ($filteredData->getAttributeList() === []) {
return new Result(0, []);
}
$copyFieldList = $this->detectFieldToCopyList($entityType, $filteredData);
$query = $this->queryBuilder->build($params);
$collection = $this->entityManager
->getRDBRepository($entityType)
->clone($query)
->sth()
->find();
$ids = [];
$count = 0;
foreach ($collection as $i => $entity) {
$itemResult = $this->processEntity($entity, $filteredData, $i, $copyFieldList, $service);
if (!$itemResult) {
continue;
}
$ids[] = $entity->getId();
$count++;
}
return new Result($count, $ids);
}
/**
* @param Service<Entity> $service
*/
private function filterData(Data $data, Service $service): Data
{
$filteredData = $data;
$values = $data->getValues();
$service->filterUpdateInput($values);
foreach ($data->getAttributeList() as $attribute) {
if (!property_exists($values, $attribute)) {
$filteredData = $filteredData->without($attribute);
continue;
}
$action = $filteredData->getAction($attribute) ?? Action::UPDATE;
$value = $values->$attribute;
$filteredData = $filteredData->with($attribute, $value, $action);
}
return $filteredData;
}
/**
* @param string[] $fieldToCopyList
* @param Service<Entity> $service
*/
private function processEntity(Entity $entity, Data $data, int $i, array $fieldToCopyList, Service $service): bool
{
if (!$this->acl->check($entity, Table::ACTION_EDIT)) {
return false;
}
$values = $this->prepareItemValueMap($entity, $data, $i, $fieldToCopyList);
$entity->set($values);
try {
$service->processValidation($entity, $values);
}
catch (Exception $e) {
return false;
}
if (!$service->checkAssignment($entity)) {
return false;
}
$this->entityManager->saveEntity($entity, [
'massUpdate' => true,
'skipStreamNotesAcl' => true,
'modifiedById' => $this->user->getId(),
]);
$service->processActionHistoryRecord('update', $entity);
return true;
}
/**
* @param string[] $copyFieldList
*/
private function prepareItemValueMap(Entity $entity, Data $data, int $i, array $copyFieldList): stdClass
{
$dataModified = $this->copy($entity->getEntityType(), $data, $i, $copyFieldList);
return $this->valueMapPreparator->prepare($entity, $dataModified);
}
/**
* @param string[] $copyFieldList
*/
private function copy(string $entityType, Data $data, int $i, array $copyFieldList): Data
{
if (!count($copyFieldList)) {
return $data;
}
if ($i === 0) {
return $data;
}
foreach ($copyFieldList as $field) {
$type = $this->fieldUtil->getEntityTypeFieldParam($entityType, $field, 'type');
if ($type === 'file' || $type === 'image') {
$data = $this->copyFileField($field, $data);
continue;
}
if ($type === 'attachmentMultiple') {
$data = $this->copyAttachmentMultipleField($field, $data);
continue;
}
}
return $data;
}
private function copyFileField(string $field, Data $data): Data
{
$attribute = $field . 'Id';
$id = $data->getValue($attribute);
if (!$id) {
return $data;
}
$attachment = $this->entityManager->getEntityById(Attachment::ENTITY_TYPE, $id);
if (!$attachment) {
return $data->with($attribute, null);
}
/** @var AttachmentRepository $attachmentRepository */
$attachmentRepository = $this->entityManager->getRepository(Attachment::ENTITY_TYPE);
$copiedAttachment = $attachmentRepository->getCopiedAttachment($attachment);
return $data->with($attribute, $copiedAttachment->getId());
}
private function copyAttachmentMultipleField(string $field, Data $data): Data
{
$attribute = $field . 'Ids';
$ids = $data->getValue($attribute) ?? [];
if (!is_array($ids)) {
throw new RuntimeException("Bad link-multiple-ids value.");
}
if (!count($ids)) {
return $data;
}
/** @var AttachmentRepository $attachmentRepository */
$attachmentRepository = $this->entityManager->getRepository(Attachment::ENTITY_TYPE);
$copiedIds = [];
foreach ($ids as $id) {
$attachment = $this->entityManager->getEntityById(Attachment::ENTITY_TYPE, $id);
if (!$attachment) {
continue;
}
$copiedIds[] = $attachmentRepository
->getCopiedAttachment($attachment)
->getId();
}
return $data->with($attribute, $copiedIds);
}
/**
* @return string[]
*/
private function detectFieldToCopyList(string $entityType, Data $data): array
{
$resultFieldList = [];
$fieldList = array_merge(
$this->fieldUtil->getFieldByTypeList($entityType, 'file'),
$this->fieldUtil->getFieldByTypeList($entityType, 'image'),
$this->fieldUtil->getFieldByTypeList($entityType, 'attachmentMultiple')
);
foreach ($fieldList as $field) {
$actualAttributeList = $this->fieldUtil->getActualAttributeList($entityType, $field);
$met = false;
foreach ($actualAttributeList as $attribute) {
if ($data->getValue($attribute)) {
$met = true;
}
}
if ($met) {
$resultFieldList[] = $field;
}
}
return $resultFieldList;
}
}
@@ -0,0 +1,254 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM - Open Source CRM application.
* Copyright (C) 2014-2022 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko
* Website: https://www.espocrm.com
*
* EspoCRM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* EspoCRM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\MassUpdate;
use Espo\ORM\Entity;
use Espo\ORM\Defs as OrmDefs;
use Espo\Core\ORM\Entity as CoreEntity;
use Espo\Core\Utils\ObjectUtil;
use stdClass;
class ValueMapPreparator
{
private OrmDefs $ormDefs;
public function __construct(OrmDefs $ormDefs)
{
$this->ormDefs = $ormDefs;
}
public function prepare(Entity $entity, Data $data): stdClass
{
$map = (object) [];
$this->loadAdditionalFields($entity, $data);
foreach ($data->getAttributeList() as $attribute) {
if ($data->getAction($attribute) === Action::UPDATE) {
$map->$attribute = $data->getValue($attribute);
continue;
}
if ($data->getValue($attribute) === null) {
continue;
}
if (!$entity->has($attribute)) {
continue;
}
if ($data->getAction($attribute) === Action::ADD) {
$map->$attribute = $this->prepareItemAdd($entity->get($attribute), $data->getValue($attribute));
continue;
}
if ($data->getAction($attribute) === Action::REMOVE) {
$map->$attribute = $this->prepareItemRemove($entity->get($attribute), $data->getValue($attribute));
continue;
}
}
return $map;
}
private function loadAdditionalFields(Entity $entity, Data $data): void
{
if (!$entity instanceof CoreEntity) {
return;
}
foreach ($data->getAttributeList() as $attribute) {
if ($entity->has($attribute)) {
continue;
}
if (
$entity->getAttributeParam($attribute, 'isLinkMultipleIdList') &&
$entity->getAttributeParam($attribute, 'relation')
) {
$field = $entity->getAttributeParam($attribute, 'relation');
$columns = $this->ormDefs
->getEntity($entity->getEntityType())
->getField($field)
->getParam('columns');
$entity->loadLinkMultipleField($field, $columns);
}
}
}
/**
* @param mixed $set
* @param mixed $ch
* @return mixed
*/
private function prepareItemAdd($set, $ch)
{
if ($set === null && $ch === null) {
return null;
}
if (is_array($set) || is_array($ch)) {
$set = $set ?? [];
$ch = $ch ?? [];
if (!is_array($set) || !is_array($ch)) {
return $set;
}
return $this->prepareItemAddArray($set, $ch);
}
if ($set instanceof stdClass || $ch instanceof stdClass) {
$set = $set ?? (object) [];
$ch = $ch ?? (object) [];
if (!$set instanceof stdClass || !$ch instanceof stdClass) {
return $set;
}
return $this->prepareItemAddObject($set, $ch);
}
return $set;
}
/**
* @param mixed[] $set
* @param mixed[] $ch
* @return mixed[]
*/
private function prepareItemAddArray(array $set, array $ch): array
{
if ($ch === []) {
return $set;
}
$result = $set;
foreach ($ch as $value) {
if (in_array($value, $result)) {
continue;
}
$result[] = $value;
}
return $result;
}
private function prepareItemAddObject(stdClass $set, stdClass $ch): stdClass
{
$result = ObjectUtil::clone($set);
foreach (get_object_vars($ch) as $key => $value) {
$result->$key = $value;
}
return $result;
}
/**
* @param mixed $set
* @param mixed $ch
* @return mixed
*/
private function prepareItemRemove($set, $ch)
{
if ($set === null && $ch === null) {
return null;
}
if (is_array($set) || is_array($ch)) {
$set = $set ?? [];
$ch = $ch ?? [];
if (!is_array($set) || !is_array($ch)) {
return $set;
}
return $this->prepareItemRemoveArray($set, $ch);
}
if ($set instanceof stdClass || $ch instanceof stdClass) {
$set = $set ?? (object) [];
$ch = $ch ?? (object) [];
if (!$set instanceof stdClass || !$ch instanceof stdClass) {
return $set;
}
return $this->prepareItemRemoveObject($set, $ch);
}
return $set;
}
/**
* @param mixed[] $set
* @param mixed[] $ch
* @return mixed[]
*/
private function prepareItemRemoveArray(array $set, array $ch): array
{
if ($ch === []) {
return $set;
}
$result = $set;
foreach ($result as $i => $value) {
if (!in_array($value, $ch)) {
continue;
}
unset($result[$i]);
}
return array_values($result);
}
private function prepareItemRemoveObject(stdClass $set, stdClass $ch): stdClass
{
$result = ObjectUtil::clone($set);
foreach (array_keys(get_object_vars($ch)) as $key) {
unset($result->$key);
}
return $result;
}
}
+1 -1
View File
@@ -29,7 +29,7 @@
{{/unless}}
<div>
<div class="fields-container grid-auto-fill-md"></div>
<div class="fields-container"></div>
</div>
</div>
+45 -1
View File
@@ -162,10 +162,54 @@
return _.union(
this.getAttributeList(type, field),
this.metadata.get(['entityDefs', entityType, 'fields', field, 'additionalAttributeList']) || []
this._getEntityTypeFieldAdditionalAttributeList(entityType, field)
);
},
getEntityTypeFieldActualAttributeList: function (entityType, field) {
let type = this.metadata.get(['entityDefs', entityType, 'fields', field, 'type']);
if (!type) {
return [];
}
return _.union(
this.getActualAttributeList(type, field),
this._getEntityTypeFieldAdditionalAttributeList(entityType, field)
);
},
_getEntityTypeFieldAdditionalAttributeList: function (entityType, field) {
let type = this.metadata.get(['entityDefs', entityType, 'fields', field, 'type']);
if (!type) {
return [];
}
let partList = this.metadata
.get(['entityDefs', entityType, 'fields', field, 'additionalAttributeList']) || [];
if (partList.length === 0) {
return [];
}
let isPrefix = (this.defs[type] || {}).naming === 'prefix';
let list = [];
partList.forEach(item => {
if (isPrefix) {
list.push(item + Espo.Utils.upperCaseFirst(field));
return;
}
list.push(field + Espo.Utils.upperCaseFirst(item));
});
return list;
},
getAttributeList: function (fieldType, fieldName) {
return _.union(
this.getActualAttributeList(fieldType, fieldName),
+153 -67
View File
@@ -38,6 +38,12 @@ define('views/modals/mass-update', ['views/modal', 'helpers/mass-action'], funct
layoutName: 'massUpdate',
ACTION_UPDATE: 'update',
ACTION_ADD: 'add',
ACTION_REMOVE: 'remove',
data: function () {
return {
scope: this.scope,
@@ -81,6 +87,8 @@ define('views/modals/mass-update', ['views/modal', 'helpers/mass-action'], funct
this.searchParams = this.options.searchParams;
this.byWhere = this.options.byWhere;
this.hasActionMap = {};
let totalCount = this.options.totalCount;
this.helper = new MassActionHelper(this);
@@ -120,8 +128,6 @@ define('views/modals/mass-update', ['views/modal', 'helpers/mass-action'], funct
},
addField: function (name) {
this.enableButton('update');
this.$el.find('[data-action="reset"]').removeClass('hidden');
this.$el.find('ul.filter-list li[data-name="'+name+'"]').addClass('hidden');
@@ -130,19 +136,46 @@ define('views/modals/mass-update', ['views/modal', 'helpers/mass-action'], funct
this.$el.find('button.select-field').addClass('disabled').attr('disabled', 'disabled');
}
this.notify('Loading...');
this.addedFieldList.push(name);
var label = this.translate(name, 'fields', this.entityType);
let label = this.getHelper().escapeString(
this.translate(name, 'fields', this.entityType)
);
var html = '<div class="cell form-group" data-name="'+name+'">' +
'<label class="control-label">' + label + '</label>' +
'<div class="field" data-name="'+name+'" /></div>';
let $cell =
$('<div>')
.addClass('cell form-group')
.attr('data-name', name)
.append(
$('<label>')
.addClass('control-label')
.text(label)
)
.append(
$('<div>')
.addClass('field')
.attr('data-name', name)
);
this.$el.find('.fields-container').append(html);
let $row =
$('<div>')
.addClass('item grid-auto-fill-md')
.attr('data-name', name)
.append($cell);
var type = this.model.getFieldType(name);
this.$el.find('.fields-container').append($row);
var viewName = this.model.getFieldParam(name, 'view') || this.getFieldManager().getViewName(type);
let type = this.model.getFieldType(name);
let viewName = this.model.getFieldParam(name, 'view') || this.getFieldManager().getViewName(type);
let actionList = this.getMetadata().get(['entityDefs', this.entityType, name, 'massUpdateActionList']) ||
this.getMetadata().get(['fields', type, 'massUpdateActionList']);
let hasActionDropdown = actionList !== null;
this.hasActionMap[name] = hasActionDropdown;
this.disableButton('update');
this.createView(name, viewName, {
model: this.model,
@@ -151,108 +184,161 @@ define('views/modals/mass-update', ['views/modal', 'helpers/mass-action'], funct
name: name,
},
mode: 'edit',
}, (view) => {
this.addedFieldList.push(name);
}, view => {
this.enableButton('update');
view.render();
view.notify(false);
});
if (hasActionDropdown) {
let $select =
$('<select>')
.addClass('item-action form-control')
.attr('data-name', name);
actionList.forEach(action => {
let label = this.translate(Espo.Utils.upperCaseFirst(action));
$select.append(
$('<option>')
.text(label)
.val(action)
);
});
let $cellAction =
$('<div>')
.addClass('cell call-action form-group')
.attr('data-name', name)
.append(
$('<label>')
.addClass('control-label hidden-xs')
.html('&nbsp;')
)
.append(
$('<div>')
.addClass('field')
.attr('data-name', name)
.append($select)
);
$row.append($cellAction);
}
},
actionUpdate: function () {
this.disableButton('update');
var attributes = {};
let attributes = {};
let actions = {};
this.addedFieldList.forEach((field) => {
var view = this.getView(field);
this.addedFieldList.forEach(field => {
let action = this.fetchAction(field);
let itemAttributes = this.getView(field).fetch();
_.extend(attributes, view.fetch());
let itemActualAttributes = {};
this.getFieldManager()
.getEntityTypeFieldActualAttributeList(this.entityType, field)
.forEach(attribute => {
actions[attribute] = action;
itemActualAttributes[attribute] = itemAttributes[attribute];
});
_.extend(attributes, itemActualAttributes);
});
this.model.set(attributes);
var notValid = false;
let notValid = false;
this.addedFieldList.forEach((field) => {
var view = this.getView(field);
this.addedFieldList.forEach(field => {
let view = this.getView(field);
notValid = view.validate() || notValid;
});
if (!notValid) {
Espo.Ui.notify(
this.translate('Saving...')
);
if (notValid) {
this.notify('Not valid', 'error');
this.enableButton('update');
Espo.Ajax
.postRequest('MassAction', {
action: 'update',
entityType: this.entityType,
params: {
ids: this.ids || null,
where: (!this.ids || this.ids.length === 0) ? this.options.where : null,
searchParams: (!this.ids || this.ids.length === 0) ? this.options.searchParams : null,
},
data: attributes,
idle: this.idle,
})
.then(result => {
var result = result || {};
return;
}
if (result.id) {
this.helper
.process(result.id, 'update')
.then(view => {
this.listenToOnce(view, 'close', () => this.close());
Espo.Ui.notify(this.translate('Saving...'));
this.listenToOnce(view, 'success', result => {
this.trigger('after:update', {
count: result.count,
idle: true,
});
Espo.Ajax
.postRequest('MassAction', {
action: 'update',
entityType: this.entityType,
params: {
ids: this.ids || null,
where: (!this.ids || this.ids.length === 0) ? this.options.where : null,
searchParams: (!this.ids || this.ids.length === 0) ? this.options.searchParams : null,
},
data: {
values: attributes,
actions: actions,
},
idle: this.idle,
})
.then(result => {
result = result || {};
if (result.id) {
this.helper
.process(result.id, 'update')
.then(view => {
this.listenToOnce(view, 'close', () => this.close());
this.listenToOnce(view, 'success', result => {
this.trigger('after:update', {
count: result.count,
idle: true,
});
});
});
return;
}
return;
}
this.trigger('after:update', {
count: result.count,
});
})
.catch(() => {
this.notify('Error occurred', 'error');
this.enableButton('update');
this.trigger('after:update', {
count: result.count,
});
}
else {
this.notify('Not valid', 'error');
})
.catch(() => {
this.enableButton('update');
});
},
this.enableButton('update');
fetchAction: function (name) {
if (!this.hasActionMap[name]) {
return this.ACTION_UPDATE;
}
let $dropdown = this.$el.find('select.item-action[data-name="'+name+'"]');
return $dropdown.val() || this.ACTION_UPDATE;
},
reset: function () {
this.addedFieldList.forEach((field) => {
this.addedFieldList.forEach(field => {
this.clearView(field);
this.$el.find('.cell[data-name="'+field+'"]').remove();
this.$el.find('.item[data-name="'+field+'"]').remove();
});
this.addedFieldList = [];
this.hasActionMap = {};
this.model.clear();
this.$el.find('[data-action="reset"]').addClass('hidden');
this.$el.find('button.select-field').removeClass('disabled').removeAttr('disabled');
this.$el.find('ul.filter-list').find('li').removeClass('hidden');
this.disableButton('update');
},
});
});
@@ -0,0 +1,131 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM - Open Source CRM application.
* Copyright (C) 2014-2022 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko
* Website: https://www.espocrm.com
*
* EspoCRM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* EspoCRM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace tests\unit\Espo\Tools\MassUpdate;
use Espo\Core\MassAction\Data as MassActionData;
use Espo\Tools\MassUpdate\Data;
use Espo\Tools\MassUpdate\Action;
class DataTest extends \PHPUnit\Framework\TestCase
{
public function testData1(): void
{
$massActionData = MassActionData::fromRaw(
(object) [
'values' => (object) [
'a1' => '1',
'a2' => '2',
'a3' => '3',
],
'actions' => (object) [
'a1' => 'update',
'a2' => 'add',
'a3' => 'remove',
],
],
);
$data = Data::fromMassActionData($massActionData);
$this->assertEquals('1', $data->getValue('a1'));
$this->assertEquals(null, $data->getValue('a0'));
$this->assertEquals(true, $data->has('a1'));
$this->assertEquals(false, $data->has('a0'));
$this->assertEquals(['a1', 'a2', 'a3'], $data->getAttributeList());
$this->assertEquals(
(object) [
'a1' => '1',
'a2' => '2',
'a3' => '3',
],
$data->getValues()
);
$this->assertEquals(Action::UPDATE, $data->getAction('a1'));
$this->assertEquals(Action::ADD, $data->getAction('a2'));
$this->assertEquals(Action::REMOVE, $data->getAction('a3'));
$this->assertEquals('1m', $data->with('a1', '1m')->getValue('a1'));
$this->assertEquals(false, $data->without('a1')->has('a1'));
$massActionDataModified = $data
->with('a1', '1m', Action::ADD)
->without('a2')
->toMassActionData();
$values = $massActionDataModified->get('values');
$actions = $massActionDataModified->get('actions');
$this->assertEquals('1m', $values->a1);
$this->assertFalse(property_exists($values, 'a2'));
$this->assertEquals(Action::ADD, $actions->a1);
$this->assertFalse(property_exists($actions, 'a2'));
}
public function testCreate(): void
{
$data = Data::create()
->with('a1', null, Action::UPDATE)
->with('a2', ['1'], Action::ADD);
$this->assertEquals(null, $data->getValue('a1'));
$this->assertEquals(['1'], $data->getValue('a2'));
$this->assertEquals(Action::ADD, $data->getAction('a2'));
}
public function testWith(): void
{
$data = Data::create()
->with('a1', '1', Action::ADD)
->with('a1', '2')
->with('a2', '2');
$this->assertEquals(Action::ADD, $data->getAction('a1'));
$this->assertEquals(Action::UPDATE, $data->getAction('a2'));
}
public function testBc(): void
{
$massActionData = MassActionData::fromRaw(
(object) [
'a1' => '1',
'a2' => '2',
'a3' => '3',
],
);
$data = Data::fromMassActionData($massActionData);
$this->assertEquals('1', $data->getValue('a1'));
$this->assertEquals(Action::UPDATE, $data->getAction('a1'));
}
}
@@ -0,0 +1,110 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM - Open Source CRM application.
* Copyright (C) 2014-2022 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko
* Website: https://www.espocrm.com
*
* EspoCRM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* EspoCRM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace tests\unit\Espo\Tools\MassUpdate;
use Espo\Tools\MassUpdate\Data;
use Espo\Tools\MassUpdate\ValueMapPreparator;
use Espo\Tools\MassUpdate\Action;
use Espo\ORM\Entity;
use Espo\ORM\Defs as OrmDefs;
class ValueMapPreparatorTest extends \PHPUnit\Framework\TestCase
{
public function testPrepare1(): void
{
$preprator = new ValueMapPreparator(
$this->createMock(OrmDefs::class)
);
$data = Data::create()
->with('a1', ['1', '2'], Action::ADD)
->with('a2', ['1', '2', '3'], Action::REMOVE)
->with('a3', ['1', '2'], Action::UPDATE)
->with('a4', ['1'], Action::REMOVE)
->with('a5', [], Action::ADD)
->with('a6', [], Action::REMOVE)
->with('a7', ['1'], Action::ADD)
->with('a8', ['1'], Action::REMOVE)
->with('a9', null, Action::REMOVE)
->with('a10', null, Action::ADD)
->with('a11', null, Action::UPDATE)
->with('a12', (object) ['k2' => 'v2'], Action::ADD)
->with('a13', (object) ['k2' => 'v2'], Action::REMOVE);
$entity = $this->createMock(Entity::class);
$entity
->expects($this->any())
->method('has')
->willReturn(true);
$entity
->expects($this->any())
->method('get')
->will(
$this->returnCallback(
function ($attribute) {
$map = [
'a1' => ['0'],
'a2' => ['0', '1', '2'],
'a3' => ['0'],
'a4' => ['1'],
'a5' => ['1'],
'a6' => ['1'],
'a7' => null,
'a8' => null,
'a12' => (object) ['k1' => 'v1'],
'a13' => (object) ['k1' => 'v1', 'k2' => 'v2'],
];
return $map[$attribute] ?? null;
}
)
);
$values = $preprator->prepare($entity, $data);
$this->assertEquals(['0', '1', '2'], $values->a1);
$this->assertEquals(['0'], $values->a2);
$this->assertEquals(['1', '2'], $values->a3);
$this->assertEquals([], $values->a4);
$this->assertEquals(['1'], $values->a5);
$this->assertEquals(['1'], $values->a6);
$this->assertEquals(['1'], $values->a7);
$this->assertEquals([], $values->a8);
$this->assertFalse(property_exists($values, 'a9'));
$this->assertFalse(property_exists($values, 'a10'));
$this->assertEquals(null, $values->a11);
$this->assertEquals((object) ['k1' => 'v1', 'k2' => 'v2'], $values->a12);
$this->assertEquals((object) ['k1' => 'v1'], $values->a13);
}
}