pm-4.1.x-dev/src/Service/PmComputedParent.php

src/Service/PmComputedParent.php
<?php

declare(strict_types=1);

namespace Drupal\pm\Service;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\pm\PmContentEntityBase;
use Drupal\pm\Service\PmConfig;

/**
 * @todo Add class description.
 */
final class PmComputedParent {

  /**
   * Constructs a PmComputedParent object.
   */
  public function __construct(
    private readonly PmConfig $pmConfig,
    private readonly EntityTypeManagerInterface $entityTypeManager,
    private readonly PmHierarchy $pmHierarchy,
  ) {}

  /**
   * Implements hook_entity_presave().
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity object that needs to be acted upon.
   */
  public function handleEntityPresave(\Drupal\Core\Entity\EntityInterface $entity): void {
    if (!$entity instanceof PmContentEntityBase) {
      return;
    }
    $children = $this->pmHierarchy->getChildren($entity);
    foreach($children as $child_item) {
      if ($child_item instanceof PmContentEntityBase) {
        $parent_field = $this->pmConfig->getParentReferenceFieldName($child_item->getEntityTypeId());
        $parent_field_type = $this->pmConfig->getParentType($child_item->getEntityTypeId());
        if ($child_item->hasField($parent_field) && $parent_field_type == $entity->getEntityTypeId()) {
            $child_item->set($parent_field, $entity->id());
            // @TODO Validate before save.
            $validations = $child_item->validate();
            if (empty($validations->count())) {
              $child_item->save();
            }
            else {
              throw new \InvalidArgumentException("Trying to set parent on child item failed");
            }
        }
      }
    }
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc