Example #1
0
 /**
  * @param \DOMNode $node
  */
 protected function postProcessXML($node)
 {
     // дата релиза
     if (!is_null($this->release)) {
         $release = date('d-m-Y', strtotime($this->release . ' 00:00:00'));
         $node->setAttribute('release', $release);
         $xDate = explode('-', $release);
         $fullDate = $xDate[0] . ' ' . \Difra\Locales::getInstance()->getXPath('portfolio/months/m_' . $xDate[1]) . ' ' . $xDate[2];
         $node->setAttribute('fullDate', $fullDate);
     }
     // авторы
     if (!is_null($this->authors)) {
         $authorsArray = unserialize($this->authors);
         if (!empty($authorsArray)) {
             foreach ($authorsArray as $k => $data) {
                 if (isset($data['role'])) {
                     $roleNode = $node->appendChild($node->ownerDocument->createElement('role'));
                     $roleNode->setAttribute('name', $data['role']);
                     if (isset($data['contibutors']) && is_array($data['contibutors'])) {
                         foreach ($data['contibutors'] as $cName) {
                             $cNode = $roleNode->appendChild($node->ownerDocument->createElement('contibutor'));
                             $cNode->setAttribute('name', $cName);
                         }
                     }
                 }
             }
         }
     }
 }
Example #2
0
 public function sanitize(\DOMNode $node)
 {
     if ($this->haveToTrim() && $node->hasAttribute($this->name)) {
         $node->setAttribute($this->name, trim($node->getAttribute($this->name)));
     }
     if ($this->repair && !$node->hasAttribute($this->name)) {
         $node->setAttribute($this->name, $this->repairValue);
     }
 }
 /**
  * Adds class="external" & rel="nofollow" to external links.
  *
  * @param \DOMNode $node Link
  * @param \Title $title
  */
 public function apply(\DOMNode $node, \Title $title)
 {
     if (!$node instanceof \DOMElement) {
         return;
     }
     $node->setAttribute('class', 'external');
     global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
     if ($wgNoFollowLinks && !wfMatchesDomainList($node->getAttribute('href'), $wgNoFollowDomainExceptions)) {
         $node->setAttribute('rel', 'nofollow');
     }
 }
Example #4
0
 /**
  * @param \DOMNode|\DOMElement $node
  * @param int $menuId
  */
 private function getEditXML($node, $menuId)
 {
     $menu = \Difra\Plugins\CMS\Menu::get($menuId);
     $node->setAttribute('depth', $menu->getDepth());
     $parentsNode = $node->appendChild($this->xml->createElement('parents'));
     \Difra\Plugins\CMS::getInstance()->getMenuItemsXML($parentsNode, $menu->getId());
 }
 public function visitArray($data, Type $type, Context $context)
 {
     if ($this->nodeStack->count() === 1 && $this->document->documentElement === null) {
         $this->createRootNode();
     }
     /** @var PropertyMetadata $metadata */
     $nodeName = 'entry';
     if (($metadata = $context->getMetadataStack()->getCurrent()) && !empty($metadata->xmlEntryName)) {
         $nodeName = $metadata->xmlEntryName;
     }
     $attributeName = null !== $metadata ? $metadata->xmlKeyAttribute : null;
     $namespace = null !== $metadata ? $metadata->xmlEntryNamespace : null;
     /** @var \DOMNode[] $nodes */
     $nodes = [];
     $elementType = $this->getElementType($type);
     foreach ($data as $k => $v) {
         $elementName = null !== $metadata && $metadata->xmlKeyValuePairs && $this->isElementNameValid($k) ? (string) $k : $nodeName;
         $this->currentNodes = $this->createElement($namespace, $elementName);
         $context->accept($v, $elementType);
         if (null !== $attributeName) {
             $this->currentNodes->setAttribute($attributeName, (string) $k);
         }
         $nodes[] = $this->currentNodes;
     }
     return $this->currentNodes = $nodes;
 }
Example #6
0
 /**
  * Get some configuration variables as XML node attributes
  * @param \DOMElement|\DOMNode $node
  */
 public static function getStateXML($node)
 {
     $config = self::getState();
     foreach ($config as $k => $v) {
         $node->setAttribute($k, $v);
     }
 }
 static function append_style(DOMNode $node, $new_style)
 {
     $style = rtrim($node->getAttribute(self::$_style_attr), ";");
     $style .= $new_style;
     $style = ltrim($style, ";");
     $node->setAttribute(self::$_style_attr, $style);
 }
Example #8
0
 public function attr($a_name, $a_value = null)
 {
     if (is_null($a_value)) {
         return $this->m_node->getAttribute($a_name);
     }
     $this->m_node->setAttribute($a_name, $a_value);
 }
Example #9
0
 /**
  * Handle body.
  * 
  * @param type $def
  * @return none
  *
  * @throws Exception
  */
 protected function handleBody($def)
 {
     $def = IdmlPxeExportParentMap::parsePixieDef($def);
     if (strtolower($def['tagName']) != 'body') {
         throw Exception('handling body that is not body. How did you get here?');
     }
     $this->pxeBody->setAttribute('class', $def['class']);
 }
 /**
  * Set error response.
  *
  * @param \WP_Error|null $error Response error.
  * @param string         $tag   Response XML tag (defaults to `authenticationFailure`).
  *
  * @uses \WP_Error
  * @uses \do_action()
  */
 public function setError(\WP_Error $error = null, $tag = 'authenticationFailure')
 {
     /**
      * Fires if the CAS server has to return an XML error.
      *
      * @param WP_Error $error WordPress error to return as XML.
      */
     \do_action('cas_server_error', $error);
     $message = __('Unknown error', 'wp-cas-server');
     $code = GeneralException::ERROR_INTERNAL_ERROR;
     if (!empty($error)) {
         $code = $error->get_error_code();
         $message = $error->get_error_message($code);
     }
     $this->response = $this->createElement($tag, $message);
     $this->response->setAttribute('code', $code);
 }
Example #11
0
 /**
  * Like addAttributes, but runs each value through normalization.
  * @see XmlPutter::addAttributes
  *
  * @param array $attributes
  */
 public function addBooleanAttributes($attributes = array())
 {
     foreach ($attributes as $key => $value) {
         if ($value === null) {
             continue;
         }
         $this->current->setAttribute($key, TypeNormalization::normalizeBooleanToString($value));
     }
 }
Example #12
0
 function set_id($id)
 {
     $this->_id = $id;
     // We can only set attributes of DOMElement objects (nodeType == 1).
     // Since these are the only objects that we can assign CSS rules to,
     // this shortcoming is okay.
     if ($this->_node->nodeType == 1) {
         $this->_node->setAttribute("frame_id", $id);
     }
 }
Example #13
0
 /**
  * Generic call-Method instead of numerous setter methods
  * @param             string              $method                       The name of the method, which is called for the Item-Object
  * @param             array               $args                         The arguments with them the method is called - minOccurance = 0, maxOccurance = 2:
  *                                                                      The first argument must be a positive integer (will be used as a index)
  *                                                                      The second argument is optional and would be used as value for the DOMNode
  */
 public function __call($method, $args)
 {
     if (substr($method, 0, 3) == "set" && $args[0] != '') {
         $attributeName = substr($method, 3);
         $value = $args[0];
         if (preg_match('/[0-9]+,[0-9]+/', $value, $match)) {
             $value = str_replace(',', '.', $match[0]);
         }
         if (preg_match('/[0-9]+.[0-9]+/', $value, $match) && $value == $match[0] && $attributeName != 'shippingCosts' && (is_int(strpos($attributeName, 'price')) || is_int(strpos($attributeName, 'Price')) || is_int(strpos($attributeName, 'Tax')) || is_int(strpos($attributeName, 'cost')) || is_int(strpos($attributeName, 'Cost')))) {
             $value = number_format(floatval($match[0]), 2, '.', '');
         }
         $this->node->setAttribute($attributeName, $value);
     } elseif ($args[0] != '') {
         if (sizeof($args) > 2) {
             die("It is not allowed to set more than 2 arguments for the node '{$method}'!");
         }
         if (!is_int($args[0]) || $args[0] < 1) {
             die("The first argument for the node '{$method}' must be whole number, bigger than 0!");
         }
         $name = $method . '[' . $args[0] . ']';
         $xpath = new \DOMXPath($this->doc);
         $qry = $xpath->query($name, $this->node);
         if ($qry->length > 0) {
             return new ORDER($this->doc, $qry->item(0));
         } else {
             if (array_key_exists(1, $args)) {
                 $value = $args[1];
                 if (preg_match('/[0-9]+,[0-9]+/', $value, $match)) {
                     $value = str_replace(',', '.', $match[0]);
                 }
                 if (preg_match('/[0-9]+.[0-9]+/', $value, $match) && $value == $match[0] && $name != 'shippingCosts' && (is_int(strpos($name, 'price')) || is_int(strpos($name, 'Price')) || is_int(strpos($name, 'Tax')) || is_int(strpos($name, 'cost')) || is_int(strpos($name, 'Cost')))) {
                     $value = number_format(floatval($match[0]), 2, '.', '');
                 }
                 $node = $this->doc->createElement($method, $value);
             } else {
                 $node = $this->doc->createElement($method);
             }
             $node = $this->node->appendChild($node);
             return new ORDER($this->doc, $node);
         }
     }
 }
Example #14
0
 public function attr($a_name, $a_value = null)
 {
     if (func_num_args() == 0) {
         return $this->m_node->getAttribute($a_name);
     }
     if (func_num_args() > 1) {
         $this->m_node->setAttribute($a_name, $a_value);
     }
     if (func_num_args() == 1) {
         $this->m_node->getAttribute($a_name);
     }
 }
Example #15
0
 /**
  * Vraci attributy
  * @param string $name
  * @throws LBoxExceptionConfig
  */
 public function __set($name = "", $value = "")
 {
     if (strlen($name) < 1) {
         throw new LBoxExceptionConfig(LBoxExceptionConfig::MSG_PARAM_STRING_NOTNULL, LBoxExceptionConfig::CODE_BAD_PARAM);
     }
     if ($value === NULL) {
         $this->node->removeAttribute($name);
     } else {
         if (!$this->node->setAttribute($name, $value)) {
             throw new LBoxExceptionConfig(LBoxExceptionConfig::MSG_ATTRIBUTE_CANNOT_CHANGE, LBoxExceptionConfig::CODE_ATTRIBUTE_CANNOT_CHANGE);
         }
     }
 }
Example #16
0
 public function visitElement(\DOMNode $domElement)
 {
     $domElement->setAttribute('class', $this->className);
     $dom = $domElement->ownerDocument;
     if (empty($this->arguments)) {
         return;
     }
     $arguments = $dom->createElement('arguments');
     $domElement->appendChild($arguments);
     foreach ($this->arguments as $argumentValue) {
         $argument = $this->createElementByType($argumentValue, $dom);
         $arguments->appendChild($argument);
     }
 }
 /**
  * Prefixes the href with base href.
  *
  * @param DOMNode $node Link
  * @param Title $title
  */
 public function apply(\DOMNode $node, \Title $title)
 {
     if (!$node instanceof \DOMElement) {
         return;
     }
     $href = $node->getAttribute('href');
     if (strpos($href, './') !== 0) {
         // If we need to handle more complex cases, we should resolve it
         // with a library like Net_URL2. This check will then be
         // unnecessary.
         return;
     }
     $href = $this->baseHref . $href;
     $node->setAttribute('href', $href);
 }
