{@inheritDoc}

@since 2.5RC1
189330
@Override
    protected XWikiSyntaxResourceRenderer createXWikiSyntaxImageRenderer(ListenerChain listenerChain,
        ResourceReferenceSerializer imageReferenceSerializer)
    {
        return new XWikiSyntaxResourceRenderer((XWikiSyntaxListenerChain) listenerChain, imageReferenceSerializer);
    }
285016
public function process($rawHtml, $name = '', $context = [], $environment = null)
    {

        try {
            $html5 = new HTML5();
            $document = $html5->loadHTML($rawHtml);

            /** @var ExtractorExtension $extractorExtension */
            $extractorExtension = $environment->getExtension(ExtractorExtension::class);
            foreach ($document->getElementsByTagName('link') as $linkTag) {
                /** @var DOMElement $linkTag */
                if ($linkTag->getAttribute('rel') == 'stylesheet') {
                    $tokenisedStylesheet = explode('?', $linkTag->getAttribute('href'));
                    $stylesheet = reset($tokenisedStylesheet);

                    if ($content = $this->fileCache->fetch($stylesheet)) {
                        $extractorExtension->addBaseRules($content);
                        continue;
                    }


                    if (($content = @file_get_contents($stylesheet)) !== false) {
                        $this->fileCache->save($stylesheet, $content);
                        $extractorExtension->addBaseRules($content);
                        continue;
                    }
                    if (($content = @file_get_contents($_SERVER['DOCUMENT_ROOT'] . $stylesheet)) !== false) {
                        $this->fileCache->save($stylesheet, $content);
                        $extractorExtension->addBaseRules($content);
                        continue;
                    }
                }
            }

        } catch (\Exception $exception) {
            error_log($exception->getMessage());
            return $rawHtml;
        }

        try {
            $criticalCss = $extractorExtension->buildCriticalCssFromSnippets();

            if (strlen($criticalCss) == 0) {
                return $rawHtml;
            }
        } catch (Twig_Error_Runtime $tew) {
            error_log($tew->getMessage());
            return $rawHtml;
        }

        try {
            $headStyle = new DOMElement('style', $criticalCss);
            $document->getElementsByTagName('head')->item(0)->appendChild($headStyle);

            return $html5->saveHTML($document);
        } catch (\Exception $exception) {
            error_log($exception->getMessage());
            return $rawHtml;
        }
    }
693045
public function normalize($object, $format = null, array $context = [])
    {
        if ($object !== $transformed = $this->transformOutput($object, $context)) {
            if (!$this->serializer instanceof NormalizerInterface) {
                throw new LogicException('Cannot normalize the transformed value because the injected serializer is not a normalizer');
            }

            $context['api_normalize'] = true;
            $context['api_resource'] = $object;
            unset($context['output']);

            return $this->serializer->normalize($transformed, $format, $context);
        }

        // Use resolved resource class instead of given resource class to support multiple inheritance child types
        $resourceClass = $this->resourceClassResolver->getResourceClass($object, $context['resource_class'] ?? null, true);
        $context = $this->initContext($resourceClass, $context);
        $iri = $context['iri'] ?? $this->iriConverter->getIriFromItem($object);
        $context['iri'] = $iri;
        $context['api_normalize'] = true;

        /*
         * When true, converts the normalized data array of a resource into an
         * IRI, if the normalized data array is empty.
         *
         * This is useful when traversing from a non-resource towards an attribute
         * which is a resource, as we do not have the benefit of {@see PropertyMetadata::isReadableLink}.
         *
         * It must not be propagated to subresources, as {@see PropertyMetadata::isReadableLink}
         * should take effect.
         */
        $emptyResourceAsIri = $context['api_empty_resource_as_iri'] ?? false;
        unset($context['api_empty_resource_as_iri']);

        if (isset($context['resources'])) {
            $context['resources'][$iri] = $iri;
        }

        $data = parent::normalize($object, $format, $context);
        if ($emptyResourceAsIri && \is_array($data) && 0 === \count($data)) {
            return $iri;
        }

        return $data;
    }
