Example #1
1
 /**
  * testRenderWithView method
  *
  * @return void
  */
 public function testRenderWithView()
 {
     $Request = new Request();
     $Response = new Response();
     $Controller = new Controller($Request, $Response);
     $Controller->name = 'Posts';
     $Controller->viewPath = 'Posts';
     $data = array(array('User' => array('username' => 'user1')), array('User' => array('username' => 'user2')));
     $Controller->set('users', $data);
     $Controller->viewClass = 'Xml';
     $View = $Controller->createView();
     $output = $View->render('index');
     $expected = array('users' => array('user' => array('user1', 'user2')));
     $expected = Xml::build($expected)->asXML();
     $this->assertSame($expected, $output);
     $this->assertSame('application/xml', $Response->type());
     $this->assertInstanceOf('Cake\\View\\HelperRegistry', $View->helpers());
 }
 /**
  * Cálculo do valor e prazo do frete
  *
  * $opcoes
  * `servico`  (int)  Código do serviço, ver as defines CORREIOS_*. (Obrigatório)
  * `cepOrigem`  (string)  CEP de origem no formato XXXXX-XXX (Obrigatório)
  * `cepDestino`  (string)  CEP de destino no formato XXXXX-XXX (Obrigatório)
  * `peso`  (float)  Peso do pacote, em quilos (Obrigatório)
  * `maoPropria`  (bool)  Usar recurso de mão própria? (Obrigatório)
  * `valorDeclarado`  (float)  Valor declarado do pacote. (Obrigatório)
  * `avisoRecebimento`  (bool)  Aviso de recebimento?. (Obrigatório)
  * `formato`  (int)  Formato da encomenda (Caixa, Rolo ou envelope) veja os campos estáticos. (Obrigatório)
  * `comprimento`  (float)  Comprimento da encomenda. (Obrigatório)
  * `altura`  (float)  Altura da encomenda, caso formato seja envolope deve ser 0
  * `largura`  (float)  Largura da encomenda (Obrigatório) > 11cm
  * `diametro`  (float)  Diametro caso formato seja rolo.
  * `empresa`  (string)  O código administrativo cadastrado no ECT.
  * `senha`  (string)  A senha da empresa
  *
  * @param array $opcoes As opções para passar para API
  * @return mixed Array com os dados do frete ou integer com erro. Ver defines ERRO_CORREIOS_* para erros.
  */
 public function valorFrete($opcoes = [])
 {
     // Validação dos parâmetros
     if ($this->__erroCorreios($this->__validaOpcoes($opcoes))) {
         return $this->__validaOpcoes($opcoes);
     }
     // Ajustes nos parâmetros
     $opcoes["maoPropria"] = $opcoes["maoPropria"] ? 'S' : 'N';
     $opcoes["avisoRecebimento"] = $opcoes["avisoRecebimento"] ? 'S' : 'N';
     $query = ['op' => 'CalcPrecoPrazo', 'nCdEmpresa' => isset($opcoes["empresa"]) ? $opcoes["empresa"] : "", 'sDsSenha' => isset($opcoes["senha"]) ? $opcoes["senha"] : "", 'nCdServico' => $opcoes["servico"], 'sCepOrigem' => $opcoes["cepOrigem"], 'sCepDestino' => $opcoes["cepDestino"], 'nVlPeso' => $opcoes["peso"], 'nCdFormato' => $opcoes["formato"], 'nVlComprimento' => $opcoes["comprimento"], 'nVlAltura' => $opcoes["formato"] === CorreiosTrait::$ENCOMENDA_ENVELOPE ? 0 : $opcoes["altura"], 'nVlLargura' => $opcoes["largura"], 'nVlDiametro' => $opcoes["formato"] === CorreiosTrait::$ENCOMENDA_ROLO ? $opcoes["diametro"] : 0, 'sCdMaoPropria' => $opcoes["maoPropria"], 'nVlValorDeclarado' => $opcoes["valorDeclarado"] ? $opcoes["valorDeclarado"] : 'n', 'sCdAvisoRecebimento' => $opcoes["avisoRecebimento"] ? $opcoes["avisoRecebimento"] : 'n', 'StrRetorno' => 'xml', 'nIndicaCalculo' => 3];
     /*
      * http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx?nCdEmpresa=09146920&sDsSenha=123456&sCepOrigem=70002900&sCepDestino=71939360&nVlPeso=1&nCdFormato=1&nVlComprimento=30&nVlAltura=30&nVlLargura=30&sCdMaoPropria=n&nVlValorDeclarado=0&sCdAvisoRecebimento=n&nCdServico=40010&nVlDiametro=0&StrRetorno=xml&nIndicaCalculo=3
      */
     $retornoCorreios = $this->_requisitaUrl('http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx', 'get', $query);
     if (is_integer($retornoCorreios)) {
         return $retornoCorreios;
     }
     $xml = Xml::build($retornoCorreios);
     $infoCorreios = Xml::toArray($xml);
     if (!isset($infoCorreios['Servicos']['cServico'])) {
         return CorreiosTrait::$ERRO_CORREIOS_CONTEUDO_INVALIDO;
     }
     extract($infoCorreios['Servicos']['cServico']);
     /**
      * @var string $ValorMaoPropria
      * @var string $ValorValorDeclarado
      * @var string $Valor
      * @var string $EntregaDomiciliar
      * @var string $EntregaSabado
      */
     return ['valorMaoPropria' => $ValorMaoPropria, 'valorTarifaValorDeclarado' => $ValorValorDeclarado, 'valorFrete' => $Valor - $ValorValorDeclarado - $ValorMaoPropria, 'valorTotal' => $Valor, 'entregaDomiciliar' => $EntregaDomiciliar === "S" ? true : false, 'entregaSabado' => $EntregaSabado === "S" ? true : false];
 }
