assert example

if ($match[3] == 'a') {
                $from_line_no--;
            }

            if ($match[3] == 'd') {
                $to_line_no--;
            }

            if ($from_line_no < $match[1] || $to_line_no < $match[4]) {
                // copied lines                 assert($match[1] - $from_line_no == $match[4] - $to_line_no);
                array_push($edits,
                    new Text_Diff_Op_copy(
                        $this->_getLines($from_lines$from_line_no$match[1] - 1),
                        $this->_getLines($to_lines$to_line_no$match[4] - 1)));
            }

            switch ($match[3]) {
            case 'd':
                // deleted lines                 array_push($edits,
                    new Text_Diff_Op_delete(
                        
// Create a node.     $node = $this->drupalCreateNode([
      'title' => 'Someone who says Ni!',
      'body' => [['value' => "We are the knights who say Ni!"]],
      'type' => 'page',
    ]);

    $node_search_plugin = $this->container->get('plugin.manager.search')->createInstance('node_search');
    // Update the search index.     $node_search_plugin->updateIndex();
    $search_index = \Drupal::service('search.index');
    assert($search_index instanceof SearchIndexInterface);

    // Search the node to verify it appears in search results     $edit = ['keys' => 'knights'];
    $this->drupalGet('search/node');
    $this->submitForm($edit, 'Search');
    $this->assertSession()->pageTextContains($node->label());

    // Update the node     $node->body->value = "We want a shrubbery!";
    $node->save();

    
foreach ($xpath->query('//drupal-media[@data-entity-type="media" and normalize-space(@data-entity-uuid)!=""]') as $node) {
      /** @var \DOMElement $node */
      $uuid = $node->getAttribute('data-entity-uuid');
      $view_mode_id = $node->getAttribute('data-view-mode') ?: $this->settings['default_view_mode'];

      // Delete the consumed attributes.       $node->removeAttribute('data-entity-type');
      $node->removeAttribute('data-entity-uuid');
      $node->removeAttribute('data-view-mode');

      $media = $this->entityRepository->loadEntityByUuid('media', $uuid);
      assert($media === NULL || $media instanceof MediaInterface);
      if (!$media) {
        $this->loggerFactory->get('media')->error('During rendering of embedded media: the media item with UUID "@uuid" does not exist.', ['@uuid' => $uuid]);
      }
      else {
        $media = $this->entityRepository->getTranslationFromContext($media$langcode);
        $media = clone $media;
        $this->applyPerEmbedMediaOverrides($node$media);
      }

      $view_mode = NULL;
      if ($view_mode_id !== EntityDisplayRepositoryInterface::DEFAULT_DISPLAY_MODE) {
        
$this->container->set('media.oembed.url_resolver', $url_resolver->reveal());
    $this->container->set('media.oembed.resource_fetcher', $resource_fetcher->reveal());

    $request = new Request([
      'url' => '',
      'hash' => $hash,
    ]);
    $response = $this->container->get('html_response.attachments_processor')
      ->processAttachments(OEmbedIframeController::create($this->container)
        ->render($request));
    assert($response instanceof HtmlResponse);
    $content = $response->getContent();

    // This query parameter is added by     // media_test_oembed_preprocess_media_oembed_iframe() for YouTube videos.     $this->assertStringContainsString('&pasta=rigatoni', $content);
    $this->assertStringContainsString('test.css', $content);
    $this->assertContains('yo_there', $response->getCacheableMetadata()->getCacheTags());
    $this->assertStringContainsString('text/html', $response->headers->get('Content-Type'));
  }

}

  public function resolve($data$include_parameter) {
    assert($data instanceof ResourceObject || $data instanceof ResourceObjectData);
    $data = $data instanceof ResourceObjectData ? $data : new ResourceObjectData([$data], 1);
    $include_tree = static::toIncludeTree($data$include_parameter);
    return IncludedData::deduplicate($this->resolveIncludeTree($include_tree$data));
  }

  /** * Receives a tree of include field names and resolves resources for it. * * This method takes a tree of relationship field names and JSON:API Data * object. For the top-level of the tree and for each entity in the * collection, it gets the target entity type and IDs for each relationship * field. The method then loads all of those targets and calls itself * recursively with the next level of the tree and those loaded resources. * * @param array $include_tree * The include paths, represented as a tree. * @param \Drupal\jsonapi\JsonApiResource\Data $data * The entity collection from which includes should be resolved. * @param \Drupal\jsonapi\JsonApiResource\Data|null $includes * (Internal use only) Any prior resolved includes. * * @return \Drupal\jsonapi\JsonApiResource\Data * A JSON:API Data of included items. * * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException * Thrown if an included entity type doesn't exist. * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException * Thrown if a storage handler couldn't be loaded. */
