sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function count($key, $value, $sampleRate = 1) { $this->updateStats($key, (int)$value, $sampleRate, 'c'); }
Sends a count to StatsD @param string $key @param int $value @param int $sampleRate (optional) the default is 1
entailment
public function updateStats($key, $delta = 1, $sampleRate = 1, $metric = 'c') { if (!is_array($key)) { $key = array($key); } $data = array(); foreach ($key as $stat) { $data[$stat] = "$delta|$metric"; } $this->send($data, $sampleRate); }
Updates one or more stats. @param string|array $key The metric(s) to update. Should be either a string or array of metrics. @param int $delta The amount to increment/decrement each metric by. @param float|int $sampleRate the rate (0-1) for sampling. @param string $metric The metric type ("c" for count, "ms" for timing, "g" for gauge, "s" for set) @return boolean
entailment
public function send(array $data, $sampleRate = 1) { if (!$this->enable) { return; } // sampling $sampledData = array(); if ($sampleRate < 1) { foreach ($data as $stat => $value) { if ((mt_rand() / mt_getrandmax()) <= $sampleRate) { $sampledData[$stat] = "$value|@$sampleRate"; } } } else { $sampledData = $data; } if (empty($sampledData)) { return; } $fp = fsockopen('udp://' . $this->host, $this->port, $errno, $errstr); if (!$fp) { return; } foreach ($sampledData as $stat => $value) { fwrite($fp, $stat . ':' . $value); } fclose($fp); }
Squirt the metrics over UDP @param array $data @param int|float $sampleRate
entailment
protected function doCreateObject(array $array) { $orderItem = new OrderItem(isset($array['attributes']) && is_array($array['attributes']) ? $array['attributes'] : $array); if (isset($array['relationships']['products'])) { $mapper = new ProductsMapper(); foreach ($array['relationships']['products'] as $item) { $product = array_merge($item['attributes'], $item['relationships']); $orderItem->product = $mapper->createObject($product); } } // old structure if (isset($array['products'][0])) { if (isset($array['images'])) { $array['products'][0]['images'] = $array['images']; } $productMapper = new ProductsMapper(); $orderItem->product = $productMapper->createObject($array['products'][0]); } return $orderItem; }
@param array $array @return OrderItem
entailment
protected function doValidate($input) { if (false === ($len = $this->getLength($input))) { $this->addError('notDetected'); return false; } if (!is_null($this->length)) { if ($this->length != $len) { $this->addError(is_scalar($input) ? 'length' : 'lengthItem'); return false; } } elseif ($this->min > $len || $this->max < $len) { $this->addError(is_scalar($input) ? 'notIn' : 'notInItem'); return false; } return true; }
{@inheritdoc}
entailment
public function getLength($input) { if (is_scalar($input)) { if ($this->countByChars) { return mb_strlen($input, $this->charset); } else { return strlen($input); } } elseif (is_array($input) || $input instanceof \Countable) { return count($input); } else { return false; } }
Return the input's length or false when could not detected @param string|array|\Countable $input @return int|false
entailment
protected function doValidate($input) { if ( in_array($input, $this->invalid, true) || ($this->isString($input) && '' === trim($input)) ) { return true; } else { $this->addError('blank'); return false; } }
{@inheritdoc}
entailment
public function setFilters($filters = []) { foreach ($filters as $field => $rules) { if ($field === 'fullSearch') { $this->addFilter($field, $rules, null); continue; } if (is_a($rules, MultiFullTextFilter::class)) { $this->addFilter($field, $rules, null); continue; } foreach ($rules as $operator => $value) { if (!in_array($operator, $this->availableFilters) || (empty($value) && $value != '0')) { continue; } $this->addFilter($field, $value, $operator); } } return $this; }
@param array $filters @return $this
entailment
public function addFilter($field, $value, $operator) { if ((is_numeric($field) || !empty($field)) && (!empty($value) || $value == '0')) { if (!is_null($operator)) { $this->filters[$field][$operator] = $value; } else { $this->filters[$field] = $value; } } return $this; }
Adds a filter to the resource request @param string $operator the filter operator (eq,ne etc) @param string $field the field to filter on @param string $value the value of the attribute to operate on @return $this
entailment
public function removeFilter($field, $operator) { if (isset($this->filters[$field][$operator])) { unset($this->filters[$field][$operator]); } return $this; }
Removes a filter operation by attribute name and operator @param string $operator the filter operator (eq,ne etc) @param string $field the field to remove filter @return $this
entailment
private function compound($field, $rules) { $out = []; if (is_array($rules)) { foreach ($rules as $operator => $value) { $out[] = json_encode([$field => [$operator => $value]]); } return $out; } elseif (is_a($rules, MultiFullTextFilter::class)) { $out[] = (string)$rules; return $out; } $out[] = json_encode([$field => $rules]); return $out; }
Removes a filter operation by attribute name and operator @param string $field the field @param array $rules the rules for this operator @return array
entailment
public function trigger($name, $args = array(), $halt = false) { $this->curName = $name; $this->loadEvent && call_user_func($this->loadEvent, $name); if (!is_array($args)) { $args = array($args); } $results = array(); if (isset($this->handlers[$name])) { krsort($this->handlers[$name]); foreach ($this->handlers[$name] as $handlers) { foreach ($handlers as $handler) { $results[] = $result = call_user_func_array($handler, $args); if ($result !== null && $halt) { return $result; } if (false === $result) { break 2; } } } } return $halt ? null : $results; }
Trigger an event @param string $name The name of event @param array $args The arguments pass to the handle @param bool $halt @return array|mixed
entailment
public function on($name, $fn = null, $priority = 0) { // ( $names ) if (is_array($name)) { foreach ($name as $item => $fn) { $this->on($item, $fn); } return $this; } // ( $name, $fn, $priority, $data ) if (!is_callable($fn)) { throw new \InvalidArgumentException(sprintf( 'Expected argument of name callable, "%s" given', is_object($fn) ? get_class($fn) : gettype($fn) )); } if (!isset($this->handlers[$name])) { $this->handlers[$name] = array(); } $this->handlers[$name][$priority][] = $fn; return $this; }
Attach a handler to an event @param string|array $name The name of event, or an array that the key is event name and the value is event hanlder @param callback $fn The event handler @param int $priority The event priority @throws \InvalidArgumentException when the second argument is not callable @return $this
entailment
public function off($name) { if (isset($this->handlers[$name])) { unset($this->handlers[$name]); } return $this; }
Remove event handlers by specified name @param string $name The name of event @return $this
entailment
public function loadConfiguration(): void { $builder = $this->getContainerBuilder(); $config = $this->validateConfig($this->defaults); Validators::assertField($config, 'enabled', 'bool'); Validators::assertField($config, 'users', 'array'); // Skip if its disabled if ($config['enabled'] !== true) return; // Throws if there's no user if ($config['users'] === []) throw new LogicException('You have to define any user or disable extension'); $def = $builder->addDefinition($this->prefix('authenticator')) ->setType(BasicAuthenticator::class) ->setArguments([$config['title']]); foreach ($config['users'] as $user => $values) { if (is_string($values)) { trigger_error('Usage of `$username => $password` is deprecated, use `$username => ["password" => $password]` instead', E_USER_DEPRECATED); $password = $values; $unsecured = true; } else { $password = $values['password']; $unsecured = $values['unsecured'] ?? false; } $def->addSetup('addUser', [$user, $password, $unsecured]); } }
Register services
entailment
public function afterCompile(ClassType $class): void { $config = $this->validateConfig($this->defaults); // Skip if its disabled or no user defined if ($config['enabled'] !== true || $config['users'] === []) return; $initialize = $class->methods['initialize']; $initialize->addBody('$this->getService(?)->authenticate($this->getByType(?), $this->getByType(?));', [ $this->prefix('authenticator'), IRequest::class, IResponse::class, ]); }
Decorate initialize
entailment
protected function doValidate($input) { if (is_float($input) || (is_numeric($input) && count(explode('.', $input)) == 2)) { return true; } $this->addError('invalid'); return false; }
{@inheritdoc}
entailment
public function log($level, $message, $context = array()) { $level = isset($this->levels[$level]) ? $level : $this->level; // Check if the level would be handled if (isset($this->levels[$level])) { if ($this->levels[$level] < $this->levels[$this->handledLevel]) { return false; } } return $this->writeLog($level, $message, $context); }
Logs with an arbitrary level @param mixed $level @param string $message @param mixed $context @return bool Whether the log record has been handled
entailment
protected function writeLog($level, $message, $context) { if (!$this->handle) { $this->handle = fopen($this->getFile(), 'a'); } $content = $this->formatLog($level, $message, $context); return (bool)fwrite($this->handle, $content); }
Write the log message @param string $level @param string $message @param mixed $context @return bool
entailment
protected function formatLog($level, $message, $context = array()) { // Format message and content $params = $this->formatParams($message, $context); $message = $params['message']; $context = $params['context']; // Format log content $content = str_replace(array( '%datetime%', '%namespace%', '%level%', '%message%', ), array( date($this->dateFormat, microtime(true)), $this->namespace, strtoupper($level), $message, ), $this->format); // Format extra context if ($this->context || $context) { $content .= print_r($this->context + $context, true) . "\n"; } return $content; }
Format the log content @param string $level @param string $message @param array $context @return string
entailment
protected function formatParams($message, $context) { if (!is_array($context)) { $context = array('context' => $context); } if ($message instanceof \Exception) { $context += array( 'code' => $message->getCode(), 'file' => $message->getFile(), 'line' => $message->getLine(), 'trace' => $message->getTraceAsString(), ); $message = $message->getMessage(); } elseif (is_array($message)) { $message = print_r($message, true); } else { $message = (string)$message; } return array('message' => $message, 'context' => $context); }
Convert message to string and content to array for writing @param string|\Exception $message @param string|array $context @return array
entailment
public function getFile() { if ($this->fileDetected) { return $this->file; } $this->handle = null; $file = &$this->file; if (!is_dir($this->dir) && !@mkdir($this->dir, 0755, true)) { $message = sprintf('Fail to create directory "%s"', $this->dir); ($e = error_get_last()) && $message .= ': ' . $e['message']; throw new \RuntimeException($message); } $file = realpath($this->dir) . '/' . date($this->fileFormat); if ($this->fileSize) { $firstFile = $file; $files = glob($file . '*', GLOB_NOSORT); if (1 < count($files)) { natsort($files); $file = array_pop($files); } if (is_file($file) && $this->fileSize < filesize($file)) { $ext = pathinfo($file, PATHINFO_EXTENSION); if (is_numeric($ext)) { $file = $firstFile . '.' . ($ext + 1); } else { $file = $firstFile . '.1'; } } } $this->fileDetected = true; return $file; }
Get log file @return string @throws \RuntimeException When unable to create logging directory
entailment
public function setContext($name, $value = null) { if (is_array($name)) { $this->context = $name + $this->context; } else { $this->context[$name] = $value; } return $this; }
Add one or multi item for log message @param array|string $name @param mixed $value @return $this
entailment
public function clean() { // Make sure the handle is close $this->close(); $dir = dirname($this->getFile()); if (is_dir($dir)) { $files = scandir($dir); foreach ($files as $file) { if ('.' != $file && '..' != $file) { $file = $dir . DIRECTORY_SEPARATOR . $file; if (is_file($file)) { unlink($file); } } } } return $this; }
Clear up all log file @return Logger
entailment
private function waitForStreamActivity($timeout) { $read = $this->readStreams; $write = $this->writeStreams; if ($this->streamSelect($read, $write, $timeout) === false) { return; } foreach ($read as $stream) { $key = (int) $stream; if (isset($this->readListeners[$key])) { $callable = $this->readListeners[$key]; $callable($stream, $this); } } foreach ($write as $stream) { $key = (int) $stream; if (isset($this->writeListeners[$key])) { $callable = $this->writeListeners[$key]; $callable($stream, $this); } } }
Wait/check for stream activity, or until the next timer is due. @param float $timeout
entailment
private function streamSelect(array &$read, array &$write, $timeout) { if ($read || $write) { $except = null; return @stream_select($read, $write, $except, $timeout === null ? null : 0, $timeout); } usleep($timeout); return 0; }
Emulate a stream_select() implementation that does not break when passed empty stream arrays. @param array &$read @param array &$write @param integer|null $timeout @return integer The total number of streams that are ready for read/write.
entailment
public function buildForm(FormBuilderInterface $builder, array $options) { parent::buildForm($builder, $options); foreach (['start', 'end', 'step'] as $o) { if (!is_numeric($options[$o])) { throw new LogicException('The option "'.$o.'" must be numeric.'); } } if (!is_bool($options['vertical'])) { throw new LogicException('The option "vertical" must be a boolean.'); } }
{@inheritdoc}
entailment
public function buildView(FormView $view, FormInterface $form, array $options) { foreach (['start', 'end', 'step'] as $o) { $view->vars[$o] = $options[$o]; } if ($options['vertical']) { $view->vars['vertical'] = 1; } }
{@inheritdoc}
entailment
public function set($key, $value = null, array $options = array()) { if (isset($options['expires']) && 0 > $options['expires'] && isset($this->data[$key])) { unset($this->data[$key]); } else { $this->data[$key] = $value; } $this->response->setCookie($key, $value, $options); return $this; }
Set response cookie @param string $key The name of cookie @param mixed $value The value of cookie @param array $options @return $this
entailment
public function remove($key) { unset($this->data[$key]); $this->response->removeCookie($key); return $this; }
Remove response cookie @param string $key the name of cookie @return $this
entailment
protected function doValidate($input) { if (!$this->isString($input)) { $this->addError('notString'); return false; } if (!preg_match($this->pattern, $input)) { $this->addError('pattern'); return false; } return true; }
{@inheritdoc}
entailment
public function get($key, $expire = null, $fn = null) { return $this->cache->get($this->getKey($key), $expire, $fn); }
{@inheritdoc}
entailment
public function set($key, $value, $expire = 0) { return $this->cache->set($this->getKey($key), $value, $expire); }
{@inheritdoc}
entailment
public function add($key, $value, $expire = 0) { return $this->cache->add($this->getKey($key), $value, $expire); }
{@inheritdoc}
entailment
public function replace($key, $value, $expire = 0) { return $this->cache->replace($this->getKey($key), $value, $expire); }
{@inheritdoc}
entailment
public function incr($key, $offset = 1) { return $this->cache->incr($this->getKey($key), $offset); }
{@inheritdoc}
entailment
public function clear() { $data = array(); foreach ($this->tags as $tag) { $data[$this->getTagKey($tag)] = $this->generateTagValue(); } $this->cache->setMulti($data); $this->reload(); return $this; }
{@inheritdoc}
entailment
protected function getTagValues() { // Step1 Get tags value from cache $keys = array_map(array($this, 'getTagKey'), $this->tags); $values = $this->cache->getMulti($keys); // Step2 Initialize new tags value $emptyKeys = array_diff($values, array_filter($values)); if ($emptyKeys) { $newValues = $this->setTagValues($emptyKeys); $values = array_merge($values, $newValues); } return $values; }
Returns tag values @return array
entailment
protected function setTagValues($keys) { $values = array(); foreach ($keys as $key => $value) { $values[$key] = $this->generateTagValue(); } $this->cache->setMulti($values); return $values; }
Initializes tag values by cache keys @param array $keys @return array
entailment
protected function doValidate($input) { if (!$this->isString($input)) { $this->addError('notString'); return false; } if (is_scalar($this->findMe)) { $pos = strlen($input) - strlen($this->findMe); $fn = $this->case ? 'strrpos' : 'strripos'; if ($pos !== $fn($input, (string)$this->findMe)) { $this->addError('notFound'); return false; } } elseif (is_array($this->findMe)) { $pattern = array(); foreach ($this->findMe as $value) { $pattern[] = preg_quote($value, '/') . '$'; } $pattern = '/' . implode('|', $pattern) . '/'; $this->case || $pattern .= 'i'; if (!preg_match($pattern, $input)) { $this->addError('notFound'); return false; } } return true; }
{@inheritdoc}
entailment
public function compile(&$view=NULL, $view_var='script_foot', $script_tags=TRUE) { $bs=$this->_bootstrap; if (isset($bs)&&isset($view)) { $bs->compileHtml($this, $view); } $sem=$this->_semantic; if (isset($sem)&&isset($view)) { $sem->compileHtml($this, $view); } return $this->js->_compile($view, $view_var, $script_tags); }
gather together all script needing to be output @param View $view @param $view_var @param $script_tags @return string
entailment
public function generate_json($result=NULL, $match_array_type=FALSE) { // JSON data can optionally be passed to this function // either as a database result object or an array, or a user supplied array if (!is_null($result)) { if (is_object($result)) { $json_result=$result->result_array(); } elseif (is_array($result)) { $json_result=$result; } else { return $this->_prep_args($result); } } else { return 'null'; } return $this->_create_json($json_result, $match_array_type); }
Can be passed a database result or associative array and returns a JSON formatted string @param mixed $result result set or array @param bool $match_array_type match array types (defaults to objects) @return string json formatted string
entailment
public function _is_associative_array($arr) { foreach ( array_keys($arr) as $key => $val ) { if ($key!==$val) { return TRUE; } } return FALSE; }
Checks for an associative array @param type @return type
entailment
public function _initialize() { if (!function_exists('imap_search')) { throw new \Exception( "imap is not installed, check http://php.net/manual/en/imap.setup.php for more information" ); } //pre-pending folder name to the path $this->config['attachments_dir'] = $this->config['attachments_dir'].'/mail_attachments'; //clearing attachments if ($this->config['auto_clear_attachments']) { $this->clearAttachments($this->config['attachments_dir']); } $this->driver = new SMTPDriver($this->config); $this->mail = null; }
{@inheritdoc}
entailment
public function seeLinkInEmail($link) { $this->assertTrue($this->contains($link, $this->driver->getLinksByEmail($this->getCurrentMail()))); }
@param string $link @throws ModuleException
entailment
public function dontSeeLinkInEmail($link) { $this->assertFalse($this->contains($link, $this->driver->getLinksByEmail($this->getCurrentMail()))); }
@param string $link @throws ModuleException
entailment
public function clickInEmail($url) { $urlFound = $this->searchForText($url, $this->driver->getLinksByEmail($this->getCurrentMail())); if (null === $urlFound) { throw new ModuleException($this, sprintf("can't find %s in the current email", $url)); } if ($this->hasModule('WebDriver')) { $this->getModule('WebDriver')->amOnUrl($urlFound); } elseif ($this->hasModule('PhpBrowser')) { $this->getModule('PhpBrowser')->amOnUrl($urlFound); } else { throw new ModuleException( $this, "In order to click on links, you need to enable either `WebDriver` or `PhpBrowser` module" ); } }
@param string $url @throws ModuleException
entailment
public function grabLinkFromEmail($url) { $urlFound = $this->searchForText($url, $this->driver->getLinksByEmail($this->getCurrentMail())); if (null === $urlFound) { throw new ModuleException($this, sprintf("can't find %s in the current email", $url)); } return $urlFound; }
@param string $url @return string @throws ModuleException
entailment
public function grabTextFromEmail($str, $length) { $stringFound = $this->searchForText($str, $this->driver->getStringsByEmail($this->getCurrentMail())); if (null === $stringFound) { throw new ModuleException($this, sprintf("can't find %s in the current email", $str)); } $text = substr( $stringFound , stripos($stringFound, $str) + strlen($str), $length); return $text; }
@param string $str @param int $length @return string @throws ModuleException
entailment
public function seeTextInEmail($str) { $this->assertTrue($this->contains($str, $this->driver->getStringsByEmail($this->getCurrentMail()))); }
@param string $str
entailment
public function openEmail($criteria, $first = true) { $this->mail = $this->driver->getEmailBy($criteria, $first); }
@param string $criteria @param bool $first @throws \Exception
entailment
public function countEmailsByCriteria($criteria, $count = false) { $mails = $this->driver->getEmailsBy($criteria, $count); return count($mails); }
@param $criteria @param bool $count @return int @ if $count = false and email is 0 throws \Exception @ if $count = true and email is 0 return 0
entailment
public function canSeeEmailAttachment($name) { $names = []; foreach ($this->getCurrentMail()->getAttachments() as $attachment) { $names[] = $attachment->name; } $this->assertTrue($this->contains($name, $names)); }
@param string $name @throws ModuleException
entailment
private function contains($str, array $arr) { foreach ($arr as $a) { if (stripos($a, $str) !== false) { return true; } } return false; }
@param string $str @param array $arr @return bool
entailment
private function searchForText($str, array $arr) { foreach ($arr as $a) { if (stripos($a, $str) !== false) { return $a; } } return null; }
@param string $str @param array $arr @return null
entailment
private function clearAttachments($dir) { if (!file_exists($dir)) { mkdir($dir, 0777, true); } $files = glob($dir.'/*'); foreach ($files as $file) { if (is_file($file)) { unlink($file); } } }
Clear all previous email attachments
entailment
public function prepareTable() { $driver = $this->db->getDriver(); $tableExistsSql = sprintf($this->checkTableSqls[$driver], $this->table); if ($this->checkTable && !$this->db->fetchColumn($tableExistsSql)) { $createTableSql = sprintf($this->createTableSqls[$driver], $this->table); $this->db->executeUpdate($createTableSql); } }
Check if table exists, if not exists, create table
entailment
public function get($key, $expire = null, $fn = null) { if ($this->exists($key)) { $result = $this->db->select($this->table, $this->namespace . $key); $result = unserialize($result['value']); } else { $result = false; } return $this->processGetResult($key, $result, $expire, $fn); }
{@inheritdoc}
entailment
public function set($key, $value, $expire = 0) { $data = array( 'value' => serialize($value), 'lastModified' => date('Y-m-d H:i:s'), 'expire' => date('Y-m-d H:i:s', $expire ? time() + $expire : 2147483647) ); $identifier = array( 'id' => $this->namespace . $key ); if ($this->exists($key)) { // In MySQL, the rowCount method return 0 when data is not modified, // so check errorCode to make sure it executed success $result = $this->db->update($this->table, $data, $identifier) || '0000' == $this->db->errorCode(); } else { $result = $this->db->insert($this->table, $data + $identifier); } return (bool)$result; }
{@inheritdoc}
entailment
public function remove($key) { return (bool)$this->db->delete($this->table, array('id' => $this->namespace . $key)); }
{@inheritdoc}
entailment
public function exists($key) { $result = $this->db->select($this->table, $this->namespace . $key); if (!$result) { return false; } if ($result['expire'] < date('Y-m-d H:i:s')) { $this->remove($key); return false; } return true; }
{@inheritdoc}
entailment
public function html($string) { if (!$string) { return $string; } $result = htmlspecialchars($string, $this->htmlSpecialCharsFlags, $this->encoding); return $result; }
Escape a string for the HTML Body context where there are very few characters of special meaning. Internally this will use htmlspecialchars(). @param string $string @return string
entailment
public function attr($string) { if (!$string) { return $string; } $string = $this->toUtf8($string); if ($string === '' || ctype_digit($string)) { return $string; } $result = preg_replace_callback('/[^a-z0-9,\.\-_]/iSu', $this->htmlAttrMatcher, $string); return $this->fromUtf8($result); }
Escape a string for the HTML Attribute context. We use an extended set of characters to escape that are not covered by htmlspecialchars() to cover cases where an attribute might be unquoted or quoted illegally (e.g. backticks are valid quotes for IE). @param string $string @return string
entailment
public function js($string) { if (!$string) { return $string; } $string = $this->toUtf8($string); if ($string === '' || ctype_digit($string)) { return $string; } $result = preg_replace_callback('/[^a-z0-9,\._]/iSu', $this->jsMatcher, $string); return $this->fromUtf8($result); }
Escape a string for the Javascript context. This does not use json_encode(). An extended set of characters are escaped beyond ECMAScript's rules for Javascript literal string escaping in order to prevent misinterpretation of Javascript as HTML leading to the injection of special characters and entities. The escaping used should be tolerant of cases where HTML escaping was not applied on top of Javascript escaping correctly. Backslash escaping is not used as it still leaves the escaped character as-is and so is not useful in a HTML context. @param string $string @return string
entailment
public function css($string) { if (!$string) { return $string; } $string = $this->toUtf8($string); if ($string === '' || ctype_digit($string)) { return $string; } $result = preg_replace_callback('/[^a-z0-9]/iSu', $this->cssMatcher, $string); return $this->fromUtf8($result); }
Escape a string for the CSS context. CSS escaping can be applied to any string being inserted into CSS and escapes everything except alphanumerics. @param string $string @return string
entailment
protected function htmlAttrMatcher($matches) { $chr = $matches[0]; $ord = ord($chr); /** * The following replaces characters undefined in HTML with the * hex entity for the Unicode replacement character. */ if (($ord <= 0x1f && $chr != "\t" && $chr != "\n" && $chr != "\r") || ($ord >= 0x7f && $ord <= 0x9f) ) { return '&#xFFFD;'; } /** * Check if the current character to escape has a name entity we should * replace it with while grabbing the integer value of the character. */ if (strlen($chr) > 1) { $chr = $this->convertEncoding($chr, 'UTF-16BE', 'UTF-8'); } $hex = bin2hex($chr); $ord = hexdec($hex); if (isset(static::$htmlNamedEntityMap[$ord])) { return '&' . static::$htmlNamedEntityMap[$ord] . ';'; } /** * Per OWASP recommendations, we'll use upper hex entities * for any other characters where a named entity does not exist. */ if ($ord > 255) { return sprintf('&#x%04X;', $ord); } return sprintf('&#x%02X;', $ord); }
Callback function for preg_replace_callback that applies HTML Attribute escaping to all matches. @param array $matches @return string
entailment
protected function jsMatcher($matches) { $chr = $matches[0]; if (strlen($chr) == 1) { return sprintf('\\x%02X', ord($chr)); } $chr = $this->convertEncoding($chr, 'UTF-16BE', 'UTF-8'); return sprintf('\\u%04s', strtoupper(bin2hex($chr))); }
Callback function for preg_replace_callback that applies Javascript escaping to all matches. @param array $matches @return string
entailment
protected function convertEncoding($string, $to, $from) { $result = ''; if (function_exists('iconv')) { $result = iconv($from, $to, $string); } elseif (function_exists('mb_convert_encoding')) { $result = mb_convert_encoding($string, $to, $from); } else { throw new \RuntimeException( get_class($this) . ' requires either the iconv or mbstring extension to be installed' . ' when escaping for non UTF-8 strings.' ); } if ($result === false) { return ''; // return non-fatal blank string on encoding errors from users } return $result; }
Encoding conversion helper which wraps iconv and mbstring where they exist or throws and exception where neither is available. @param string $string @param string $to @param array|string $from @throws \RuntimeException @return string
entailment
public function getData($key, $default = null) { $data = $this->cache->fetch($key); if ($data) { return $data; } return $default; }
{@inheritdoc}
entailment
public function makeSingle(Response $response) { if (!$response->getSuccess()) { return null; } $result = []; $data = $response->getData(); foreach ($data as $type => $items) { switch ($type) { case 'attributes': $result[$type] = (new FacetAttributesMapper())->createObject($items); break; case 'priceRange': $result[$type] = $items; break; case 'factorValues': $mapper = new FactorValuesMapper(); $result[$type] = $this->createList($mapper, $items); break; case 'functionalNames' : $mapper = new FunctionalNamesMapper(); $result[$type] = $this->createList($mapper, $items); break; case 'brands' : $mapper = new BrandsMapper(); $result[$type] = $this->createList($mapper, $items); break; case 'productGroups' : $mapper = new ProductGroupsMapper(); $result[$type] = $this->createList($mapper, $items); break; } } return $result; }
@param Response $response @return array
entailment
private function createList(Mapper $mapper, array $items) { $result = []; foreach ($items as $item) { $result[] = $mapper->createObject($item); } return $result; }
@param Mapper $mapper @param array $items @return array
entailment
public function setIcons($value) { if (is_string($value)) { if (Text::startsWith($value, "{")) ; $value="%".$value."%"; } return $this->setParam("icons", $value); }
Icons to display, with or without text (see text option). By default, the primary icon is displayed on the left of the label text and the secondary is displayed on the right. The positioning can be controlled via CSS. The value for the primary and secondary properties must match an icon class name, e.g., "ui-icon-gear". For using only one icon: icons: { primary: "ui-icon-locked" }. For using two icons: icons: { primary: "ui-icon-gear", secondary: "ui-icon-triangle-1-s" }. @param String $value default : { primary: null, secondary: null } @return $this
entailment
public function get($key, $expire = null, $fn = null) { $result = $this->front->get($key); if (false === $result) { $result = $this->back->get($key); if (false !== $result) { $this->front->set($key, $result, $expire); } } return $this->processGetResult($key, $result, $expire, $fn); }
{@inheritdoc}
entailment
public function set($key, $value, $expire = 0) { $this->front->set($key, $value, $expire); return $this->back->set($key, $value, $expire); }
First write data to front cache (eg local cache), then write to back cache (eg memcache) {@inheritdoc}
entailment
public function remove($key) { $result1 = $this->front->remove($key); $result2 = $this->back->remove($key); return $result1 && $result2; }
{@inheritdoc}
entailment
public function exists($key) { return $this->front->exists($key) || $this->back->exists($key); }
{@inheritdoc}
entailment
public function add($key, $value, $expire = 0) { $result = $this->back->add($key, $value, $expire); if ($result) { $this->front->set($key, $value, $expire); } return $result; }
{@inheritdoc}
entailment
public function incr($key, $offset = 1) { $result = $this->back->incr($key, $offset); if ($result) { $this->front->set($key, $result); } return $result; }
{@inheritdoc}
entailment
public function clear() { $result1 = $this->front->clear(); $result2 = $this->back->clear(); return $result1 && $result2; }
{@inheritdoc}
entailment
private function addGraphLink($sourceIndex, $value, array $meta) { $targetIndex = $this->getTargetIndex($value, $meta); $type = $this->getType($value); $this->graph['links'][] = ['source' => $sourceIndex, 'target' => $targetIndex, 'type' => $type]; return $targetIndex; }
@param int $sourceIndex @param mixed $value @param array $meta @return int
entailment
private function getTargetIndex($value, array $meta) { if (is_object($value)) { return $this->getObjectId($value, $meta); } $node = $this->nodeFactory->newInstance($value, $meta); $this->addNode($node); return $this->nodeIndex; }
@param mixed $value @param array $meta @return int
entailment
private function getObjectId($object, array $meta) { if ($this->objectIdStorage->contains($object)) { return (int) $this->objectIdStorage[$object]; } $node = $this->nodeFactory->newInstance($object, $meta); $index = $this->addNode($node); $this->objectIdStorage->attach($object, (string) $index); return $index; }
@param $object @return int
entailment
private function addNode(NodeInterface $node) { $this->nodeIndex++; $this->graph['nodes'][] = $node->toArray(); return $this->nodeIndex; }
@param NodeInterface $node @return int
entailment
public function fromArray($array) { if (is_array($array) && sizeof($array)>0) { foreach ( $array as $value ) { if (is_array($value)) { $this->addImage($value ["src"], @$value ["alt"], @$value ["caption"], @$value ["description"]); } else { $this->addImage($value); } } } return $this; }
/* (non-PHPdoc) @see \Ajax\bootstrap\html\base\BaseHtml::fromArray()
entailment
protected function doValidate($input) { if (false !== filter_var($input, FILTER_VALIDATE_INT) && $input > 0) { return true; } else { $this->addError('invalid'); return false; } }
{@inheritdoc}
entailment
protected function getResultFromResponse(Response $response) { $result = []; foreach ($response->getData() as $element) { $attributes = $this->getAttributes($element); $attributes['type'] = $element['type']; $result[] = $attributes; } return $result; }
@param Response $response @return array
entailment
public function render($name, $data = array()) { // Assign to double underscored variables to avoid conflict with view parameters $__file = $this->getFile($name); $__data = $data + $this->data; $__layout = $this->layout; // Render view extract($__data, EXTR_OVERWRITE); ob_start(); try { require $__file; } catch (\Exception $e) { ob_end_clean(); throw $e; } $content = ob_get_clean(); // If layout is configured, render layout if ($__layout != $this->layout) { $layout = $this->layout; $this->layout = array(); $__data[$layout['variable']] = $content; $content = $this->render($layout['name'], $__data); } return $content; }
Render a template @param string $name The name of template @param array $data The variables pass to template @return null|string @throws \Exception View file not found
entailment
public function assign($name, $value = null) { if (is_array($name)) { $this->data = $name + $this->data; } else { $this->data[$name] = $value; } return $this; }
Assign variables to template @param string|array $name The name of the variable or variables array @param mixed $value The value of the variable @return $this
entailment
public function getFile($name) { if ($file = $this->resolveFile($name)) { return $file; } else { $components = $this->parseResource($name); throw new \RuntimeException(sprintf('Template "%s" not found in directories "%s"', $components['file'], implode('", "', $components['dirs']))); } }
Get the template file by name @param string $name The name of template @return string The template file path @throws \RuntimeException When template file not found
entailment
public function resolveFile($name) { $components = $this->parseResource($name); foreach ($components['dirs'] as $dir) { if (is_file($file = $dir . ($dir ? '/' : '') . $components['file'])) { return $file; } } return false; }
Resolve the template file by name @param string $name The name of template @return string|false The template file path or false if file not found
entailment
public function layout($name = null, $variable = 'content') { $this->layout = array( 'name' => $name ?: $this->defaultLayout, 'variable' => $variable ); return $this; }
Set layout file for current view @param string $name The name of layout template @param string $variable The variable name of layout content @return $this
entailment
public function setOptions($options) { $this->renderer->getElement()->setOptions($options); $this->renderer->getHtmlElement()->setOptions($options); }
Set the choice’s options @param mixed $options array of options to add
entailment
public function addOption($option) { $this->renderer->getElement()->addOption($option); $this->renderer->getHtmlElement()->addOption($option); }
Adds an option to the current options @param mixed $option option to add
entailment
public function incr($key, $offset = 1) { return $this->object->inc($this->namespace . $key, $offset, true, 0, $offset); }
{@inheritdoc}
entailment
public function setMulti(array $items, $expire = 0) { $results = $this->object->setMulti($items, $expire); foreach ($results as &$result) { $result = (bool)$result; } return $results; }
{@inheritdoc}
entailment
public function tick() { $count = $this->queue->count(); while ($count-- && $this->loop->isRunning()) { $this->callback = $this->queue->dequeue(); $callback = $this->callback; // without this proxy PHPStorm marks line as fatal error. $callback($this->loop); } }
Flush the callback queue. Invokes as many callbacks as were on the queue when tick() was called.
entailment
public function buildView(FormView $view, FormInterface $form, array $options) { if ($form->count() === 0) { return; } array_map([$this, 'validateButton'], $form->all()); }
{@inheritdoc} @param FormView $view @param FormInterface $form @param array $options
entailment
protected function addButton($builder, $name, $config) { $options = isset($config['options']) ? $config['options'] : []; if (!in_array($config['type'], $this->allowedTypes)) { throw new \LogicException(sprintf( 'Allowed button types : "%s", given "%s".', implode('", "', $this->allowedTypes), $config['type'] )); } return $builder->add($name, $config['type'], $options); }
Adds a button. @param FormBuilderInterface $builder @param $name @param $config @throws \InvalidArgumentException @return ButtonBuilder
entailment
public function addLabel($label, $before=false, $icon=NULL) { $this->tagName="div"; $this->addToProperty("class", "labeled"); $this->content=new HtmlButton("button-" . $this->identifier, $this->content); $this->content->setTagName("div"); $label=new HtmlLabel("label-" . $this->identifier, $label, "a"); if(isset($icon)) $label->addIcon($icon); $label->setBasic(); $this->addContent($label, $before); return $label; }
Add and return a button label @param string $caption @param string $before @param string $icon @return \Ajax\semantic\html\elements\HtmlLabel
entailment
public function toArray(): array { $response = [ 'from' => $this->from, 'size' => $this->size, ]; if ($this->sort) { $response['sort'] = $this->sort; } return [ 'bucket_sort' => $response ]; }
Convert to array @return array
entailment