/** * 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)); }
/** * {@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; }
/** * 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)); }
/** * 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); }
/** * 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); }
/** * 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 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; }
/** * Note that the following features are not supported: * * strings with escaped quotes are not supported "foo\"bar"; * * string concatenation ("foo" "bar"). */ private function phpize($value) { // trim on the right as comments removal keep whitespaces $value = rtrim($value); $lowercaseValue = strtolower($value); switch (true) { case defined($value): return constant($value); case 'yes' === $lowercaseValue || 'on' === $lowercaseValue: return true; case 'no' === $lowercaseValue || 'off' === $lowercaseValue || 'none' === $lowercaseValue: return false; case isset($value[1]) && ("'" === $value[0] && "'" === $value[strlen($value) - 1] || '"' === $value[0] && '"' === $value[strlen($value) - 1]): // quoted string return substr($value, 1, -1); default: return XmlUtils::phpize($value); } }
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; }
/** * @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; }
/** * @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; }
protected function loadFile($file) { return XmlUtils::loadFile($file, function () { return true; }); }
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'); }
/** * 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); }
/** * {@inheritdoc} */ public function parse($filePath, $locale) { $dom = XmlUtils::loadFile($filePath); return $this->extractData($dom, $locale); }
/** * @dataProvider getDataForPhpize */ public function testPhpize($expected, $value) { $this->assertSame($expected, XmlUtils::phpize($value)); }
/** * Converts an xml value to a PHP type. * * @param mixed $value * * @return mixed */ public static function phpize($value) { return XmlUtils::phpize($value); }
/** * 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); } return simplexml_import_dom($dom, 'Symfony\\Component\\DependencyInjection\\SimpleXMLElement'); }
/** * 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); } }
/** * 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); }
/** * Transforms an XML attribute's value in a PHP value. * * @param \SimpleXMLElement $array * @param string $key * @param string $type * * @return bool|string|null */ private function phpize(\SimpleXMLElement $array, string $key, string $type) { if (!isset($array[$key])) { return; } switch ($type) { case 'string': return (string) $array[$key]; case 'bool': return (bool) XmlUtils::phpize($array[$key]); } }
/** * {@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); }
/** * Converts a \DomElement object to a PHP array. * * The following rules applies during the conversion: * * * Each tag is converted to a key value or an array * if there is more than one "value" * * * The content of a tag is set under a "value" key (<foo>bar</foo>) * if the tag also has some nested tags * * * The attributes are converted to keys (<foo foo="bar"/>) * * * The nested-tags are converted to keys (<foo><foo>bar</foo></foo>) * * @param \DomElement $element A \DomElement instance * * @return array A PHP array */ public static function convertDomElementToArray(\DomElement $element) { return XmlUtils::convertDomElementToArray($element); }
/** * 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); } }