85230
public function it_throws_circular_redirection_exception_on_alternating_redirect(
        UriInterface $uri,
        UriInterface $redirectUri,
        RequestInterface $request,
        ResponseInterface $redirectResponse1,
        ResponseInterface $redirectResponse2,
        RequestInterface $modifiedRequest
    ) {
        $redirectResponse1->getStatusCode()->willReturn(302);
        $redirectResponse1->hasHeader('Location')->willReturn(true);
        $redirectResponse1->getHeaderLine('Location')->willReturn('/redirect');

        $redirectResponse2->getStatusCode()->willReturn(302);
        $redirectResponse2->hasHeader('Location')->willReturn(true);
        $redirectResponse2->getHeaderLine('Location')->willReturn('/original');

        $next = function (RequestInterface $currentRequest) use ($request, $redirectResponse1, $redirectResponse2): Promise {
            return ($currentRequest === $request->getWrappedObject())
                ? new HttpFulfilledPromise($redirectResponse1->getWrappedObject())
                : new HttpFulfilledPromise($redirectResponse2->getWrappedObject())
            ;
        };

        $redirectPlugin = $this;
        $firstCalled = false;
        $first = function (RequestInterface $request) use (&$firstCalled, $redirectPlugin, $next, &$first) {
            if ($firstCalled) {
                throw new \Exception('only one redirect expected');
            }
            $firstCalled = true;

            return $redirectPlugin->getWrappedObject()->handleRequest($request, $next, $first);
        };

        $request->getUri()->willReturn($uri);
        $uri->__toString()->willReturn('/original');

        $modifiedRequest->getUri()->willReturn($redirectUri);
        $redirectUri->__toString()->willReturn('/redirect');

        $uri->withPath('/redirect')->willReturn($redirectUri);
        $redirectUri->withFragment('')->willReturn($redirectUri);
        $redirectUri->withQuery('')->willReturn($redirectUri);

        $redirectUri->withPath('/original')->willReturn($uri);
        $uri->withFragment('')->willReturn($uri);
        $uri->withQuery('')->willReturn($uri);

        $request->withUri($redirectUri)->willReturn($modifiedRequest);
        $request->getMethod()->willReturn('GET');
        $modifiedRequest->withUri($uri)->willReturn($request);
        $modifiedRequest->getMethod()->willReturn('GET');

        $promise = $this->handleRequest($request, $next, $first);
        $promise->shouldReturnAnInstanceOf(HttpRejectedPromise::class);
        $promise->shouldThrow(CircularRedirectionException::class)->duringWait();
    }
801999
public function func()
    {
        $args = func_get_args();
        $fns  = explode('|', array_shift($args));
        $res  = null;

        foreach (array_reverse($fns) as $fnc) {
            if (!isset($this->functions[$fnc])) {
                throw new \RuntimeException(sprintf('Template function "%s" does not exist.', $fnc));
            }

            $res = $this->functions[$fnc]->call($args);

            if (!$this->functions[$fnc]->getOption('is_safe_html')) {
                $res = $this->escape($res);
            }

            $args = [$res];
        }

        return $res;
    }
1104951
private function resolveForVersion5(string $namespace, string $class, string $method): string
    {
        $bundle = Strings::match($namespace, '#(?<bundle>[\w]*Bundle)#')['bundle'] ?? '';
        $bundle = Strings::replace($bundle, '#Bundle$#');
        $bundle = $bundle !== '' ? '@' . $bundle . '/' : '';

        $controller = $this->resolveControllerVersion5($class);
        $action = Strings::replace($method, '#Action$#');

        return sprintf('%s%s%s.html.twig', $bundle, $controller, $action);
    }
