<?php

namespace Drupal\pagedesigner;

use Drupal\Core\Render\Markup;
use Drupal\Core\Security\TrustedCallbackInterface;
use Drupal\pagedesigner\Entity\Element;
use Drupal\pagedesigner\Plugin\CompoundHandlerBase;

/**
 * Provides a trusted callback to alter pagedesigner element info.
 *
 * @see pagedesigner_element_info_alter()
 */
class PagedesignerPatternBuilder implements TrustedCallbackInterface {

  /**
   * {@inheritdoc}
   */
  public static function trustedCallbacks() {
    return ['postRender'];
  }

  /**
   * Add the entity and type information to the markup for editing in PD.
   */
  public static function postRender($markupObject, $element) {
    if (!empty($element['#pagedesigner_entity']) && $markupObject) {
      $entity = $element['#pagedesigner_entity'];
      if ($entity instanceof Element) {
        $markup = $markupObject->__toString();
        $edit = (isset($element['#pagedesigner_edit'])) ? (bool) $element['#pagedesigner_edit'] : FALSE;
        return Markup::create(CompoundHandlerBase::augmentEditPattern($markup, $entity, $edit));
      }
    }
    return $markupObject;
  }

}
