<?php

namespace Drupal\custom_commerce\Normalizer;

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\serialization\Normalizer\ContentEntityNormalizer;
use Drupal\serialization\Normalizer\NormalizerBase;

class CustomNormalizer extends NormalizerBase {

  protected $supportedInterfaceOrClass = 'Drupal\commerce_order\Entity\Order';

  public function normalize($cart, $format = NULL, array $context = array()) {
    $order_items = $cart->getItems();
    $total_price = $cart->getTotalPrice()->toArray();

    foreach ($order_items as $order_item) {
      $price = $order_item->getTotalPrice()->toArray();

      $referenses = $order_item->referencedEntities();

      foreach ($referenses as $referens) {
        $referens_arr = $referens->toArray();
        if (!empty($referens_arr['attribute_size'])) {
          $size = $referens->getAttributeValue('attribute_size')->label();
        }
        if (!empty($referens_arr['product_id'])) {
          $product = $referens->getProduct();

          if ($product->hasField('field_node')) {
            $node = $product->get('field_node')->referencedEntities();
            $node = $node[0];
            $media = $node->get('field_media')->referencedEntities();
            $media = $media[0];
            $uri = $media->get('field_media_image')->entity->getFileUri();
            $uri = explode('//', $uri);
          }
        }
      }

      $items[] = [
        'name' => $product->label(),
        'quantity' => $order_item->getQuantity(),
        'attribute_size' => $size,
        'item_total_price' => $price,
        'uri' => $uri[1],
      ];
    }

    $data = [
      'items' => $items,
      'total_price' => $total_price,
    ];

    return $data;
  }
}
