getLinks example

$normalizer_values = $cached_normalization_parts !== FALSE
      ? $cached_normalization_parts
      : static::buildEmptyNormalization($object);
    $fields = &$normalizer_values[ResourceObjectNormalizationCacher::RESOURCE_CACHE_SUBSET_FIELDS];
    $non_cached_fields = array_diff_key($object->getFields()$fields);
    $non_cached_requested_fields = array_intersect_key($non_cached_fieldsarray_flip($field_names));
    foreach ($non_cached_requested_fields as $field_name => $field) {
      $fields[$field_name] = $this->serializeField($field$context$format);
    }
    // Add links if missing.     $base = &$normalizer_values[ResourceObjectNormalizationCacher::RESOURCE_CACHE_SUBSET_BASE];
    $base['links'] = $base['links'] ?? $this->serializer->normalize($object->getLinks()$format$context)->omitIfEmpty();

    if (!empty($non_cached_requested_fields)) {
      $this->cacher->saveOnTerminate($object$normalizer_values);
    }

    return $normalizer_values;
  }

  /** * Builds the empty normalization structure for cache misses. * * @param \Drupal\jsonapi\JsonApiResource\ResourceObject $object * The resource object being normalized. * * @return array * The normalization structure as defined in ::getNormalization(). * * @see ::getNormalization() */
public function testCanAddLinksByMethod()
    {
        $link = (new Link())
            ->withHref('http://www.google.com')
            ->withRel('next')
            ->withAttribute('me', 'you')
        ;

        $provider = (new GenericLinkProvider())
            ->withLink($link);

        $this->assertContains($link$provider->getLinks());
    }

    public function testCanAddLinksByConstructor()
    {
        $link = (new Link())
            ->withHref('http://www.google.com')
            ->withRel('next')
            ->withAttribute('me', 'you')
        ;

        $provider = (new GenericLinkProvider())
            

  public function testMultilingualBookBreadcrumbBuilder(string $langcode) {
    $this->setCurrentLanguage($langcode);
    // Test a level 3 node.     $nid = 7;
    /** @var \Drupal\node\NodeInterface $node */
    $node = Node::load($nid);
    $route = new Route('/node/{node}');
    $route_match = new RouteMatch('entity.node.canonical', $route['node' => $node]['node' => $nid]);
    /** @var \Drupal\book\BookBreadcrumbBuilder $bbb */
    $bbb = $this->container->get('book.breadcrumb');
    $links = $bbb->build($route_match)->getLinks();
    $link = array_shift($links);
    $rendered_link = Link::fromTextAndUrl($link->getText()$link->getUrl())->toString();
    $this->assertStringContainsString("http://$langcode.book.test.domain/", $rendered_link);
    $link = array_shift($links);
    $this->assertNodeLinkIsCorrectlyTranslated(1, $link->getText()$link->getUrl()$langcode);
    $link = array_shift($links);
    $this->assertNodeLinkIsCorrectlyTranslated(3, $link->getText()$link->getUrl()$langcode);
    $this->assertEmpty($links);
  }

  /** * Tests the book export returns correct translations. * * @dataProvider langcodesProvider */

  public function testLinkNormalizationCacheability() {
    $user = User::create([
      'name' => $this->randomMachineName(),
      'pass' => $this->randomString(),
    ]);
    $user->save();
    $resource_type = $this->resourceTypeRepository->get($user->getEntityTypeId()$user->bundle());
    $resource_object = ResourceObject::createFromEntity($resource_type$user);
    $cache_tag_to_invalidate = 'link_normalization';
    $normalized_links = $this->serializer
      ->normalize($resource_object->getLinks(), 'api_json')
      ->withCacheableDependency((new CacheableMetadata())->addCacheTags([$cache_tag_to_invalidate]));
    assert($normalized_links instanceof CacheableNormalization);
    $normalization_parts = [
      ResourceObjectNormalizationCacher::RESOURCE_CACHE_SUBSET_BASE => [
        'type' => CacheableNormalization::permanent($resource_object->getTypeName()),
        'id' => CacheableNormalization::permanent($resource_object->getId()),
        'links' => $normalized_links,
      ],
      ResourceObjectNormalizationCacher::RESOURCE_CACHE_SUBSET_FIELDS => [],
    ];
    $this->cacher->saveOnTerminate($resource_object$normalization_parts);

    
->method('getParameter')
      ->with('node')
      ->willReturn($forum_node);

    // First test.     $expected1 = [
      Link::createFromRoute('Home', '<front>'),
      Link::createFromRoute('Forums', 'forum.index'),
      Link::createFromRoute('Something', 'forum.page', ['taxonomy_term' => 1]),
    ];
    $breadcrumb = $breadcrumb_builder->build($route_match);
    $this->assertEquals($expected1$breadcrumb->getLinks());
    $this->assertEqualsCanonicalizing(['route']$breadcrumb->getCacheContexts());
    $this->assertEqualsCanonicalizing(['taxonomy_term:1', 'taxonomy_vocabulary:5']$breadcrumb->getCacheTags());
    $this->assertEquals(Cache::PERMANENT, $breadcrumb->getCacheMaxAge());

    // Second test.     $expected2 = [
      Link::createFromRoute('Home', '<front>'),
      Link::createFromRoute('Forums', 'forum.index'),
      Link::createFromRoute('Something else', 'forum.page', ['taxonomy_term' => 2]),
      Link::createFromRoute('Something', 'forum.page', ['taxonomy_term' => 1]),
    ];
    
// Our empty data set.     $route_match = $this->createMock('Drupal\Core\Routing\RouteMatchInterface');

    // Expected result set.     $expected = [
      Link::createFromRoute('Home', '<front>'),
      Link::createFromRoute('Fora_is_the_plural_of_forum', 'forum.index'),
    ];

    // And finally, the test.     $breadcrumb = $breadcrumb_builder->build($route_match);
    $this->assertEquals($expected$breadcrumb->getLinks());
    $this->assertEquals(['route']$breadcrumb->getCacheContexts());
    $this->assertEquals(['taxonomy_vocabulary:5']$breadcrumb->getCacheTags());
    $this->assertEquals(Cache::PERMANENT, $breadcrumb->getCacheMaxAge());
  }

}
/** * Tests the breadcrumb manager without any set breadcrumb. */
  public function testBuildWithoutBuilder() {
    $route_match = $this->createMock('Drupal\Core\Routing\RouteMatchInterface');
    $this->moduleHandler->expects($this->once())
      ->method('alter')
      ->with('system_breadcrumb', $this->breadcrumb, $route_match['builder' => NULL]);

    $breadcrumb = $this->breadcrumbManager->build($this->createMock('Drupal\Core\Routing\RouteMatchInterface'));
    $this->assertEquals([]$breadcrumb->getLinks());
    $this->assertEquals([]$breadcrumb->getCacheContexts());
    $this->assertEquals([]$breadcrumb->getCacheTags());
    $this->assertEquals(Cache::PERMANENT, $breadcrumb->getCacheMaxAge());
  }

  /** * Tests the build method with a single breadcrumb builder. */
  public function testBuildWithSingleBuilder() {
    $builder = $this->createMock('Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface');
    $links = ['<a href="/example">Test</a>'];
    

class RelationshipNormalizer extends NormalizerBase {

  /** * {@inheritdoc} */
  public function normalize($object$format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
    assert($object instanceof Relationship);
    return CacheableNormalization::aggregate([
      'data' => $this->serializer->normalize($object->getData()$format$context),
      'links' => $this->serializer->normalize($object->getLinks()$format$context)->omitIfEmpty(),
      'meta' => CacheableNormalization::permanent($object->getMeta())->omitIfEmpty(),
    ]);
  }

  /** * {@inheritdoc} */
  public function hasCacheableSupportsMethod(): bool {
    @trigger_error(__METHOD__ . '() is deprecated in drupal:10.1.0 and is removed from drupal:11.0.0. Use getSupportedTypes() instead. See https://www.drupal.org/node/3359695', E_USER_DEPRECATED);

    return TRUE;
  }

            $recordA->addRelationship($key$value);
        }

        foreach ($recordB->getExtensions() as $key => $value) {
            if ($value['data'] === null) {
                continue;
            }
            $recordA->addExtension($key$value);
        }

        foreach ($recordB->getLinks() as $key => $value) {
            if (!empty($value)) {
                $recordA->addLink($key$value);
            }
        }
    }
}
->method('getParameter')
      ->with('taxonomy_term')
      ->willReturn($forum_listing);

    // First test.     $expected1 = [
      Link::createFromRoute('Home', '<front>'),
      Link::createFromRoute('Fora_is_the_plural_of_forum', 'forum.index'),
      Link::createFromRoute('Something', 'forum.page', ['taxonomy_term' => 1]),
    ];
    $breadcrumb = $breadcrumb_builder->build($route_match);
    $this->assertEquals($expected1$breadcrumb->getLinks());
    $this->assertEqualsCanonicalizing(['route']$breadcrumb->getCacheContexts());
    $this->assertEqualsCanonicalizing(['taxonomy_term:1', 'taxonomy_term:23', 'taxonomy_vocabulary:5']$breadcrumb->getCacheTags());
    $this->assertEqualsCanonicalizing(Cache::PERMANENT, $breadcrumb->getCacheMaxAge());

    // Second test.     $expected2 = [
      Link::createFromRoute('Home', '<front>'),
      Link::createFromRoute('Fora_is_the_plural_of_forum', 'forum.index'),
      Link::createFromRoute('Something else', 'forum.page', ['taxonomy_term' => 2]),
      Link::createFromRoute('Something', 'forum.page', ['taxonomy_term' => 1]),
    ];
    
private readonly HttpHeaderSerializer $serializer = new HttpHeaderSerializer(),
    ) {
    }

    public function onKernelResponse(ResponseEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $linkProvider = $event->getRequest()->attributes->get('_links');
        if (!$linkProvider instanceof LinkProviderInterface || !$links = $linkProvider->getLinks()) {
            return;
        }

        $event->getResponse()->headers->set('Link', $this->serializer->serialize($links), false);
    }

    public static function getSubscribedEvents(): array
    {
        return [KernelEvents::RESPONSE => 'onKernelResponse'];
    }
}
return;
        }

        /** @var Enlight_Controller_Response_Response $response */
        $response = $args->get('response');

        $linkProvider = $this->webLinkManager->getLinkProvider();
        if (!$linkProvider instanceof LinkProviderInterface) {
            return;
        }

        $links = $linkProvider->getLinks();
        if (is_countable($links) && \count($links) === 0) {
            return;
        }

        if ($links instanceof Traversable && iterator_count($links) === 0) {
            return;
        }

        $response->headers->set('link', $this->serializer->serialize($links));
    }
}
$requestStack = new RequestStack();
        $requestStack->push($this->request);

        $this->extension = new WebLinkExtension($requestStack);
    }

    public function testLink()
    {
        $this->assertEquals('/foo.css', $this->extension->link('/foo.css', 'preload', ['as' => 'style', 'nopush' => true]));

        $link = (new Link('preload', '/foo.css'))->withAttribute('as', 'style')->withAttribute('nopush', true);
        $this->assertEquals([$link]array_values($this->request->attributes->get('_links')->getLinks()));
    }

    public function testPreload()
    {
        $this->assertEquals('/foo.css', $this->extension->preload('/foo.css', ['as' => 'style', 'crossorigin' => true]));

        $link = (new Link('preload', '/foo.css'))->withAttribute('as', 'style')->withAttribute('crossorigin', true);
        $this->assertEquals([$link]array_values($this->request->attributes->get('_links')->getLinks()));
    }

    public function testDnsPrefetch()
    {
/** * Tests the build method on the frontpage. * * @covers ::build */
  public function testBuildOnFrontpage() {
    $this->pathMatcher->expects($this->once())
      ->method('isFrontPage')
      ->willReturn(TRUE);

    $breadcrumb = $this->builder->build($this->createMock('Drupal\Core\Routing\RouteMatchInterface'));
    $this->assertEquals([]$breadcrumb->getLinks());
    $this->assertEqualsCanonicalizing(['url.path.is_front', 'url.path.parent']$breadcrumb->getCacheContexts());
    $this->assertEqualsCanonicalizing([]$breadcrumb->getCacheTags());
    $this->assertEquals(Cache::PERMANENT, $breadcrumb->getCacheMaxAge());
  }

  /** * Tests the build method with one path element. * * @covers ::build */
  public function testBuildWithOnePathElement() {
    
foreach ($product->getDownloads() as $download) {
            $data['sDownloads'][] = [
                'id' => $download->getId(),
                'description' => $download->getDescription(),
                'filename' => $this->mediaService->getUrl($download->getFile()),
                'size' => $download->getSize(),
                'attributes' => $download->getAttributes(),
            ];
        }

        foreach ($product->getLinks() as $link) {
            $temp = [
                'id' => $link->getId(),
                'description' => $link->getDescription(),
                'link' => $link->getLink(),
                'target' => $link->getTarget(),
                'supplierSearch' => false,
                'attributes' => $link->getAttributes(),
            ];

            if (strpos($temp['link'], 'http') === false) {
                $temp['link'] = 'http://' . $link->getLink();
            }
Home | Imprint | This part of the site doesn't use cookies.