Example #3
0
 /**
  * Latest Posts method.
  *
  * @return void
  */
 public function latestPosts()
 {
     $rss = file_get_contents('http://cakemanager.org/rss', false);
     if ($rss) {
         $xml = Xml::toArray(Xml::build($rss));
         $data = $xml['rss']['channel']['item'];
     }
     $this->set('posts', isset($data) ? $data : []);
 }
Example #4
0
 /**
  * Dump all assets
  */
 public function all()
 {
     foreach ($this->getAssetsXMLFiles() as $path => $XMLFile) {
         $this->out('');
         $this->out(sprintf('<info>Start dumping "%s" assets:</info>', $path));
         $xml = new Xml();
         $domDocument = $xml->build($XMLFile, ['return' => 'domdocument']);
         $xpath = new DOMXPath($domDocument);
         $assetsNodeList = $xpath->query('/assetic/assets/asset');
         $assetManager = new AssetManager();
         /** @var $assetNode DOMElement */
         foreach ($assetsNodeList as $assetNode) {
             $source = strtr($assetNode->getElementsByTagName('source')->item(0)->nodeValue, $this->paths);
             $destination = strtr($assetNode->getElementsByTagName('destination')->item(0)->nodeValue, $this->paths);
             $assetManager->set($assetNode->getAttribute('name'), $fileAsset = new FileAsset($source));
             $fileAsset->setTargetPath($destination);
             $this->out($source . ' <info> >>> </info> ' . WWW_ROOT . $destination);
         }
         $assetWriter = new AssetWriter(WWW_ROOT);
         $assetWriter->writeManagerAssets($assetManager);
         $this->dumpStaticFiles($domDocument);
         $this->out('<info>End</info>');
     }
 }
Example #5
0
 /**
  * Entity constructor.
  *
  * @param array $properties
  * @param array $options
  */
 public function __construct(array $properties = [], array $options = [])
 {
     $Theme = Theme::getInstance();
     if (isset($properties['alias'])) {
         $name = UnionPlugin::aliasToName($properties['alias']);
         $this->_xmlPath = $Theme->getPath() . $name . DS . $Theme->getFileName();
     }
     if ($this->_xmlPath) {
         $xml = Xml::build($this->_xmlPath);
         if ($xml instanceof \SimpleXMLElement) {
             $this->_xmlAttr = $Theme->setAttributes($xml);
         }
     }
     parent::__construct($properties, $options);
 }
Example #6
0
 /**
  * @param string $query
  *
  * @return \Geocoder\Model\AddressCollection
  */
 private function executeQuery($query)
 {
     $content = (string) $this->getAdapter()->get($query)->getBody();
     if (empty($content)) {
         throw new NoResult(sprintf('Could not execute query %s', $query));
     }
     $data = Xml::build($content);
     if (empty($data) || empty($data->result)) {
         throw new NoResult(sprintf('Could not execute query %s', $query));
     }
     $data = (array) $data->result;
     $adminLevels = [];
     if (!empty($data['isp']) || !empty($data['isp'])) {
         $adminLevels[] = ['name' => isset($data['isp']) ? $data['isp'] : null, 'code' => null, 'level' => 1];
     }
     return $this->returnResults([array_merge($this->getDefaults(), ['latitude' => isset($data['latitude']) ? $data['latitude'] : null, 'longitude' => isset($data['longitude']) ? $data['longitude'] : null, 'locality' => isset($data['city']) ? $data['city'] : null, 'adminLevels' => $adminLevels, 'country' => isset($data['countryname']) ? $data['countryname'] : null, 'countryCode' => isset($data['countrycode']) ? $data['countrycode'] : null])]);
 }
 private static function searchDnb($isbn)
 {
     //$scheme = 'oai_dc';
     $scheme = 'MARC21-xml';
     $options = ['operation=searchRetrieve', 'accessToken=' . Configure::read('DNB.accessToken'), 'recordSchema=' . $scheme, 'query=' . $isbn];
     $url = 'http://services.dnb.de/sru/dnb?version=1.1&' . implode($options, '&');
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     $output = curl_exec($ch);
     curl_close($ch);
     $xml = simplexml_load_string($output, 'SimpleXMLElement', LIBXML_NOCDATA);
     $xml = Xml::toArray($xml);
     if (isset($xml['searchRetrieveResponse']['numberOfRecords']) && $xml['searchRetrieveResponse']['numberOfRecords'] > 0) {
         return $xml;
     } else {
         return false;
     }
 }
 public function map()
 {
     $xml = Xml::build('/etc/shibboleth/attribute-map.xml');
     foreach ($xml->Attribute as $attr) {
         $attributeMap[(string) $attr->attributes()->id][] = (string) $attr->attributes()->name;
     }
     foreach ($attributeMap as $key => $values) {
         unset($oid);
         unset($name);
         $schema = "Undetected";
         if (count($values) > 2) {
             die('too much');
         }
         foreach ($values as $value) {
             if (preg_match_all("/[0-9]/", $value) > 3) {
                 $oid = $value;
             } else {
                 $temp = explode(':', $value);
                 $name = end($temp);
                 if (substr(strtolower($name), 0, strlen('schac')) === 'schac') {
                     $schema = 'schac';
                 }
                 if (substr(strtolower($name), 0, strlen('eduperson')) === 'eduperson') {
                     $schema = 'eduperson';
                 }
                 if (substr(strtolower($name), 0, strlen('funeteduperson')) === 'funeteduperson') {
                     $schema = 'funeteduperson';
                 }
             }
         }
         if (!isset($oid)) {
             $oid = null;
         }
         $attributes = array('friendlyname' => $name, 'name' => $name, 'oid' => $oid, 'schema' => $schema);
         if ($this->Attributes->findByOid($oid)->isEmpty()) {
             $attribute = $this->Attributes->newEntity();
             $attribute = $this->Attributes->patchEntity($attribute, $attributes);
             $this->Attributes->save($attribute);
         }
     }
     $this->setAction('index');
 }
Example #9
0
 /**
  * Generate the sitemap.
  *
  * For each plugin, it calls dynamically all methods from class
  * `$PLUGIN\Utility\Sitemap`.
  * Each method must be return an array or urls to add to the sitemap.
  * @return string
  * @see MeCms\Utility\Sitemap
  * @uses MeCms\Core\Plugin::all()
  * @uses parse()
  */
 public function generate()
 {
     //Adds the homepage
     $url = [self::parse('/')];
     foreach (Plugin::all() as $plugin) {
         //Sets the class name
         $class = sprintf('\\%s\\Utility\\Sitemap', $plugin);
         //Gets all methods from `$PLUGIN\Utility\Sitemap` class
         $methods = getChildMethods($class);
         if (empty($methods)) {
             continue;
         }
         //Calls all methods
         foreach ($methods as $method) {
             $url = am($url, call_user_func([$class, $method]));
         }
     }
     $xml = Xml::fromArray(['urlset' => ['xmlns:' => 'http://www.sitemaps.org/schemas/sitemap/0.9', 'url' => $url]], ['pretty' => true]);
     return $xml->asXML();
 }
 /**
  * Index method
  *
  * @return void
  */
 public function index()
 {
     $it = new StoresController();
     $it->index();
     $masters = $this->paginate($this->Masters);
     $this->set('masters', $masters);
     //pr($masters);
     $items = array();
     foreach ($masters as $value) {
         //pr($value);
         $items[] = ['brand_code' => $value['brand_code'], 'item_code' => $value['item_code'], 'model_code' => $value['model_code'], 'store_code' => $value['store_code'], 'category_code' => $value['category_code'], 'sku' => $value['sku'], 'urn' => $value['urn'], 'price' => $value['price']];
     }
     //pr($items);
     $xmlArray = ['root' => ['xmlns:' => 'http://cakephp.org', 'child' => $items]];
     //$xmlObject = Xml::fromArray($xmlArray);
     //$xmlString = $xmlObject->asXML();
     $xml = Xml::build($xmlArray, ['return' => 'domdocument']);
     echo 'Wrote: ' . $xml->save(WWW_ROOT . 'uploads' . DS . "test.xml") . ' bytes';
     $this->set('_serialize', ['masters']);
 }
Example #11
0
 /**
  * Extract zip archive.
  *
  * @return bool
  */
 public function open()
 {
     $path = $this->_request->data($this->_inputName);
     $this->setPath($path);
     $Zip = $this->zip();
     if ($Zip->open($path) === true) {
         $Theme = ThemeExtension::getInstance();
         $search = $Theme->getFileName();
         $index = $Zip->locateName($search, $Zip::FL_NODIR);
         if ($index !== false) {
             $file = $Zip->getNameIndex($index);
             $this->_rootPath[$path] = str_replace($search, '', $file);
             $xmlStr = $Zip->getFromIndex($index);
             $xmlElement = Xml::build($xmlStr);
             $attr = $Theme->setAttributes($xmlElement);
             if ($Theme->isValid($attr)) {
                 $this->_setXml($xmlElement)->_setAttributes($attr);
                 return true;
             }
         }
     }
     return false;
 }
Example #12
0
 /**
  * CurrencyLib::_loadXml()
  *
  * @param string $url
  * @return array
  */
 protected function _loadXml($url)
 {
     $CurrencyXml = Xml::build($url);
     return Xml::toArray($CurrencyXml);
 }
Example #13
0
 /**
  * Generates an XML element
  *
  * @param string $name The name of the XML element
  * @param array $attrib The attributes of the XML element
  * @param string|array|null $content XML element content
  * @param bool $endTag Whether the end tag of the element should be printed
  * @return string XML
  */
 public function elem($name, $attrib = [], $content = null, $endTag = true)
 {
     $namespace = null;
     if (isset($attrib['namespace'])) {
         $namespace = $attrib['namespace'];
         unset($attrib['namespace']);
     }
     $cdata = false;
     if (is_array($content) && isset($content['cdata'])) {
         $cdata = true;
         unset($content['cdata']);
     }
     if (is_array($content) && array_key_exists('value', $content)) {
         $content = $content['value'];
     }
     $children = [];
     if (is_array($content)) {
         $children = $content;
         $content = null;
     }
     $xml = '<' . $name;
     if (!empty($namespace)) {
         $xml .= ' xmlns';
         if (is_array($namespace)) {
             $xml .= ':' . $namespace['prefix'];
             $namespace = $namespace['url'];
         }
         $xml .= '="' . $namespace . '"';
     }
     $bareName = $name;
     if (strpos($name, ':') !== false) {
         list($prefix, $bareName) = explode(':', $name, 2);
         switch ($prefix) {
             case 'atom':
                 $xml .= ' xmlns:atom="http://www.w3.org/2005/Atom"';
                 break;
         }
     }
     if ($cdata && !empty($content)) {
         $content = '<![CDATA[' . $content . ']]>';
     }
     $xml .= '>' . $content . '</' . $name . '>';
     $elem = Xml::build($xml, ['return' => 'domdocument']);
     $nodes = $elem->getElementsByTagName($bareName);
     if ($attrib) {
         foreach ($attrib as $key => $value) {
             $nodes->item(0)->setAttribute($key, $value);
         }
     }
     foreach ($children as $child) {
         $child = $elem->createElement($name, $child);
         $nodes->item(0)->appendChild($child);
     }
     $xml = $elem->saveXml();
     $xml = trim(substr($xml, strpos($xml, '?>') + 2));
     return $xml;
 }