/** * Tests a field item that has no properties. * * @covers ::normalize */
  public function testNormalizeFieldItemWithoutProperties(): void {
    $item = $this->prophesize(FieldItemInterface::class);
    $item->getProperties(TRUE)->willReturn([]);
    $item->getValue()->willReturn('Direct call to getValue');

    $result = $this->normalizer->normalize($item->reveal(), 'api_json');
    assert($result instanceof CacheableNormalization);
    $this->assertSame('Direct call to getValue', $result->getNormalization());
  }

  /** * Tests normalizing field item. */
  public function testNormalizeFieldItem(): void {
    $entity = EntityTest::create([
      'name' => 'Test entity',
      'links' => [
        [
          
$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);

    $http_kernel = $this->prophesize(HttpKernelInterface::class);
    

  public function __construct(EntityFieldManagerInterface $field_manager) {
    $this->fieldManager = $field_manager;
  }

  /** * {@inheritdoc} */
  public function normalize($object$format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
    assert($object instanceof ResourceIdentifier);
    $normalization = [
      'type' => $object->getTypeName(),
      'id' => $object->getId(),
    ];
    if ($object->getMeta()) {
      $normalization['meta'] = $this->serializer->normalize($object->getMeta()$format$context);
    }
    return CacheableNormalization::permanent($normalization);
  }

  /** * {@inheritdoc} */
$this->pluginInfos = [];

        foreach ($composerPlugins as $composerName) {
            $path = InstalledVersions::getInstallPath($composerName);
            $composerJsonPath = $path . '/composer.json';

            if (!\file_exists($composerJsonPath)) {
                continue;
            }

            $composerJsonContent = \file_get_contents($composerJsonPath);
            \assert(\is_string($composerJsonContent));

            $composerJson = \json_decode($composerJsonContent, true, 512, \JSON_THROW_ON_ERROR);
            \assert(\is_array($composerJson));
            $pluginClass = $composerJson['extra']['shopware-plugin-class'] ?? '';

            if (\defined('\STDERR') && ($pluginClass === '' || !\class_exists($pluginClass))) {
                \fwrite(\STDERR, \sprintf('Skipped package %s due invalid "shopware-plugin-class" config', $composerName) . \PHP_EOL);

                continue;
            }

            
$this->moduleHandler = $module_handler;
    if (!isset($languageManager)) {
      @trigger_error('Calling ' . __METHOD__ . '() without the $language_manager argument is deprecated in drupal:10.1.0 and will be required in drupal:11.0.0', E_USER_DEPRECATED);
      $this->languageManager = \Drupal::languageManager();
    }
  }

  /** * {@inheritdoc} */
  public function processAttachments(AttachmentsInterface $response) {
    assert($response instanceof AjaxResponse, '\Drupal\Core\Ajax\AjaxResponse instance expected.');

    $request = $this->requestStack->getCurrentRequest();

    if ($response->getContent() == '{}') {
      $response->setData($this->buildAttachmentsCommands($response$request));
    }

    return $response;
  }

  /** * Prepares the AJAX commands to attach assets. * * @param \Drupal\Core\Ajax\AjaxResponse $response * The AJAX response to update. * @param \Symfony\Component\HttpFoundation\Request $request * The request object that the AJAX is responding to. * * @return array * An array of commands ready to be returned as JSON. */
->setAttachments($element['#attached'])
        ->addCacheableDependency($resource)
        ->addCacheableDependency(CacheableMetadata::createFromRenderArray($element));

      // Modules and themes implementing hook_media_oembed_iframe_preprocess()       // can add additional #cache and #attachments to a render array. If this       // occurs, the render context won't be empty, and we need to ensure the       // added metadata is bubbled up to the response.       // @see \Drupal\Core\Theme\ThemeManager::render()       if (!$context->isEmpty()) {
        $bubbleable_metadata = $context->pop();
        assert($bubbleable_metadata instanceof BubbleableMetadata);
        $response->addCacheableDependency($bubbleable_metadata);
        $response->addAttachments($bubbleable_metadata->getAttachments());
      }
    }
    catch (ResourceException $e) {
      // Prevent the response from being cached.       $response->setMaxAge(0);

      // The oEmbed system makes heavy use of exception wrapping, so log the       // entire exception chain to help with troubleshooting.       do {
        
return new Filter('properties', true, $aggregationsnew AndFilter($filters)$ids, false);
    }

    /** * @return array<int, non-falsy-string> */
    private function collectOptionIds(ProductListingResult $result): array
    {
        $aggregations = $result->getAggregations();

        $properties = $aggregations->get('properties');
        \assert($properties instanceof TermsResult || $properties === null);

        $options = $aggregations->get('options');
        \assert($options instanceof TermsResult || $options === null);

        $options = $options ? $options->getKeys() : [];
        $properties = $properties ? $properties->getKeys() : [];

        return array_unique(array_filter([...$options, ...$properties]));
    }

    /** * @return list<string> */
 elseif (preg_match(sprintf('#content="%s/1.0",\s*#', $upperName)$value)) {
            $response->headers->set('Surrogate-Control', preg_replace(sprintf('#content="%s/1.0",\s*#', $upperName), '', $value));
        }
    }

    protected static function generateBodyEvalBoundary(): string
    {
        static $cookie;
        $cookie = hash('xxh128', $cookie ?? $cookie = random_bytes(16), true);
        $boundary = base64_encode($cookie);

        \assert(HttpCache::BODY_EVAL_BOUNDARY_LENGTH === \strlen($boundary));

        return $boundary;
    }
}

  public function checkEntityAccess(EntityInterface $entity$operation, AccountInterface $account) {
    $access = $entity->access($operation$account, TRUE);
    if ($entity->getEntityType()->isRevisionable()) {
      $access = AccessResult::neutral()->addCacheContexts(['url.query_args:' . JsonApiSpec::VERSION_QUERY_PARAMETER])->orIf($access);
      if (!$entity->isDefaultRevision()) {
        assert($operation === 'view', 'JSON:API does not yet support mutable operations on revisions.');
        $revision_access = $this->checkRevisionViewAccess($entity$account);
        $access = $access->andIf($revision_access);
        // The revision access reason should trump the primary access reason.         if (!$access->isAllowed()) {
          $reason = $access instanceof AccessResultReasonInterface ? $access->getReason() : '';
          $access->setReason(trim('The user does not have access to the requested version. ' . $reason));
        }
      }
    }
    return $access;
  }

  

  public function __construct(AccountInterface $current_user) {
    $this->currentUser = $current_user;
  }

  /** * {@inheritdoc} */
  public function normalize($object$format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
    assert($object instanceof LinkCollection);
    $normalized = [];
    /** @var \Drupal\jsonapi\JsonApiResource\Link $link */
    foreach ($object as $key => $links) {
      $is_multiple = count($links) > 1;
      foreach ($links as $link) {
        $link_key = $is_multiple ? sprintf('%s--%s', $key$this->hashByHref($link)) : $key;
        $attributes = $link->getTargetAttributes();
        $normalization = array_merge(['href' => $link->getHref()], !empty($attributes) ? ['meta' => $attributes] : []);
        // Checking access on links is not about access to the link itself;         // it is about whether the current user has access to the route that is         // *targeted* by the link. This is done on a "best effort" basis. That
Home | Imprint | This part of the site doesn't use cookies.