createFromEntity example



    parent::tearDown();
  }

  /** * @covers ::normalize */
  public function testNormalize() {
    $resource_type = $this->container->get('jsonapi.resource_type.repository')->get('node', 'article');

    $resource_object = ResourceObject::createFromEntity($resource_type$this->node);
    $includes = $this->includeResolver->resolve($resource_object, 'uid,field_tags,field_image');

    $jsonapi_doc_object = $this
      ->getNormalizer()
      ->normalize(
        new JsonApiDocumentTopLevel(new ResourceObjectData([$resource_object], 1)$includesnew LinkCollection([])),
        'api_json',
        [
          'resource_type' => $resource_type,
          'account' => NULL,
          'sparse_fieldset' => [
            
// Validate the file against field-level validators first while the file is     // still a temporary file. Validation is split up in 2 steps to be the same     // as in \Drupal\file\Upload\FileUploadHandler::handleFileUpload().     // For backwards compatibility this part is copied from ::validate() to     // leave that method behavior unchanged.     // @todo Improve this with a file uploader service in     // https://www.drupal.org/project/drupal/issues/2940383     $errors = file_validate($file$validators);
    if (!empty($errors)) {
      $violations = new EntityConstraintViolationList($file);
      $translator = new DrupalTranslator();
      $entity = EntityAdapter::createFromEntity($file);
      foreach ($errors as $error) {
        $violation = new ConstraintViolation($translator->trans($error),
          $error,
          [],
          $entity,
          '',
          NULL
        );
        $violations->add($violation);
      }
      return $violations;
    }
$this->units = null;
    }

    private function calculatePrice(Entity $product, SalesChannelContext $context, UnitCollection $units): void
    {
        $price = $product->get('price');
        $taxId = $product->get('taxId');

        if ($price === null || $taxId === null) {
            return;
        }
        $reference = ReferencePriceDto::createFromEntity($product);

        $definition = $this->buildDefinition($product$price$context$units$reference);

        $price = $this->calculator->calculate($definition$context);

        $product->assign([
            'calculatedPrice' => $price,
        ]);
    }

    private function calculateAdvancePrices(Entity $product, SalesChannelContext $context, UnitCollection $units): void
    {

  public function toArray() {
    return [];
  }

  /** * {@inheritdoc} */
  public function getTypedData() {
    if (!isset($this->typedData)) {
      $class = $this->getTypedDataClass();
      $this->typedData = $class::createFromEntity($this);
    }
    return $this->typedData;
  }

  /** * Returns the typed data class name for this entity. * * @return string * The string representing the typed data class name. * * @see \Drupal\Core\Entity\Plugin\DataType\EntityAdapter */


    private function buildSingleDelivery(
        ShippingMethodEntity $shippingMethod,
        LineItemCollection $collection,
        SalesChannelContext $context
    ): ?Delivery {
        $positions = new DeliveryPositionCollection();
        $deliveryTime = null;
        // use shipping method delivery time as default         if ($shippingMethod->getDeliveryTime() !== null) {
            $deliveryTime = DeliveryTime::createFromEntity($shippingMethod->getDeliveryTime());
        }

        $this->buildPositions($collection$positions$deliveryTime);

        if ($positions->count() <= 0) {
            return null;
        }

        return new Delivery(
            $positions,
            $this->getDeliveryDateByPositions($positions),
            
 iterator_to_array($violations)));
      throw new UnprocessableEntityHttpException($message);
    }

    // @todo Remove line below in favor of commented line in https://www.drupal.org/project/drupal/issues/2878463.     $self_link = new Link(new CacheableMetadata(), Url::fromRoute('jsonapi.file--file.individual', ['entity' => $file->uuid()]), 'self');
    /* $self_link = new Link(new CacheableMetadata(), $this->entity->toUrl('jsonapi'), ['self']); */
    $links = new LinkCollection(['self' => $self_link]);

    $relatable_resource_types = $resource_type->getRelatableResourceTypesByField($resource_type->getPublicName($file_field_name));
    $file_resource_type = reset($relatable_resource_types);
    $resource_object = ResourceObject::createFromEntity($file_resource_type$file);
    return new ResourceResponse(new JsonApiDocumentTopLevel(new ResourceObjectData([$resource_object], 1)new NullIncludedData()$links), 201, []);
  }

  /** * Ensures that the given account is allowed to upload a file. * * @param \Drupal\Core\Session\AccountInterface $account * The account for which access should be checked. * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition * The field for which the file is to be uploaded. * @param \Drupal\Core\Entity\FieldableEntityInterface|null $entity * The entity, if one exists, for which the file is to be uploaded. */
static::validate($parsed_entity);

    // Return a 409 Conflict response in accordance with the JSON:API spec. See     // http://jsonapi.org/format/#crud-creating-responses-409.     if ($this->entityExists($parsed_entity)) {
      throw new ConflictHttpException('Conflict: Entity already exists.');
    }

    $parsed_entity->save();

    // Build response object.     $resource_object = ResourceObject::createFromEntity($resource_type$parsed_entity);
    $primary_data = new ResourceObjectData([$resource_object], 1);
    $response = $this->buildWrappedResponse($primary_data$request$this->getIncludes($request$primary_data), 201);

    // According to JSON:API specification, when a new entity was created     // we should send "Location" header to the frontend.     if ($resource_type->isLocatable()) {
      $url = $resource_object->toUrl()->setAbsolute()->toString(TRUE);
      $response->headers->set('Location', $url->getGeneratedUrl());
    }

    // Return response object with updated headers info.

  public function testEntityDeriver() {
    $definition = \Drupal::typedDataManager()->getDefinition('entity:config_test');
    $this->assertEquals(ConfigEntityAdapter::class$definition['class']);
  }

  /** * @covers ::validate */
  public function testValidate() {
    $adapter = ConfigEntityAdapter::createFromEntity($this->entity);
    $violations = $adapter->validate();
    $this->assertEmpty($violations);
    $this->entity = \Drupal::entityTypeManager()->getStorage('config_test')->create([
      'id' => 'system',
      'label' => 'foobar',
      // Set weight to be a string which should not validate.       'weight' => 'very heavy',
    ]);
    $adapter = ConfigEntityAdapter::createFromEntity($this->entity);
    $violations = $adapter->validate();
    $this->assertCount(1, $violations);
    

  protected function normalize(EntityInterface $entity, Url $url) {
    // Don't use cached normalizations in tests.     $this->container->get('cache.jsonapi_normalizations')->deleteAll();

    $self_link = new Link(new CacheableMetadata()$url, 'self');
    $resource_type = $this->container->get('jsonapi.resource_type.repository')->getByTypeName(static::$resourceTypeName);
    $doc = new JsonApiDocumentTopLevel(new ResourceObjectData([ResourceObject::createFromEntity($resource_type$entity)], 1)new NullIncludedData()new LinkCollection(['self' => $self_link]));
    return $this->serializer->normalize($doc, 'api_json', [
      'resource_type' => $resource_type,
      'account' => $this->account,
    ])->getNormalization();
  }

  /** * Creates the entity to be tested. * * @return \Drupal\Core\Entity\EntityInterface * The entity to be tested. */
'unit' => $unit,
            'min' => $min,
            'max' => $max,
            'translated' => [
                'name' => 'deliveryTime',
            ],
        ]);
    }

    private static function createDeliveryTime(int $min, int $max): DeliveryTime
    {
        return DeliveryTime::createFromEntity(self::createDeliveryTimeEntity(DeliveryTimeEntity::DELIVERY_TIME_DAY, $min$max));
    }

    private static function createDeliveryInformation(?DeliveryTime $deliveryTime, int $restockTime): DeliveryInformation
    {
        return new DeliveryInformation(
            10,
            0.0,
            false,
            $restockTime,
            $deliveryTime
        );
    }
    $constraints = $this->getConstraintObjects();
    $entity_type_manager = \Drupal::entityTypeManager();
    $entity_type_id = $this->getEntityTypeId();
    $entity_type = $entity_type_manager->getDefinition($entity_type_id);
    $storage = $entity_type_manager->getStorage($entity_type_id);
    // If the storage can generate a sample entity we might delegate to that.     if ($storage instanceof ContentEntityStorageInterface) {
      if (!empty($constraints['Bundle']) && $constraints['Bundle'] instanceof BundleConstraint) {
        foreach ($constraints['Bundle']->getBundleOption() as $bundle) {
          // We have a bundle, we are bundleable and we can generate a sample.           $values = [$entity_type->getKey('bundle') => $bundle];
          yield EntityAdapter::createFromEntity($storage->create($values));
        }
        return;
      }
    }

    // Either no bundle, or not bundleable, so generate an entity adapter.     $definition = EntityDataDefinition::create($entity_type_id);
    yield new EntityAdapter($definition);
  }

  /** * Creates a context definition from a given entity type ID. * * @param string $entity_type_id * The entity type ID from which to derive a context definition. * * @return static */