Example #14
0
 public function result()
 {
     $results = Xml::toArray(Xml::build('test.xml'));
     $this->set('results', $results);
 }
 /**
  * Helper method to parse xml input data, due to lack of anonymous functions
  * this lives here.
  *
  * @param string $xml XML string.
  * @return array Xml array data
  */
 public function convertXml($xml)
 {
     try {
         $xml = Xml::build($xml);
         if (isset($xml->data)) {
             return Xml::toArray($xml->data);
         }
         return Xml::toArray($xml);
     } catch (XmlException $e) {
         return [];
     }
 }
Example #16
0
 /**
  * Serialize view vars.
  *
  * ### Special parameters
  * `_xmlOptions` You can set an array of custom options for Xml::fromArray() this way, e.g.
  *   'format' as 'attributes' instead of 'tags'.
  *
  * @param array|string $serialize The name(s) of the view variable(s) that need(s) to be serialized
  * @return string The serialized data
  */
 protected function _serialize($serialize)
 {
     $rootNode = isset($this->viewVars['_rootNode']) ? $this->viewVars['_rootNode'] : 'response';
     if ($serialize === true) {
         $serialize = array_diff(array_keys($this->viewVars), $this->_specialVars);
         if (empty($serialize)) {
             $serialize = null;
         } elseif (count($serialize) === 1) {
             $serialize = current($serialize);
         }
     }
     if (is_array($serialize)) {
         $data = [$rootNode => []];
         foreach ($serialize as $alias => $key) {
             if (is_numeric($alias)) {
                 $alias = $key;
             }
             if (array_key_exists($key, $this->viewVars)) {
                 $data[$rootNode][$alias] = $this->viewVars[$key];
             }
         }
     } else {
         $data = isset($this->viewVars[$serialize]) ? $this->viewVars[$serialize] : null;
         if (is_array($data) && Hash::numeric(array_keys($data))) {
             $data = [$rootNode => [$serialize => $data]];
         }
     }
     $options = [];
     if (isset($this->viewVars['_xmlOptions'])) {
         $options = $this->viewVars['_xmlOptions'];
     }
     if (Configure::read('debug')) {
         $options['pretty'] = true;
     }
     if (isset($options['return']) && strtolower($options['return']) === 'domdocument') {
         return Xml::fromArray($data, $options)->saveXML();
     }
     return Xml::fromArray($data, $options)->asXML();
 }
