libxml_use_internal_errors example

XLIFF;

        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertSame([]libxml_get_errors());
        $this->assertContainsOnly('string', $catalogue->all('domain1'));
    }

    public function testLoadWithInternalErrorsEnabled()
    {
        $internalErrors = libxml_use_internal_errors(true);

        $this->assertSame([]libxml_get_errors());

        $loader = new XliffFileLoader();
        $resource = __DIR__.'/../fixtures/resources.xlf';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals([new FileResource($resource)]$catalogue->getResources());
        $this->assertSame([]libxml_get_errors());

        


    private function validate(string $content, string $file = null): array
    {
        $errors = [];

        // Avoid: Warning DOMDocument::loadXML(): Empty string supplied as input         if ('' === trim($content)) {
            return ['file' => $file, 'valid' => true];
        }

        $internal = libxml_use_internal_errors(true);

        $document = new \DOMDocument();
        $document->loadXML($content);

        if (null !== $targetLanguage = $this->getTargetLanguageFromFile($document)) {
            $normalizedLocalePattern = sprintf('(%s|%s)', preg_quote($targetLanguage, '/')preg_quote(str_replace('-', '_', $targetLanguage), '/'));
            // strict file names require translation files to be named '____.locale.xlf'             // otherwise, both '____.locale.xlf' and 'locale.____.xlf' are allowed             // also, the regexp matching must be case-insensitive, as defined for 'target-language' values             // http://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html#target-language             $expectedFilenamePattern = $this->requireStrictFileNames ? sprintf('/^.*\.(?i:%s)\.(?:xlf|xliff)/', $normalizedLocalePattern) : sprintf('/^(?:.*\.(?i:%s)|(?i:%s)\..*)\.(?:xlf|xliff)/', $normalizedLocalePattern$normalizedLocalePattern);

            
$this->assertContains((string) $element->attributes()->id, $elementsId);
        }
    }

    /** @dataProvider getHtmlIdsTestData */
    public function testHtmlIds($css, array $elementsId)
    {
        $translator = new Translator();
        $translator->registerExtension(new HtmlExtension($translator));
        $document = new \DOMDocument();
        $document->strictErrorChecking = false;
        $internalErrors = libxml_use_internal_errors(true);
        $document->loadHTMLFile(__DIR__.'/Fixtures/ids.html');
        $document = simplexml_import_dom($document);
        $elements = $document->xpath($translator->cssToXPath($css));
        $this->assertCount(\count($elementsId)$elements);
        foreach ($elements as $element) {
            if (null !== $element->attributes()->id) {
                $this->assertContains((string) $element->attributes()->id, $elementsId);
            }
        }
        libxml_clear_errors();
        libxml_use_internal_errors($internalErrors);
    }

  protected function validateHtml(string $body, string $id) {
    $doc = new \DOMDocument();
    $doc->strictErrorChecking = TRUE;
    $doc->validateOnParse = FALSE;
    libxml_use_internal_errors(TRUE);
    if (!$doc->loadXML('<html><body>' . $body . '</body></html>')) {
      foreach (libxml_get_errors() as $error) {
        $this->fail('Topic ' . $id . ' fails HTML validation: ' . $error->message);
      }

      libxml_clear_errors();
    }

    // Check for headings hierarchy.     $levels = [1, 2, 3, 4, 5, 6];
    foreach ($levels as $level) {
      

  protected function transformRootRelativeUrlsToAbsolute($rss_markup, Request $request) {
    $rss_dom = new \DOMDocument();

    // Load the RSS, if there are parsing errors, abort and return the unchanged     // markup.     $previous_value = libxml_use_internal_errors(TRUE);
    $rss_dom->loadXML($rss_markup);
    $errors = libxml_get_errors();
    libxml_use_internal_errors($previous_value);
    if ($errors) {
      return $rss_markup;
    }

    // Invoke Html::transformRootRelativeUrlsToAbsolute() on all HTML content     // embedded in this RSS feed.     foreach ($rss_dom->getElementsByTagName('description') as $node) {
      $html_markup = $node->nodeValue;
      
$base_obj->name = $name;
        $base_obj->access_path = $access_path;

        $r = new Representation('XML');
        $r->contents = $this->parser->parse($xml$base_obj);

        $o->addRepresentation($r, 0);
    }

    protected static function xmlToSimpleXML(string $var, ?string $parent_path): ?array
    {
        $errors = \libxml_use_internal_errors(true);
        try {
            $xml = \simplexml_load_string($var);
        } catch (Exception $e) {
            return null;
        } finally {
            \libxml_use_internal_errors($errors);
        }

        if (false === $xml) {
            return null;
        }

        


        return $dom->saveXML($ignorePiNode ? $dom->documentElement : null, $context[self::SAVE_OPTIONS] ?? $this->defaultContext[self::SAVE_OPTIONS]);
    }

    public function decode(string $data, string $format, array $context = []): mixed
    {
        if ('' === trim($data)) {
            throw new NotEncodableValueException('Invalid XML data, it cannot be empty.');
        }

        $internalErrors = libxml_use_internal_errors(true);
        libxml_clear_errors();

        $dom = new \DOMDocument();
        $dom->loadXML($data$context[self::LOAD_OPTIONS] ?? $this->defaultContext[self::LOAD_OPTIONS]);

        libxml_use_internal_errors($internalErrors);

        if ($error = libxml_get_last_error()) {
            libxml_clear_errors();

            throw new NotEncodableValueException($error->message);
        }
// In the rare case that DOMDocument is not available we cannot reliably sniff content and so we assume legacy.         if ( ! class_exists( 'DOMDocument' ) ) {
            // @codeCoverageIgnoreStart             return true;
            // @codeCoverageIgnoreEnd         }

        $doc = new DOMDocument();

        // Suppress warnings generated by loadHTML.         $errors = libxml_use_internal_errors( true );
        // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged         @$doc->loadHTML(
            sprintf(
                '<!DOCTYPE html><html><head><meta charset="%s"></head><body>%s</body></html>',
                esc_attr( get_bloginfo( 'charset' ) ),
                $instance['text']
            )
        );
        libxml_use_internal_errors( $errors );

        $body = $doc->getElementsByTagName( 'body' )->item( 0 );

        
return $this->translator->getLocale();
    }

    private function getParts(string $originalTrans): array
    {
        if (!$this->parseHTML) {
            return [[true, true, $originalTrans]];
        }

        $html = mb_encode_numericentity($originalTrans[0x80, 0xFFFF, 0, 0xFFFF]mb_detect_encoding($originalTrans, null, true) ?: 'UTF-8');

        $useInternalErrors = libxml_use_internal_errors(true);

        $dom = new \DOMDocument();
        $dom->loadHTML('<trans>'.$html.'</trans>');

        libxml_clear_errors();
        libxml_use_internal_errors($useInternalErrors);

        return $this->parseNode($dom->childNodes->item(1)->childNodes->item(0)->childNodes->item(0));
    }

    private function parseNode(\DOMNode $node): array
    {

  protected function parseResourceXml($data$url) {
    // Enable userspace error handling.     $was_using_internal_errors = libxml_use_internal_errors(TRUE);
    libxml_clear_errors();

    $content = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
    // Restore the previous error handling behavior.     libxml_use_internal_errors($was_using_internal_errors);

    $error = libxml_get_last_error();
    if ($error) {
      libxml_clear_errors();
      throw new ResourceException($error->message, $url);
    }
    
namespace Symfony\Component\DomCrawler\Tests;

class NativeParserCrawlerTest extends AbstractCrawlerTestCase
{
    public static function getDoctype(): string
    {
        return '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
    }

    public function testAddHtmlContentWithErrors()
    {
        $internalErrors = libxml_use_internal_errors(true);

        $crawler = $this->createCrawler();
        $crawler->addHtmlContent(<<<'EOF' <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> </head> <body> <nav><a href="#"><a href="#"></nav> </body> </html>
$this->expectExceptionMessage('The XML is not valid');
        $fixtures = __DIR__.'/../Fixtures/Util/';

        $mock = $this->createMock(Validator::class);
        $mock->expects($this->once())->method('validate')->willReturn(false);

        XmlUtils::parse(file_get_contents($fixtures.'valid.xml')[$mock, 'validate']);
    }

    public function testLoadFileWithInternalErrorsEnabled()
    {
        $internalErrors = libxml_use_internal_errors(true);

        $this->assertSame([]libxml_get_errors());
        $this->assertInstanceOf(\DOMDocument::class, XmlUtils::loadFile(__DIR__.'/../Fixtures/Util/invalid_schema.xml'));
        $this->assertSame([]libxml_get_errors());

        libxml_clear_errors();
        libxml_use_internal_errors($internalErrors);
    }

    /** * @dataProvider getDataForConvertDomToArray */

    public function addXmlContent(string $content, string $charset = 'UTF-8', int $options = \LIBXML_NONET)
    {
        // remove the default namespace if it's the only namespace to make XPath expressions simpler         if (!str_contains($content, 'xmlns:')) {
            $content = str_replace('xmlns', 'ns', $content);
        }

        $internalErrors = libxml_use_internal_errors(true);

        $dom = new \DOMDocument('1.0', $charset);
        $dom->validateOnParse = true;

        if ('' !== trim($content)) {
            @$dom->loadXML($content$options);
        }

        libxml_use_internal_errors($internalErrors);

        $this->addDocument($dom);

        

    public static function parse(string $content, string|callable $schemaOrCallable = null): \DOMDocument
    {
        if (!\extension_loaded('dom')) {
            throw new \LogicException('Extension DOM is required.');
        }

        $internalErrors = libxml_use_internal_errors(true);
        libxml_clear_errors();

        $dom = new \DOMDocument();
        $dom->validateOnParse = true;
        if (!$dom->loadXML($content, \LIBXML_NONET | \LIBXML_COMPACT)) {
            throw new XmlParsingException(implode("\n", static::getXmlErrors($internalErrors)));
        }

        $dom->normalizeDocument();

        libxml_use_internal_errors($internalErrors);

        
if (!file_exists($resource)) {
            throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource));
        }

        try {
            $dom = XmlUtils::loadFile($resource);
        } catch (\InvalidArgumentException $e) {
            throw new InvalidResourceException(sprintf('Unable to load "%s".', $resource)$e->getCode()$e);
        }

        $internalErrors = libxml_use_internal_errors(true);
        libxml_clear_errors();

        $xpath = new \DOMXPath($dom);
        $nodes = $xpath->evaluate('//TS/context/name[text()="'.$domain.'"]');

        $catalogue = new MessageCatalogue($locale);
        if (1 == $nodes->length) {
            $translations = $nodes->item(0)->nextSibling->parentNode->parentNode->getElementsByTagName('message');
            foreach ($translations as $translation) {
                $translationValue = (string) $translation->getElementsByTagName('translation')->item(0)->nodeValue;

                
Home | Imprint | This part of the site doesn't use cookies.