1064474
public function toEntity(
        $parent,
        ResourceTransformer $resourceTransformer,
        PropertyResolver $propertyResolver,
        PropertySetter $propertySetter,
        EntityFactory $factory,
        Context $context
    ) {
        $children = $this->getChildrenToProcess();

        $childrenToAdd = [];
        $childrenToEdit = [];

        /**
         * Keep a list of all identifies we've touched, so we can removed those we haven't
         * @var PropertyValueCollection[] $identifiersToKeep
         */
        $identifiersToKeep = [];

        /** @var RelationshipField $field */
        $field = $this->getField();

        foreach ($children as $child) {
            if (!$child) {
                continue;
            }

            /** @var RESTResource $child */

            /** @var bool $isNew */
            $isNew = $child->isNew();

            $childIdentifiers = $child->getProperties()->getIdentifiers();

            $childEntity = null;
            if (!$isNew) {
                $childEntity = $this->getChildByIdentifiers(
                    $resourceTransformer,
                    $propertyResolver,
                    $parent,
                    $childIdentifiers,
                    $context
                );

                if ($childEntity) {
                    $identifiersToKeep[] = $childIdentifiers;
                }
            }

            // Do we just link the resource? In this case we can't edit it right now.
            if ($field->canLinkExistingEntities()) {
                $entity = $factory->resolveLinkedEntity(
                    $parent,
                    $child->getResourceDefinition()->getEntityClassName(),
                    $childIdentifiers->toMap(),
                    $context
                );

                if ($entity) {
                    $childrenToAdd[] = $entity;
                    $identifiersToKeep[] = $childIdentifiers;
                    continue;
                }
            }

            // Is this a new child? We might not be able to add it...
            if (!$childEntity && !$field->canCreateNewChildren()) {
                throw new InvalidPropertyException(
                    "Only existing items can be linked to " . get_class($parent) . "->" . $field->getName()
                );
            }

            $entity = $resourceTransformer->toEntity(
                $child,
                $child->getResourceDefinition(),
                $factory,
                $context,
                $childEntity
            );

            if (!isset($childEntity)) {
                $childrenToAdd[] = $entity;
            } else {
                $childrenToEdit[] = $entity;
            }
        }

        if (count($childrenToAdd) > 0) {
            $this->addChildren(
                $resourceTransformer,
                $propertySetter,
                $parent,
                $this->getField(),
                $childrenToAdd,
                $context
            );
        }

        if (count($childrenToEdit) > 0) {
            $this->editChildren(
                $resourceTransformer,
                $propertySetter,
                $parent,
                $this->getField(),
                $childrenToEdit,
                $context
            );
        }

        // Notify the setter to remove all children that haven't been touched (in the range defined in the context)
        $this->removeAllChildrenExcept(
            $resourceTransformer,
            $propertyResolver,
            $propertySetter,
            $parent,
            $this->getField(),
            $identifiersToKeep,
            $context
        );
    }
877944
public function processCancel(FormActionEvent $event)
    {
        /** @var \EzSystems\RepositoryForms\Data\Content\ContentCreateData|\EzSystems\RepositoryForms\Data\Content\ContentUpdateData $data */
        $data = $event->getData();

        if ($data->isNew()) {
            $response = new RedirectResponse($this->router->generate(
                '_ezpublishLocation',
                ['locationId' => $data->getLocationStructs()[0]->parentLocationId]
            ));
            $event->setResponse($response);

            return;
        }

        $content = $data->contentDraft;
        $contentInfo = $content->contentInfo;
        $versionInfo = $data->contentDraft->getVersionInfo();

        $event->setPayload('content', $content);

        // if there is only one version you have to remove whole content instead of a version itself
        if (1 === count($this->contentService->loadVersions($contentInfo))) {
            $parentLocation = $this->locationService->loadParentLocationsForDraftContent($versionInfo)[0];
            $redirectionLocationId = $parentLocation->id;
            $this->contentService->deleteContent($contentInfo);
        } else {
            $redirectionLocationId = $contentInfo->mainLocationId;
            $this->contentService->deleteVersion($versionInfo);
        }

        $url = $this->router->generate(
            '_ezpublishLocation',
            ['locationId' => $redirectionLocationId],
            UrlGeneratorInterface::ABSOLUTE_URL
        );

        $event->setResponse(new RedirectResponse($url));
    }
69953
public function convertUriToObject($uri, NodeInterface $contextNode = null)
    {
        if ($uri instanceof Uri) {
            $uri = (string)$uri;
        }

        if (preg_match(self::PATTERN_SUPPORTED_URIS, $uri, $matches) === 1) {
            switch ($matches[1]) {
                case 'node':
                    if ($contextNode === null) {
                        throw new \RuntimeException('node:// URI conversion requires a context node to be passed', 1409734235);
                    };

                    return $contextNode->getContext()->getNodeByIdentifier($matches[2]);
                case 'asset':
                    return $this->assetRepository->findByIdentifier($matches[2]);
            }
        }

        return null;
    }
1350788
public function c ()
    {
        $fields = array();
        foreach ($this->getFields() as $field)
            /* @var $field Field */
            if ($field->getCollectData())
                $fields[] = $field;
        return $fields;
    }
205372
public function execute()
    {
        $data = $this->getData();

        /*
         * Step 1) Apply sorting
         *
         * @see http://php.net/manual/de/function.array-multisort.php
         * @see example number 3
         */
        if (!empty($this->getSortConditions())) {
            $data = $this->sortArrayMultiple($data, $this->getSortConditions());
        }

        /*
         * Step 2) Apply filters
         */
        foreach ($this->getFilters() as $filter) {
            /* @var $filter \ZfcDatagrid\Filter */
            if ($filter->isColumnFilter() === true) {
                $data = array_filter($data, [
                    new PhpArray\Filter($filter),
                    'applyFilter',
                ]);
            }
        }

        /**
         * Step 3) Remove unneeded columns.
         *
         * @todo ? Better performance or let it be?
         */
        $selectedColumns = [];
        foreach ($this->getColumns() as $col) {
            if (! $col instanceof Column\Select) {
                continue;
            }

            $colString = $col->getSelectPart1();
            if ($col->getSelectPart2() != '') {
                $colString = $col->getSelectPart1().'_'.$col->getSelectPart2();
            }

            $selectedColumns[] = $colString;
        }

        foreach ($data as &$row) {
            foreach ($row as $keyRowCol => $rowCol) {
                if (! in_array($keyRowCol, $selectedColumns)) {
                    unset($row[$keyRowCol]);
                }
            }
        }

        /*
         * Step 4) Pagination
         */
        $this->setPaginatorAdapter(new PaginatorAdapter($data));
    }
283045
public function resolve(Document $document, Uri $ref, $name, $depth, PropertyInterface $property = null)
    {
        $uri = $this->resolver->resolve($document->getBaseUri(), $ref);

        if (isset($this->objects[$uri->toString()])) {
            return $this->objects[$uri->toString()];
        }

        if ($property === null) {
            $property = new PropertyType();
            $property->setRef($uri->toString());
        }

        $this->objects[$uri->toString()] = $property;

        $doc  = $this->getDocument($uri, $document);
        $doc->getProperty($uri->getFragment(), $name, $depth, $property);

        return $property;
    }
442950
public static function SelectValuesWithParamAndResolver( $xpath, $resolver, $vars )
	{
		/**
		 * @var XPath2NodeIterator $iter
		 */
		$iter = XPath2NodeIterator::Create( Compile( $xpath, $resolver )->EvaluateWithVars( null, $vars ) );
		while ( $iter->MoveNext() )
		{
			yield $iter->getCurrent()->GetTypedValue();
		}
	}
1245581
public function compile()
	{
		if ($this->multiSelect)
		{
			if (is_array($arrData = \StringUtil::deserialize($this->data->multiSelectField)))
			{
				foreach ($arrData as &$data)
				{
					$data = substr($data,1); // Remove the alphabetic character
				}
				
				$this->writeToTemplate($arrData);
			}
		}
		else
		{
			$this->writeToTemplate(substr($this->data->singleSelectField,1)); // Remove the alphabetic character
		}
	}
