public static function body($alias, $vars = null) { if (!$vars) { $vars = []; } $content = self::get($alias, 'body'); return Text::insert($content, $vars); }
/** * Wrapper para Configure::load(). * Faz uma verificação para ver se o plugin está instalado. (@see PluginStarter::install()). * * @param string $pluginName O nome do plugin a ser carregado. * @return bool O retorno do chamado Configure::load(). */ public function load($pluginName) { $settingsFile = $this->pluginInstallationFolder . $pluginName . DS . 'settings.php'; if (!file_exists($settingsFile)) { $this->install($pluginName); } $configPath = Text::insert('Plugins/:plugin/settings', ['plugin' => $pluginName]); return Configure::load($configPath); }
/** * Register a new collection. * * @param string $id The collection identifier. * @param array $options The collection options. */ public static function register($id, $options) { $id = (string) $id; if (self::exists($id)) { user_error(Text::insert('A collection with id ":id" is already registered.', ['id' => $id])); return; } $defaults = ['model' => 'Plugin.Model', 'displayName' => 'Translated Name']; $options = array_merge($defaults, $options); self::_instance()->_items[$id] = $options; }
/** * 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(Text::insert(__d('debug_kit', 'Total Requests made: :requests'), compact('requests'))); $this->out(Text::insert(__d('debug_kit', 'Total Time elapsed: :duration (seconds)'), compact('duration'))); $this->out(""); $this->out(Text::insert(__d('debug_kit', 'Requests/Second: :rps req/sec'), ['rps' => round($requests / $duration, 3)])); $this->out(Text::insert(__d('debug_kit', 'Average request time: :average-time seconds'), ['average-time' => round($duration / $requests, 3)])); $this->out(Text::insert(__d('debug_kit', 'Standard deviation of average request time: :std-dev'), ['std-dev' => round($this->_deviation($times, true), 3)])); $this->out(Text::insert(__d('debug_kit', 'Longest/shortest request: :longest sec/:shortest sec'), ['longest' => round(max($times), 3), 'shortest' => round(min($times), 3)])); $this->out(""); }
/** * {@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 Text::insert($options['templates']['link'], compact('title', 'url')); }
/** * Turns a string (and optionally a dynamic, data-injected string) into a slugged value * @param $pattern string a simple string (e.g. 'slug me') or Text::insert-friendly string (e.g. ':id-:name') * @param $data mixed an Array or Entity of data to Text::insert inject into $pattern * @param $replacement string the character to replace non-slug-friendly characters with (default '-') * @return string the slugged string */ public static function generate($pattern, $data = [], $replacement = '-') { # if given an Entity object, covert it to a hydrated array $data = $data instanceof \Cake\ORM\Entity ? json_decode(json_encode($data->jsonSerialize()), true) : $data; # build the slug $value = Text::insert($pattern, $data); # inject data into pattern (if applicable) $value = Inflector::slug($value, $replacement); # slug it $value = strtolower($value); # convert to lowercase return $value; }
/** * @param string $url * @param mixed $data * @param string $requestType * @return mixed * @author Gustav Wellner Bou <*****@*****.**> */ protected function _post($url, $data, $requestType = 'POST') { $slug = Text::insert($url, $this->settings, ['before' => '{', 'after' => '}']); $slug = str_replace(static::BASE_URL, '', $slug); $slug = strtolower($requestType) . '_' . Inflector::slug($slug) . '_' . md5($data); $file = Plugin::path('Transifex') . 'tests/test_files/json/' . $slug . '.json'; if (!$this->settings['debug'] && file_exists($file)) { $content = file_get_contents($file); return json_decode($content, true); } $result = parent::_post($url, $data, $requestType); if ($this->settings['debug']) { $file = Plugin::path('Transifex') . 'tests/test_files/json/' . $slug . '.json'; file_put_contents($file, json_encode($result, JSON_OPTIONS)); } return $result; }
/** * Renders * * @param string|array $config Either the config file to load or the menu config as an array * @return string rendered HTML */ public function renderSidebarMenuItems($config) { $config = $this->prepareMenuConfig($config); $this->setPageTitle($config); $out = ''; foreach ($config as $mainItem => $mainData) { $childrenContainer = ''; if (!empty($mainData['children'])) { $children = ''; foreach ($mainData['children'] as $child) { $children .= Text::insert($this->_defaultConfig['templates']['item'], ['class' => $child['active'] ? 'active' : '', 'title' => $child['title'], 'icon' => isset($child['icon']) ? Text::insert($this->_defaultConfig['templates']['icon'], ['icon' => $child['icon']]) : '', 'href' => isset($child['url']) ? Router::url($child['url']) : '', 'childrenArrow' => '', 'childrenContainer' => '', 'liclass' => '']); } $childrenContainer = Text::insert($this->_defaultConfig['templates']['childrenContainer'], ['children' => $children]); } $out .= Text::insert($this->_defaultConfig['templates']['item'], ['class' => $mainData['active'] ? 'active' : '', 'liclass' => $mainData['active'] ? 'active' : '', 'title' => '<span class="mm-text">' . $mainData['title'] . '</span>', 'icon' => isset($mainData['icon']) ? Text::insert($this->_defaultConfig['templates']['icon'], ['icon' => $mainData['icon']]) : '', 'href' => isset($mainData['url']) ? Router::url($mainData['url']) : '', 'childrenArrow' => !empty($mainData['children']) ? $this->_defaultConfig['templates']['childrenArrow'] : '', 'childrenContainer' => $childrenContainer]); } return $out; }
/** * Sets a context given through a request to identify the creation * point of the revision. * * @param string $type Context type * @param object $dataObject Optional dataobject to get additional data from * @param string $slug Optional slug. Must implement getContexts() when using */ public function setHistoryContext($type, $dataObject = null, $slug = null) { if (!in_array($type, array_keys(ModelHistory::getContextTypes()))) { throw new InvalidArgumentException("{$type} is not allowed as context type. Allowed types are: " . implode(', ', ModelHistory::getContextTypes())); } switch ($type) { case ModelHistory::CONTEXT_TYPE_SHELL: if (!$dataObject instanceof Shell) { throw new InvalidArgumentException('You have to specify a Shell data object for this context type.'); } $context = ['OptionParser' => $dataObject->OptionParser, 'interactive' => $dataObject->interactive, 'params' => $dataObject->params, 'command' => $dataObject->command, 'args' => $dataObject->args, 'name' => $dataObject->name, 'plugin' => $dataObject->plugin, 'tasks' => $dataObject->tasks, 'taskNames' => $dataObject->taskNames]; $contextSlug = null; if ($slug !== null) { $contextSlug = $slug; } break; case ModelHistory::CONTEXT_TYPE_CONTROLLER: if (!$dataObject instanceof Request) { throw new InvalidArgumentException('You have to specify a Request data object for this context type.'); } $context = ['params' => $dataObject->params, 'method' => $dataObject->method()]; if ($slug !== null) { $contextSlug = $slug; } else { $contextSlug = Text::insert(':plugin/:controller/:action', ['plugin' => $context['params']['plugin'], 'controller' => $context['params']['controller'], 'action' => $context['params']['action']]); } break; case ModelHistory::CONTEXT_TYPE_SLUG: default: $context = []; if ($slug === null) { throw new InvalidArgumentException('You have to specify a slug for this context type.'); } $contextSlug = $slug; break; } $this->_context = Hash::merge(['type' => $type], $context); $this->_contextSlug = $contextSlug; $this->_contextType = $type; }
public function testReplaceWithQuestionMarkInString() { $string = ':a, :b and :c?'; $expected = '2 and 3?'; $result = Text::insert($string, ['b' => 2, 'c' => 3], ['clean' => true]); $this->assertEquals($expected, $result); }
/** * @param float $value (0...X) * @param array $options * - stars (defaults to 5) * - steps per image (defaults to 4 => 1/4 accuracy) * - ... * @param array $attributes for div container (id, style, ...) * @return string $divContainer with rating images */ public function image($value, array $options = array(), array $attr = array()) { $defaults = ['data-symbol' => '', 'escape' => false, 'data-rating-class' => 'rating-fa', 'stars' => 5, 'steps' => 4]; $options += $defaults; if ($value <= 0) { $roundedValue = 0; } else { $roundedValue = round($value * $options['steps']) / $options['steps']; } $percent = $this->percentage($roundedValue, $options['stars']); $precision = 2; if ((int) $roundedValue == $roundedValue) { $precision = 0; } elseif ((int) (2 * $roundedValue) == 2 * $roundedValue) { $precision = 1; } $title = __d('ratings', '{0} of {1} stars', number_format(min($roundedValue, $options['stars']), $precision, ',', '.'), $options['stars']); $attrContent = ['class' => 'rating-stars', 'data-content' => str_repeat($options['data-symbol'], $options['stars']), 'escape' => $options['escape'], 'style' => 'width: ' . $percent . '%']; $content = $this->Html->div(null, '', $attrContent); //<div class="rating-container rating-fa" data-content="" title="x of y stars"> // <div class="rating-stars" data-content="" style="width: 20%;"></div> //</div> $attr += ['title' => $title]; $attr = ['data-content' => str_repeat($options['data-symbol'], $options['stars']), 'escape' => $options['escape']] + $attr; return $this->Html->div('rating-container ' . $options['data-rating-class'], $content, $attr); $size = !empty($options['size']) ? $options['size'] : ''; if (!empty($size)) { $options['pixels'] = $this->sizes[$size]; } $pixels = !empty($options['pixels']) ? $options['pixels'] : 16; $steps = !empty($options['steps']) ? $options['steps'] : 4; if ($value <= 0) { $roundedValue = 0; } else { $roundedValue = round($value * $steps) / $steps; } $stars = !empty($options['stars']) ? $options['stars'] : 5; $array = array(0 => '<div class="ui-stars-star' . ($size ? '-' . $size : '') . ' ui-stars-star' . ($size ? '-' . $size : '') . '-on" style="cursor: default; width: {width}px;"><a style="margin-left: {margin}px;">#</a></div>', 1 => '<div class="ui-stars-star' . ($size ? '-' . $size : '') . ' ui-stars-star' . ($size ? '-' . $size : '') . '-disabled" style="cursor: default; width: {width}px;"><a style="margin-left: {margin}px;">#</a></div>'); $res = ''; $disable = 0; for ($i = 0; $i < $stars; $i++) { for ($j = 0; $j < $steps; $j++) { if (!$disable && $i + $j * (1 / $steps) >= $roundedValue) { $disable = 1; } $v = $array[$disable]; if ($j === 0) { # try to use a single image if possible if ($i < floor($roundedValue) || $i >= ceil($roundedValue) || $i === 0 && $roundedValue >= 1) { $res .= Text::insert($v, array('margin' => 0, 'width' => $pixels), array('before' => '{', 'after' => '}')); break; } } $margin = 0 - $pixels / $steps * $j; $res .= Text::insert($v, array('margin' => $margin, 'width' => $pixels / $steps), array('before' => '{', 'after' => '}')); } } $precision = 2; if ((int) $roundedValue == $roundedValue) { $precision = 0; } elseif ((int) (2 * $roundedValue) == 2 * $roundedValue) { $precision = 1; } $defaults = array('title' => number_format(min($roundedValue, $stars), $precision, ',', '.') . ' ' . __('von') . ' ' . $stars . ' ' . __('Sternen')); $attr = array_merge($defaults, $attr); return $this->Html->div('ratingStars clearfix', $res, $attr); }
/** * Build url * * @return string url (full) */ protected function _url() { $params = ['host' => $this->options['host']]; $url = Text::insert(static::BASE_URL, $params, ['before' => '{', 'after' => '}', 'clean' => true]); return $url; }
/** * Expand all scalar values from a CrudSubject * and use them for a Text::insert() interpolation * of a path * * @param \Crud\Event\Subject $subject Subject * @param string $path Path * @return string */ protected function _expandPath(Subject $subject, $path) { $keys = []; $subjectArray = (array) $subject; foreach (array_keys($subjectArray) as $key) { if (!is_scalar($subjectArray[$key])) { continue; } $keys[$key] = $subjectArray[$key]; } return Text::insert($path, $keys, ['before' => '{', 'after' => '}']); }
/** * Render a field by replacing the placeholders * * @param string $field field name * @param Notification $notification notification containing the view vars * @return string */ public function render($field, Notification $notification) { return Text::insert($this->get($field), $notification->config, ['before' => '{{', 'after' => '}}']); }
/** * Checks if a set of conditions match a nested resource * * @param array $conditions The conditions in a query * * @return bool|string Either a URL or false in case no nested resource matched */ public function nestedResource(array $conditions) { foreach ($this->_nestedResources as $url => $options) { if (count(array_intersect_key(array_flip($options['requiredFields']), $conditions)) !== count($options['requiredFields'])) { continue; } return Text::insert($url, $conditions); } return false; }
public function getRoutes() { $blogs = $this->find('all')->select(['id', 'slug'])->contain(['Categories' => function ($q) { return $q->select(['id', 'slug']); }])->toArray(); $routes = []; foreach ($blogs as $blog) { $id = $blog->id; $replacements = ['category_slug' => $blog->category->slug, 'blog_slug' => $blog->slug]; $slug = Text::insert(Setting::read('CMS.BlogsUrl'), $replacements); $routes[$id] = $slug; } return $routes; }
/** * _getBody * * Getter for the body. * Data is used from the vars-column. * The template is used from the configurations. * * @return string */ protected function _getBody() { $templates = Configure::read('Notifier.templates'); if (array_key_exists($this->_properties['template'], $templates)) { $template = $templates[$this->_properties['template']]; $vars = json_decode($this->_properties['vars'], true); return Text::insert($template['body'], $vars); } return ''; }
/** * @param string $url * @param mixed $data * @param string $requestType * @throws \RuntimeException * @return mixed * @author Gustav Wellner Bou <*****@*****.**> */ protected function _post($url, $data, $requestType = 'POST') { $error = false; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, Text::insert($url, $this->settings, ['before' => '{', 'after' => '}'])); curl_setopt($ch, CURLOPT_USERPWD, $this->settings['user'] . ':' . $this->settings['password']); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $requestType); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); if ($this->settings['debug']) { curl_setopt($ch, CURLOPT_VERBOSE, true); } $result = curl_exec($ch); $info = curl_getinfo($ch); if (($errMsg = curl_error($ch)) || !in_array((int) $info['http_code'], [200, 201])) { $error = true; } curl_close($ch); if ($error) { throw new RuntimeException('Unable to send data to API (' . $errMsg . ')'); } return json_decode($result, true); }
/** * Get the address in text format * @param string $separator used for fields * @return string */ public function _getAddressText($separator = "\n") { return Text::insert($this->_addressFormat, $this->address_full); }
/** * return the config for a given message type * * @param string $type Message type. * @param array $replacements Replacements * @return array * @throws \Exception for a missing or undefined message type */ public function message($type, array $replacements = []) { if (empty($type)) { throw new \Exception('Missing message type'); } $crud = $this->_crud(); $config = $this->config('messages.' . $type); if (empty($config)) { $config = $crud->config('messages.' . $type); if (empty($config)) { throw new \Exception(sprintf('Invalid message type "%s"', $type)); } } if (is_string($config)) { $config = ['text' => $config]; } $config = Hash::merge(['element' => 'default', 'params' => ['class' => 'message'], 'key' => 'flash', 'type' => $this->config('action') . '.' . $type, 'name' => $this->resourceName()], $config); if (!isset($config['text'])) { throw new \Exception(sprintf('Invalid message config for "%s" no text key found', $type)); } $config['params']['original'] = ucfirst(str_replace('{name}', $config['name'], $config['text'])); $domain = $this->config('messages.domain'); if (!$domain) { $domain = $crud->config('messages.domain') ?: 'crud'; } $config['text'] = __d($domain, $config['params']['original']); $config['text'] = Text::insert($config['text'], $replacements + ['name' => $config['name']], ['before' => '{', 'after' => '}']); $config['params']['class'] .= ' ' . $type; return $config; }
/** * Takes a processed array of data from an error and displays it in the chosen format. * * @param string $data Data to output. * @return void */ public function outputError($data) { $defaults = ['level' => 0, 'error' => 0, 'code' => 0, 'description' => '', 'file' => '', 'line' => 0, 'context' => [], 'start' => 2]; $data += $defaults; $files = $this->trace(['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(['start' => $data['start'], 'depth' => '20']); $insertOpts = ['before' => '{:', 'after' => '}']; $context = []; $links = []; $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 = $this->_templates[$this->_outputFormat] + $this->_templates['base']; if (isset($tpl['links'])) { foreach ($tpl['links'] as $key => $val) { $links[$key] = Text::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 .= Text::insert($tpl[$key], [$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 Text::insert($tpl['error'], compact('links', 'info') + $data, $insertOpts); }
/** * Load entries and filter them if necessary. * * @param string $model Model name * @param string $foreignKey Model's foreign key * @param int $limit Entries limit * @param int $page Current page to view * @param bool $showFilterBox Show Filter Box * @param bool $showCommentBox Show comment Box * @return string Index View */ public function filter($model = null, $foreignKey = null, $limit = null, $page = null, $showFilterBox = null, $showCommentBox = null) { $this->request->allowMethod(['post']); $filterConditions = []; if (isset($this->request->data['filter'])) { foreach ($this->request->data['filter'] as $filterName => $filterValue) { if (empty($filterValue)) { continue; } switch ($filterName) { case 'fields': $filterConditions = Hash::merge(['`data` LIKE' => Text::insert('%:fieldName%', ['fieldName' => $filterValue])], $filterConditions); break; } } } // Prepare conditions $searchConditions = []; if (isset($this->request->data['search'])) { foreach ($this->request->data['search'] as $searchName => $searchValue) { if (empty($searchValue)) { continue; } switch ($searchName) { case 'date': if (!empty($searchValue['from']['year']) && !empty($searchValue['from']['month']) && !empty($searchValue['from']['day'])) { $fromDate = Time::now()->year($searchValue['from']['year'])->month($searchValue['from']['month'])->day($searchValue['from']['day'])->hour(0)->minute(0)->second(0); $searchConditions = Hash::merge(['ModelHistory.created >=' => $fromDate], $searchConditions); } if (!empty($searchValue['to']['year']) && !empty($searchValue['to']['month']) && !empty($searchValue['to']['day'])) { $toDate = Time::now()->year($searchValue['to']['year'])->month($searchValue['to']['month'])->day($searchValue['to']['day'])->hour(23)->minute(59)->second(59); $searchConditions = Hash::merge(['ModelHistory.created <=' => $toDate], $searchConditions); } break; case 'context_type': $searchConditions = Hash::merge(['context_type' => $searchValue], $searchConditions); break; case 'context_slug': $searchConditions = Hash::merge(['context_slug' => $searchValue], $searchConditions); break; } } } $conditions = Hash::merge($filterConditions, $searchConditions); $modelHistory = $this->ModelHistory->getModelHistory($model, $foreignKey, $limit, $page, $conditions); $entries = TableRegistry::get('ModelHistory.ModelHistory')->getModelHistoryCount($model, $foreignKey, $conditions); $showNextEntriesButton = $entries > 0 && $limit * $page < $entries; $showPrevEntriesButton = $page > 1; $this->FrontendBridge->setBoth('showPrevEntriesButton', $showPrevEntriesButton); $this->FrontendBridge->setBoth('showNextEntriesButton', $showNextEntriesButton); $this->FrontendBridge->setBoth('showFilterBox', $showFilterBox); $this->FrontendBridge->setBoth('showCommentBox', $showCommentBox); $this->FrontendBridge->setBoth('modelHistory', $modelHistory); $this->FrontendBridge->setBoth('limit', $limit); $this->FrontendBridge->setBoth('model', $model); $this->FrontendBridge->setBoth('page', $page); $this->FrontendBridge->setBoth('foreignKey', $foreignKey); $this->FrontendBridge->setBoth('searchableFields', TableRegistry::get($model)->getTranslatedFields()); $this->FrontendBridge->set('filter', isset($this->request->data['filter']) ? $this->request->data['filter'] : []); $entity = $this->ModelHistory->getEntityWithHistory($model, $foreignKey); $contexts = []; if (method_exists($entity, 'getContexts')) { $contexts = $entity::getContexts(); } $this->FrontendBridge->setBoth('contexts', $contexts); return $this->render('index'); }
public function buildUrl($item, $request) { $url = $item['url']; $params = Hash::flatten($request); $result = []; if (is_array($url)) { foreach ($url as $key => $value) { if (is_string($value)) { if (!is_int($key)) { $result[$key] = Text::insert($value, $params); } else { $result[] = Text::insert($value, $params); } } else { $result[$key] = $value; } } } else { $result = Text::insert($url, $params); } return Router::url($result); }
/** * Shorten the given $url, handle response errors and return a BitlyResponseData object. * * @param string $url * @return BitlyResponseData|null */ public function shorten($url) { $longUrl = urlencode($url); $apiRequest = Text::insert(':shortenEndpoint?login=:login&apiKey=:apiKey&longUrl=:longUrl', ['shortenEndpoint' => self::ENDPOINT . self::SHORTEN, 'login' => $this->_login, 'apiKey' => $this->_apiKey, 'longUrl' => $longUrl]); /** @var null|BitlyResponse $response */ $response = $this->http->get($apiRequest)->body('json_decode'); $this->_handleBitlyResponse($response, $longUrl); return $response->data; }