/** * {@inheritdoc} * * @api */ public function load($resource, $locale, $domain = 'messages') { if (!stream_is_local($resource)) { throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource)); } 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 ($nodes->length == 1) { $translations = $nodes->item(0)->nextSibling->parentNode->parentNode->getElementsByTagName('message'); foreach ($translations as $translation) { $translationValue = (string) $translation->getElementsByTagName('translation')->item(0)->nodeValue; if (!empty($translationValue)) { $catalogue->set((string) $translation->getElementsByTagName('source')->item(0)->nodeValue, $translationValue, $domain); } $translation = $translation->nextSibling; } $catalogue->addResource(new FileResource($resource)); } libxml_use_internal_errors($internalErrors); return $catalogue; }
/** * Validates and parses the given file into a SimpleXMLElement * * @param string $file * * @throws \RuntimeException * * @return \SimpleXMLElement * * @throws InvalidResourceException */ private function parseFile($file) { try { $dom = XmlUtils::loadFile($file); } catch (\InvalidArgumentException $e) { throw new InvalidResourceException(sprintf('Unable to load "%s": %s', $file, $e->getMessage()), $e->getCode(), $e); } $internalErrors = libxml_use_internal_errors(true); $location = str_replace('\\', '/', __DIR__) . '/schema/dic/xliff-core/xml.xsd'; $parts = explode('/', $location); if (0 === stripos($location, 'phar://')) { $tmpfile = tempnam(sys_get_temp_dir(), 'sf2'); if ($tmpfile) { copy($location, $tmpfile); $parts = explode('/', str_replace('\\', '/', $tmpfile)); } } $drive = '\\' === DIRECTORY_SEPARATOR ? array_shift($parts) . '/' : ''; $location = 'file:///' . $drive . implode('/', array_map('rawurlencode', $parts)); $source = file_get_contents(__DIR__ . '/schema/dic/xliff-core/xliff-core-1.2-strict.xsd'); $source = str_replace('http://www.w3.org/2001/xml.xsd', $location, $source); if (!@$dom->schemaValidateSource($source)) { throw new InvalidResourceException(implode("\n", $this->getXmlErrors($internalErrors))); } $dom->normalizeDocument(); libxml_clear_errors(); libxml_use_internal_errors($internalErrors); return array(simplexml_import_dom($dom), strtoupper($dom->encoding)); }
/** * Carga un recurso de tipo Xml * * @param mixed $file * @param null $type * @return array */ public function load($file, $type = null) { $path = $this->locator->locate($file); $dom = XmlUtils::loadFile($path); $arrayXml = XmlUtils::convertDomElementToArray($dom->documentElement); $this->container->addResource(new FileResource($path)); return $arrayXml; }
public function provideFullConfiguration() { $yaml = Yaml::parse(__DIR__ . '/Fixtures/config/yml/full.yml'); $yaml = $yaml['doctrine_mongodb']; $xml = XmlUtils::loadFile(__DIR__ . '/Fixtures/config/xml/full.xml'); $xml = XmlUtils::convertDomElementToArray($xml->getElementsByTagName('config')->item(0)); return array(array($yaml), array($xml)); }
/** * Loads internal. * * @param string $file * * @return \SimpleXMLElement */ protected function loadFile($file) { try { $dom = XmlUtils::loadFile($file); } catch (\Exception $e) { throw new \Exception(sprintf('Unable to parse file "%s".', $file), $e->getCode()); } return simplexml_import_dom($dom); }
/** * Parses a XML File. * * @param string $file Path of file * * @return \SimpleXMLElement * * @throws MappingException */ private function parseFile($file) { try { $dom = XmlUtils::loadFile($file, __DIR__ . '/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd'); } catch (\Exception $e) { throw new MappingException($e->getMessage(), $e->getCode(), $e); } return simplexml_import_dom($dom); }
/** * Lee el contenido de un fichero XML. * * @param string $type The resource type * @return array. */ public function load($file, $type = null) { $path = $this->locator->locate($file); try { $dom = XmlUtils::loadFile($path); } catch (\InvalidArgumentException $e) { throw new \InvalidArgumentException(sprintf('Unable to parse file "%s".', $file), $e->getCode(), $e); } $arrayXml = XmlUtils::convertDomElementToArray($dom->documentElement); return $arrayXml; }
/** * {@inheritdoc} */ protected function extractPath(string $path) { try { $xml = simplexml_import_dom(XmlUtils::loadFile($path, self::RESOURCE_SCHEMA)); } catch (\InvalidArgumentException $e) { throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e); } foreach ($xml->resource as $resource) { $resourceClass = (string) $resource['class']; $this->resources[$resourceClass] = ['shortName' => $this->phpize($resource, 'shortName', 'string'), 'description' => $this->phpize($resource, 'description', 'string'), 'iri' => $this->phpize($resource, 'iri', 'string'), 'itemOperations' => $this->getAttributes($resource, 'itemOperation') ?: null, 'collectionOperations' => $this->getAttributes($resource, 'collectionOperation') ?: null, 'attributes' => $this->getAttributes($resource, 'attribute') ?: null, 'properties' => $this->getProperties($resource) ?: null]; } }
/** * {@inheritdoc} */ protected function loadMetadataFromFile(\ReflectionClass $class, $file) { $classMetadata = new MergeableClassMetadata($class->getName()); // load xml file // TODO xsd validation $xmlDoc = XmlUtils::loadFile($file); $xpath = new \DOMXPath($xmlDoc); $xpath->registerNamespace('x', 'http://schemas.sulu.io/class/general'); $xpath->registerNamespace('list', 'http://schemas.sulu.io/class/list'); foreach ($xpath->query('/x:class/x:properties/x:*') as $propertyNode) { $classMetadata->addPropertyMetadata($this->getPropertyMetadata($xpath, $propertyNode, $class->getName())); } return $classMetadata; }
/** * {@inheritdoc} */ public function supports($resource, $type = null) { if (!is_string($resource) || 'xml' !== pathinfo($resource, PATHINFO_EXTENSION)) { return false; } $document = XmlUtils::loadFile($resource); $namespaces = $document->documentElement->attributes->getNamedItem('schemaLocation')->nodeValue; $start = strpos($namespaces, static::SCHEMA_IDENTIFIER) + strlen(static::SCHEMA_IDENTIFIER) + 1; $namespace = substr($namespaces, $start); $end = strpos($namespace, ' '); if ($end !== false) { $namespace = substr($namespace, 0, $end); } return $namespace === static::SCHEMA_URI; }
private function extract($resource, MessageCatalogue $catalogue, $domain) { try { $dom = XmlUtils::loadFile($resource); } catch (\InvalidArgumentException $e) { throw new InvalidResourceException(sprintf('Unable to load "%s": %s', $resource, $e->getMessage()), $e->getCode(), $e); } $xliffVersion = $this->getVersionNumber($dom); $this->validateSchema($xliffVersion, $dom, $this->getSchema($xliffVersion)); if ('1.2' === $xliffVersion) { $this->extractXliff1($dom, $catalogue, $domain); } if ('2.0' === $xliffVersion) { $this->extractXliff2($dom, $catalogue, $domain); } }
/** * {@inheritdoc} */ public function load($resource, $type = 'page') { // init running vars $tags = []; $schemaPath = __DIR__ . static::SCHEME_PATH; // read file $xmlDocument = XmlUtils::loadFile($resource, function (\DOMDocument $dom) use($resource, $schemaPath) { $dom->documentURI = $resource; $dom->xinclude(); return @$dom->schemaValidate($schemaPath); }); // generate xpath for file $xpath = new \DOMXPath($xmlDocument); $xpath->registerNamespace('x', 'http://schemas.sulu.io/template/template'); // init result $result = $this->loadTemplateAttributes($resource, $xpath, $type); // load properties $result['properties'] = $this->loadProperties($result['key'], '/x:template/x:properties/x:*', $tags, $xpath); // check if required properties are existing foreach ($this->requiredPropertyNames as $requiredPropertyName) { $requiredPropertyNameFound = false; if (array_key_exists($requiredPropertyName, $result['properties'])) { $requiredPropertyNameFound = true; } // check all section properties as well foreach ($result['properties'] as $property) { if (!$requiredPropertyNameFound && $property['type'] == 'section' && array_key_exists($requiredPropertyName, $property['properties'])) { $requiredPropertyNameFound = true; } } if (!$requiredPropertyNameFound) { throw new RequiredPropertyNameNotFoundException($result['key'], $requiredPropertyName); } } // FIXME until excerpt-template is no page template anymore // - https://github.com/sulu-io/sulu/issues/1220#issuecomment-110704259 if (!array_key_exists('internal', $result) || !$result['internal']) { if (isset($this->requiredTagNames[$type])) { foreach ($this->requiredTagNames[$type] as $requiredTagName) { if (!array_key_exists($requiredTagName, $tags)) { throw new RequiredTagNotFoundException($result['key'], $requiredTagName); } } } } return $result; }
private function parseXml($path) { // load xml file $xmlDoc = XmlUtils::loadFile($path); $xpath = new \DOMXPath($xmlDoc); $result = []; foreach ($xpath->query('/replacers/item') as $node) { $locale = strtolower($xpath->query('column[@name="locale"]', $node)->item(0)->nodeValue); $from = $xpath->query('column[@name="from"]', $node)->item(0)->nodeValue; $to = $xpath->query('column[@name="to"]', $node)->item(0)->nodeValue; if (!isset($result[$locale])) { $result[$locale] = []; } $result[$locale][$from] = $to; } return $result; }
public function import($fileName) { $this->handleSession($this->session, $fileName); $this->handleSession($this->liveSession, $fileName); $doc = XmlUtils::loadFile($fileName); $xpath = new \DOMXPath($doc); $xpath->registerNamespace('sv', 'http://www.jcp.org/jcr/sv/1.0'); $data = []; /** @var \DOMNode $node */ foreach ($xpath->query('//sv:value[text()="sulu:page"]/../..') as $node) { $parent = $node; $path = ''; do { $path = '/' . XmlUtil::getValueFromXPath('@sv:name', $xpath, $parent) . $path; $parent = $parent->parentNode; } while (XmlUtil::getValueFromXPath('@sv:name', $xpath, $parent) !== 'contents'); $data[] = ['id' => XmlUtil::getValueFromXPath('sv:property[@sv:name="jcr:uuid"]/sv:value', $xpath, $node), 'path' => $path, 'title' => XmlUtil::getValueFromXPath('sv:property[@sv:name="i18n:en-title"]/sv:value', $xpath, $node), 'template' => XmlUtil::getValueFromXPath('sv:property[@sv:name="i18n:en-template"]/sv:value', $xpath, $node), 'url' => XmlUtil::getValueFromXPath('sv:property[@sv:name="i18n:en-url"]/sv:value', $xpath, $node), 'article' => XmlUtil::getValueFromXPath('sv:property[@sv:name="i18n:en-article"]/sv:value', $xpath, $node)]; } return $data; }
/** * Loads an XML File. * * @param string $path An XML file path * @param string|null $type * * @return MappingData[] * * @throws \InvalidArgumentException When the $file cannot be parsed */ public function load($file, $type = null) { $path = $this->locator->locate($file); if (!stream_is_local($path)) { throw new \InvalidArgumentException(sprintf('This is not a local file "%s".', $path)); } if (!file_exists($path)) { throw new \InvalidArgumentException(sprintf('File "%s" not found.', $path)); } // empty file if ('' === trim(file_get_contents($path))) { return; } $xml = XmlUtils::loadFile($path, __DIR__ . static::SCHEMA_FILE); $metadatas = array(); foreach ($xml->documentElement->getElementsByTagNameNS(self::NAMESPACE_URI, 'mapping') as $mappingNode) { $metadatas[] = $this->parseMappingNode($mappingNode, $path); } return $metadatas; }
/** * @param $file * * @return array */ private function parseXml($file) { $formats = []; // load xml file $xmlDoc = XmlUtils::loadFile($file, __DIR__ . static::SCHEME_PATH); $this->xpath = new \DOMXPath($xmlDoc); $this->xpath->registerNamespace('x', static::XML_NAMESPACE_URI); /* * @var DOMElement */ foreach ($this->xpath->query('/x:formats/x:format') as $formatNode) { $name = $this->xpath->query('x:name', $formatNode)->item(0)->nodeValue; if (!isset($formats[$name])) { $commands = []; foreach ($this->xpath->query('x:commands/x:command', $formatNode) as $commandNode) { $action = $this->xpath->query('x:action', $commandNode)->item(0)->nodeValue; $parameters = []; $parameterNodes = $this->xpath->query('x:parameters/x:parameter', $commandNode); foreach ($parameterNodes as $parameterNode) { $value = $parameterNode->nodeValue; if ($value === 'true') { $value = true; } elseif ($value === 'false') { $value = false; } $parameters[$parameterNode->attributes->getNamedItem('name')->nodeValue] = $value; } $command = ['action' => $action, 'parameters' => $parameters]; $commands[] = $command; } $options = []; $optionNodes = $this->xpath->query('x:options/x:option', $formatNode); foreach ($optionNodes as $optionNode) { $options[$optionNode->attributes->getNamedItem('name')->nodeValue] = $optionNode->nodeValue; } $formats[$name] = ['name' => $name, 'commands' => $commands, 'options' => array_merge($this->defaultOptions, $options)]; } } return $formats; }
public function testLoadFile() { $fixtures = __DIR__ . '/../Fixtures/Util/'; try { XmlUtils::loadFile($fixtures . 'invalid.xml'); $this->fail(); } catch (\InvalidArgumentException $e) { $this->assertContains('ERROR 77', $e->getMessage()); } try { XmlUtils::loadFile($fixtures . 'document_type.xml'); $this->fail(); } catch (\InvalidArgumentException $e) { $this->assertContains('Document types are not allowed', $e->getMessage()); } try { XmlUtils::loadFile($fixtures . 'invalid_schema.xml', $fixtures . 'schema.xsd'); $this->fail(); } catch (\InvalidArgumentException $e) { $this->assertContains('ERROR 1845', $e->getMessage()); } try { XmlUtils::loadFile($fixtures . 'invalid_schema.xml', 'invalid_callback_or_file'); $this->fail(); } catch (\InvalidArgumentException $e) { $this->assertContains('XSD file or callable', $e->getMessage()); } $mock = $this->getMock(__NAMESPACE__ . '\\Validator'); $mock->expects($this->exactly(2))->method('validate')->will($this->onConsecutiveCalls(false, true)); try { XmlUtils::loadFile($fixtures . 'valid.xml', array($mock, 'validate')); $this->fail(); } catch (\InvalidArgumentException $e) { $this->assertContains('is not valid', $e->getMessage()); } $this->assertInstanceOf('DOMDocument', XmlUtils::loadFile($fixtures . 'valid.xml', array($mock, 'validate'))); }
/** * @param $file * * @return Portal */ private function parseXml($file) { // load xml file $xmlDoc = XmlUtils::loadFile($file, __DIR__ . static::SCHEME_PATH); $this->xpath = new \DOMXPath($xmlDoc); $this->xpath->registerNamespace('x', 'http://schemas.sulu.io/webspace/webspace'); // set simple webspace properties $this->webspace = new Webspace(); $this->webspace->setName($this->xpath->query('/x:webspace/x:name')->item(0)->nodeValue); $this->webspace->setKey($this->xpath->query('/x:webspace/x:key')->item(0)->nodeValue); $this->webspace->setTheme($this->generateTheme()); $this->webspace->setNavigation($this->generateNavigation()); // set security $this->generateSecurity(); // set localizations on webspaces $this->generateWebspaceLocalizations(); // set segments on webspaces $this->generateSegments(); // set portals on webspaces $this->generatePortals(); // validate the webspace, and throw exceptions if not valid $this->validate(); return $this->webspace; }
/** * {@inheritdoc} */ public function parse($filePath, $locale) { $dom = XmlUtils::loadFile($filePath); return $this->extractData($dom, $locale); }
/** * Parses a XML file. * * @param string $file Path to a file * * @return SimpleXMLElement * * @throws InvalidArgumentException When loading of XML file returns error */ protected function parseFile($file) { try { $dom = XmlUtils::loadFile($file, array($this, 'validateSchema')); } catch (\InvalidArgumentException $e) { throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e); } $this->validateExtensions($dom, $file); return simplexml_import_dom($dom, 'Symfony\\Component\\DependencyInjection\\SimpleXMLElement'); }
/** * Loads the XML class descriptions from the given file. * * @param string $path The path of the XML file * * @return \SimpleXMLElement The class descriptions * * @throws MappingException If the file could not be loaded */ protected function parseFile($path) { try { $dom = XmlUtils::loadFile($path, __DIR__ . '/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd'); } catch (\Exception $e) { throw new MappingException($e->getMessage(), $e->getCode(), $e); } return simplexml_import_dom($dom); }
public function testLoadWrongEmptyXMLWithErrorHandler() { $originalDisableEntities = libxml_disable_entity_loader(false); $errorReporting = error_reporting(-1); set_error_handler(function ($errno, $errstr) { throw new \Exception($errstr, $errno); }); $file = __DIR__ . '/../Fixtures/foo.xml'; try { try { XmlUtils::loadFile($file); $this->fail('An exception should have been raised'); } catch (\InvalidArgumentException $e) { $this->assertEquals(sprintf('File %s does not contain valid XML, it is empty.', $file), $e->getMessage()); } } catch (\Exception $e) { restore_error_handler(); error_reporting($errorReporting); throw $e; } restore_error_handler(); error_reporting($errorReporting); $disableEntities = libxml_disable_entity_loader(true); libxml_disable_entity_loader($disableEntities); libxml_disable_entity_loader($originalDisableEntities); $this->assertFalse($disableEntities); // should not throw an exception XmlUtils::loadFile(__DIR__ . '/../Fixtures/Util/valid.xml', __DIR__ . '/../Fixtures/Util/schema.xsd'); }
protected function loadFile($file) { return XmlUtils::loadFile($file, function () { return true; }); }
/** * {@inheritDoc} */ protected function loadFile($file) { if (class_exists('Symfony\\Component\\Config\\Util\\XmlUtils')) { $dom = XmlUtils::loadFile($file); $this->validate($dom); return $dom; } return parent::loadFile($file); }
/** * Parses a XML file * * @param string $file * * @return \DOMDocument */ protected function parseFile($file) { return XmlUtils::loadFile($file); }
/** * Loads an XML file. * * @param string $file An XML file path * * @return \DOMDocument * * @throws \InvalidArgumentException When loading of XML file fails because of syntax errors * or when the XML structure is not as expected by the scheme - * see validate() */ protected function loadFile($file) { return XmlUtils::loadFile($file, __DIR__ . static::SCHEME_PATH); }
/** * Check that there are no duplicate route ids. */ public function testNoDuplicateIds() { $existingIds = []; foreach (static::$routingFiles as $filePath => $fileNames) { $routerFileLocator = $this->routerFileLocators[$filePath]; foreach ($fileNames as $fileName) { $xml = XmlUtils::loadFile($routerFileLocator->locate($fileName), static::$routingXSDPath); foreach ($xml->documentElement->childNodes as $node) { if (!$node instanceof \DOMElement) { continue; } if ($node->localName != 'route') { continue; } $id = $node->getAttribute('id'); $this->assertFalse(in_array($id, $existingIds), "Duplicate route id '{$id}'."); $existingIds[] = $id; } } } }
/** * Tries to load the DOM Document of a given image formats xml. * * @param $file string The path to the xml file * * @return \DOMDocument * * @throws InvalidMediaFormatException */ private function tryLoad($file) { try { return XmlUtils::loadFile($file, __DIR__ . static::SCHEME_PATH); } catch (\InvalidArgumentException $e) { throw new InvalidMediaFormatException(sprintf('Could not parse image formats XML file "%s"', $file), null, $e); } }
/** * Parses a XML file to a \DOMDocument. * * @param string $file Path to a file * * @return \DOMDocument * * @throws InvalidArgumentException When loading of XML file returns error */ private function parseFileToDOM($file) { try { $dom = XmlUtils::loadFile($file, array($this, 'validateSchema')); } catch (\InvalidArgumentException $e) { throw new InvalidArgumentException(sprintf('Unable to parse file "%s".', $file), $e->getCode(), $e); } $this->validateExtensions($dom, $file); return $dom; }
/** * Returns xml-doc when one scheme matches. * * @param string $file * * @return \DOMDocument * * @throws InvalidWebspaceException */ protected function tryLoad($file) { try { return XmlUtils::loadFile($file, __DIR__ . static::SCHEMA_LOCATION); } catch (\InvalidArgumentException $e) { throw new InvalidWebspaceException(sprintf('Could not parse webspace XML file "%s"', $file), null, $e); } }