Example #18
0
 public function setNode(DOMNode $node)
 {
     if (!$this->parentNode) {
         throw new Exception('Parent Node must be set before actual Node');
     }
     $this->externalNode = $node;
     $this->element = $this->doc->createElement($this->getTagName());
     if ($this->keepAttributes) {
         foreach ($this->externalNode->attributes as $attr) {
             if ($attr->name == 'class') {
                 $this->className = strlen($this->className) ? $this->className . ' ' . $attr->value : $attr->value;
             } elseif ($attr->name == "data-pxe-attributes") {
                 $attributes = json_decode($attr->value);
                 foreach ($attributes as $name => $value) {
                     $this->element->setAttribute($name, $value);
                 }
             } elseif (substr($attr->name, 0, 8) != 'data-pxe' && substr($attr->name, 0, 7) !== 'data-ca') {
                 if (!array_key_exists($attr->name, $this->element->attributes)) {
                     $this->element->setAttribute($attr->name, $attr->value);
                 }
             }
         }
     }
     // Keep attribute explicitly asked for by editor regardless of how smart you think you are.
     foreach ($this->attributes as $key => $value) {
         if ($this->element->hasAttribute($key)) {
             $value = $this->element->getAttribute($key)->value . ' ' . $value;
         }
         $this->element->setAttribute($key, $value);
     }
     if ($this->className) {
         $this->element->setAttribute('class', $this->className);
     }
     $this->parentNode->appendChild($this->element);
     return $this;
 }
Example #19
0
 /**
  * Adds form elements related to this form.
  *
  * Creates an internal copy of the submitted 'button' element and
  * the form node or the entire document depending on whether we need
  * to find non-descendant elements through HTML5 'form' attribute.
  */
 private function initialize()
 {
     $this->fields = new FormFieldRegistry();
     $document = new \DOMDocument('1.0', 'UTF-8');
     $xpath = new \DOMXPath($document);
     $root = $document->appendChild($document->createElement('_root'));
     // add submitted button if it has a valid name
     if ('form' !== $this->button->nodeName && $this->button->hasAttribute('name') && $this->button->getAttribute('name')) {
         if ('input' == $this->button->nodeName && 'image' == $this->button->getAttribute('type')) {
             $name = $this->button->getAttribute('name');
             $this->button->setAttribute('value', '0');
             // temporarily change the name of the input node for the x coordinate
             $this->button->setAttribute('name', $name . '.x');
             $this->set(new Field\InputFormField($document->importNode($this->button, true)));
             // temporarily change the name of the input node for the y coordinate
             $this->button->setAttribute('name', $name . '.y');
             $this->set(new Field\InputFormField($document->importNode($this->button, true)));
             // restore the original name of the input node
             $this->button->setAttribute('name', $name);
         } else {
             $this->set(new Field\InputFormField($document->importNode($this->button, true)));
         }
     }
     // find form elements corresponding to the current form
     if ($this->node->hasAttribute('id')) {
         // traverse through the whole document
         $node = $document->importNode($this->node->ownerDocument->documentElement, true);
         $root->appendChild($node);
         // corresponding elements are either descendants or have a matching HTML5 form attribute
         $formId = Crawler::xpathLiteral($this->node->getAttribute('id'));
         $fieldNodes = $xpath->query(sprintf('descendant::input[@form=%s] | descendant::button[@form=%s] | descendant::textarea[@form=%s] | descendant::select[@form=%s] | //form[@id=%s]//input[not(@form)] | //form[@id=%s]//button[not(@form)] | //form[@id=%s]//textarea[not(@form)] | //form[@id=%s]//select[not(@form)]', $formId, $formId, $formId, $formId, $formId, $formId, $formId, $formId), $root);
         foreach ($fieldNodes as $node) {
             $this->addField($node);
         }
     } else {
         // parent form has no id, add descendant elements only
         $node = $document->importNode($this->node, true);
         $root->appendChild($node);
         // descendant elements with form attribute are not part of this form
         $fieldNodes = $xpath->query('descendant::input[not(@form)] | descendant::button[not(@form)] | descendant::textarea[not(@form)] | descendant::select[not(@form)]', $root);
         foreach ($fieldNodes as $node) {
             $this->addField($node);
         }
     }
 }
Example #20
0
 /**
  * @param \DOMNode|\DOMElement $node
  * @param mixed $json
  */
 protected function transferTo(\DOMNode $node, $json)
 {
     /** @var Document $dom */
     $dom = $node->ownerDocument ?: $node;
     if ($json instanceof \stdClass) {
         foreach ($json as $name => $data) {
             if ($name == '@attributes') {
                 if ($data instanceof \stdClass) {
                     foreach ($data as $attributeName => $attributeValue) {
                         $node->setAttribute($attributeName, $this->getValueAsString($attributeValue));
                     }
                 }
             } else {
                 $this->transferChildTo($node, $name, $data);
             }
         }
     } elseif (is_scalar($json)) {
         $node->appendChild($dom->createTextNode($this->getValueAsString($json)));
     }
 }
Example #21
0
 /**
  * Adds form elements related to this form.
  *
  * Creates an internal copy of the submitted 'button' element and
  * the form node or the entire document depending on whether we need
  * to find non-descendant elements through HTML5 'form' attribute.
  */
 private function initialize()
 {
     $this->fields = new FormFieldRegistry();
     $xpath = new \DOMXPath($this->node->ownerDocument);
     // add submitted button if it has a valid name
     if ('form' !== $this->button->nodeName && $this->button->hasAttribute('name') && $this->button->getAttribute('name')) {
         if ('input' == $this->button->nodeName && 'image' == strtolower($this->button->getAttribute('type'))) {
             $name = $this->button->getAttribute('name');
             $this->button->setAttribute('value', '0');
             // temporarily change the name of the input node for the x coordinate
             $this->button->setAttribute('name', $name . '.x');
             $this->set(new Field\InputFormField($this->button));
             // temporarily change the name of the input node for the y coordinate
             $this->button->setAttribute('name', $name . '.y');
             $this->set(new Field\InputFormField($this->button));
             // restore the original name of the input node
             $this->button->setAttribute('name', $name);
         } else {
             $this->set(new Field\InputFormField($this->button));
         }
     }
     // find form elements corresponding to the current form
     if ($this->node->hasAttribute('id')) {
         // corresponding elements are either descendants or have a matching HTML5 form attribute
         $formId = Crawler::xpathLiteral($this->node->getAttribute('id'));
         $fieldNodes = $xpath->query(sprintf('descendant::input[@form=%s] | descendant::button[@form=%s] | descendant::textarea[@form=%s] | descendant::select[@form=%s] | //form[@id=%s]//input[not(@form)] | //form[@id=%s]//button[not(@form)] | //form[@id=%s]//textarea[not(@form)] | //form[@id=%s]//select[not(@form)]', $formId, $formId, $formId, $formId, $formId, $formId, $formId, $formId));
         foreach ($fieldNodes as $node) {
             $this->addField($node);
         }
     } else {
         // do the xpath query with $this->node as the context node, to only find descendant elements
         // however, descendant elements with form attribute are not part of this form
         $fieldNodes = $xpath->query('descendant::input[not(@form)] | descendant::button[not(@form)] | descendant::textarea[not(@form)] | descendant::select[not(@form)]', $this->node);
         foreach ($fieldNodes as $node) {
             $this->addField($node);
         }
     }
     if ($this->baseHref && '' !== $this->node->getAttribute('action')) {
         $this->currentUri = $this->baseHref;
     }
 }
Example #22
0
 /**
  * Возвращает список дополнительных полей в XML
  * @param \DOMNode|\DOMElement $node
  */
 public static function getListXML($node)
 {
     $Cache = Cache::getInstance();
     $res = $Cache->get('announcements_additionals');
     if (!$res) {
         $db = MySQL::getInstance();
         $res = $db->fetch("SELECT * FROM `announcements_additionals`");
     } else {
         $node->setAttribute('cached', true);
     }
     if (!empty($res)) {
         $saveToCache = null;
         foreach ($res as $n => $data) {
             /** @var \DOMElement $itemNode */
             $itemNode = $node->appendChild($node->ownerDocument->createElement('item'));
             $itemNode->setAttribute('id', $data['id']);
             $itemNode->setAttribute('name', $data['name']);
             $itemNode->setAttribute('alias', $data['alias']);
             $saveToCache[$data['id']] = $data;
         }
         $Cache->put('announcements_additionals', $saveToCache, 10800);
     }
 }
