Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- declare(strict_types=1);
- namespace App\Service;
- use App\Entity\BaseEntity;
- use App\Entity\CustomFieldValue;
- use App\Entity\Interface\BaseEntityInterface;
- use App\Entity\Interface\BatchByTemplateInterface;
- use App\Entity\Interface\CustomFieldEntityInterface;
- use App\Entity\Model\JoinFilter;
- use App\Entity\User;
- use App\Enum\Entity\BatchType;
- use App\Enum\Entity\BoolType;
- use App\Enum\Entity\VatTypeEnum;
- use App\Enum\Response\ResponseFormatType;
- use App\Event\Entity\EntityBatchTemplateUpdateEvent;
- use App\Event\Entity\PostBulkEvent;
- use App\Exception\Entity\EntityValidationException;
- use App\Exception\Exception;
- use App\Exception\ObjectNotFoundException;
- use App\Exception\ObjectNotImplementException;
- use App\Helper\SerializerExtractorHelper;
- use App\Model\BaseModel;
- use App\Model\IdArrayModel;
- use App\Model\Interface\BaseModelInterface;
- use App\Model\Interface\CustomFieldModelInterface;
- use App\Model\Interface\PaginatedModelInterface;
- use App\Model\Interface\PatchableModelInterface;
- use App\Model\Pagination\PaginatedBatchModel;
- use App\Model\Pagination\PaginatedModel;
- use App\Model\Pagination\PaginationModel;
- use App\Service\Api\BatchApiService;
- use App\Service\Api\Interface\ApiServiceInterface;
- use App\Service\Api\Interface\DocumentExcelServiceInterface;
- use App\Service\Api\Interface\ExportExcelServiceInterface;
- use App\Service\Locator\EntityServiceLocator;
- use App\Service\Utility\EntityHelperService;
- use App\Service\Utility\ExcelExportService;
- use App\Service\Utility\MappingModelService;
- use App\Trait\Service\GetServiceTrait;
- use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
- use Symfony\Component\DependencyInjection\ServiceLocator;
- use Symfony\Component\EventDispatcher\EventDispatcherInterface;
- use Symfony\Component\Serializer\SerializerInterface;
- use Symfony\Component\Uid\UuidV7;
- use Symfony\Component\Validator\Validator\ValidatorInterface;
- use Symfony\Contracts\Service\Attribute\Required;
- class ApiService implements ApiServiceInterface
- {
- use GetServiceTrait;
- public const int DEFAULT_LIMIT = 30;
- protected EventDispatcherInterface $dispatcher;
- protected ExcelExportService $excelExportService;
- protected ValidatorInterface $validator;
- /**
- * @var ServiceLocator<EntityService>
- */
- protected ServiceLocator $locator;
- protected ValidationService $validationService;
- protected BatchApiService $batchApiService;
- protected MappingModelService $mappingModelService;
- protected EntityHelperService $entityHelperService;
- protected ParameterBagInterface $params;
- protected SerializerInterface $serializer;
- #[Required]
- public function setDependencies(
- BatchApiService $batchApiService,
- EventDispatcherInterface $dispatcher,
- EntityHelperService $entityHelperService,
- ExcelExportService $excelExportService,
- MappingModelService $mappingModelService,
- ParameterBagInterface $params,
- EntityServiceLocator $entityServiceLocator,
- ValidationService $validationService,
- ValidatorInterface $validator,
- SerializerInterface $serializer,
- ): void {
- $this->dispatcher = $dispatcher;
- $this->validator = $validator;
- $this->locator = $entityServiceLocator->getLocator();
- $this->batchApiService = $batchApiService;
- $this->validationService = $validationService;
- $this->mappingModelService = $mappingModelService;
- $this->entityHelperService = $entityHelperService;
- $this->params = $params;
- $this->serializer = $serializer;
- $this->excelExportService = $excelExportService;
- }
- #[\Override]
- public function map(
- BaseEntityInterface $entity,
- array $context,
- int $tree = 0,
- array $propNameLimit = [],
- ?int $mappingModelHelperTree = null,
- bool $showArchived = false,
- ): BaseModelInterface {
- $model = $this->mapProperties(
- $entity,
- $context,
- $tree,
- $propNameLimit,
- $mappingModelHelperTree,
- $showArchived,
- );
- $this->mapCustomFields([$entity], [$model], $context);
- return $this->postMap($model, $entity, $context);
- }
- #[\Override]
- public function preMap(
- BaseEntityInterface $entity,
- array $context,
- ): array {
- return [];
- }
- #[\Override]
- public function postMap(
- BaseModelInterface $model,
- BaseEntityInterface $entity,
- array $context,
- ): BaseModelInterface {
- return $model;
- }
- /**
- * @param BaseEntityInterface[] $entities
- *
- * @return BaseEntityInterface[]
- */
- #[\Override]
- public function preMapAll(
- array $entities,
- array $context,
- ): array {
- return $entities;
- }
- /**
- * @param BaseEntityInterface[] $entities
- *
- * @return BaseModelInterface[]
- */
- #[\Override]
- public function mapAll(
- array $entities,
- array $context = [],
- ): array {
- if (method_exists($this, 'preMapAll')) {
- $entities = $this->preMapAll($entities, $context);
- }
- $list = [];
- foreach ($entities as $k => $entity) {
- $list[$k] = $this->mapProperties($entity, $context);
- }
- $this->mapCustomFields($entities, $list, $context);
- foreach ($entities as $k => $entity) {
- $this->postMap($list[$k], $entity, $context);
- }
- return $list;
- }
- #[\Override]
- public function getAll(
- ?User $currentUser = null,
- ?int $limit = null,
- int $offset = 0,
- array $filter = [],
- string $search = '',
- array $context = [],
- array $orderBy = [],
- bool $criteriaAlreadyPrepared = false,
- bool $isAccurateSearch = false,
- ): PaginatedModel {
- $service = $this->getService();
- $account = $currentUser?->getCurrentAccount();
- if (!$criteriaAlreadyPrepared) {
- $criteria = $service->prepareCriteria(
- criteria: $filter,
- account: $account,
- search: $search,
- exclude: ['account'],
- isAccurateSearch: $isAccurateSearch,
- );
- $criteriaAlreadyPrepared = true;
- } else {
- $criteria = $filter;
- }
- $count = $service->getCount($criteria, $criteriaAlreadyPrepared);
- $model = new PaginatedModel();
- $limit = $this->prepareLimit($limit);
- $offset = $this->prepareOffset($offset);
- $results = $count ? $service->getAll(
- criteria: $criteria,
- limit: $limit,
- offset: $offset,
- orderBy: $orderBy,
- criteriaAlreadyPrepared: $criteriaAlreadyPrepared,
- ) : [];
- $model->setItems(
- $this->mapAll(
- $results,
- $context,
- ),
- )->setTotals(
- $service->getTotals($account, $criteria),
- )->setPagination(
- $this->mapPagination($limit, $offset, $count),
- );
- if (in_array('pagination:hash', $context, true)) {
- $lastDate = null;
- foreach ($results as $result) {
- if (method_exists($result, 'getModifiedAt')) {
- if (null === $lastDate) {
- $lastDate = $result->getModifiedAt();
- }
- if ($lastDate < $result->getModifiedAt()) {
- $lastDate = $result->getModifiedAt();
- }
- }
- }
- if (null === $lastDate) {
- $lastDate = new \DateTimeImmutable();
- }
- $model->setHash(hash('xxh3', $lastDate->format(\DateTimeInterface::ATOM)));
- }
- return $model;
- }
- #[\Override]
- public function getAllStreamed(
- ?User $currentUser = null,
- ?int $limit = null,
- int $offset = 0,
- array $filter = [],
- string $search = '',
- array $orderBy = [],
- bool $criteriaAlreadyPrepared = false,
- bool $isAccurateSearch = false,
- ?ResponseFormatType $format = null,
- ): void {
- $service = $this->getService();
- $account = $currentUser?->getCurrentAccount();
- if (!$criteriaAlreadyPrepared) {
- $criteria = $service->prepareCriteria(
- criteria: $filter,
- account: $account,
- search: $search,
- exclude: ['account'],
- isAccurateSearch: $isAccurateSearch,
- );
- $criteriaAlreadyPrepared = true;
- } else {
- $criteria = $filter;
- }
- $callbackFunction = fn () => $service->getAllIterable(
- criteria: $criteria,
- limit: $limit,
- offset: $offset,
- orderBy: $orderBy,
- criteriaAlreadyPrepared: $criteriaAlreadyPrepared,
- );
- if (ResponseFormatType::Excel === $format) {
- if ($this instanceof ExportExcelServiceInterface) {
- $this->getExcel($callbackFunction, $service, $criteria);
- } else {
- throw new ObjectNotImplementException($this::class, ExportExcelServiceInterface::class);
- }
- }
- }
- public function getOneStreamed(
- ?User $currentUser = null,
- ?string $id = null,
- array $criteria = [],
- bool $criteriaAlreadyPrepared = false,
- ?ResponseFormatType $format = null,
- ): void {
- $service = $this->getService();
- $entity = $this->entityHelperService->getName($service);
- if ($this->entityHelperService->isPropertyExist($entity, 'account')) {
- $account = $currentUser?->getCurrentAccount();
- } else {
- $account = null;
- }
- if (!$criteriaAlreadyPrepared) {
- $criteria = $service->prepareCriteria(
- criteria: $criteria,
- id: $id,
- account: $account,
- exclude: ['account'],
- );
- $criteriaAlreadyPrepared = true;
- }
- $entity = $service->get(
- id: $id,
- account: $account,
- criteria: $criteria,
- criteriaAlreadyPrepared: $criteriaAlreadyPrepared,
- );
- if (ResponseFormatType::Excel === $format) {
- if ($service instanceof DocumentExcelServiceInterface) {
- $service->getDocument($entity);
- } else {
- throw new ObjectNotImplementException($service::class, DocumentExcelServiceInterface::class);
- }
- }
- }
- #[\Override]
- public function get(
- ?User $currentUser = null,
- ?string $id = null,
- array $criteria = [],
- array $context = [],
- array $orderBy = [],
- bool $criteriaAlreadyPrepared = false,
- array $limits = [],
- ): BaseModelInterface {
- $service = $this->getService();
- $entity = $this->entityHelperService->getName($service);
- if ($this->entityHelperService->isPropertyExist($entity, 'account')) {
- $account = $currentUser?->getCurrentAccount();
- } else {
- $account = null;
- }
- if (!$criteriaAlreadyPrepared) {
- $criteria = $service->prepareCriteria(
- criteria: $criteria,
- id: $id,
- account: $account,
- exclude: ['account'],
- );
- $criteriaAlreadyPrepared = true;
- }
- return $this->map(
- $service->get(
- id: $id,
- account: $account,
- criteria: $criteria,
- orderBy: $orderBy,
- criteriaAlreadyPrepared: $criteriaAlreadyPrepared,
- ),
- $context,
- );
- }
- #[\Override]
- public function create(
- BaseModelInterface $model,
- User $currentUser,
- array $context,
- ): BaseModelInterface|BaseEntityInterface {
- throw new Exception('Create method not found in '.$this::class);
- }
- #[\Override]
- public function update(
- BaseModelInterface $model,
- User $currentUser,
- array $context,
- ): BaseModelInterface|BaseEntityInterface {
- throw new Exception('Update method not found in '.$this::class);
- }
- public function patch(
- BaseModelInterface $model,
- User $currentUser,
- array $context,
- ): BaseEntityInterface|BaseModelInterface {
- $model = $this->resetModel(
- $model,
- $currentUser,
- );
- return $this->update(
- model: $model,
- currentUser: $currentUser,
- context: $context,
- );
- }
- #[\Override]
- public function delete(
- int|string|null $id,
- ?User $currentUser = null,
- array $criteria = [],
- ): void {
- $service = $this->getService();
- $account = $currentUser?->getCurrentAccount();
- $service->delete(
- entity: $service->get(
- id: $id,
- account: $account,
- criteria: $criteria,
- ),
- account: $account,
- );
- }
- public function batchCreate(
- PaginatedModelInterface $inputModel,
- User $currentUser,
- array $context = [],
- array $inputArgs = [],
- ): BaseModelInterface {
- return $this->batchApiService->create(
- model: $inputModel,
- currentUser: $currentUser,
- context: $context,
- inputArgs: $inputArgs,
- entityName: $this->entityHelperService->getName($this),
- type: BatchType::Create,
- );
- }
- public function batchUpdate(
- PaginatedModelInterface $inputModel,
- User $currentUser,
- array $inputArgs = [],
- array $context = [],
- ): BaseModelInterface {
- return $this->batchApiService->create(
- model: $inputModel,
- currentUser: $currentUser,
- context: $context,
- inputArgs: $inputArgs,
- entityName: $this->entityHelperService->getName($this),
- type: BatchType::Update,
- );
- }
- public function batchDelete(
- IdArrayModel $inputModel,
- User $currentUser,
- array $filter = [],
- array $criteria = [],
- ): ?BaseModelInterface {
- $isSync = false;
- $service = $this->getService();
- $account = $currentUser->getCurrentAccount();
- $ids = [];
- if ($filter) {
- $criteria = $service->prepareCriteria(
- criteria: array_merge($filter, $criteria),
- account: $account,
- exclude: ['account'],
- );
- $ids = $this->getService()->getIds($criteria, true, $account);
- } elseif ($inputModel->getIds()) {
- foreach ($inputModel->getIds() as $id) {
- if (null !== $id) {
- $ids[] = $id;
- }
- }
- $max = (int) $this->params->get('app.max_sync_delete_limit');
- if ($max && count($ids) < $max) {
- $isSync = true;
- }
- }
- if ($isSync) {
- foreach ($ids as $id) {
- try {
- $service->delete($service->get(id: $id, account: $account), $account);
- } catch (ObjectNotFoundException) {
- }
- }
- return null;
- }
- return $this->batchApiService->create(
- new PaginatedModel(),
- $currentUser,
- [],
- $ids,
- $this->entityHelperService->getName($this),
- BatchType::Delete,
- );
- }
- public function bulk(
- PaginatedModelInterface $inputModel,
- User $currentUser,
- array $criteria = [],
- array $contextList = [],
- array $contextCreate = [],
- array $contextUpdate = [],
- array $inputArgs = [],
- string $entity = '',
- ): BaseModelInterface {
- $items = $inputModel->getItems();
- foreach ($items as $item) {
- $itemId = $item->getId();
- $this->validationService->validate($item, $itemId ? $contextUpdate : $contextCreate);
- }
- $ids = [];
- foreach ($items as $item) {
- if (null !== $item->getId()) {
- $ids[] = $item->getId();
- }
- }
- $criteria['account'] = $currentUser->getCurrentAccount();
- $service = $this->getService();
- $entities = $service->getAll($criteria);
- $allEntities = [];
- /** @var BaseEntity $entityItem */
- foreach ($entities as $entityItem) {
- if (in_array($entityItem->getIdStr(), $ids, true)) {
- $allEntities[$entityItem->getIdStr()] = $entityItem;
- } else {
- $this->delete($entityItem->getId()?->toRfc4122());
- }
- }
- foreach ($items as $item) {
- $itemId = $item->getId();
- if ($itemId) {
- if (array_key_exists($itemId, $allEntities)) {
- $this->update(
- model: $item,
- currentUser: $currentUser,
- context: $contextUpdate,
- );
- }
- } else {
- $this->create(
- model: $item,
- currentUser: $currentUser,
- context: $contextCreate,
- );
- }
- }
- $this->dispatcher->dispatch(new PostBulkEvent($items));
- return $this->getAll(
- currentUser: $currentUser,
- limit: 300,
- filter: $criteria,
- context: $contextList,
- );
- }
- protected function mapProperties(
- BaseEntityInterface $entity,
- array $context,
- int $tree = 0,
- array $propNameLimit = [],
- ?int $mappingModelHelperTree = null,
- bool $showArchived = false,
- ): BaseModelInterface {
- $preMapResult = $this->preMap($entity, $context);
- $mappingModelService = $this->mappingModelService->setTreeLimit($mappingModelHelperTree);
- return $mappingModelService->mapProperties(
- entity: $entity,
- mapGroups: $context,
- treeLimit: $tree,
- propNameLimit: $propNameLimit,
- customModelClass: $preMapResult['modelClassName'] ?? null,
- showArchived: $showArchived,
- );
- }
- protected function mapCustomFields(
- array $entities,
- array $models,
- array $context,
- ): void {
- if (!(
- isset($this->customFieldValueService, $this->customFieldValueApiService)
- && count($entities)
- && count($models)
- && current($entities) instanceof CustomFieldEntityInterface
- && current($models) instanceof CustomFieldModelInterface
- )) {
- return;
- }
- $allCustomFields = [];
- $ids = array_filter(array_map(
- static fn (BaseEntityInterface $entity) => $entity->getId(),
- $entities,
- ));
- if (!count($ids)) {
- return;
- }
- $this->customFieldValueService->with('customField');
- $criteria = [
- 'entityId' => $ids,
- 'deleted' => false,
- 'customField.deleted' => new JoinFilter('customField', ['deleted' => 'false']),
- 'filter' => true,
- ];
- $items = $this->customFieldValueService->getAll(criteria: $criteria, criteriaAlreadyPrepared: true);
- /* @var CustomFieldValue $item */
- foreach ($items as $item) {
- if (!$item->getEntityId()) {
- continue;
- }
- $allCustomFields[$item->getEntityId()->toRfc4122()][] = $item;
- }
- foreach ($models as $model) {
- $modelId = $model->getId();
- $customFields = $allCustomFields[$modelId] ?? [];
- $model->setCustomFields($this->customFieldValueApiService->mapAll($customFields, $context));
- }
- }
- protected function getUuid(
- ?string $id,
- ): ?UuidV7 {
- return $id ? UuidV7::fromRfc4122($id) : null;
- }
- protected function entityArray(
- object $model,
- object $entity,
- array $context = [],
- ): ?array {
- $entityArray = [];
- $entityReflection = new \ReflectionClass($entity);
- $entityProperties = $entityReflection->getProperties();
- $serializerExtractor = SerializerExtractorHelper::getSerializerExtractor();
- $properties = $serializerExtractor->getProperties($model::class, ['serializer_groups' => $context]);
- foreach ($properties as $property) {
- $getMethodName = $this->entityHelperService->getGetter($property);
- if (method_exists($model, $getMethodName)) {
- $entityPropertyTypeFull = '';
- $entityPropertyType = 'NULL';
- foreach ($entityProperties as $entityProperty) {
- if ($property === $entityProperty->getName()) {
- $entityPropertyTypeFull = str_replace('?', '', (string) $entityProperty->getType());
- $entityPropertyType = preg_replace('/^(\w+\\\)*/', '', $entityPropertyTypeFull);
- break;
- }
- }
- $value = $model->{$getMethodName}();
- if (null !== $value) {
- if (in_array(gettype($value), [
- 'NULL',
- 'integer',
- 'double',
- 'string',
- 'boolean',
- 'bool',
- 'array',
- ], true)) {
- $entityArray[$property] = $value;
- } elseif ('VatTypeEnum' === $entityPropertyType) {
- $entityArray[$property] = null === $value->getId() ? VatTypeEnum::Vat_none :
- VatTypeEnum::tryFrom((int) $value->getId());
- } elseif ('DateTimeImmutable' === $entityPropertyType) {
- $entityArray[$property] = $value;
- } elseif ('UuidV7' === $entityPropertyType) {
- $entityArray[$property] = $value;
- } elseif (enum_exists($entityPropertyTypeFull)) {
- $reflectionEnum = new \ReflectionEnum($entityPropertyTypeFull);
- if ($reflectionEnum->hasCase((string) $value)) {
- $entityArray[$property] = $reflectionEnum->getCase((string) $value)->getValue();
- }
- } elseif ('BoolTypeInterface' === $entityPropertyType) {
- $entityArray[$property] = BoolType::true->name === $value->name;
- } elseif (is_object($value) && $model === $entity) {
- $entityArray[$property] = $this->entityArray($value, $value, $context);
- }
- }
- }
- }
- return $entityArray;
- }
- public function modelAsArray(
- ?object $model,
- array $context = [],
- bool $isFlat = false,
- int $tree = 0,
- ): ?array {
- if (!$model || ($isFlat && $tree > 0)) {
- return null;
- }
- ++$tree;
- $modelArray = [];
- $serializerExtractor = SerializerExtractorHelper::getSerializerExtractor();
- $properties = $serializerExtractor->getProperties($model::class, ['serializer_groups' => $context]);
- foreach ($properties as $property) {
- $getMethodName = $this->entityHelperService->getGetter($property);
- if (method_exists($model, $getMethodName)) {
- $value = $model->{$getMethodName}();
- if (is_array($value)) {
- foreach ($value as $key => $object) {
- if (is_object($object)) {
- $result = $this->modelAsArray($object, $context, $isFlat, $tree);
- if ($result) {
- $modelArray[$property][$key] = $result;
- }
- }
- }
- } elseif ($value instanceof \DateTimeImmutable) {
- $modelArray[$property] = $value->format('Y-m-d H:i:s');
- } elseif ($value instanceof \BackedEnum) {
- $modelArray[$property] = $value->value;
- } elseif (is_object($value)) {
- $result = $this->modelAsArray($value, $context, $isFlat, $tree);
- if ($result) {
- $modelArray[$property] = $result;
- }
- } elseif (in_array(gettype($value), [
- 'NULL',
- 'integer',
- 'double',
- 'string',
- 'boolean',
- 'bool',
- ], true)) {
- $modelArray[$property] = $value;
- }
- }
- }
- return $modelArray;
- }
- protected function entityToArray(
- BaseModel $model,
- array $context = [],
- ): array {
- $entityClass = str_replace('\Model\\', '\Entity\\', $model::class);
- $entityClass = ucfirst(str_replace('Model', '', $entityClass));
- try {
- $entity = new $entityClass();
- } catch (\Exception $e) {
- throw new \LogicException(sprintf('В рамках преобразования в массив не удалось создать копию объекта "%s" (%s).', $entityClass, $e->getMessage()), $e->getCode(), $e);
- }
- return $this->entityArray(
- model: $model,
- entity: $entity,
- context: $context,
- );
- }
- protected function prepareLimit(
- ?int $limit,
- ): ?int {
- if (null === $limit || $limit < 0) {
- $limit = null;
- } elseif (0 === $limit) {
- $limit = self::DEFAULT_LIMIT;
- }
- /*if ($limit > static::$maxLimit) {
- $limit = static::$maxLimit;
- }*/
- return $limit;
- }
- protected function prepareOffset(
- ?int $offset,
- ): int {
- if (null === $offset || $offset < 0) {
- $offset = 0;
- }
- return $offset;
- }
- protected function mapPagination(
- ?int $limit,
- ?int $offset,
- int $total,
- ): PaginationModel {
- return (new PaginationModel())
- ->setTotal($total)
- ->setLimit($limit)
- ->setOffset($offset);
- }
- public function batchByTemplate(
- BaseModel $model,
- array $filter,
- User $currentUser,
- array $context,
- ): ?PaginatedBatchModel {
- if (!$model instanceof BatchByTemplateInterface) {
- throw new \RuntimeException(sprintf('Class %s not implements %s', $model::class, BatchByTemplateInterface::class));
- }
- $models = [];
- $items = $model->getItemsId() ?: (isset($filter['itemsId']) ? explode(',', $filter['itemsId']) : []);
- unset($filter['itemsId']);
- $ids = array_unique(array_filter($items));
- if (!$ids && !$filter) {
- $exception = new EntityValidationException();
- $exception->addCustomError('Empty items id');
- throw $exception;
- }
- $template = $model->getTemplate();
- unset($template['id']);
- if (!$template) {
- $exception = new EntityValidationException();
- $exception->addCustomError('Not found fields on update');
- throw $exception;
- }
- if ($ids) {
- /** @var BaseModel $modelTemplate */
- $modelTemplate = $this->serializer->deserialize(
- data: json_encode($template, \JSON_UNESCAPED_UNICODE),
- type: $model::class,
- format: 'json',
- context: $context,
- );
- if ($modelTemplate instanceof PatchableModelInterface) {
- $modelTemplate->setRequestFields(array_keys($template));
- }
- $max = (int) $this->params->get('app.max_sync_template_limit');
- $isSync = ($max && count($ids) <= $max);
- foreach ($ids as $id) {
- $modelEntity = (clone $modelTemplate)->setId($id);
- if ($isSync) {
- $this->patch(
- model: $modelEntity,
- currentUser: $currentUser,
- context: $context,
- );
- continue;
- }
- $models[] = $modelEntity;
- }
- if ($models) {
- $this->batchUpdate(
- inputModel: (new PaginatedModel())->setItems($models),
- currentUser: $currentUser,
- context: $context,
- );
- unset($models);
- }
- } elseif ($filter) {
- $service = $this->getService();
- $entityClass = $this->entityHelperService->getEntity($service);
- $countFilter = array_merge($filter, ['account' => $currentUser->getCurrentAccount()]);
- $count = $service->getCount($countFilter);
- $partition = $this->params->get('app.template.batch.partition');
- if (0 === $count) {
- return null;
- }
- for ($i = 0; $i <= $count; $i += $partition) {
- $this->dispatcher->dispatch(
- new EntityBatchTemplateUpdateEvent(
- template: $template,
- serviceClass: $this->entityHelperService->getService($this),
- entityName: $this->entityHelperService->getName($entityClass),
- context: $context,
- userId: $currentUser->getIdStr(),
- employeeId: $currentUser->getCurrentEmployee()->getIdStr(),
- accountId: $currentUser->getCurrentAccount()->getIdStr(),
- filter: $filter,
- limit: $partition,
- offset: $i,
- ),
- );
- }
- }
- return null;
- }
- protected function resetModel(
- BaseModelInterface $model,
- ?User $currentUser,
- ): BaseModelInterface {
- if (!$model->getId()) {
- return $model;
- }
- $modelName = $this->entityHelperService->getModel($this);
- $entityModel = $this->get(
- currentUser: $currentUser,
- id: $model->getId(),
- context: $modelName::CONTEXT_VIEW,
- );
- return $this->fillEntityModel(
- model: $model,
- entityModel: $entityModel,
- );
- }
- protected function fillEntityModel(
- BaseModelInterface $model,
- BaseModelInterface $entityModel,
- ): BaseModelInterface {
- if (!$model instanceof PatchableModelInterface) {
- return $model;
- }
- foreach ($model->getRequestFields() as $field) {
- $getter = $this->entityHelperService->getGetter($field);
- $setter = $this->entityHelperService->getSetter($field);
- if (method_exists($entityModel, $setter) && method_exists($model, $getter)) {
- $value = $model->{$getter}();
- $entityModel->{$setter}($value);
- }
- }
- return $entityModel;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment