Link example

use PHPUnit\Framework\TestCase;
use Symfony\Component\WebLink\Link;

/** * Test case borrowed from https://github.com/php-fig/link/. */
class LinkTest extends TestCase
{
    public function testCanSetAndRetrieveValues()
    {
        $link = (new Link())
            ->withHref('http://www.google.com')
            ->withRel('next')
            ->withAttribute('me', 'you')
        ;

        $this->assertEquals('http://www.google.com', $link->getHref());
        $this->assertContains('next', $link->getRels());
        $this->assertArrayHasKey('me', $link->getAttributes());
        $this->assertEquals('you', $link->getAttributes()['me']);
    }

    
public function __construct(AttributeHydrator $attributeHydrator)
    {
        $this->attributeHydrator = $attributeHydrator;
    }

    /** * @return Link */
    public function hydrate(array $data)
    {
        $link = new Link();
        $link->setId((int) $data['__link_id']);
        $link->setDescription($data['__link_description']);
        $link->setLink($data['__link_link']);
        $link->setTarget($data['__link_target']);

        if (!empty($data['__linkAttribute_id'])) {
            $this->attributeHydrator->addAttribute($link$data, 'linkAttribute');
        }

        return $link;
    }
}
    $this->testUsers[] = $this->createUser([], NULL, FALSE, ['uid' => 2]);
    $this->testUsers[] = $this->createUser([], NULL, FALSE, ['uid' => 3]);
    $this->serializer = $this->container->get('jsonapi.serializer');
  }

  /** * Tests the link collection normalizer. */
  public function testNormalize() {
    $link_context = new ResourceObject(new CacheableMetadata()new ResourceType('n/a', 'n/a', 'n/a'), 'n/a', NULL, []new LinkCollection([]));
    $link_collection = (new LinkCollection([]))
      ->withLink('related', new Link(new CacheableMetadata(), Url::fromUri('http://example.com/post/42'), 'related', ['title' => 'Most viewed']))
      ->withLink('related', new Link(new CacheableMetadata(), Url::fromUri('http://example.com/post/42'), 'related', ['title' => 'Top rated']))
      ->withContext($link_context);
    // Create the SUT.     $normalized = $this->getNormalizer()->normalize($link_collection)->getNormalization();
    $this->assertIsArray($normalized);
    foreach (array_keys($normalized) as $key) {
      $this->assertStringStartsWith('related', $key);
    }
    $this->assertSame([
      [
        'href' => 'http://example.com/post/42',
        
$url->setUrlGenerator($this->urlGenerator);
    $expected_link_markup = '<a href="/test-route-1">Test</a>';

    // Test ::generate().     $this->assertSame($expected_link_markup(string) $this->linkGenerator->generate('Test', $url));
    $generated_link = $this->linkGenerator->generate('Test', $url);
    $this->assertSame($expected_link_markup(string) $generated_link->getGeneratedLink());
    $this->assertInstanceOf('\Drupal\Core\Render\BubbleableMetadata', $generated_link);

    // Test ::generateFromLink().     $this->expectDeprecation('\Drupal\Core\Utility\LinkGeneratorInterface::generateFromLink() is deprecated in drupal:10.1.0 and is removed from drupal:11.0.0. Use \Drupal\Core\Utility\LinkGeneratorInterface::generate() instead. See https://www.drupal.org/node/3342992');
    $link = new Link('Test', $url);
    $this->assertSame($expected_link_markup(string) $this->linkGenerator->generateFromLink($link));
    $generated_link = $this->linkGenerator->generateFromLink($link);
    $this->assertSame($expected_link_markup(string) $generated_link->getGeneratedLink());
    $this->assertInstanceOf('\Drupal\Core\Render\BubbleableMetadata', $generated_link);
  }

  /** * Tests altering the URL object using hook_link_alter(). * * @covers ::generate */
  
$this->assertEquals('<a href="http://example.com"></a>', $output);
    /** @var \Drupal\Core\Render\BubbleableMetadata $metadata */
    $metadata = $context->pop();
    $this->assertEquals(['foo']$metadata->getCacheTags());
    $this->assertEquals(['library' => ['system/base']]$metadata->getAttachments());
  }

  /** * Ensure cache metadata is bubbled when using theme_render_and_autoescape(). */
  public function testBubblingMetadataWithRenderable() {
    $link = new Link('', Url::fromRoute('<current>'));

    $context = new RenderContext();
    // Use a closure here since we need to render with a render context.     $theme_render_and_autoescape = function D) use ($link) {
      return theme_render_and_autoescape($link);
    };
    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = \Drupal::service('renderer');
    $output = $renderer->executeInRenderContext($context$theme_render_and_autoescape);
    $this->assertEquals('<a href="/' . urlencode('<none>') . '"></a>', $output);
    /** @var \Drupal\Core\Render\BubbleableMetadata $metadata */
    
$builder = $this->get('models')->createQueryBuilder();
        $links = $builder->select(['links', 'attribute'])
            ->from(Link::class, 'links')
            ->leftJoin('links.attribute', 'attribute')
            ->where('links.articleId = ?1')
            ->setParameter(1, $articleId)
            ->getQuery()
            ->getArrayResult();

        foreach ($links as $data) {
            $link = new Link();
            $link->fromArray($data);
            $link->setArticle($product);
            $this->get('models')->persist($link);
        }
        $this->get('models')->flush();
    }

    /** * Internal helper function to duplicate the product translations from the passed product * to the new product. * * @param int $articleId * @param int $newArticleId */
protected static function buildLinksFromEntity(ResourceType $resource_type, EntityInterface $entity, LinkCollection $links) {
    if ($resource_type->isLocatable() && !$resource_type->isInternal()) {
      $self_url = Url::fromRoute(Routes::getRouteName($resource_type, 'individual')['entity' => $entity->uuid()]);
      if ($resource_type->isVersionable()) {
        assert($entity instanceof RevisionableInterface);
        if (!$links->hasLinkWithKey('self')) {
          // If the resource is versionable, the `self` link should be the exact           // link for the represented version. This helps a client track           // revision changes and to disambiguate resource objects with the same           // `type` and `id` in a `version-history` collection.           $self_with_version_url = $self_url->setOption('query', [JsonApiSpec::VERSION_QUERY_PARAMETER => 'id:' . $entity->getRevisionId()]);
          $links = $links->withLink('self', new Link(new CacheableMetadata()$self_with_version_url, 'self'));
        }
        if (!$entity->isDefaultRevision()) {
          $latest_version_url = $self_url->setOption('query', [JsonApiSpec::VERSION_QUERY_PARAMETER => 'rel:' . VersionByRel::LATEST_VERSION]);
          $links = $links->withLink(VersionByRel::LATEST_VERSION, new Link(new CacheableMetadata()$latest_version_url, VersionByRel::LATEST_VERSION));
        }
        if (!$entity->isLatestRevision()) {
          $working_copy_url = $self_url->setOption('query', [JsonApiSpec::VERSION_QUERY_PARAMETER => 'rel:' . VersionByRel::WORKING_COPY]);
          $links = $links->withLink(VersionByRel::WORKING_COPY, new Link(new CacheableMetadata()$working_copy_url, VersionByRel::WORKING_COPY));
        }
      }
      if (!$links->hasLinkWithKey('self')) {
        
// The set of breadcrumb links depends on the access result, so merge         // the access result's cacheability metadata.         $breadcrumb = $breadcrumb->addCacheableDependency($access);
        if ($access->isAllowed()) {
          $title = $this->titleResolver->getTitle($route_request$route_match->getRouteObject());
          if (!isset($title)) {
            // Fallback to using the raw path component as the title if the             // route is missing a _title or _title_callback attribute.             $title = str_replace(['-', '_'], ' ', Unicode::ucfirst(end($path_elements)));
          }
          $url = Url::fromRouteMatch($route_match);
          $links[] = new Link($title$url);
        }
      }
    }

    // Add the Home link.     $links[] = Link::createFromRoute($this->t('Home'), '<front>');

    return $breadcrumb->setLinks(array_reverse($links));
  }

  /** * Matches a path in the router. * * @param string $path * The request path with a leading slash. * @param array $exclude * An array of paths or system paths to skip. * * @return \Symfony\Component\HttpFoundation\Request * A populated request object or NULL if the path couldn't be matched. */
if ($file instanceof EntityConstraintViolationListInterface) {
      $violations = $file;
      $message = "Unprocessable Entity: file validation failed.\n";
      $message .= implode("\n", array_map(function DConstraintViolationInterface $violation) {
        return PlainTextOutput::renderFromHtml($violation->getMessage());
      }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. */

  protected function createLink($uri) {
    if ($uri !== NULL && UrlHelper::isValid($uri, TRUE)) {
      return new Link($uri, Url::fromUri($uri));
    }
    return $uri;
  }

  /** * Shows the most frequent log messages of a given event type. * * Messages are not truncated on this page because events detailed herein do * not have links to a detailed view. * * @param string $type * Type of database log events to display (e.g., 'search'). * * @return array * A build array in the format expected by * \Drupal\Core\Render\RendererInterface::render(). */
$actual = Link::compare($a$b);
    $this->assertSame($expected$actual === 0);
  }

  /** * Provides test data for link comparison. */
  public function linkComparisonProvider() {
    $this->mockUrlAssembler();
    return [
      'same href and same link relation type' => [
        new Link(new CacheableMetadata(), Url::fromUri('https://jsonapi.org/foo'), 'self'),
        new Link(new CacheableMetadata(), Url::fromUri('https://jsonapi.org/foo'), 'self'),
        TRUE,
      ],
      'different href and same link relation type' => [
        new Link(new CacheableMetadata(), Url::fromUri('https://jsonapi.org/foo'), 'self'),
        new Link(new CacheableMetadata(), Url::fromUri('https://jsonapi.org/bar'), 'self'),
        FALSE,
      ],
      'same href and different link relation type' => [
        new Link(new CacheableMetadata(), Url::fromUri('https://jsonapi.org/foo'), 'self'),
        new Link(new CacheableMetadata(), Url::fromUri('https://jsonapi.org/foo'), 'related'),
        

    public function link(string $uri, string $rel, array $attributes = []): string
    {
        if (!$request = $this->requestStack->getMainRequest()) {
            return $uri;
        }

        $link = new Link($rel$uri);
        foreach ($attributes as $key => $value) {
            $link = $link->withAttribute($key$value);
        }

        $linkProvider = $request->attributes->get('_links', new GenericLinkProvider());
        $request->attributes->set('_links', $linkProvider->withLink($link));

        return $uri;
    }

    /** * Preloads a resource. * * @param array $attributes The attributes of this link (e.g. "['as' => true]", "['crossorigin' => 'use-credentials']") * * @return string The path of the asset */
use PHPUnit\Framework\TestCase;
use Symfony\Component\DomCrawler\Link;

class LinkTest extends TestCase
{
    public function testConstructorWithANonATag()
    {
        $this->expectException(\LogicException::class);
        $dom = new \DOMDocument();
        $dom->loadHTML('<html><div><div></html>');

        new Link($dom->getElementsByTagName('div')->item(0), 'http://www.example.com/');
    }

    public function testBaseUriIsOptionalWhenLinkUrlIsAbsolute()
    {
        $dom = new \DOMDocument();
        $dom->loadHTML('<html><a href="https://example.com/foo">foo</a></html>');

        $link = new Link($dom->getElementsByTagName('a')->item(0));
        $this->assertSame('https://example.com/foo', $link->getUri());
    }

    


  /** * {@inheritdoc} */
  public function build(RouteMatchInterface $route_match) {
    $breadcrumb = new Breadcrumb();
    $breadcrumb->addCacheContexts(['route']);
    $breadcrumb->addLink(Link::createFromRoute($this->t('Home'), '<front>'));

    $entity = $route_match->getParameter('entity');
    $breadcrumb->addLink(new Link($entity->label()$entity->toUrl()));
    $breadcrumb->addCacheableDependency($entity);

    if (($pid = $route_match->getParameter('pid')) && ($comment = $this->entityTypeManager->getStorage('comment')->load($pid))) {
      /** @var \Drupal\comment\CommentInterface $comment */
      $breadcrumb->addCacheableDependency($comment);
      // Display link to parent comment.       // @todo Clean-up permalink in https://www.drupal.org/node/2198041       $breadcrumb->addLink(new Link($comment->getSubject()$comment->toUrl()));
    }

    return $breadcrumb;
  }

  protected function buildWrappedResponse(TopLevelDataInterface $data, Request $request, IncludedData $includes$response_code = 200, array $headers = [], LinkCollection $links = NULL, array $meta = []) {
    $links = ($links ?: new LinkCollection([]));
    if (!$links->hasLinkWithKey('self')) {
      $self_link = new Link(new CacheableMetadata(), self::getRequestLink($request), 'self');
      $links = $links->withLink('self', $self_link);
    }
    $document = new JsonApiDocumentTopLevel($data$includes$links$meta);
    if (!$request->isMethodCacheable()) {
      return new ResourceResponse($document$response_code$headers);
    }
    $response = new CacheableResourceResponse($document$response_code$headers);
    $cacheability = (new CacheableMetadata())->addCacheContexts([
      // Make sure that different sparse fieldsets are cached differently.       'url.query_args:fields',
      // Make sure that different sets of includes are cached differently.
Home | Imprint | This part of the site doesn't use cookies.