Esempio n. 1
0
 /**
  * Delete nodes that have "acl" attribute but value is "not allowed"
  * In any case, the "acl" attribute will be unset
  *
  * @param \Magento\Framework\Simplexml\Element $xml
  * @return void
  */
 public function filterAclNodes(\Magento\Framework\Simplexml\Element $xml)
 {
     $limitations = $xml->xpath('//*[@acl]') ?: array();
     foreach ($limitations as $node) {
         if (!$this->_authorization->isAllowed($node['acl'])) {
             $node->unsetSelf();
         } else {
             unset($node['acl']);
         }
     }
 }
Esempio n. 2
0
 /**
  * Adds a child element to the XML node
  *
  * @param string $name The name of the child element to add.
  * @param string $value If specified, the value of the child element.
  * @param string $namespace If specified, the namespace to which the child element belongs.
  * @return \Magento\Shipping\Model\Simplexml\Element
  */
 public function addChild($name, $value = null, $namespace = null)
 {
     if (!is_null($value)) {
         $value = $this->xmlentities($value);
     }
     return parent::addChild($name, $value, $namespace);
 }
Esempio n. 3
0
 /**
  * Install an application
  *
  * @param string $adminUserName
  * @param string $adminPassword
  * @param string $adminRoleName
  * @throws \Magento\Framework\Exception
  */
 public function install($adminUserName, $adminPassword, $adminRoleName)
 {
     $this->_ensureDirExists($this->_installDir);
     $this->_ensureDirExists($this->_installEtcDir);
     $this->_ensureDirExists($this->_installDir . '/media');
     $this->_ensureDirExists($this->_installDir . '/static');
     // Copy configuration files
     $globalConfigFiles = glob($this->_globalConfigDir . '/{*,*/*}.xml', GLOB_BRACE);
     foreach ($globalConfigFiles as $file) {
         $targetFile = $this->_installEtcDir . str_replace($this->_globalConfigDir, '', $file);
         $this->_ensureDirExists(dirname($targetFile));
         copy($file, $targetFile);
     }
     foreach ($this->_moduleEtcFiles as $file) {
         $targetModulesDir = $this->_installEtcDir . '/modules';
         $this->_ensureDirExists($targetModulesDir);
         copy($file, $targetModulesDir . '/' . basename($file));
     }
     /* Make sure that local.xml does not contain an invalid installation date */
     $installDate = (string) $this->_localXml->install->date;
     if ($installDate && strtotime($installDate)) {
         throw new \Magento\Framework\Exception('Local configuration must contain an invalid installation date.');
     }
     /* Replace local.xml */
     $targetLocalXml = $this->_installEtcDir . '/local.xml';
     $this->_localXml->asNiceXml($targetLocalXml);
     /* Initialize an application in non-installed mode */
     $this->initialize();
     \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get('Magento\\Framework\\App\\AreaList')->getArea('install')->load(\Magento\Framework\App\Area::PART_CONFIG);
     /* Run all install and data-install scripts */
     /** @var $updater \Magento\Framework\Module\Updater */
     $updater = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get('Magento\\Framework\\Module\\Updater');
     $updater->updateScheme();
     $updater->updateData();
     /* Enable configuration cache by default in order to improve tests performance */
     /** @var $cacheState \Magento\Framework\App\Cache\StateInterface */
     $cacheState = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get('Magento\\Framework\\App\\Cache\\StateInterface');
     $cacheState->setEnabled(\Magento\Framework\App\Cache\Type\Config::TYPE_IDENTIFIER, true);
     $cacheState->setEnabled(\Magento\Framework\App\Cache\Type\Layout::TYPE_IDENTIFIER, true);
     $cacheState->setEnabled(\Magento\Framework\App\Cache\Type\Translate::TYPE_IDENTIFIER, true);
     $cacheState->setEnabled(\Magento\Eav\Model\Cache\Type::TYPE_IDENTIFIER, true);
     $cacheState->persist();
     /* Fill installation date in local.xml to indicate that application is installed */
     $localXml = file_get_contents($targetLocalXml);
     $localXml = str_replace($installDate, date('r'), $localXml, $replacementCount);
     if ($replacementCount != 1) {
         throw new \Magento\Framework\Exception("Unable to replace installation date properly in '{$targetLocalXml}' file.");
     }
     file_put_contents($targetLocalXml, $localXml, LOCK_EX);
     /* Add predefined admin user to the system */
     $this->_createAdminUser($adminUserName, $adminPassword, $adminRoleName);
     /* Switch an application to installed mode */
     $this->initialize();
     //hot fix for \Magento\Catalog\Model\Product\Attribute\Backend\SkuTest::testGenerateUniqueLongSku
     /** @var $appState \Magento\Framework\App\State */
     $appState = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get('Magento\\Framework\\App\\State');
     $appState->setInstallDate(date('r', strtotime('now')));
 }
Esempio n. 4
0
 /**
  * Extends one node
  *
  * @param \Magento\Framework\Simplexml\Element $source
  * @param boolean $overwrite
  * @return $this
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.UnusedLocalVariable)
  */
 public function extendChild($source, $overwrite = false)
 {
     // this will be our new target node
     $targetChild = null;
     // name of the source node
     $sourceName = $source->getName();
     // here we have children of our source node
     $sourceChildren = $source->children();
     if (!$source->hasChildren()) {
         // handle string node
         if (isset($this->{$sourceName})) {
             // if target already has children return without regard
             if ($this->{$sourceName}->hasChildren()) {
                 return $this;
             }
             if ($overwrite) {
                 unset($this->{$sourceName});
             } else {
                 return $this;
             }
         }
         $targetChild = $this->addChild($sourceName, $source->xmlentities());
         $targetChild->setParent($this);
         foreach ($source->attributes() as $key => $value) {
             $targetChild->addAttribute($key, $this->xmlentities($value));
         }
         return $this;
     }
     if (isset($this->{$sourceName})) {
         $targetChild = $this->{$sourceName};
     }
     if (is_null($targetChild)) {
         // if child target is not found create new and descend
         $targetChild = $this->addChild($sourceName);
         $targetChild->setParent($this);
         foreach ($source->attributes() as $key => $value) {
             $targetChild->addAttribute($key, $this->xmlentities($value));
         }
     }
     // finally add our source node children to resulting new target node
     foreach ($sourceChildren as $childKey => $childNode) {
         $targetChild->extendChild($childNode, $overwrite);
     }
     return $this;
 }
 protected function _prepareAnswerText(XmlElement $answer)
 {
     $text = $answer->getAttribute('Text');
     if ($this->_isPrice()) {
         $id = $answer->getAttribute('Id');
         if (preg_match('@^_P(\\d+)_(\\d+)$@', $id, $matches)) {
             $text = str_replace('<min>', $matches[1], $text);
             $text = str_replace('<max>', $matches[2], $text);
         }
     }
     return $text;
 }
Esempio n. 6
0
 /**
  * Create node by $path and set its value.
  *
  * @param string $path separated by slashes
  * @param string $value
  * @param boolean $overwrite
  * @return $this
  */
 public function setNode($path, $value, $overwrite = true)
 {
     $xml = $this->_xml->setNode($path, $value, $overwrite);
     return $this;
 }
 protected function _specialCasesToHandleString(XmlElement $xml)
 {
     return implode('^', $xml->children());
 }
Esempio n. 8
0
File: X.php Progetto: mage2pro/core
 /**
 * Этот метод разработал сам, но не тестировал,
 * потому что после разработки только заметил,
 * что применять его к стандартным файлам XML (@see Mage::getConfig()) всё равно нельзя:
 * в стандартном мега-файле, возвращаемом Mage::getConfig(),
 * одноимённые дочерние узлы уже отсутствуют (перетёрты друг другом).
 *
 * Отличие от стандартного метода @see asArray():
 * если дерево XML содержит несколько одноимённых дочерних узлов,
 * то родительский метод при конвертации дерева XML в массив
 * перетирает содержимое дочерних узлов друг другом:
 * @see \Magento\Framework\Simplexml\Element::_asArray():
 * $result[$childName] = $child->_asArray($isCanonical);
 * Например, дерево XML
 		<url>
 			<demo>http://fortis.magento-demo.ru/default/</demo>
 			<demo>http://fortis.magento-demo.ru/second/</demo>
 			<demo>http://fortis.magento-demo.ru/third/</demo>
 			<demo>http://fortis.magento-demo.ru/fourth/</demo>
 			<demo>http://fortis.magento-demo.ru/fifth/</demo>
 			<demo_images_base>http://fortis.infortis-themes.com/demo/</demo_images_base>
 			<forum>http://magento-forum.ru/forum/350/</forum>
 			<official_site>http://themeforest.net/item/fortis-responsive-magento-theme/1744309?ref=dfediuk</official_site>
 		</url>
 * будет сконвертировано в такой массив:
 		[url] => Array
 		 (
 			 [demo] => http://fortis.magento-demo.ru/fifth/
 			 [demo_images_base] => http://fortis.infortis-themes.com/demo/
 			 [forum] => http://magento-forum.ru/forum/350/
 			 [official_site] => http://themeforest.net/item/fortis-responsive-magento-theme/1744309?ref=dfediuk
 		 )
 * Обратите внимание, что содержимым ключа «demo» массива
 * стало содержимое последнего (по порядку следования) дочернего узла исходного дерева XML:
 	 <demo>http://fortis.magento-demo.ru/fifth/</demo>
 *
 * Наш метод @see asMultiArray()
 * при наличии в исходном дереве XML нескольких одноимённых дочерних узлов
 * добавляет их все в массив, создавая подмассив:
 		[url] => Array
 		 (
 			 [demo] => Array
 			  (
 				[0] => http://fortis.magento-demo.ru/default/
 				[1] => http://fortis.magento-demo.ru/second/
 				[2] => http://fortis.magento-demo.ru/third/
 				[3] => http://fortis.magento-demo.ru/fourth/
 				[4] => http://fortis.magento-demo.ru/fifth/
 		  )
 			 [demo_images_base] => http://fortis.infortis-themes.com/demo/
 			 [forum] => http://magento-forum.ru/forum/350/
 			 [official_site] => http://themeforest.net/item/fortis-responsive-magento-theme/1744309?ref=dfediuk
 		 )
 *
 * @param MX $e
 * @param bool $isCanonical [optional]
 * @return array(string => string|array())
 */
 public static function asMultiArray(MX $e, $isCanonical = true)
 {
     /** @var array(string => string|array()) $result */
     $result = [];
     if (!$e->hasChildren()) {
         /** Просто повторяем алгоритм метода @see \Magento\Framework\Simplexml\Element::_asArray() */
         $result = $e->_asArray($isCanonical);
     } else {
         if (!$isCanonical) {
             /** Просто повторяем алгоритм метода @see \Magento\Framework\Simplexml\Element::_asArray() */
             foreach ($e->attributes() as $attributeName => $attribute) {
                 /** @var string $attributeName */
                 /** @var MX $attribute */
                 if ($attribute) {
                     $result['@'][$attributeName] = (string) $attribute;
                 }
             }
         } else {
             /**
              * Обратите внимание, что,
              * в отличие от метода @see \Magento\Framework\Simplexml\Element::_asArray(),
              * мы не можем использовать синтаксис
              * foreach ($e->children() as $childName => $child) {
              * потому что при таком синтаксисе мы не сможем получить доступ
              * ко всем одноимённым дочерним узлам.
              */
             foreach ($e->children() as $child) {
                 /** @var MX $child */
                 /** @var string $childName */
                 $childName = $child->getName();
                 /** @var array(string => string|array()) $childAsArray */
                 $childAsArray = self::asMultiArray($child, $isCanonical);
                 if (!isset($result[$childName])) {
                     /**
                      * Просто повторяем алгоритм метода
                      * @see \Magento\Framework\Simplexml\Element::_asArray()
                      */
                     $result[$childName] = $childAsArray;
                 } else {
                     // у нас уже есть дочерний узел с данным именем
                     if (!is_array($result[$childName])) {
                         // преобразуем узел в массив
                         $result[$childName] = [$result[$childName]];
                     }
                     $result[$childName][] = $childAsArray;
                 }
             }
         }
     }
     return $result;
 }