Example #17
0
 /**
  * Serialize view vars.
  *
  * @param string|array $serialize The viewVars that need to be serialized.
  * @return string The serialized data
  * @throws RuntimeException When the prefix is not specified
  */
 protected function _serialize($serialize)
 {
     $rootNode = isset($this->viewVars['_rootNode']) ? $this->viewVars['_rootNode'] : 'channel';
     if (is_array($serialize)) {
         $data = [$rootNode => []];
         foreach ($serialize as $alias => $key) {
             if (is_numeric($alias)) {
                 $alias = $key;
             }
             $data[$rootNode][$alias] = $this->viewVars[$key];
         }
     } else {
         $data = isset($this->viewVars[$serialize]) ? $this->viewVars[$serialize] : null;
         if (is_array($data) && Hash::numeric(array_keys($data))) {
             $data = [$rootNode => [$serialize => $data]];
         }
     }
     $defaults = ['document' => [], 'channel' => [], 'items' => []];
     $data += $defaults;
     if (!empty($data['document']['namespace'])) {
         foreach ($data['document']['namespace'] as $prefix => $url) {
             $this->setNamespace($prefix, $url);
         }
     }
     $channel = $this->channel($data['channel']);
     if (!empty($channel['image']) && empty($channel['image']['title'])) {
         $channel['image']['title'] = $channel['title'];
     }
     foreach ($data['items'] as $item) {
         $channel['item'][] = $this->_prepareOutput($item);
     }
     $array = ['rss' => ['@version' => $this->version, 'channel' => $channel]];
     $namespaces = [];
     foreach ($this->_usedNamespaces as $usedNamespacePrefix) {
         if (!isset($this->_namespaces[$usedNamespacePrefix])) {
             throw new \RuntimeException(sprintf('The prefix %s is not specified.', $usedNamespacePrefix));
         }
         $namespaces['xmlns:' . $usedNamespacePrefix] = $this->_namespaces[$usedNamespacePrefix];
     }
     $array['rss'] += $namespaces;
     $options = [];
     if (Configure::read('debug')) {
         $options['pretty'] = true;
     }
     $output = Xml::fromArray($array, $options)->asXML();
     $output = $this->_replaceCdata($output);
     return $output;
 }
