Esempio n. 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());
 }
Esempio n. 2
0
 /**
  * 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];
 }
Esempio n. 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 : []);
 }
Esempio n. 4
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);
 }
Esempio n. 5
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])]);
 }
 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');
 }
 /**
  * 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']);
 }
Esempio n. 8
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;
 }
Esempio n. 9
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>');
     }
 }
Esempio n. 10
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 [];
     }
 }
Esempio n. 12
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();
 }
Esempio n. 14
0
 public function sources()
 {
     $this->viewBuilder()->layout('ajax');
     $xml = Xml::toArray(Xml::build(__DIR__ . '/../Resources/feeds.xml'));
     $this->set('data', $xml);
 }
Esempio n. 15
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');
        }
    }
Esempio n. 16
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);
 }
    /**
     * 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']);
    }
Esempio n. 18
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;
 }
Esempio n. 19
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;
                     }
                 }
             }
         }
     }
 }
Esempio n. 20
0
 /**
  * CurrencyLib::_loadXml()
  *
  * @param string $url
  * @return array
  */
 protected function _loadXml($url)
 {
     $CurrencyXml = Xml::build($url);
     return Xml::toArray($CurrencyXml);
 }