// set the label if its empty or the context does not have the permission to overwrite it         if ($label === '' || !$behavior->hasPermission(self::ALLOW_PRODUCT_LABEL_OVERWRITES)) {
            $lineItem->setLabel($product->getTranslation('name'));
        }

        if ($product->getCover()) {
            $lineItem->setCover($product->getCover()->getMedia());
        }

        $deliveryTime = null;
        if ($product->getDeliveryTime() !== null) {
            $deliveryTime = DeliveryTime::createFromEntity($product->getDeliveryTime());
        }

        $weight = $product->getWeight();

        $lineItem->setStates($product->getStates());

        if ($lineItem->hasState(State::IS_PHYSICAL)) {
            $lineItem->setDeliveryInformation(
                new DeliveryInformation(
                    (int) $product->getAvailableStock(),
                    $weight,
                    
$value['alt'] = 'Ugly llama';
          $value['title'] = 'My alter ego';
          break;

        case 'image2':
          $value['alt'] = 'Adorable llama';
          $value['title'] = 'My spirit animal 😍';
          break;
      }
      return $value;
    }$entity_property_names);
    $resource_object = ResourceObject::createFromEntity($this->referencingResourceType, $this->referencer);
    $relationship = Relationship::createFromEntityReferenceField($resource_object$resource_object->getField($field_name));
    // Normalize.     $actual = $this->normalizer->normalize($relationship, 'api_json');
    // Assert.     assert($actual instanceof CacheableNormalization);
    $this->assertEquals($expected$actual->getNormalization());
  }

  /** * Data provider for testNormalize. */
  