Example #18
0
    /**
     * Test that entity loading is disabled by default.
     *
     * @return void
     */
    public function testNoEntityLoading()
    {
        $file = str_replace(' ', '%20', CAKE . 'VERSION.txt');
        $xml = <<<XML
<!DOCTYPE cakephp [
  <!ENTITY payload SYSTEM "file://{$file}" >]>
<request>
  <xxe>&payload;</xxe>
</request>
XML;
        $result = Xml::build($xml);
    }
 /**
  * Render sitemap
  * @return string as xml
  */
 public function render()
 {
     // respond as xml
     $this->RequestHandler->respondAs('xml');
     // start xml
     $xml = Xml::build(sprintf($this->_root, $this->_path('Unimatrix/Utility.xsl/sitemap.xsl')));
     // get urls from router
     $this->_router();
     // append urls
     $this->_append($xml, Xml::fromArray(['urlset' => ['url' => $this->_url]]));
     // return xml
     return $xml->asXML();
 }
    /**
     * generate xml data method
     *
     * @return void
     */
    public function xmldatafile()
    {
        $this->autoRender = FALSE;
        $vender_id = 3;
        $conn = ConnectionManager::get('default');
        $query = $conn->query('SELECT `secondaries`.* ,(CASE WHEN `item_discounts`.`discount` IS NULL THEN `brand_discounts`.`discount` ELSE `item_discounts`.`discount` END) as `final_discount` FROM `secondaries` 
LEFT JOIN brand_discounts ON (`brand_discounts`.`brand_code` = `secondaries`.`brand_code` AND `brand_discounts`.`vendor_id` = ' . $vender_id . ' and `brand_discounts`.`status` =1 AND (NOW() BETWEEN `brand_discounts`.`start_date` AND `brand_discounts`.`end_date`)) 
LEFT JOIN item_discounts ON ( `item_discounts`.`sku` = `secondaries`.`sku` AND `item_discounts`.`vendor_id` = ' . $vender_id . ' AND (NOW() BETWEEN `item_discounts`.`start_date` AND `item_discounts`.`end_date`)) 
INNER JOIN brands on (`brands`.`brand_code` = `secondaries`.`brand_code` AND `brands`.`status` =1) 
INNER JOIN stores on (`stores`.`store_code` = `secondaries`.`store_code` AND `stores`.`status` =1) WHERE `secondaries`.`stock` > `secondaries`.`layaway`');
        $items = array();
        foreach ($query as $key => $item) {
            if ($key > 10) {
                continue;
            }
            $items[] = ['brand_code' => $item['brand_code'], 'item_code' => $item['item_code'], 'model_code' => $item['model_code'], 'store_code' => $item['store_code'], 'category_code' => $item['category_code'], 'sku' => $item['sku'], 'urn' => $item['urn'], 'price' => $item['price']];
        }
        //pr($items);
        $xmlArray = ['root' => ['xmlns:' => 'http://cakephp.org', 'child' => $items]];
        //$xmlObject = Xml::fromArray($xmlArray);
        //$xmlString = $xmlObject->asXML();
        $xml = Xml::build($xmlArray, ['return' => 'domdocument']);
        echo 'Wrote: ' . $xml->save(WWW_ROOT . 'uploads' . DS . "test.xml") . ' bytes';
        $this->set('_serialize', ['masters']);
    }
Example #21
0
 /**
  * Find and create valid modules.
  *
  * @return void
  */
 public function create()
 {
     $folder = new Folder($this->_path);
     list($folders, $files) = $folder->read();
     foreach ($folders as $dir) {
         $dir = trim($dir);
         $data = $this->_getData($folder, $dir);
         if ($data['class'] !== null && $data['config'] !== null) {
             $xml = Xml::build($data['config']);
             $attr = $this->setAttributes($xml);
             if ($this->isValid($attr)) {
                 $name = $attr->get('name');
                 if (!isset(self::$__loaded[$name])) {
                     $alias = Inflector::underscore($name);
                     $class = $this->getClassName($name);
                     /** @noinspection PhpIncludeInspection */
                     require_once $data['class'];
                     if (class_exists($class)) {
                         $module = new $class($name);
                         if (!$module instanceof ModuleAbstract) {
                             throw new \InvalidArgumentException(__d('union_dev', 'The class "%s" in file "%s" must extend \\Union\\Modules\\Module\\ModuleAbstract', $class));
                         }
                         $module->setAttr($attr);
                         self::$__loaded[$name] = $module;
                         self::$__modMap[$alias] = $name;
                     }
                 }
             }
         }
     }
 }
 public function sources()
 {
     $this->viewBuilder()->layout('ajax');
     $xml = Xml::toArray(Xml::build(__DIR__ . '/../Resources/feeds.xml'));
     $this->set('data', $xml);
 }
Example #23
0
 /**
  * Load xml file.
  *
  * @param $file
  * @return bool
  */
 public function loadFile($file)
 {
     if (!is_file($file)) {
         return false;
     }
     $xml = Xml::build($file);
     $this->_setXmlPath($file);
     return $this->load($xml);
 }
Example #24
0
    /**
     * Test that entity loading is disabled by default.
     *
     * @return void
     */
    public function testNoEntityLoading()
    {
        $file = str_replace(' ', '%20', CAKE . 'VERSION.txt');
        $xml = <<<XML
<!DOCTYPE cakephp [
  <!ENTITY payload SYSTEM "file://{$file}" >]>
<request>
  <xxe>&payload;</xxe>
</request>
XML;
        try {
            $result = Xml::build($xml);
            $this->assertEquals('', (string) $result->xxe);
        } catch (Exception $e) {
            $this->assertTrue(true, 'A warning was raised meaning external entities were not loaded');
        }
    }
Example #25
0
 /**
  * Serialize view vars.
  *
  * @param array|string $serialize The name(s) of the view variable(s) that need(s) to be serialized
  * @return string The serialized data
  */
 protected function _serialize($serialize)
 {
     $rootNode = isset($this->viewVars['_rootNode']) ? $this->viewVars['_rootNode'] : 'response';
     if (is_array($serialize)) {
         $data = [$rootNode => []];
         foreach ($serialize as $alias => $key) {
             if (is_numeric($alias)) {
                 $alias = $key;
             }
             $data[$rootNode][$alias] = $this->viewVars[$key];
         }
     } else {
         $data = isset($this->viewVars[$serialize]) ? $this->viewVars[$serialize] : null;
         if (is_array($data) && Hash::numeric(array_keys($data))) {
             $data = [$rootNode => [$serialize => $data]];
         }
     }
     $options = [];
     if (Configure::read('debug')) {
         $options['pretty'] = true;
     }
     return Xml::fromArray($data, $options)->asXML();
 }