sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected function arrayToHtml($content, $html = '') { // scalar types can be return directly if (is_scalar($content)) { return $content; } $html = "<ul>\n"; // field name foreach ($content as $field => $value) { $html .= "<li><strong>" . $field . ":</strong> "; if (is_array($value)) { // recurse $html .= $this->arrayToHtml($value); } else { // value, with hyperlinked hyperlinks if (is_bool($value)) { $value = $value ? 'true' : 'false'; } $value = htmlentities($value, ENT_COMPAT, 'UTF-8'); if ((strpos($value, 'http://') === 0) || (strpos($value, 'https://') === 0)) { $html .= "<a href=\"" . $value . "\">" . $value . "</a>"; } else { $html .= $value; } } $html .= "</li>\n"; } $html .= "</ul>\n"; return $html; }
Recursively render an array to an HTML list @param mixed $content data to be rendered @return null
entailment
protected function determineMediaType($acceptHeader) { if (!empty($acceptHeader)) { $negotiator = new Negotiator(); $mediaType = $negotiator->getBest($acceptHeader, $this->knownMediaTypes); if ($mediaType) { return $mediaType->getValue(); } } return $this->getDefaultMediaType(); }
Read the accept header and determine which media type we know about is wanted. @param string $acceptHeader Accept header from request @return string
entailment
public function determinePeferredFormat($acceptHeader, $allowedFormats = ['json', 'xml', 'html'], $default = 'json') { if (empty($acceptHeader)) { return $default; } $negotiator = new Negotiator(); try { $elements = $negotiator->getOrderedElements($acceptHeader); } catch (InvalidMediaType $e) { return $default; } foreach ($elements as $element) { $subpart = $element->getSubPart(); foreach ($allowedFormats as $format) { if (stripos($subpart, $format) !== false) { return $format; } } } return $default; }
Read the accept header and work out which format is preferred @param string $acceptHeader Accept header from request @param array $allowedFormats Array of formats that are preferred @param string $default Default format to return if no allowedFormats are found @return string
entailment
protected function renderXml($data) { $xml = $this->arrayToXml($data); $dom = new \DOMDocument('1.0'); $dom->preserveWhiteSpace = false; $dom->formatOutput = $this->pretty; $dom->loadXML($xml->asXML()); return $dom->saveXML(); }
Render Array as XML @return string
entailment
protected function arrayToXml($data, $xmlElement = null) { if ($xmlElement === null) { $rootElementName = $this->getXmlRootElementName(); $xmlElement = new \SimpleXMLElement("<?xml version=\"1.0\"?><$rootElementName></$rootElementName>"); } foreach ($data as $key => $value) { if (is_array($value)) { if (!is_numeric($key)) { $subnode = $xmlElement->addChild("$key"); if (count($value) > 1 && is_array($value)) { $jump = false; $count = 1; foreach ($value as $k => $v) { if (is_array($v)) { if ($count++ > 1) { $subnode = $xmlElement->addChild("$key"); } $this->arrayToXml($v, $subnode); $jump = true; } } if ($jump) { goto LE; } $this->arrayToXml($value, $subnode); } else { $this->arrayToXml($value, $subnode); } } else { $this->arrayToXml($value, $xmlElement); } } else { if (is_bool($value)) { $value = (int)$value; } if (is_numeric($key)) { $key = "_$key"; } $xmlElement->addChild("$key", "$value"); } LE: ; } return $xmlElement; }
Simple Array to XML conversion Based on http://www.codeproject.com/Questions/553031/JSONplusTOplusXMLplusconvertionpluswithplusphp @param array $data Data to convert @param SimpleXMLElement $xmlElement XMLElement @return SimpleXMLElement
entailment
public function assign($name, $value = null) { $this->object->assign($name, $value); return $this; }
{@inheritdoc}
entailment
public function display($name, $vars = array()) { $vars && $this->object->assign($vars); return $this->object->display($name); }
{@inheritdoc}
entailment
public function render($name, $vars = array()) { $vars && $this->object->assign($vars); return $this->object->fetch($name); }
{@inheritdoc}
entailment
public function setObject(\Smarty $object = null) { $this->object = $object ? $object : new \Smarty(); return $this; }
Set Smarty object @param \Smarty $object @return Smarty
entailment
public function setOptions(array $options) { foreach ($options as $key => $value) { $this->options[$key] = $value; $value && $this->object->$key = $value; } return $this; }
Set property value for Smarty @param array $options @return Smarty
entailment
protected function doValidate($input) { switch ( true ) { case is_string($input) : $file = $originFile = $input; break; // File array from $_FILES case is_array($input) : if (!isset($input['tmp_name']) || !isset($input['name'])) { $this->addError('notFound'); return false; } $file = $input['tmp_name']; $originFile = $input['name']; break; case $input instanceof \SplFileInfo: $file = $originFile = $input->getPathname(); break; default: $this->addError('notString'); return false; } $this->originFile = $originFile; $this->file = $file = stream_resolve_include_path($file); if (!$file || !is_file($file)) { $this->addError('notFound'); return false; } // Validate file extension if ($this->exts || $this->excludeExts) { $ext = $this->getExt(); } if ($this->excludeExts && in_array($ext, $this->excludeExts)) { $this->addError('excludeExts'); } if ($this->exts && !in_array($ext, $this->exts)) { $this->addError('exts'); } // Validate file size if ($this->maxSize || $this->minSize) { $this->size = filesize($file); $this->sizeString = $this->fromBytes($this->size); } if ($this->maxSize && $this->maxSize <= $this->size) { $this->addError('maxSize'); } if ($this->minSize && $this->minSize > $this->size) { $this->addError('minSize'); } // Validate file mime type if ($this->mimeTypes || $this->excludeMimeTypes) { $mimeType = $this->getMimeType(); if (!$mimeType) { $this->addError('mimeTypeNotDetected'); return false; } } if ($this->mimeTypes && !$this->inMimeType($mimeType, $this->mimeTypes)) { $this->addError('mimeTypes'); } if ($this->excludeMimeTypes && $this->inMimeType($mimeType, $this->excludeMimeTypes)) { $this->addError('excludeMimeTypes'); } return !$this->errors; }
{@inheritdoc}
entailment
public function inMimeType($findMe, $mimeTypes) { foreach ($mimeTypes as $mimeType) { if ($mimeType == $findMe) { return true; } $type = strstr($mimeType, '/*', true); if ($type && $type === strstr($findMe, '/', true)) { return true; } } return false; }
Checks if a mime type exists in a mime type array @param string $findMe The mime type to be searched @param array $mimeTypes The mime type array, allow element likes "image/*" to match all image mime type, such as "image/gif", "image/jpeg", etc @return boolean
entailment
protected function setMaxSize($maxSize) { $this->maxSize = $this->toBytes($maxSize); $this->maxSizeString = $this->fromBytes($this->maxSize); return $this; }
Set maximum file size @param string|int $maxSize @return File
entailment
protected function setMinSize($minSize) { $this->minSize = $this->toBytes($minSize); $this->minSizeString = $this->fromBytes($this->minSize); return $this; }
Set the minimum file size @param string|int $minSize @return File
entailment
public function toBytes($size) { if (is_numeric($size)) { return (int) $size; } $unit = strtoupper(substr($size, -2)); $value = substr($size, 0, -1); if (!is_numeric($value)) { $value = substr($value, 0, -1); } $exponent = array_search($unit, $this->units); return (int)($value * pow(1024, $exponent)); }
Converts human readable file size (e.g. 1.2MB, 10KB) into bytes @param string|int $size @return int
entailment
public function fromBytes($bytes) { for ($i=0; $bytes >= 1024 && $i < 8; $i++) { $bytes /= 1024; } return round($bytes, 2) . $this->units[$i]; }
Formats bytes to human readable file size (e.g. 1.2MB, 10KB) @param int $bytes @return string
entailment
public function getMimeType() { if (!$this->mimeType) { $finfo = finfo_open(FILEINFO_MIME_TYPE, $this->magicFile); if (!$finfo) { throw new \UnexpectedValueException('Failed to open fileinfo database'); } $this->mimeType = finfo_file($finfo, $this->file); } return $this->mimeType; }
Returns the file mime type on success @return string|false @throws \UnexpectedValueException When failed to open fileinfo database
entailment
public function getExt() { if (is_null($this->ext) && $this->originFile) { $file = basename($this->originFile); // Use substr instead of pathinfo, because pathinfo may return error value in unicode if (false !== $pos = strrpos($file, '.')) { $this->ext = strtolower(substr($file, $pos + 1)); } else { $this->ext = ''; } } return $this->ext; }
Returns the file extension, if file is not exists, return null instead @return string
entailment
public function init() { // define the path that your publishable resources live $this->sourcePath = '@rias/passwordpolicy/assetbundles/PasswordPolicy/dist'; // define the dependencies $this->depends = [ CpAsset::class, ]; // define the relative path to CSS/JS files that should be registered with the page // when this asset bundle is registered $this->js = [ 'js/zxcvbn.min.js', 'js/PasswordPolicy.js', ]; Craft::$app->view->registerJsVar('passwordpolicy', [ 'showStrengthIndicator' => PasswordPolicy::$plugin->settings->showStrengthIndicator, ]); $this->css = [ 'css/PasswordPolicy.css', ]; parent::init(); }
Initializes the bundle.
entailment
protected function doCreateObject(array $array) { $consumerFactor = new ConsumerFactorHistory($array); $consumerFactor->context = json_decode($consumerFactor->context); $consumerFactor->factors = json_decode($consumerFactor->factors); return $consumerFactor; }
@param array $array @return ConsumerFactorHistory
entailment
protected function doValidate($input) { // Adds "atLeast" error at first, make sure this error at the top of // stack, if any rule is passed, the error will be removed $this->addError('atLeast'); $passed = 0; $validator = null; $props = array('name' => $this->name); foreach ($this->rules as $rule => $options) { if ($this->validate->validateOne($rule, $input, $options, $validator, $props)) { $passed++; if ($passed >= $this->atLeast) { // Removes all error messages $this->errors = array(); return true; } } else { $this->validators[$rule] = $validator; } } $this->count = count($this->rules) - $passed; $this->left = $this->atLeast - $passed; return false; }
{@inheritdoc}
entailment
public function getMessages($name = null) { /** * Combines messages into single one * * FROM * array( * 'atLeast' => 'atLeast message', * 'validator.rule' => 'first message', * 'validator.rul2' => 'second message', * 'validator2.rule' => 'third message' * ) * TO * array( * 'atLeast' => "atLeast message\n" * . "first message;second message\n" * . "third message" * ) */ if ($this->combineMessages) { $messages = parent::getMessages(); $key = key($messages); foreach ($this->validators as $rule => $validator) { $messages[$rule] = implode(';', $validator->getMessages($name)); } return array( $key => implode("\n", $messages) ); } else { $messages = array(); foreach ($this->validators as $rule => $validator) { foreach ($validator->getMessages($name) as $option => $message) { $messages[$rule . '.' . $option] = $message; } } return $messages; } }
{@inheritdoc}
entailment
public function get($key, $expire = null, $fn = null) { if (!is_file($file = $this->getFile($key))) { $result = false; } else { $content = $this->getContent($file);; if ($content && is_array($content) && time() < $content[0]) { $result = $content[1]; } else { $this->remove($key); $result = false; } } return $this->processGetResult($key, $result, $expire, $fn); }
{@inheritdoc}
entailment
public function set($key, $value, $expire = 0) { $file = $this->getFile($key); $content = $this->prepareContent($value, $expire); return (bool) file_put_contents($file, $content, LOCK_EX); }
{@inheritdoc}
entailment
public function remove($key) { if (is_file($file = $this->getFile($key))) { return unlink($file); } else { return false; } }
{@inheritdoc}
entailment
public function exists($key) { if (!is_file($file = $this->getFile($key))) { return false; } $content = $this->getContent($file); if ($content && is_array($content) && time() < $content[0]) { return true; } else { $this->remove($key); return false; } }
{@inheritdoc}
entailment
public function add($key, $value, $expire = 0) { $file = $this->getFile($key); if (!is_file($file)) { // Open and try to lock file immediately if (!$handle = $this->openAndLock($file, 'wb', LOCK_EX | LOCK_NB)) { return false; } $rewrite = false; } else { // Open file for reading and rewriting if (!$handle = $this->openAndLock($file, 'r+b', LOCK_EX)) { return false; } // The cache is not expired if ($this->readAndVerify($handle, $file)) { fclose($handle); return false; } $rewrite = true; } $content = $this->prepareContent($value, $expire); return $this->writeAndRelease($handle, $content, $rewrite); }
{@inheritdoc}
entailment
public function incr($key, $offset = 1) { $file = $this->getFile($key); if (!is_file($file)) { return $this->set($key, $offset) ? $offset : false; } // Open file for reading and rewriting if (!$handle = $this->openAndLock($file, 'r+b', LOCK_EX)) { return false; } // Prepare file content if (!$content = $this->readAndVerify($handle, $file)) { $content = $this->prepareContent($offset, 0); $result = $offset; } else { $result = $content[1] += $offset; $content = $this->prepareContent($content[1], $content[0]); } // Rewrite content return $this->writeAndRelease($handle, $content, true) ? $result : false; }
{@inheritdoc}
entailment
public function clear() { $result = true; foreach (glob($this->dir . '/' . '*.' . $this->ext) as $file) { $result = $result && @unlink($file); } return $result; }
{@inheritdoc}
entailment
public function getFile($key) { $key = str_replace($this->illegalChars, '_', $this->namespace . $key); return $this->dir . '/' . $key . '.' . $this->ext; }
Get cache file by key @param string $key @return string
entailment
public function setDir($dir) { if (!is_dir($dir) && !@mkdir($dir, 0755, true)) { $message = sprintf('Failed to create directory "%s"', $dir); ($e = error_get_last()) && $message .= ': ' . $e['message']; throw new \RuntimeException($message); } $this->dir = realpath($dir); return $this; }
Set the cache directory @param string $dir @return $this @throws \RuntimeException When failed to create the cache directory
entailment
protected function openAndLock($file, $mode, $operation) { if (!$handle = fopen($file, $mode)) { return false; } if (!flock($handle, $operation)) { fclose($handle); return false; } return $handle; }
Open and lock file @param string $file file path @param string $mode open mode @param int $operation lock operation @return resource|false file handle or false
entailment
protected function readAndVerify($handle, $file) { // Read all content $content = fread($handle, filesize($file)); $content = @unserialize($content); // Check if content is valid if ($content && is_array($content) && time() < $content[0]) { return $content; } else { return false; } }
Read file by handle and verify if content is expired @param resource $handle file handle @param string $file file path @return false|array false or file content array
entailment
protected function writeAndRelease($handle, $content, $rewrite = false) { $rewrite && rewind($handle) && ftruncate($handle, 0); $result = fwrite($handle, $content); flock($handle, LOCK_UN); fclose($handle); return (bool) $result; }
Write content, release lock and close file @param resource $handle file handle @param string $content the value of cache @param bool $rewrite whether rewrite the whole file @return boolean
entailment
protected function doValidate($input) { if (!$this->isString($input)) { $this->addError('notString'); return false; } if (!$this->regex) { if (strpos($input, $this->search) === false) { $this->addError('notContains'); return false; } } else { if (!preg_match($this->search, $input)) { $this->addError('notContains'); return false; } } return true; }
{@inheritdoc}
entailment
public function getOrders(OrderListMessage $message): array { $path = 'orders'; $response = $this->getClient()->sendRequest('GET', $path, $message->build()); /** @var Order[] $models */ $models = $this->getModelFactory()->createMany(Order::class, $response['data']); return $models; }
@param OrderListMessage $message @return Order[]
entailment
public function tick() { while (!$this->queue->isEmpty() && $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 callbacks which were on the queue when tick() was called and newly added ones.
entailment
public function setValues($values=array()) { $count=$this->count(); $isArray=true; if (\is_array($values) === false) { $values=\array_fill(0, $count, $values); $isArray=false; } if (JArray::dimension($values) == 1 && $isArray) $values=[ $values ]; $count=\min(\sizeof($values), $count); for($i=0; $i < $count; $i++) { $row=$this->content[$i]; $row->setValues($values[$i]); } return $this; }
Sets the cells values @param mixed $values
entailment
protected function doCreateObject(array $array) { $this->data = $array; $this->entityGroup = new EntityGroup($this->data); $this->setMedia() ->setAttributes(); return $this->entityGroup; }
@param array $array @return mixed
entailment
private function getTargetInfos() { $targetInfos = array (); foreach ( $this->targetLanguages as $language ) { $targetInfo = new TargetInfo (); $targetInfo->targetLocale = $language; if (isset ( $submission->dueDate )) { $targetInfo->requestedDueDate = $submission->dueDate; } else { $targetInfo->requestedDueDate = 0; } if (isset ( $this->encoding )) { $targetInfo->encoding = $this->encoding; } else { $targetInfo->encoding = "UTF-8"; } $targetInfos [] = $targetInfo; } return $targetInfos; }
Internal method used by the UCF API @return TargetInfo array
entailment
public function getResourceInfo() { $resourceInfo = new ResourceInfo (); if (isset ( $this->encoding )) { $resourceInfo->encoding = $this->encoding; } else { $resourceInfo->encoding = "UTF-8"; } $resourceInfo->size = strlen ( $this->data ); $resourceInfo->classifier = $this->fileformat; $resourceInfo->name = $this->name; if (isset ( $this->clientIdentifier )) { $resourceInfo->clientIdentifier = $this->clientIdentifier; } return $resourceInfo; }
Internal method used by the UCF API @return ResourceInfo object @throws IOException
entailment
public function setValueRange($minValue, $maxValue) { if (preg_match('/^([1-9][0-9]*)|([0]{1})$/', $minValue) !== 1) { throw new InvalidArgumentException( 'Min value must contain only digits.' ); } if (preg_match('/^[1-9][0-9]*$/', $maxValue) !== 1) { throw new InvalidArgumentException( 'Max value must start with a nonzero digit and contain only digits.' ); } if (gmp_cmp($maxValue, $minValue) < 1) { throw new InvalidArgumentException('Max value must be greater than min value.'); } $this->minValue = $minValue; $this->maxValue = $maxValue; // find the minimum number of even bits to span whole set $this->binSize = 2; $span = gmp_init('4', 10); $multiplier = gmp_init('4', 10); do { $this->binSize += 2; $span = gmp_mul($span, $multiplier); } while (gmp_cmp($span, $this->maxValue) < 1); $this->decSize = strlen($this->maxValue); $this->hexSize = $this->binSize / 4; $this->sideSize = (int) $this->binSize / 2; if ($this->sideSize > $this->cipherLength) { throw new LogicException(sprintf( 'Side size (%d bits) must be less or equal to cipher length (%d bits)', $this->sideSize, $this->cipherLength )); } return $this; }
Set value range and pad sizes. @param string $minValue Minimum value. String representation of positive integer value or zero. @param string $maxValue Maximum value. String representation of positive integer value. @throws InvalidArgumentException If provided invalid parameters. @return Cryptomute
entailment
public function encrypt($input, $base = 10, $pad = false, $password = null, $iv = null) { return $this->_encryptInternal($input, $base, $pad, $password, $iv, true); }
Encrypts input data. Acts as a public alias for _encryptInternal method. @param string $input String representation of input number. @param int $base Input number base. @param bool $pad Pad left with zeroes? @param string|null $password Encryption password. @param string|null $iv Encryption initialization vector. Must be unique! @return string Outputs encrypted data in the same format as input data.
entailment
private function _encryptInternal($input, $base, $pad, $password, $iv, $checkVal = false) { $this->_validateInput($input, $base, $checkVal); $this->_validateIv($iv); $hashPassword = $this->_hashPassword($password); $roundKeys = $this->_roundKeys($hashPassword, $iv); $binary = $this->_convertToBin($input, $base); for ($i = 1; $i <= $this->rounds; $i++) { $left = substr($binary, 0, $this->sideSize); $right = substr($binary, -1 * $this->sideSize); $key = $roundKeys[$i]; $round = $this->_round($right, $key, $hashPassword, $iv); $newLeft = $right; $newRight = $this->_binaryXor($left, $round); $binary = $newLeft . $newRight; } $output = $this->_convertFromBin($binary, $base, $pad); $compare = DataConverter::binToDec($binary); return (gmp_cmp($this->minValue, $compare) > 0 || gmp_cmp($compare, $this->maxValue) > 0) ? $this->_encryptInternal($output, $base, $pad, $password, $iv, false) : $output; }
Encrypts input data. @param string $input String representation of input number. @param int $base Input number base. @param bool $pad Pad left with zeroes? @param string|null $password Encryption password. @param string|null $iv Encryption initialization vector. Must be unique! @param bool $checkVal Should check if input value is in range? @return string Outputs encrypted data in the same format as input data.
entailment
private function _encrypt($input, $password, $iv = null) { return (self::$allowedCiphers[$this->cipher]['iv']) ? openssl_encrypt($input, $this->cipher, $password, true, $iv) : openssl_encrypt($input, $this->cipher, $password, true); }
Encrypt helper. @param string $input @param string $password @param string|null $iv @return string Steam of encrypted bytes.
entailment
private function _round($input, $key, $hashPassword, $iv = null) { $bin = DataConverter::rawToBin($this->_encrypt($input . $key, $hashPassword, $iv)); return substr($bin, -1 * $this->sideSize); }
Round function helper. @param string $input @param string $key @param string $hashPassword @param string|null $iv @return string Binary string.
entailment
private function _binaryXor($left, $round) { $xOr = gmp_xor( gmp_init($left, 2), gmp_init($round, 2) ); $bin = gmp_strval($xOr, 2); return str_pad($bin, $this->sideSize, '0', STR_PAD_LEFT); }
Binary xor helper. @param string $left @param string $round @return string Binary string.
entailment
private function _convertToBin($input, $base) { switch ($base) { case 2: return DataConverter::pad($input, $this->binSize); case 10: return DataConverter::decToBin($input, $this->binSize); case 16: return DataConverter::hexToBin($input, $this->binSize); } }
Helper method converting input data to binary string. @param string $input @param string $base @return string
entailment
private function _convertFromBin($binary, $base, $pad) { switch ($base) { case 2: return DataConverter::pad($binary, ($pad ? $this->binSize : 0)); case 10: return DataConverter::binToDec($binary, ($pad ? $this->decSize : 0)); case 16: return DataConverter::binToHex($binary, ($pad ? $this->hexSize : 0)); } }
Helper method converting input data from binary string. @param string $binary @param string $type @param string $pad @return string
entailment
private function _validateInput($input, $base, $checkDomain = false) { if (!array_key_exists($base, self::$allowedBases)) { throw new InvalidArgumentException(sprintf( 'Type must be one of "%s".', implode(', ', array_keys(self::$allowedBases)) )); } if (preg_match(self::$allowedBases[$base], $input) !== 1) { throw new InvalidArgumentException(sprintf( 'Input data "%s" does not match pattern "%s".', $input, self::$allowedBases[$base] )); } if ($checkDomain) { $compare = gmp_init($input, $base); if (gmp_cmp($this->minValue, $compare) > 0 || gmp_cmp($compare, $this->maxValue) > 0) { throw new InvalidArgumentException(sprintf( 'Input value "%d" is out of domain range "%d - %d".', gmp_strval($compare, 10), $this->minValue, $this->maxValue )); } } }
Validates input data. @param string $input @param string $base @param bool $checkDomain Should check if input is in domain? @throws InvalidArgumentException If provided invalid type.
entailment
private function _validateIv($iv = null) { if (self::$allowedCiphers[$this->cipher]['iv']) { $this->blockSize = openssl_cipher_iv_length($this->cipher); $ivLength = mb_strlen($iv, '8bit'); if ($ivLength !== $this->blockSize) { throw new InvalidArgumentException(sprintf( 'Initialization vector of %d bytes is required for cipher "%s", %d given.', $this->blockSize, $this->cipher, $ivLength )); } } }
Validates initialization vector. @param string|null $iv
entailment
private function _hashPassword($password = null) { if (null !== $password) { $this->password = md5($password); } return $this->password; }
Hashes the password. @param string|null $password @return string
entailment
private function _roundKeys($hashPassword = null, $iv = null) { $roundKeys = []; $prevKey = $this->_encrypt($this->key, $hashPassword, $iv); for ($i = 1; $i <= $this->rounds; $i++) { $prevKey = $this->_encrypt($prevKey, $hashPassword, $iv); $roundKeys[$i] = substr(DataConverter::rawToBin($prevKey), -1 * $this->sideSize); } return $roundKeys; }
Generates hash keys. @param string|null $hashPassword @param string|null $iv @return array
entailment
public function _output($array_js='') { if (!is_array($array_js)) { $array_js=array ( $array_js ); } foreach ( $array_js as $js ) { $this->jquery_code_for_compile[]="\t$js\n"; } }
Outputs script directly @param string The element to attach the event to @param string The code to execute @return string
entailment
public function _genericCallValue($jQueryCall,$element='this', $param="", $immediatly=false) { $element=$this->_prep_element($element); if (isset($param)) { $param=$this->_prep_value($param); $str="$({$element}).{$jQueryCall}({$param});"; } else $str="$({$element}).{$jQueryCall}();"; if ($immediatly) $this->jquery_code_for_compile[]=$str; return $str; }
Execute a generic jQuery call with a value. @param string $jQueryCall @param string $element @param string $param @param boolean $immediatly delayed if false
entailment
public function _genericCallElement($jQueryCall,$to='this', $element, $immediatly=false) { $to=$this->_prep_element($to); $element=$this->_prep_element($element); $str="$({$to}).{$jQueryCall}({$element});"; if ($immediatly) $this->jquery_code_for_compile[]=$str; return $str; }
Execute a generic jQuery call with 2 elements. @param string $jQueryCall @param string $to @param string $element @param boolean $immediatly delayed if false @return string
entailment
public function sortable($element, $options=array()) { if (count($options)>0) { $sort_options=array (); foreach ( $options as $k => $v ) { $sort_options[]="\n\t\t".$k.': '.$v.""; } $sort_options=implode(",", $sort_options); } else { $sort_options=''; } return "$(".$this->_prep_element($element).").sortable({".$sort_options."\n\t});"; }
Creates a jQuery sortable @param string $element @param array $options @return void
entailment
public function _add_event($element, $js, $event, $preventDefault=false, $stopPropagation=false,$immediatly=true) { if (is_array($js)) { $js=implode("\n\t\t", $js); } if ($preventDefault===true) { $js="event.preventDefault();\n".$js; } if ($stopPropagation===true) { $js="event.stopPropagation();\n".$js; } if (array_search($event, $this->jquery_events)===false) $event="\n\t$(".$this->_prep_element($element).").bind('{$event}',function(event){\n\t\t{$js}\n\t});\n"; else $event="\n\t$(".$this->_prep_element($element).").{$event}(function(event){\n\t\t{$js}\n\t});\n"; if($immediatly) $this->jquery_code_for_compile[]=$event; return $event; }
Constructs the syntax for an event, and adds to into the array for compilation @param string $element The element to attach the event to @param string $js The code to execute @param string $event The event to pass @param boolean $preventDefault If set to true, the default action of the event will not be triggered. @param boolean $stopPropagation Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. @return string
entailment
public function _compile(&$view=NULL, $view_var='script_foot', $script_tags=TRUE) { // Components UI $ui=$this->ui(); if ($this->ui()!=NULL) { if ($ui->isAutoCompile()) { $ui->compile(true); } } // Components BS $bootstrap=$this->bootstrap(); if ($this->bootstrap()!=NULL) { if ($bootstrap->isAutoCompile()) { $bootstrap->compile(true); } } // Components Semantic $semantic=$this->semantic(); if ($semantic!=NULL) { if ($semantic->isAutoCompile()) { $semantic->compile(true); } } // External references $external_scripts=implode('', $this->jquery_code_for_load); extract(array ( 'library_src' => $external_scripts )); if (count($this->jquery_code_for_compile)==0) { // no inline references, let's just return return; } // Inline references $script='$(document).ready(function() {'."\n"; $script.=implode('', $this->jquery_code_for_compile); $script.='});'; $this->jquery_code_for_compile=array(); if($this->params["debug"]==false){ $script=$this->minify($script); } $output=($script_tags===FALSE) ? $script : $this->inline($script); if ($view!==NULL){ $this->jsUtils->createScriptVariable($view,$view_var, $output); } return $output; }
As events are specified, they are stored in an array This function compiles them all for output on a page @param view $view @param string $view_var @param boolean $script_tags @return string
entailment
public function _document_ready($js) { if (!is_array($js)) { $js=array ( $js ); } foreach ( $js as $script ) { $this->jquery_code_for_compile[]=$script; } }
A wrapper for writing document.ready() @return string
entailment
public function _prep_element($element) { if (strrpos($element, 'this')===false&&strrpos($element, 'event')===false&&strrpos($element, 'self')===false) { $element='"'.addslashes($element).'"'; } return $element; }
Puts HTML element in quotes for use in jQuery code unless the supplied element is the Javascript 'this' object, in which case no quotes are added @param string $element @return string
entailment
public function _prep_value($value) { if (is_array($value)) { $value=implode(",", $value); } if (strrpos($value, 'this')===false&&strrpos($value, 'event')===false&&strrpos($value, 'self')===false) { $value='"'.$value.'"'; } return $value; }
Puts HTML values in quotes for use in jQuery code unless the supplied value contains the Javascript 'this' or 'event' object, in which case no quotes are added @param string $value @return string
entailment
protected function doValidate($input) { if (!in_array($input, $this->array, $this->strict)) { $this->addError('notIn'); return false; } return true; }
{@inheritdoc}
entailment
public function setSize($size) { if (is_int($size)) { return $this->addToPropertyUnique("class", CssRef::sizes("pagination")[$size], CssRef::sizes("pagination")); } if(!PhalconUtils::startsWith($size, "pagination-") && $size!=="") $size="pagination-".$size; return $this->addToPropertyCtrl("class", $size, CssRef::sizes("pagination")); }
define the buttons size available values : "lg","","sm","xs" @param string|int $size @return HtmlPagination default : ""
entailment
protected function doValidate($input) { if (!$this->isString($input)) { $this->addError('notString'); return false; } if ($this->format) { $date = date_create_from_format($this->format, $input); } else { $date = date_create($input); } $lastErrors = date_get_last_errors(); if ($lastErrors['warning_count'] || $lastErrors['error_count']) { $this->addError('invalid'); return false; } if ($this->before) { $before = date_create($this->before); if ($before < $date) { $this->addError('tooLate'); } } if ($this->after) { $after = date_create($this->after); if ($after > $date) { $this->addError('tooEarly'); } } return !$this->errors; }
{@inheritdoc}
entailment
public function resolveEarthMeanRadius($measurement = null) { $measurement = ($measurement === null) ? key(static::$MEASUREMENTS) : strtolower($measurement); if (array_key_exists($measurement, static::$MEASUREMENTS)) return static::$MEASUREMENTS[$measurement]; throw new InvalidMeasurementException('Invalid measurement'); }
@param string Grabs the earths mean radius in a specific measurment based on the key provided, throws an exception if no mean readius measurement is found @throws InvalidMeasurementException @return float
entailment
public function scopeWithin($q, $distance, $measurement = null, $lat = null, $lng = null) { $pdo = DB::connection()->getPdo(); $latColumn = $this->getLatColumn(); $lngColumn = $this->getLngColumn(); $lat = ($lat === null) ? $this->lat() : $lat; $lng = ($lng === null) ? $this->lng() : $lng; $meanRadius = $this->resolveEarthMeanRadius($measurement); $distance = floatval($distance); // first-cut bounding box (in degrees) $maxLat = floatval($lat) + rad2deg($distance/$meanRadius); $minLat = floatval($lat) - rad2deg($distance/$meanRadius); // compensate for degrees longitude getting smaller with increasing latitude $maxLng = floatval($lng) + rad2deg($distance/$meanRadius/cos(deg2rad(floatval($lat)))); $minLng = floatval($lng) - rad2deg($distance/$meanRadius/cos(deg2rad(floatval($lat)))); $lat = $pdo->quote(floatval($lat)); $lng = $pdo->quote(floatval($lng)); $meanRadius = $pdo->quote(floatval($meanRadius)); // Paramater bindings havent been used as it would need to be within a DB::select which would run straight away and return its result, which we dont want as it will break the query builder. // This method should work okay as our values have been cooerced into correct types and quoted with pdo. return $q->select(DB::raw("*, ( $meanRadius * acos( cos( radians($lat) ) * cos( radians( $latColumn ) ) * cos( radians( $lngColumn ) - radians($lng) ) + sin( radians($lat) ) * sin( radians( $latColumn ) ) ) ) AS distance")) ->from(DB::raw( "( Select * From {$this->getTable()} Where $latColumn Between $minLat And $maxLat And $lngColumn Between $minLng And $maxLng ) As {$this->getTable()}" )) ->having('distance', '<=', $distance) ->orderby('distance', 'ASC'); }
@param Query @param integer @param mixed @param mixed @todo Use pdo paramater bindings, instead of direct variables in query @return Query Implements a distance radius search using Haversine formula. Returns a query scope. credit - https://developers.google.com/maps/articles/phpsqlsearch_v3
entailment
protected function doValidate($input) { if (!$this->isString($input)) { $this->addError('notString'); return false; } $this->data = $this->db->find($this->table, array($this->field => $input)); if (empty($this->data)) { $this->addError('notFound'); return false; } return true; }
{@inheritdoc}
entailment
public static function bootstrap($coverageEnabled, $storageDirectory, $phpunitConfigFilePath = null) { Assert::boolean($coverageEnabled); if (!$coverageEnabled) { return function () { // do nothing - code coverage is not enabled }; } $coverageGroup = isset($_GET[self::COVERAGE_GROUP_KEY]) ? $_GET[self::COVERAGE_GROUP_KEY] : (isset($_COOKIE[self::COVERAGE_GROUP_KEY]) ? $_COOKIE[self::COVERAGE_GROUP_KEY] : null); $storageDirectory .= ($coverageGroup ? '/' . $coverageGroup : ''); if (isset($_GET[self::EXPORT_CODE_COVERAGE_KEY])) { header('Content-Type: text/plain'); echo self::exportCoverageData($storageDirectory); exit; } $coverageId = isset($_GET[self::COVERAGE_ID_KEY]) ? $_GET[self::COVERAGE_ID_KEY] : (isset($_COOKIE[self::COVERAGE_ID_KEY]) ? $_COOKIE[self::COVERAGE_ID_KEY] : 'live-coverage'); return LiveCodeCoverage::bootstrap( isset($_COOKIE[self::COLLECT_CODE_COVERAGE_KEY]) && (bool)$_COOKIE[self::COLLECT_CODE_COVERAGE_KEY], $storageDirectory, $phpunitConfigFilePath, $coverageId ); }
Enable remote code coverage. @param bool $coverageEnabled Whether or not code coverage should be enabled @param string $storageDirectory Where to store the generated coverage data files @param string $phpunitConfigFilePath The path to the PHPUnit XML file containing the coverage filter configuration @return callable Call this value at the end of the request life cycle.
entailment
public function prepend(ContainerBuilder $container) { $bundles = $container->getParameter('kernel.bundles'); $configs = $container->getExtensionConfig($this->getAlias()); $config = $this->processConfiguration(new Configuration(), $configs); if ($config['theme']['form']) { if (isset($bundles['TwigBundle'])) { $container->prependExtensionConfig('twig', ['form_themes' => [$config['template']['form']]]); } else { throw new InvalidConfigurationException('You need to enable Twig Bundle to theme form or set the configuration of flob_foundation.theme.form to false'); } } if ($config['theme']['knp_menu']) { if ((isset($bundles['TwigBundle'])) && (isset($bundles['KnpMenuBundle']))) { $container->prependExtensionConfig('knp_menu', ['twig' => ['template' => $config['template']['knp_menu']]]); } else { throw new InvalidConfigurationException('You need to enable Twig Bundle and KNP Menu Bundle to theme menu or set the configuration of flob_foundation.theme.knp_menu to false'); } } if ($config['theme']['knp_paginator']) { if ((isset($bundles['TwigBundle'])) && (isset($bundles['KnpPaginatorBundle']))) { $container->prependExtensionConfig('knp_paginator', ['template' => ['pagination' => $config['template']['knp_paginator']]]); } else { throw new InvalidConfigurationException('You need to enable Twig Bundle and KNP Paginator Bundle to theme pagination or set the configuration of flob_foundation.theme.knp_paginator to false'); } } if ($config['theme']['pagerfanta']) { if ((isset($bundles['TwigBundle'])) && (isset($bundles['WhiteOctoberPagerfantaBundle']))) { $container->prependExtensionConfig('white_october_pagerfanta', ['default_view' => $config['template']['pagerfanta']]); } else { throw new InvalidConfigurationException('You need to enable Twig Bundle and WhiteOctober Pagerfanta Bundle to theme pagination or set the configuration of flob_foundation.theme.pagerfanta to false'); } } }
{@inheritdoc}
entailment
protected function doCreateObject(array $array) { $entityFactor = new EntityFactor($array); $factor = [ 'id' => $array['factorId'] ?? null, 'code' => $array['factorCode'] ?? null, 'name' => $array['factorName'] ?? null, ]; $mapper = new FactorsMapper(); $entityFactor->factor = $mapper->createObject($factor); $factorValue = [ 'id' => $array['id'] ?? null, 'name' => $array['name'] ?? null, 'factorId' => $array['factorId'] ?? null, 'image' => $array['image'] ?? null, 'description' => $array['description'] ?? null, ]; $mapper = new FactorValuesMapper(); $entityFactor->factorValue = $mapper->createObject($factorValue); return $entityFactor; }
@param array $array @return EntityFactor
entailment
public function _attr($element='this', $attributeName, $value="", $immediatly=false) { $element=$this->_prep_element($element); if (isset($value)) { $value=$this->_prep_value($value); $str="$({$element}).attr(\"$attributeName\",{$value});"; } else $str="$({$element}).attr(\"$attributeName\");"; if ($immediatly) $this->jquery_code_for_compile[]=$str; return $str; }
Get or set the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element. @param string $element @param string $attributeName @param string $value @param boolean $immediatly delayed if false
entailment
public function after($element='this', $value='', $immediatly=false){ $element=$this->_prep_element($element); $value=$this->_prep_value($value); $str="$({$element}).after({$value});"; if ($immediatly) $this->jquery_code_for_compile[]=$str; return $str; }
Insert content, specified by the parameter, after each element in the set of matched elements @param string $element @param string $value @param boolean $immediatly defers the execution if set to false @return string
entailment
public function _animate($element='this', $params=array(), $speed='', $extra='', $immediatly=false) { $element=$this->_prep_element($element); $speed=$this->_validate_speed($speed); $animations="\t\t\t"; if (is_array($params)) { foreach ( $params as $param => $value ) { $animations.=$param.': \''.$value.'\', '; } } $animations=substr($animations, 0, -2); // remove the last ", " if ($speed!='') { $speed=', '.$speed; } if ($extra!='') { $extra=', '.$extra; } $str="$({$element}).animate({\n$animations\n\t\t}".$speed.$extra.");"; if ($immediatly) $this->jquery_code_for_compile[]=$str; return $str; }
Execute a jQuery animate action @param string $element element @param string|array $params One of 'slow', 'normal', 'fast', or time in milliseconds @param string $speed @param string $extra @param boolean $immediatly delayed if false @return string
entailment
public function _fadeIn($element='this', $speed='', $callback='', $immediatly=false) { $element=$this->_prep_element($element); $speed=$this->_validate_speed($speed); if ($callback!='') { $callback=", function(){\n{$callback}\n}"; } $str="$({$element}).fadeIn({$speed}{$callback});"; if ($immediatly) $this->jquery_code_for_compile[]=$str; return $str; }
Execute a jQuery hide action @param string $element element @param string $speed One of 'slow', 'normal', 'fast', or time in milliseconds @param string $callback Javascript callback function @param boolean $immediatly delayed if false @return string
entailment
public function _toggle($element='this', $immediatly=false) { $element=$this->_prep_element($element); $str="$({$element}).toggle();"; if ($immediatly) $this->jquery_code_for_compile[]=$str; return $str; }
Outputs a jQuery toggle event @param string $element element @param boolean $immediatly delayed if false @return string
entailment
public function _trigger($element='this', $event='click', $immediatly=false) { $element=$this->_prep_element($element); $str="$({$element}).trigger(\"$event\");"; if ($immediatly) $this->jquery_code_for_compile[]=$str; return $str; }
Execute all handlers and behaviors attached to the matched elements for the given event. @param string $element @param string $event @param boolean $immediatly delayed if false
entailment
public function _condition($condition, $jsCodeIfTrue, $jsCodeIfFalse=null, $immediatly=false) { $str="if(".$condition."){".$jsCodeIfTrue."}"; if (isset($jsCodeIfFalse)) { $str.="else{".$jsCodeIfFalse."}"; } if ($immediatly) $this->jquery_code_for_compile[]=$str; return $str; }
Places a condition @param string $condition @param string $jsCodeIfTrue @param string $jsCodeIfFalse @param boolean $immediatly delayed if false @return string
entailment
public function _doJQuery($element, $jqueryCall, $param="", $jsCallback="", $immediatly=false) { $param=$this->_prep_value($param); $callback=""; if ($jsCallback!="") $callback=", function(event){\n{$jsCallback}\n}"; $script="$(".$this->_prep_element($element).").".$jqueryCall."(".$param.$callback.");\n"; if ($immediatly) $this->jquery_code_for_compile[]=$script; return $script; }
Call the JQuery method $jqueryCall on $element with parameters $param @param string $element @param string $jqueryCall @param mixed $param @param string $jsCallback javascript code to execute after the jquery call @param boolean $immediatly @return string
entailment
public function _exec($js, $immediatly=false) { $script=$js."\n"; if ($immediatly) $this->jquery_code_for_compile[]=$script; return $script; }
Execute the code $js @param string $js Code to execute @param boolean $immediatly diffère l'exécution si false @return String
entailment
public function handle(string $method, $body = false, $uriAppend = false, array $queryParams = []) { $clientBuilder = new ClientBuilder(); $url = HttpHelper::setHttPortToUrl($this->client->getGatewayUrl(), false) . '/' . $this->resource->getVersion() . '/' . $this->resource->getURI(); $client = $clientBuilder->setConnectionParams(['client' => ['headers' => $this->setAuthorization()]]) ->setHosts(['host' => $url]) ->build(); try { $size = $queryParams['body']['size'] ?? 0; $from = $queryParams['body']['from'] ?? 0; $response = new ElasticSearchResponse($this->multi ? $client->msearch($queryParams) : $client->search($queryParams), $this->multi, $size, $from); } catch (\Exception $ex) { $error = json_decode($ex->getMessage()); throw new \Exception($error->error->reason ?? $ex->getMessage()); } return $response; }
@param string $method @param bool $body @param bool $uriAppend @param array $queryParams @return \GuzzleHttp\Promise\PromiseInterface|ElasticSearchResponse|Response @throws \GuzzleHttp\Exception\GuzzleException @throws \Exception
entailment
public function bind(callable $function) : Monadic { return new self(function ($state) use ($function) { list($initial, $final) = $this->run($state); return $function($initial)->run($final); }); }
bind method. @param callable $function @return object State
entailment
public function filter($filter) { if (is_array($filter)) { $filter = new GridFilter($filter); } if ($filter instanceof FilterSpecification) { $filter = new GridFilter($filter->asFilter()); } $this->filter = $filter; return $this; }
Set filter to the resource selecting @param array|FilterSpecification|GridFilter $filter @return $this
entailment
public function toArray(): array { $result = [ 'terms' => array_merge([ 'field' => $this->field, 'size' => $this->size, ], $this->additionalParams), ]; if ($this->subAggregations) { $result['aggs'] = $this->subAggregations; } return $result; }
Convert to array @return array
entailment
private function getParamsFromFilter(FilterBuilder $filter) { $result = []; $must = []; $mustNot = []; $params = $filter->getParams(); if ($params['entities']) { $result['index'] = $params['entities']; } if (isset($params['keyword'])) { $must[] = new MultiMatchQuery($params['keyword']['value'], $params['keyword']['fields']); } foreach ($params['params'] ?? [] as $param) { list($query, $operator) = $param->createFilter(); if ($operator == FilterOperators::IN) { $must[] = $query; } else { $mustNot[] = $query; } } if ($mustNot || $must) { $query = new QueryBuilder(); if ($mustNot) { $query->setMustNot(new MustNotQuery($mustNot)); } if ($must) { $query->setMust(new MustQuery($must)); } $result['query'] = $query->toArray(); } return $result; }
@param $filter @return array
entailment
public function makeArray(Response $response) { if (!$response->getSuccess()) { if ($this->asCollection) { return new Collection([], new Meta()); } return []; } $result = $this->getResultFromResponse($response); if ($this->asCollection) { $collection = new Collection($result, $response->getMeta()); return $collection; } return $result; }
@param Response $response @return array|Collection @throws EntityNotFoundException
entailment
public function makeSingle(Response $response) { if (!$response->getSuccess()) { return null; } $result = $this->getResultFromResponse($response); return $result[0] ?? null; }
@param Response $response @return null|Entity @throws EntityNotFoundException
entailment
protected function getRelationships(array $item, array $included) { if (!isset($item['relationships']) || !is_array($item['relationships'])) { return []; } $result = []; foreach ($item['relationships'] as $relationKey => $relationValue) { foreach ($relationValue['data'] as $relationData) { if (!isset($included[$relationData['type']][$relationData['id']])) { throw new EntityNotFoundException("Data for type[{$relationData['type']}] and id[{$relationData['id']}] was not found in includes"); } $result[$relationKey][$relationData['id']] = $included[$relationData['type']][$relationData['id']]; } } return $result; }
Get relationships from array @param array $item @param array $included @return array @throws EntityNotFoundException
entailment
public static function addFilter(array $filters, array $filterArray, string $key, string $name): array { if (isset($filterArray[$name][$key])) { unset($filterArray[$name][$key]); } if (sizeof($filterArray[$name]) > 0) { $filters['filter']['bool']['must'][] = $filterArray; } return $filters; }
@param array $filters @param array $filterArray @param string $key @param string $name @return array
entailment
public static function addAggregation(array $param, array $filters): array { if ($filters) { $aggregations = $filters; $aggregations['aggs'] = $param; return $aggregations; } return $param; }
@param array $param @param array $filters @return array
entailment
public function getSql() { $table = $this->table; if ($this->hasTable($table)) { $this->isChange = true; } $columnSql = $this->getCreateDefinition(); if ($this->isChange) { $sql = "ALTER TABLE $table" . $columnSql; } else { $sql = "CREATE TABLE $table ($columnSql)"; $sql .= $this->getTableOptionSql(); } return $sql; }
Return create/change table sql @return string
entailment
public function drop($table, $ifExists = false) { $sql = 'DROP TABLE '; if ($ifExists) { $sql .= 'IF EXISTS '; } $sql .= $table; $this->db->executeUpdate($sql); return $this; }
Execute a drop table sql @param string $table @param bool $ifExists @return $this
entailment
public function hasTable($table) { $parts = explode('.', $table); if (count($parts) == 1) { $db = $this->db->getDbname(); $table = $parts[0]; } else { list($db, $table) = $parts; } $tableExistsSql = $this->checkTableSqls[$this->db->getDriver()]; return (bool) $this->db->fetchColumn($tableExistsSql, array($db, $table)); }
Check if table exists @param string $table @return bool
entailment
public function decimal($column, $length = 10, $scale = 2) { return $this->addColumn($column, self::TYPE_DECIMAL, array('length' => $length, 'scale' => $scale)); }
Add a decimal column @param string $column @param int $length @param int $scale @return $this
entailment
public function int($column, $length = null) { return $this->addColumn($column, self::TYPE_INT, array('length' => $length)); }
Add a int column @param string $column @param int|null $length @return $this
entailment
public function tinyInt($column, $length = null) { return $this->addColumn($column, self::TYPE_TINY_INT, array('length' => $length)); }
Add a tiny int column @param $column @param int|null $length @return $this
entailment
public function smallInt($column, $length = null) { return $this->addColumn($column, self::TYPE_SMALL_INT, array('length' => $length)); }
Add a small int column @param $column @param int|null $length @return $this
entailment
public function id($column = 'id') { $this->int($column)->unsigned()->autoIncrement(); return $this->primary($column); }
Add a int auto increment id to table @param string $column @return $this
entailment
public function rename($from, $to) { $sql = sprintf('RENAME TABLE %s TO %s', $from, $to); $this->db->executeUpdate($sql); return $this; }
Execute a rename table sql @param string $from @param string $to @return $this
entailment
protected function getQueryParams(array $additionalParams = []) { $params = parent::getQueryParams($additionalParams); if (empty($params['where'])) { return $params; } foreach (explode('&', $params['where']) as $where) { list($key, $value) = explode('=', $where); $params[$key] = $value; } unset($params['where']); return $params; }
@param array $additionalParams @return array|mixed
entailment