887154
public function process(ContainerBuilder $container): void
    {
        $collector = $container->findDefinition('fivelab.resource.serializer.context_collector');
        $services = $container->findTaggedServiceIds('resource.serializer.collector');

        foreach ($services as $serviceId => $tags) {
            try {
                $collectorDefinition = $container->getDefinition($serviceId);
                $collectorClass = $container->getParameterBag()->resolveValue($collectorDefinition->getClass());

                if (!is_a($collectorClass, SerializationContextCollectorInterface::class, true)) {
                    throw new \RuntimeException(sprintf(
                        'The serialization context collector should implement "%s".',
                        SerializationContextCollectorInterface::class
                    ));
                }

                $collector->addMethodCall('add', [
                    new Reference($serviceId),
                ]);
            } catch (\Exception $e) {
                throw new \RuntimeException(sprintf(
                    'Can\'t compile resource serialization collector with service id "%s".',
                    $serviceId
                ), 0, $e);
            }
        }
    }
122836
public function execute()
    {
        parent::execute();

        HpsInputValidation::checkAmount($this->amount);

        $xml = new DOMDocument();
        $hpsTransaction = $xml->createElement('hps:Transaction');
        $hpsRecurringBilling = $xml->createElement('hps:RecurringBilling');
        $hpsBlock1 = $xml->createElement('hps:Block1');

        $hpsBlock1->appendChild($xml->createElement('hps:AllowDup', 'Y'));
        $hpsBlock1->appendChild($xml->createElement('hps:Amt', $this->amount));
        if ($this->cardHolder != null) {
            $hpsBlock1->appendChild($this->service->_hydrateCardHolderData($this->cardHolder, $xml));
        }
        if ($this->details != null) {
            $hpsBlock1->appendChild($this->service->_hydrateAdditionalTxnFields($this->details, $xml));
        }

        if ($this->card != null) {
            $cardData = $xml->createElement('hps:CardData');
            $cardData->appendChild($this->service->_hydrateManualEntry($this->card, $xml));
            $hpsBlock1->appendChild($cardData);
        } else if ($this->token != null) {
            $cardData = $xml->createElement('hps:CardData');
            $cardData->appendChild($this->service->_hydrateTokenData($this->token, $xml));
            $hpsBlock1->appendChild($cardData);
        } else if ($this->paymentMethodKey != null) {
            $hpsBlock1->appendChild($xml->createElement('hps:PaymentMethodKey', $this->paymentMethodKey));
        }

        $recurringData = $xml->createElement('hps:RecurringData');
        if ($this->schedule != null) {
            $id = $this->schedule;
            if ($this->schedule instanceof HpsPayPlanSchedule) {
                $id = $this->schedule->scheduleIdentifier;
            }
            $recurringData->appendChild($xml->createElement('hps:ScheduleID', $id));
        }
        $recurringData->appendChild($xml->createElement('hps:OneTime', ($this->oneTime ? 'Y' : 'N')));

        $hpsBlock1->appendChild($recurringData);
        $hpsRecurringBilling->appendChild($hpsBlock1);
        $hpsTransaction->appendChild($hpsRecurringBilling);

        return $this->service->_submitTransaction($hpsTransaction, 'RecurringBilling', (isset($this->details->clientTransactionId) ? $this->details->clientTransactionId : null));
    }
671468
public function &c() {
    $args = func_get_args();
    if (count($args) > $this->argsCount) {
      $rel = array_pop($args); // rel ist übergeben worden
    } else {
      $rel = 0;
    }
    for ($i=0; $i < $this->argsCount; $i++) {
      $this->values[$i][] = $args[$i];
    }

    $key = $this->getKey($args);
    if (!array_key_exists($key,$this->counts)) {
      $this->counts[$key] = $this->initCount;
    }
    $ref =& $this->counts[$key];
    $ref += $rel;
    return $ref;
  }