/** * Helper function used to replace query placeholders by the real * params used to execute the query * * @param LoggedQuery $query * @return string */ protected function _interpolate($query) { $params = array_map(function ($p) { if ($p === null) { return 'NULL'; } return is_string($p) ? "'{$p}'" : $p; }, $query->params); return String::insert($query->query, $params); }
/** * {@inheritdoc} */ public function link($title, $url = null, array $options = array()) { $url = Router::url($url, ['full' => true]); if ('html' == $this->getType()) { return parent::link($title, $url, $this->_mergeAttributes($options, $this->config('attributes.link'))); } if (empty($url)) { return $title; } $options += ['templates' => []]; $options['templates'] += ['link' => ':title: :url']; return String::insert($options['templates']['link'], compact('title', 'url')); }
/** * Prints calculated results * * @param array $times Array of time values * @return void */ protected function _results($times) { $duration = array_sum($times); $requests = count($times); $this->out(String::insert(__d('debug_kit', 'Total Requests made: :requests'), compact('requests'))); $this->out(String::insert(__d('debug_kit', 'Total Time elapsed: :duration (seconds)'), compact('duration'))); $this->out(""); $this->out(String::insert(__d('debug_kit', 'Requests/Second: :rps req/sec'), array('rps' => round($requests / $duration, 3)))); $this->out(String::insert(__d('debug_kit', 'Average request time: :average-time seconds'), array('average-time' => round($duration / $requests, 3)))); $this->out(String::insert(__d('debug_kit', 'Standard deviation of average request time: :std-dev'), array('std-dev' => round($this->_deviation($times, true), 3)))); $this->out(String::insert(__d('debug_kit', 'Longest/shortest request: :longest sec/:shortest sec'), array('longest' => round(max($times), 3), 'shortest' => round(min($times), 3)))); $this->out(""); }
/** * Takes a processed array of data from an error and displays it in the chosen format. * * @param string $data * @return void */ public function outputError($data) { $defaults = array('level' => 0, 'error' => 0, 'code' => 0, 'description' => '', 'file' => '', 'line' => 0, 'context' => array(), 'start' => 2); $data += $defaults; $files = $this->trace(array('start' => $data['start'], 'format' => 'points')); $code = ''; $file = null; if (isset($files[0]['file'])) { $file = $files[0]; } elseif (isset($files[1]['file'])) { $file = $files[1]; } if ($file) { $code = $this->excerpt($file['file'], $file['line'] - 1, 1); } $trace = $this->trace(array('start' => $data['start'], 'depth' => '20')); $insertOpts = array('before' => '{:', 'after' => '}'); $context = array(); $links = array(); $info = ''; foreach ((array) $data['context'] as $var => $value) { $context[] = "\${$var} = " . $this->exportVar($value, 3); } switch ($this->_outputFormat) { case false: $this->_data[] = compact('context', 'trace') + $data; return; case 'log': $this->log(compact('context', 'trace') + $data); return; } $data['trace'] = $trace; $data['id'] = 'cakeErr' . uniqid(); $tpl = array_merge($this->_templates['base'], $this->_templates[$this->_outputFormat]); if (isset($tpl['links'])) { foreach ($tpl['links'] as $key => $val) { $links[$key] = String::insert($val, $data, $insertOpts); } } if (!empty($tpl['escapeContext'])) { $context = h($context); } $infoData = compact('code', 'context', 'trace'); foreach ($infoData as $key => $value) { if (empty($value) || !isset($tpl[$key])) { continue; } if (is_array($value)) { $value = implode("\n", $value); } $info .= String::insert($tpl[$key], array($key => $value) + $data, $insertOpts); } $links = implode(' ', $links); if (isset($tpl['callback']) && is_callable($tpl['callback'])) { return call_user_func($tpl['callback'], $data, compact('links', 'info')); } echo String::insert($tpl['error'], compact('links', 'info') + $data, $insertOpts); }
public function testReplaceWithQuestionMarkInString() { $string = ':a, :b and :c?'; $expected = '2 and 3?'; $result = String::insert($string, array('b' => 2, 'c' => 3), array('clean' => true)); $this->assertEquals($expected, $result); }
/** * Função auxiliar para montar a estrutura HTML do flexslider. * @param array $slides Um array com as informações de cada slide. * Formato: * $slides = array( * 0 => array( * 'img_src' => '/my/img/source/file.jpg' * 'img_title' => 'The Image Title', * 'img_description' => 'This is the description of the awesome image', * 'img_options' => array(the_options), * 'img_link' => 'http://www.thecoolwebsite.com/', * 'link_options' => array(the_options), * 'li_options' => array(the_options), * ), * .... * ); * 'img_src': É o caminho da imagem a partir de webroot/img. * 'img_options': Opções para a imagem (html tag <img>). Mesmo formato para a função HtmlHelper::image(). * 'img_title': O título da imagem. * 'img_description': A descrição da imagem. * 'img_link': A url para onde o link irá apontar. * 'link_options': Opções para o link (html tag <a>). Mesmo formato para a função HtmlHelper::link(). * 'li_options': Opções para a tag li. Quando for necessário uma configuração diferente para um slide (li) específico, use esta opção. Esta opção sobrescreve a opção global para tag li. array de opções como em HtmlHelper::tag(). * * @param array $options Um array com opções de configuração. * Formato: * $options = array( * 'div' => array(the_options), * 'ul' => array(the_options), * 'li' => array(the_options), * 'slide_template' => ':link_image<p class='my_class'>:description</p>', * 'webroot' => 'site', * ); * 'div': array de opções como em HtmlHelper::tag(). * 'ul': array de opções como em HtmlHelper::tag(). * 'li': array de opções como em HtmlHelper::tag(). * 'webroot': string, 'app' ou 'site', para escolher de qual webroot será lido a imagem. Se é do app ou se é do plugin Site. * 'slide_template': a formatação do li, caso precise alterá-lo. Padrão ':image'. Não informar <li></li>. * Em slide_template há "variáveis" que podem ser usadas, sendo elas: * :link_image Um exemplo de saída seria <a href="/to/my/page"><img src="/myimg.jpg"></a> * :image <img src="/myimg.jpg"> * :description Uma string para ser usada como descrição. * :title Uma string para ser usada como título. * @throws InvalidArgumentException Caso $slides[x]['img_src'] esteja vazio, ele lança uma exception. * @return string Toda a estrutura do flexslider em HTML com cada slide de acordo com os valores informados por parâmetro. */ public function flexslider($slides, $options = array()) { // validações iniciais if (!isset($options['slide_template'])) { $options['slide_template'] = ':image'; } if (!isset($options['li'])) { $options['li'] = array(); } if (!isset($options['webroot'])) { $options['webroot'] = 'site'; } switch ($options['webroot']) { case 'app': $webDir = ''; break; case 'site': default: $webDir = 'Site.'; } $options['div'] = $this->checkFlexSliderDivOptions($options); $options['ul'] = $this->checkFlexSliderUlOptions($options); // gera o <li> primeiro $liHtml = ''; foreach ($slides as $slide) { // verifica se existe opções para a tag <img>, senão existe, cria um array vazio para não dar problema. if (!isset($slide['img_options'])) { $slide['img_options'] = array(); } // verifica se existe opções para a tag <a>, senão existe, cria um array com a opção escape => false. Se existe ele faz um merge com a opção escape => false. if (!isset($slide['link_options'])) { $slide['link_options'] = array('escape' => false); } else { $slide['link_options'] = Hash::merge($slide['link_options'], array('escape' => false)); } // verifica se existe descrição, senão existe, cria uma string vazia. if (!isset($slide['img_description'])) { $slide['img_description'] = ''; } // verifica se existe titulo, senão existe, cria uma string vazia. if (!isset($slide['img_title'])) { $slide['img_title'] = ''; } // verifica se existe opção específica para o slide(li). Se existe, junta essas opções com as opções globais e guarda para ser usado ao criar o elemento li. Senão, guarda as opções globais para serem usadas. if (isset($slide['li_options'])) { $liOptions = array_merge($options['li'], $slide['li_options']); } else { $liOptions = $options['li']; } $image = $this->Html->image($webDir . $slide['img_src'], $slide['img_options']); if (isset($slide['image_link'])) { $image_link = $this->Html->link($image, $slide['image_link'], $slide['link_options']); } else { $image_link = ''; } $liContent = String::insert($options['slide_template'], array('image' => $image, 'image_link' => $image_link, 'description' => $slide['img_description'], 'title' => $slide['img_title'])); $liHtml .= $this->Html->tag('li', $liContent, $liOptions); } // depois gera o <ul> e coloca os <li> dentro do <ul> $ulHtml = $this->Html->tag('ul', $liHtml, $options['ul']); // depois gera a <div> final e coloca o <ul> dentro dela. $generatedHtml = $this->Html->tag('div', $ulHtml, $options['div']); // finished! return $generatedHtml; }
/** * Create a new Nginx website by generating a virtual host file, creating a * symoblic link and reloading the webserver. * * @param string $url Fully Qualified Domain Name used to expose the site. * @param string $webroot Full path to the site's webroot directory. * @param array $options Hash with options * @return boolean True on success */ public function addVhost($url, $webroot, array $options = null) { $this->_flushLogs(); $this->_logStart("Creating virtual host for {$url}"); // Prevent overwriting default Cakebox site if ($url == 'default') { $this->_error("Using 'default' as <url> is prohibited as this would overwrite the default Cakebox site"); return false; } // Check for existing site file $vhostFile = $this->Info->webserverMeta['nginx']['sites-available'] . DS . $url; if (file_exists($vhostFile)) { if (!$options['force']) { $this->_error("* Virtual host file {$vhostFile} already exists. Use --force to drop."); return false; } $this->_log("* Overwriting existing file"); } // Load template into string, replace placeholders if ($options['hhvm']) { $template = APP . 'Template' . DS . 'Bake' . DS . 'vhost_hhvm.ctp'; } else { $template = APP . 'Template' . DS . 'Bake' . DS . 'vhost_nginx.ctp'; } $config = String::insert(file_get_contents($template), ['url' => $url, 'webroot' => $webroot]); // Write generated vhost configuration to file if (!$this->_writeSystemFile($vhostFile, $config)) { $this->_error("Error writing virtual hosts file {$vhostFile}"); return false; } $this->_log("* Successfully created {$vhostFile}"); // Create symbolic link in sites-enabled if (!$this->enableVhost($url)) { $this->_error("Error creating symbolic link"); return false; } // Reload nginx service to effectuate changes if (!$this->reloadNginx()) { return false; } // Reload hhvm service if needed if (!$this->reloadHhvm()) { return false; } return true; }