Example #23
0
 /**
  * mapAttributes
  *
  * @return bool
  */
 private function mapAttributes(\DOMNode $node, $key, $value)
 {
     if (null !== ($attrName = $this->getAttributeName($key))) {
         foreach ((array) $value as $attrKey => $attrValue) {
             $node->setAttribute($attrKey, $this->getAttributeValue($attrValue, $attrKey));
         }
         return true;
     }
     if (is_scalar($value) && $this->isMappedAttribute($node->nodeName, $key) && $this->isValidNodeName($key)) {
         $node->setAttribute($key, $this->getAttributeValue($value, $key));
         return true;
     }
     return false;
 }
Example #24
0
 /**
  * Make an attribute absolute (href or src).
  *
  * @param string   $base The base url
  * @param \DOMNode $e    Element on which we'll retrieve the attribute
  * @param string   $attr Attribute that contains the url to absolutize
  */
 private function makeAbsoluteAttr($base, \DOMNode $e, $attr)
 {
     if (!$e->attributes->getNamedItem($attr)) {
         return;
     }
     // Trim leading and trailing white space. I don't really like this but
     // unfortunately it does appear on some sites. e.g.  <img src=" /path/to/image.jpg" />
     $url = trim(str_replace('%20', ' ', $e->getAttribute($attr)));
     $url = str_replace(' ', '%20', $url);
     if (!preg_match('!https?://!i', $url)) {
         if ($absolute = \SimplePie_IRI::absolutize($base, $url)) {
             $e->setAttribute($attr, $absolute);
         }
     }
 }
Example #25
0
 /**
  * Set the attribute $name with a value of $value for $element.
  * $value must already be UTF8-encoded; this is to be handled
  * by self::_executeEncoder() and $options['encoder'].
  *
  * @param DOMNode $element    An instance of DOMNode
  * @param string  $name       The name of the attribute to set.
  * @param string  $value      The value of the attribute to set.
  * @param string  $configPath The config path; used for exception messages.
  *
  * @return void
  * @throws XML_Query2XML_XMLException Any lower-level DOMException will be
  *                 wrapped and re-thrown as a XML_Query2XML_XMLException. This
  *                 will happen if $name is not a valid attribute name. It will
  *                 also be thrown if $value is an object or an array (and can
  *                 therefore not be converted into a string).
  */
 private static function _setDOMAttribute(DOMNode $element, $name, $value, $configPath)
 {
     if (is_object($value) || is_array($value)) {
         /*
          * Objects and arrays cannot be cast
          * to a string without an error.
          *
          * unit test:
          * _setDOMAttribute/throwXMLException.phpt
          */
         throw new XML_Query2XML_XMLException($configPath . ': A value of the type ' . gettype($value) . ' cannot be used for an attribute value.');
     }
     try {
         $element->setAttribute($name, $value);
     } catch (DOMException $e) {
         // no unit test available for this one
         throw new XML_Query2XML_XMLException($configPath . ': "' . $name . '" is an invalid XML attribute name: ' . $e->getMessage(), $e);
     }
 }
Example #26
0
 /**
  * Возвращает локацию по её id
  * @param int $id
  * @param \DOMNode|\DOMElement $node
  */
 public function getLocationByIdXML($id, $node)
 {
     $db = MySQL::getInstance();
     $res = $db->fetchRow("SELECT `locationData` FROM `anouncements_locations` WHERE `id`='" . intval($id) . "'");
     if (!empty($res)) {
         $data = unserialize($res['locationData']);
         foreach ($data as $k => $value) {
             $node->setAttribute($k, $value);
         }
     }
 }
Example #27
0
 /**
  * Process the header of an editable node
  * @param I2CE_Template $template
  * @param DOMNode $node
  * @param DOMNode $head_node
  */
 protected function processHeaderEditable($template, $node, $head_node)
 {
     if ($this->getOption('required')) {
         $asterisk = $template->createElement("span");
         $asterisk->appendChild($template->createTextNode("*"));
         $asterisk->setAttribute("class", "required_field_notice");
         $head_node->appendChild($asterisk);
         $head_node->setAttribute("class", $head_node->getAttribute("class") . " required_field");
     }
 }
Example #28
0
 /**
  * Parse the data and convert it to DOMElements
  *
  * @param DOMNode $parentNode
  * @param array|object $data data
  * @return Boolean
  */
 private function buildXml($parentNode, $data)
 {
     $append = true;
     if (is_array($data) || $data instanceof \Traversable) {
         foreach ($data as $key => $data) {
             //Ah this is the magic @ attribute types.
             if (0 === strpos($key, "@") && is_scalar($data) && $this->isElementNameValid($attributeName = substr($key, 1))) {
                 $parentNode->setAttribute($attributeName, $data);
             } elseif ($key === '#') {
                 $append = $this->selectNodeType($parentNode, $data);
             } elseif (is_array($data) && false === is_numeric($key)) {
                 /**
                  * Is this array fully numeric keys?
                  */
                 if (ctype_digit(implode('', array_keys($data)))) {
                     /**
                      * Create nodes to append to $parentNode based on the $key of this array
                      * Produces <xml><item>0</item><item>1</item></xml>
                      * From array("item" => array(0,1));
                      */
                     foreach ($data as $subData) {
                         $append = $this->appendNode($parentNode, $subData, $key);
                     }
                 } else {
                     $append = $this->appendNode($parentNode, $data, $key);
                 }
             } elseif (is_numeric($key) || !$this->isElementNameValid($key)) {
                 $append = $this->appendNode($parentNode, $data, "item", $key);
             } else {
                 $append = $this->appendNode($parentNode, $data, $key);
             }
         }
         return $append;
     }
     if (is_object($data)) {
         $data = $this->serializer->normalizeObject($data, $this->format);
         if (null !== $data && !is_scalar($data)) {
             return $this->buildXml($parentNode, $data);
         }
         // top level data object was normalized into a scalar
         if (!$parentNode->parentNode->parentNode) {
             $root = $parentNode->parentNode;
             $root->removeChild($parentNode);
             return $this->appendNode($root, $data, $this->rootNodeName);
         }
         return $this->appendNode($parentNode, $data, 'data');
     }
     throw new \UnexpectedValueException('An unexpected value could not be serialized: ' . var_export($data, true));
 }
 public function xml($parent, $suppliedRegions, &$incompatibilities, $needles = [], $needleUserData = [], $backup = false)
 {
     foreach ($this->results as $result) {
         $resultNode = new DOMNode("result");
         $resultNode->setAttribute('name', $this->result->name);
         $parent->appendChild($resultNode);
     }
     $regions = [];
     $regionsNode = new DOMElement("regions");
     $parent->appendChild($regionsNode);
     foreach ($this->Regions as $region) {
         $entries = $suppliedRegions->filter(function ($r) use($region) {
             return in_array($r->SegmentationType, $region->SegmentationTypes);
         });
         $entries->each(function ($e) {
             $e->Location = strtolower($e->FileId) . '/' . $e->FileName . '.' . $e->Extension;
         });
         $suppliedCount = $entries->count();
         $pivot = $region->pivot;
         if (Config::get('gosmart.check_regions') !== false) {
             if ($pivot->Maximum !== null && $suppliedCount > $pivot->Maximum) {
                 $incompatibilities[] = "Too many region entries for {$region->Name} (max {$pivot->Maximum}, provided {$suppliedCount})";
             }
             if ($pivot->Minimum !== null && $suppliedCount < $pivot->Minimum) {
                 $incompatibilities[] = "Too few region entries for {$region->Name} (min {$pivot->Minimum}, provided {$suppliedCount})";
             }
         } else {
             if ($pivot->Minimum) {
                 for ($k = 0; $k < $pivot->Minimum - $entries->count(); $k++) {
                     $entry = clone $region;
                     $entries[] = $entry;
                     $entry->Location = $region->Name . '.vtp';
                 }
             }
         }
         $k = 0;
         foreach ($entries as $entry) {
             $regionNode = new DOMElement("region");
             $regionsNode->appendChild($regionNode);
             $regionNode->setAttribute('id', $region->Name . '-' . $k);
             $regionNode->setAttribute('name', $region->Name);
             $regionNode->setAttribute('format', $region->Format);
             $regionNode->setAttribute('input', $entry->Location);
             $regionNode->setAttribute('groups', $region->Groups);
             /* groups should be a JSON array */
             $k += 1;
         }
         $suppliedRegions = $suppliedRegions->reject(function ($r) use($region) {
             return $r->SegmentationType == $region->SegmentationType;
         });
     }
     //if (count($suppliedRegions))
     //  $incompatibilities[] = "Unknown regions for model $this->Name : " . implode(', ', $suppliedRegions->lists('Name'));
     $needlesNode = new DOMElement("needles");
     $parent->appendChild($needlesNode);
     $i = 1;
     foreach ($needles as $simulationNeedle) {
         $needle = $simulationNeedle->Needle;
         if ($simulationNeedle->Index) {
             $needleIx = 'needle' . $simulationNeedle->Index;
         } else {
             $needleIx = 'needle' . $i;
         }
         $i += 1;
         $needleNode = new DOMElement("needle");
         $needlesNode->appendChild($needleNode);
         $needleNode->setAttribute("index", $needleIx);
         if ($backup) {
             $needleNode->setAttribute("id", $needle->Id);
             $needleNode->setAttribute("name", $needle->Name);
         }
         /* isset checks value whether NULL */
         if (isset($needleUserData[$needleIx]) && isset($needleUserData[$needleIx]['class'])) {
             $needleNode->setAttribute("class", $needleUserData[$needleIx]['class']);
         } else {
             if (!empty($needle->Class)) {
                 $needleNode->setAttribute("class", $needle->Class);
             } else {
                 $incompatibilities[] = "Needle class is not given for " . $needleIx;
             }
         }
         if (isset($needleUserData[$needleIx]) && isset($needleUserData[$needleIx]['file'])) {
             $needleNode->setAttribute("file", $needleUserData[$needleIx]['file']);
         } else {
             if (!empty($needle->Geometry)) {
                 $needleNode->setAttribute("file", $needle->Geometry);
             } else {
                 $incompatibilities[] = "Needle file is not given for " . $needleIx;
             }
         }
         $parametersNode = new DOMElement("parameters");
         $needleNode->appendChild($parametersNode);
         $tipParameter = Parameter::whereName("NEEDLE_TIP_LOCATION")->first();
         $tipParameter->Value = json_encode($simulationNeedle->Target->asArray);
         $entryParameter = Parameter::whereName("NEEDLE_ENTRY_LOCATION")->first();
         $entryParameter->Value = json_encode($simulationNeedle->Entry->asArray);
         $tipParameter->xml($parametersNode, $backup);
         $entryParameter->xml($parametersNode, $backup);
         $simulationNeedle->Parameters->each(function ($parameter) use($parametersNode, $backup) {
             $parameter->xml($parametersNode, $backup);
         });
     }
     $definition = new DOMElement("definition");
     $definitionText = new DOMText($this->Definition);
     $parent->appendChild($definition);
     $definition->setAttribute('family', $this->Family);
     $definition->appendChild($definitionText);
 }
Example #30
0
 protected static function attrClass($action, DOMNode $node, $class)
 {
     $classes = $node->getAttribute('class');
     $found = stripos($classes, $class) !== false && in_array(strtolower($class), explode(' ', strtolower($classes)));
     if ($action == 'has') {
         return $found;
     }
     if ($action == 'toggle') {
         $action = $found ? 'remove' : 'add';
     }
     if ($action == 'add' && !$found) {
         $node->setAttribute('class', trim(preg_replace('/\\s{2,}/i', ' ', $classes . ' ' . $class)));
     }
     if ($action == 'remove' && $found) {
         $classes = trim(preg_replace('/\\s{2,}/i', ' ', preg_replace('/(^|\\s)' . preg_quote($class, '/') . '(?:\\s|$)/i', ' ', $classes)));
         if ($classes !== '') {
             $node->setAttribute('class', $classes);
         } else {
             $node->removeAttribute('class');
         }
     }
     return $node;
 }