$resource_type = $this->resourceTypeRepository->get($entity->getEntityTypeId()$entity->bundle());
    $entity = $this->entityRepository->getTranslationFromContext($entity, NULL, ['operation' => 'entity_upcast']);
    $access = $this->checkEntityAccess($entity, 'view', $account);
    $entity->addCacheableDependency($access);
    if (!$access->isAllowed()) {
      // If this is the default revision or the entity is not revisionable, then       // check access to the entity label. Revision support is all or nothing.       if (!$entity->getEntityType()->isRevisionable() || $entity->isDefaultRevision()) {
        $label_access = $entity->access('view label', NULL, TRUE);
        $entity->addCacheableDependency($label_access);
        if ($label_access->isAllowed()) {
          return LabelOnlyResourceObject::createFromEntity($resource_type$entity);
        }
        $access = $access->orIf($label_access);
      }
      return new EntityAccessDeniedHttpException($entity$access, '/data', 'The current user is not allowed to GET the selected resource.');
    }
    return ResourceObject::createFromEntity($resource_type$entity);
  }

  /** * Checks access to the given entity. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity for which access should be evaluated. * @param string $operation * The entity operation for which access should be evaluated. * @param \Drupal\Core\Session\AccountInterface $account * (optional) The account with which access should be checked. Defaults to * the current user. * * @return \Drupal\Core\Access\AccessResultInterface|\Drupal\Core\Access\AccessResultReasonInterface * The access check result. */
$this->container->setAlias('sut', 'jsonapi.serializer');
    $this->resourceType = $this->container->get('jsonapi.resource_type.repository')->get($this->node->getEntityTypeId()$this->node->bundle());
    $this->sut = $this->container->get('sut');
  }

  /** * @covers \Drupal\jsonapi\Serializer\Serializer::normalize */
  public function testFallbackNormalizer() {
    $context = [
      'account' => $this->user,
      'resource_object' => ResourceObject::createFromEntity($this->resourceType, $this->node),
    ];

    $value = $this->sut->normalize($this->node->field_text, 'api_json', $context);
    $this->assertInstanceOf(CacheableNormalization::class$value);

    $nested_field = [
      $this->node->field_text,
    ];

    // When an object implements \IteratorAggregate and has corresponding     // fallback normalizer, it should be normalized by fallback normalizer.
Home | Imprint | This part of the site doesn't use cookies.