loadXML example

use PHPUnit\Framework\TestCase;
use Symfony\Component\Translation\Util\XliffUtils;

class TranslationFilesTest extends TestCase
{
    /** * @dataProvider provideTranslationFiles */
    public function testTranslationFileIsValid($filePath)
    {
        $document = new \DOMDocument();
        $document->loadXML(file_get_contents($filePath));

        $errors = XliffUtils::validateSchema($document);

        $this->assertCount(0, $errorssprintf('"%s" is invalid:%s', $filePath, \PHP_EOL.implode(\PHP_EOL, array_column($errors, 'message'))));
    }

    /** * @dataProvider provideTranslationFiles */
    public function testTranslationFileIsValidWithoutEntityLoader($filePath)
    {
        
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);
        }

        $rootNode = null;
        $decoderIgnoredNodeTypes = $context[self::DECODER_IGNORED_NODE_TYPES] ?? $this->defaultContext[self::DECODER_IGNORED_NODE_TYPES];
        
use PHPUnit\Framework\TestCase;
use Symfony\Component\Translation\Util\XliffUtils;

class TranslationFilesTest extends TestCase
{
    /** * @dataProvider provideTranslationFiles */
    public function testTranslationFileIsValid($filePath)
    {
        $document = new \DOMDocument();
        $document->loadXML(file_get_contents($filePath));

        $errors = XliffUtils::validateSchema($document);

        $this->assertCount(0, $errorssprintf('"%s" is invalid:%s', $filePath, \PHP_EOL.implode(\PHP_EOL, array_column($errors, 'message'))));
    }

    /** * @dataProvider provideTranslationFiles */
    public function testTranslationFileIsValidWithoutEntityLoader($filePath)
    {
        
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);

        foreach ($dom->childNodes as $child) {
            if (\XML_DOCUMENT_TYPE_NODE === $child->nodeType) {
                throw new XmlParsingException('Document types are not allowed.');
            }
        }
$message = 'The "alias_for_foo" service alias is deprecated. You should stop using it, as it will be removed in the future.';
        $this->assertSame($message$container->getAlias('alias_for_foo')->getDeprecation('alias_for_foo')['message']);

        $this->assertTrue($container->getAlias('alias_for_foobar')->isDeprecated());
        $message = 'The "alias_for_foobar" service alias is deprecated.';
        $this->assertSame($message$container->getAlias('alias_for_foobar')->getDeprecation('alias_for_foobar')['message']);
    }

    public function testConvertDomElementToArray()
    {
        $doc = new \DOMDocument('1.0');
        $doc->loadXML('<foo>bar</foo>');
        $this->assertEquals('bar', XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');

        $doc = new \DOMDocument('1.0');
        $doc->loadXML('<foo foo="bar" />');
        $this->assertEquals(['foo' => 'bar'], XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');

        $doc = new \DOMDocument('1.0');
        $doc->loadXML('<foo><foo>bar</foo></foo>');
        $this->assertEquals(['foo' => 'bar'], XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');

        $doc = new \DOMDocument('1.0');
        
$validator->validate($schema);
    }

    /** * @param class-string<\Throwable> $exceptionClass * * @dataProvider xmlProvider */
    public function testValidate(string $xml, string $exceptionClass, string $expectedMessage): void
    {
        $dom = new \DOMDocument();
        $dom->loadXML($xml);

        \assert($dom->documentElement instanceof \DOMElement);

        $entities = new Entities([
            Entity::fromXml($dom->documentElement),
        ]);
        $schema = new CustomEntityXmlSchema(__DIR__, $entities);

        $validator = new CustomEntityXmlSchemaValidator();

        $this->expectException($exceptionClass);
        

  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) {
      $num_headings[$level] = $doc->getElementsByTagName('h' . $level)->length;
      
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);
        }

        $rootNode = null;
        $decoderIgnoredNodeTypes = $context[self::DECODER_IGNORED_NODE_TYPES] ?? $this->defaultContext[self::DECODER_IGNORED_NODE_TYPES];
        
$this->autoclose($this->onlyInline);
            $this->onlyInline = null;
        }

        try {
            $prefix = ($pos = strpos($lname, ':')) ? substr($lname, 0, $pos) : '';

            if (false !== $needsWorkaround) {
                $xml = "<$lname xmlns=\"$needsWorkaround\" " . (strlen($prefix) && isset($this->nsStack[0][$prefix]) ? ("xmlns:$prefix=\"" . $this->nsStack[0][$prefix] . '"') : '') . '/>';

                $frag = new \DOMDocument('1.0', 'UTF-8');
                $frag->loadXML($xml);

                $ele = $this->doc->importNode($frag->documentElement, true);
            } else {
                if (!isset($this->nsStack[0][$prefix]) || ('' === $prefix && isset($this->options[self::OPT_DISABLE_HTML_NS]) && $this->options[self::OPT_DISABLE_HTML_NS])) {
                    $ele = $this->doc->createElement($lname);
                } else {
                    $ele = $this->doc->createElementNS($this->nsStack[0][$prefix]$lname);
                }
            }
        } catch (\DOMException $e) {
            $this->parseError("Illegal tag name: <$lname>. Replaced with <invalid>.");
            
unlink($tmpfile);
        }

        return $valid;
    }

    private function shouldEnableEntityLoader(): bool
    {
        static $dom$schema;
        if (null === $dom) {
            $dom = new \DOMDocument();
            $dom->loadXML('<?xml version="1.0"?><test/>');

            $tmpfile = tempnam(sys_get_temp_dir(), 'symfony');
            register_shutdown_function(static function D) use ($tmpfile) {
                @unlink($tmpfile);
            });
            $schema = '<?xml version="1.0" encoding="utf-8"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:include schemaLocation="file:///'.rawurlencode(str_replace('\\', '/', $tmpfile)).'" /> </xsd:schema>';
            file_put_contents($tmpfile, '<?xml version="1.0" encoding="utf-8"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="test" type="testType" /> <xsd:complexType name="testType"/> </xsd:schema>');


        return $this->createCrawler($xml$uri);
    }

    protected function createDomDocument()
    {
        $dom = new \DOMDocument();
        $dom->loadXML('<html><div class="foo"></div></html>');

        return $dom;
    }

    protected function createNodeList()
    {
        $dom = new \DOMDocument();
        $dom->loadXML('<html><div class="foo"></div></html>');
        $domxpath = new \DOMXPath($dom);

        return $domxpath->query('//div');
    }

        $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);

            if (0 === preg_match($expectedFilenamePatternbasename($file))) {
                $errors[] = [
                    

    protected static function xmlToDOMDocument(string $var, ?string $parent_path): ?array
    {
        // There's no way to check validity in DOMDocument without making errors. For shame!         if (!self::xmlToSimpleXML($var$parent_path)) {
            return null;
        }

        $xml = new DOMDocument();
        $xml->loadXML($var);

        if ($xml->childNodes->count() > 1) {
            $xml = $xml->childNodes;
            $access_path = 'childNodes';
        } else {
            $xml = $xml->firstChild;
            $access_path = 'firstChild';
        }

        if (null === $parent_path) {
            $access_path = null;
        }
use PHPUnit\Framework\TestCase;
use Symfony\Component\Translation\Util\XliffUtils;

class TranslationFilesTest extends TestCase
{
    /** * @dataProvider provideTranslationFiles */
    public function testTranslationFileIsValid($filePath)
    {
        $document = new \DOMDocument();
        $document->loadXML(file_get_contents($filePath));

        $errors = XliffUtils::validateSchema($document);

        $this->assertCount(0, $errorssprintf('"%s" is invalid:%s', $filePath, \PHP_EOL.implode(\PHP_EOL, array_column($errors, 'message'))));
    }

    /** * @dataProvider provideTranslationFiles * * @group Legacy */
    

        $xml = <<<'XML' <entity name="my_entity" custom-fields-aware="true" label-property="name"> <fields> <string name="id"/> <string name="name" translatable="true" /> </fields> </entity> XML;

        $dom = new \DOMDocument();
        $dom->loadXML($xml);

        \assert($dom->documentElement instanceof \DOMElement);

        $entity = Entity::fromXml($dom->documentElement);

        static::assertSame('my_entity', $entity->getName());
        static::assertTrue($entity->isCustomFieldsAware());
        static::assertSame('name', $entity->getLabelProperty());

        $fields = $entity->getFields();
        static::assertCount(2, $fields);

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