rdf_sync-1.x-dev/src/Encoder/RdfSyncEncoder.php

src/Encoder/RdfSyncEncoder.php
<?php

declare(strict_types=1);

namespace Drupal\rdf_sync\Encoder;

use Drupal\rdf_sync\Model\RdfSyncFormat;
use EasyRdf\Format;
use EasyRdf\Graph;
use Symfony\Component\Serializer\Encoder\EncoderInterface;
use Symfony\Component\Serializer\Exception\NotEncodableValueException;

/**
 * Base encoder.
 */
class RdfSyncEncoder implements EncoderInterface {

  /**
   * Memory cache for supported formats.
   *
   * @var \EasyRdf\Serialiser[]
   */
  protected static array $supportedFormats;

  /**
   * {@inheritdoc}
   */
  public function supportsEncoding($format): bool {
    return isset(static::getSupportedFormats()[$format]);
  }

  /**
   * {@inheritdoc}
   */
  public function encode($data, $format, array $context = []): string {
    try {
      $graph = new Graph();
      $graph->parse($data, 'php');
      return $graph->serialise($format);
    }
    catch (\Exception $e) {
      throw new NotEncodableValueException($e->getMessage(), 0, $e);
    }
  }

  /**
   * Builds a list of supported formats.
   *
   * @return \EasyRdf\Format[]
   *   List of supported formats.
   */
  public static function getSupportedFormats(): array {
    if (!isset(static::$supportedFormats)) {
      $registeredFormats = array_map(
        fn(RdfSyncFormat $format): string => $format->value,
        RdfSyncFormat::cases(),
      );
      static::$supportedFormats = array_intersect_key(Format::getFormats(), array_flip($registeredFormats));
    }
    return static::$supportedFormats;
  }

}

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

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