sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function setError($code, $node, $message = '')
{
$this->errorCode = $code;
$this->errorNode = $node;
$this->errorMessage = $message;
} | Sets error.
@param int $code
@param string $message | entailment |
public function initialize() {
$types = Registry::get_field_types();
if ( array_key_exists( $type = $this->get_type(), $types ) ) {
$this->field_type = $types[ $type ];
}
if ( ! $this->group ) {
$this->setup_storage();
}
if ( ! $this->storage ) {
$this->set_storage( $this->builder->get_storage() );
}
$this->setup_data();
return $this;
} | {@inheritdoc} | entailment |
protected function setup_storage() {
$storage = $this->get_option( 'storage' );
if ( 'option' === $storage ) {
$storage = Option_Storage::get_instance();
} elseif ( 'thememod' === $storage ) {
$storage = Theme_Mod_Storage::get_instance();
} elseif ( is_string( $storage ) && is_subclass_of( $storage, Storage::class ) ) {
$storage = new $storage;
} elseif ( is_callable( $storage ) ) {
$storage = $storage( $this );
}
if ( $storage instanceof Storage ) {
$this->set_storage( $storage );
}
} | Setup the field storage.
@retun void | entailment |
protected function setup_data() {
if ( ! $storage = $this->get_storage() ) {
return;
}
$_hash = spl_object_hash( $storage );
if ( $storage instanceof Deferred_Storage && ! isset( static::$storages_was_read[ $_hash ] ) ) {
$storage->read();
static::$storages_was_read[ $_hash ] = true;
}
$this->set_value(
$storage->get( $this->get_map_key() )
);
} | Setup field data from the storage.
@return void | entailment |
public function is_required() {
if ( $this->group && $this->group->is_required() ) {
return true;
}
return $this->get_option( 'required' ) || $this->get_attribute( 'required' );
} | {@inheritdoc} | entailment |
public function is_disabled() {
if ( $this->group && $this->group->is_disabled() ) {
return true;
}
return $this->get_option( 'disabled' ) || $this->get_attribute( 'disabled' );
} | {@inheritdoc} | entailment |
public function get_value() {
if ( $this->group && null === $this->value ) {
return $this->value = $this->get_value_in_group();
}
return $this->value;
} | Gets the field value.
@return mixed | entailment |
protected function get_value_in_group() {
$id = $this->get_id();
$data = $this->group->get_value();
return is_array( $data ) && isset( $data[ $this->group->index ][ $id ] )
? $data[ $this->group->index ][ $id ]
: null;
} | Returns current value in group.
@return mixed | entailment |
public function get_sanitization_value( $value ) {
if ( $this->is_repeatable() && is_callable( $sanitizer = $this->get_option( 'sanitization_cb' ) ) ) {
$sanitized = is_array( $value ) ? array_map( $sanitizer, $value ) : [];
return Utils::filter_blank( $sanitized );
}
return $this->sanitization_cb( $value );
} | Perform the sanitization a given value.
@param mixed $value
@return mixed | entailment |
public function check_capabilities() {
$caps = $this->get_option( 'capability' );
if ( $caps && ! call_user_func_array( 'current_user_can', (array) $caps ) ) {
return false;
}
$theme_supports = $this->get_option( 'current_theme_supports' );
/* @noinspection IfReturnReturnSimplificationInspection */
if ( $theme_supports && ! call_user_func_array( 'current_theme_supports', (array) $theme_supports ) ) {
return false;
}
return true;
} | {@inheritdoc} | entailment |
public function js_data() {
$json = array_merge( parent::js_data(), [
'repeatable' => $this->is_repeatable(),
'required' => $this->is_required(),
'disabled' => $this->is_disabled(),
'active' => $this->active(),
'deps' => $this->get_option( 'deps' ) ?: null,
'value' => $this->get_value(),
] );
// Merge data from the field type.
if ( $this->field_type && method_exists( $this->field_type, 'js_data' ) ) {
$json = array_merge( $json, (array) $this->field_type->js_data( $this ) );
}
return $json;
} | {@inheritdoc} | entailment |
protected function get_default_field_args( $args ) {
return array_merge( parent::get_default_field_args( $args ), [
'deps' => [],
'validate' => [],
'row_attributes' => [],
'required' => false,
'disabled' => false,
'capability' => null,
'current_theme_supports' => null,
] );
} | {@inheritdoc} | entailment |
private function getExtension(UploadedFile $file): ?string
{
$originalName = $file->getClientOriginalName();
if ($extension = pathinfo($originalName, PATHINFO_EXTENSION)) {
return strtolower($extension);
}
if ($extension = $file->guessExtension()) {
return strtolower($extension);
}
return null;
} | Guess the extension of the given file.
@param UploadedFile $file
@return string|null | entailment |
public static function newPhpDateTime($time = 'now', \DateTimeZone $timeZone = null)
{
if (self::DATETIME_SYSTEM === self::$type) {
return new \DateTime($time, $timeZone);
}
if (self::DATETIME_FIXED === self::$type) {
return self::getFixedTimeFromConfiguredTimestamp($time, $timeZone);
}
$date = self::getFixedTimeFromConfiguredTimestamp($time, $timeZone);
$timePassedSinceInstantiation = abs(
(new \DateTime())->getTimestamp() - self::$offsetTimestamp
);
$date->modify("+{$timePassedSinceInstantiation} seconds");
return $date;
} | @param string $time
@param \DateTimeZone $timeZone
@return \DateTime | entailment |
public static function newImmutablePhpDateTime($time = 'now', \DateTimeZone $timeZone = null)
{
if (self::DATETIME_SYSTEM === self::$type) {
return new \DateTimeImmutable($time, $timeZone);
}
if (self::DATETIME_FIXED === self::$type) {
return self::getFixedImmutableTimeFromConfiguredTimestamp($time, $timeZone);
}
$date = self::getFixedImmutableTimeFromConfiguredTimestamp($time, $timeZone);
$timePassedSinceInstantiation = abs(
(new \DateTime())->getTimestamp() - self::$offsetTimestamp
);
return $date->modify("+{$timePassedSinceInstantiation} seconds");
} | @param string $time
@param \DateTimeZone $timeZone
@return \DateTimeImmutable | entailment |
private static function getFixedTimeFromConfiguredTimestamp($time, $timeZone = null)
{
$date = new \DateTime(sprintf('@%d', self::$timestamp));
if ('now' !== $time) {
$date = $date->modify($time);
}
if (null !== $timeZone) {
$date = $date->setTimezone($timeZone);
}
if (false === $date) {
throw new \RuntimeException('An error happened creating the immutable date');
}
return $date;
} | @param mixed $time
@param null|mixed $timeZone
@throws \Exception
@return \DateTime | entailment |
private static function getFixedImmutableTimeFromConfiguredTimestamp($time, $timeZone = null)
{
$date = new \DateTimeImmutable(sprintf('@%d', self::$timestamp));
if ('now' !== $time) {
$date = $date->modify($time);
}
if (null !== $timeZone) {
$date = $date->setTimezone($timeZone);
}
if (false === $date) {
throw new \RuntimeException('An error happened creating the immutable date');
}
return $date;
} | @param mixed $time
@param null|mixed $timeZone
@throws \Exception
@return \DateTimeImmutable | entailment |
public function cache()
{
if ($this->cache !== null) {
return $this->cache;
}
switch ($this->driver) {
case self::DRIVER_MYSQL:
return $this->cache = new Cache\MySQL\Manage($this->pdo);
}
throw new DatabaseException('Unsupported PDO driver.');
} | Cache manager
@return Cache\ManageInterface
@throws DatabaseException | entailment |
public function delay()
{
if ($this->delay !== null) {
return $this->delay;
}
switch ($this->driver) {
case self::DRIVER_MYSQL:
return $this->delay = new Delay\MySQL\Manage($this->pdo);
}
throw new DatabaseException('Unsupported PDO driver.');
} | Delay manager
@return Delay\ManageInterface
@throws DatabaseException | entailment |
public function get_dir(Request $request)
{
$root = base_path() . DIRECTORY_SEPARATOR;
$postDir = rawurldecode(base_path($request->get('dir')));
if (file_exists($postDir))
{
$files = scandir($postDir);
$returnDir = substr($postDir, strlen($root));
natcasesort($files);
if (count($files) > 2)
{ // The 2 accounts for . and ..
echo "<ul class='jqueryFileTree'>";
foreach ($files as $file)
{
$htmlRel = htmlentities($returnDir . $file);
$htmlName = htmlentities($file);
$ext = preg_replace('/^.*\./', '', $file);
if (file_exists($postDir . $file) && $file != '.' && $file != '..')
{
if (is_dir($postDir . $file))
{
echo "<li class='directory collapsed'><a rel='" . $htmlRel . "/'>" . $htmlName . "</a></li>";
}
else
{
echo "<li class='file ext_{$ext}'><a rel='" . $htmlRel . "'>" . $htmlName . "</a></li>";
}
}
}
echo "</ul>";
}
}
} | Get Directory Files : Jquery File Tree
http://jqueryfiletree.github.io
@param string $dir
@return \Illuminate\Http\Response | entailment |
public function get_file(Request $request)
{
$filepath = $request->input('filepath');
$data = file_get_contents(base_path($filepath));
echo $data;
} | Get file content
@return \Illuminate\Http\Response | entailment |
public function save_file(Request $request)
{
$filepath = $request->input('filepath');
$filedata = $request->input('filedata');
$data = file_put_contents(base_path($filepath), $filedata);
return response()->json(['success' => true]);
} | Save file content
@return \Illuminate\Http\Response | entailment |
public function register() {
$builder = $this->get_builder();
// Sets the builder configures.
foreach ( $this->get_builder_config() as $key => $value ) {
$builder->set_option( $key, $value );
}
( new Loader( $builder ) )->fire();
} | Register the box.
@return void | entailment |
public function get_builder_config() {
$vars = Arr::except( get_object_vars( $this ),
[ 'sections', 'containers', 'properties', 'builder', '_form' ]
);
return array_merge( $vars, $this->properties );
} | Returns the form builder config.
@return array | entailment |
public function get_property( $key ) {
return isset( $this->properties[ $key ] ) ? $this->properties[ $key ] : null;
} | Get box property.
@param string $key
@return mixed | entailment |
public function parse( $rules ) {
$attributes = [];
$rules = $this->parser->parse( $rules );
foreach ( $rules as list( $rule, $parameters ) ) {
$rule = strtolower( $rule );
if ( method_exists( $this, $rule ) ) {
$attributes += $this->$rule( $parameters );
}
}
return $attributes;
} | Parse a rule for an input into an array of attributes.
@param string|array $rules
@return array | entailment |
protected function between( $params ) {
list ( $min, $max ) = $params;
if ( $this->is_numeric() ) {
return [
'min' => $min,
'max' => $max,
];
}
return [
'minlength' => $min,
'maxlength' => $max,
];
} | For number/range inputs, check if the number is between the values.
For strings, check the length of the string.
@param array $params
@return array | entailment |
protected function length( $params ) {
$size = $params[0];
if ( $this->is_numeric() ) {
return [
'min' => $size,
'max' => $size,
'title' => $this->get_title( 'size.numeric', compact( 'size' ) ),
];
}
return [
'pattern' => '.{' . $size . '}',
'title' => $this->get_title( 'size.string', compact( 'size' ) ),
];
} | For numbers: Check an exact value.
For strings: Check the length of the string.
@param array $params
@return array | entailment |
protected function get_date_attribute( $string ) {
$format = 'Y-m-d';
if ( $this->is_type( [ 'datetime', 'datetime-local' ] ) ) {
$format .= '\TH:i:s';
}
return date( $format, strtotime( $string ) );
} | Format a date to the correct format, based on the current field.
@param string $string
@return bool|string | entailment |
public function curlCallback($handler, $line)
{
$this->curlHandler = $handler;
$split = explode(':', $line, 2);
$this->headers[strtolower($split[0])] = trim(end($split));
return strlen($line);
} | cURL CURLOPT_HEADERFUNCTION callback
@link https://tools.ietf.org/html/rfc7230#section-3.2.4
This callback function must return the number of bytes actually taken care of.
If that amount differs from the amount passed in to your function, it'll signal an error to the library.
This will cause the transfer to get aborted and the libcurl function in progress will return CURLE_WRITE_ERROR.
@link https://curl.haxx.se/libcurl/c/CURLOPT_HEADERFUNCTION.html
@param resource $handler - cURL resource
@param string $line - cURL header line string
@return int - the number of bytes written | entailment |
public function getCharset()
{
if (isset($this->headers['content-type']) &&
($value = $this->getInlineValue($this->headers['content-type'], 'charset', ';')) !== false
) {
return $value;
}
return self::ENCODING;
} | Content-Type encoding HTTP header
@link https://tools.ietf.org/html/rfc2616#section-14.17
@return string | entailment |
private function getInlineValue($header, $part, $delimiter = ";")
{
foreach (array_map('trim', explode($delimiter, $header)) as $string) {
if (stripos($string, $part . '=') === 0) {
return trim(explode('=', $string, 2)[1]);
}
}
return false;
} | Get inline header variable value
@param string $header
@param string $part
@param string $delimiter
@return string|false | entailment |
public function getMaxAge()
{
if (isset($this->headers['cache-control']) &&
($value = $this->getInlineValue($this->headers['cache-control'], 'max-age', ',')) !== false
) {
return intval($value);
}
return 0;
} | Cache-Control max-age HTTP header
@link https://tools.ietf.org/html/rfc7234#section-5.2.1.1
@link https://tools.ietf.org/html/rfc7234#section-5.2.2.8
@link https://tools.ietf.org/html/rfc2616#section-14.9.3
@return int | entailment |
public function getRetryAfter($requestTime)
{
if (isset($this->headers['retry-after'])) {
if (is_numeric($this->headers['retry-after'])) {
return intval($this->headers['retry-after']);
} elseif (($time = $this->parseHttpDate($this->headers['retry-after'])) !== false) {
return max(0, $time - $requestTime);
}
}
// If no valid Retry-after header is found, retry after 15 minutes
return 900;
} | Cache-Control Retry-After HTTP header
@link https://tools.ietf.org/html/rfc2616#section-14.37
@param int $requestTime
@return int | entailment |
private function parseHttpDate($string)
{
foreach (self::DATE_HTTP as $format) {
if (($dateTime = date_create_from_format($format, $string, new \DateTimeZone('UTC'))) !== false) {
return (int)date_format($dateTime, 'U');
}
}
return false;
} | Parse HTTP-date
@link https://tools.ietf.org/html/rfc7231#section-7.1.1
@link https://tools.ietf.org/html/rfc2616#section-3.3
@param string $string
@return int|false | entailment |
public function getValidScopes($appId, $userId, $scopes, array $exclude = array())
{
$scopes = self::split($scopes);
$scopes = Table\Scope::getNames($this->appScopeTable->getValidScopes($appId, $scopes, $exclude));
$scopes = Table\Scope::getNames($this->userScopeTable->getValidScopes($userId, $scopes, $exclude));
return $scopes;
} | Returns all scope names which are valid for the app and the user. The
scopes are a comma separated list. All scopes which are listed in the
$exclude array are excluded
@param integer $appId
@param integer $userId
@param string $scopes
@param array $exclude
@return array | entailment |
private function arrayMergeRecursiveEx(array $array1, array &$array2)
{
foreach ($array2 as $key => &$value) {
if (is_array($value) &&
isset($array1[$key]) &&
is_array($array1[$key])
) {
$array1[$key] = $this->arrayMergeRecursiveEx($array1[$key], $value);
} elseif (!is_int($key)) {
$array1[$key] = $value;
} elseif (!in_array($value, $array1)) {
$array1[] = $value;
}
}
return $array1;
} | array_merge_recursive_ex
@link http://stackoverflow.com/a/25712428/4396537
@param array $array1
@param array $array2
@return array | entailment |
private function buildCleanParam($array)
{
$result = [];
foreach ($array as $param => $paths) {
foreach ($paths as $path) {
$result[] = self::DIRECTIVE_CLEAN_PARAM . ':' . $param . ' ' . $path;
}
}
return $result;
} | Clean-param
@param string[][] $array
@return string[] | entailment |
private function buildUserAgent($array)
{
$result = [];
foreach ($array as $userAgent => $rules) {
$rules = $this->arrayMergeRecursiveEx(self::TEMPLATE_SUB, $rules);
$result = array_merge(
$result,
[self::DIRECTIVE_USER_AGENT . ':' . $userAgent],
$this->buildString($rules[self::DIRECTIVE_ROBOT_VERSION], self::DIRECTIVE_ROBOT_VERSION),
$this->buildVisitTime($rules[self::DIRECTIVE_VISIT_TIME]),
$this->buildArray($rules[self::DIRECTIVE_NO_INDEX], self::DIRECTIVE_NO_INDEX),
$this->buildArray($rules[self::DIRECTIVE_DISALLOW], self::DIRECTIVE_DISALLOW),
$this->buildArray($rules[self::DIRECTIVE_ALLOW], self::DIRECTIVE_ALLOW),
$this->buildString($rules[self::DIRECTIVE_CRAWL_DELAY], self::DIRECTIVE_CRAWL_DELAY),
$this->buildString($rules[self::DIRECTIVE_CACHE_DELAY], self::DIRECTIVE_CACHE_DELAY),
$this->buildRequestRate($rules[self::DIRECTIVE_REQUEST_RATE]),
$this->buildArray($rules[self::DIRECTIVE_COMMENT], self::DIRECTIVE_COMMENT)
);
}
return $result;
} | User-agent
@param array $array
@return string[] | entailment |
private function buildVisitTime($array)
{
$result = [];
foreach ($array as $pair) {
$result[] = self::DIRECTIVE_VISIT_TIME . ':' . $pair['from'] . '-' . $pair['to'];
}
return $result;
} | Visit-time
@param int[]|string[] $array
@return string[] | entailment |
private function buildRequestRate($array)
{
$result = [];
foreach ($array as $pair) {
$string = self::DIRECTIVE_REQUEST_RATE . ':' . $pair['ratio'];
if (isset($pair['from']) &&
isset($pair['to'])
) {
$string .= ' ' . $pair['from'] . '-' . $pair['to'];
}
$result[] = $string;
}
return $result;
} | Request-rate
@param array $array
@return string[] | entailment |
public function getIgnoredImportData()
{
$pair = [
'source' => $this->array,
'parsed' => $this->export(),
];
foreach ($pair as &$array) {
$array = $this->arrayFilterRecursive($array);
array_multisort($array);
$this->kSortRecursive($array);
}
return $this->arrayDiffAssocRecursive($pair['source'], $pair['parsed']);
} | Get difference
@return array | entailment |
private function arrayFilterRecursive(array &$array)
{
foreach ($array as $key => &$item) {
is_array($item) && $array[$key] = $this->arrayFilterRecursive($item);
if ($array[$key] === null ||
$array[$key] === []
) {
unset($array[$key]);
}
}
return $array;
} | array_filter_recursive
@link http://php.net/manual/en/function.array-filter.php#87581
@param array $array
@return array | entailment |
private function kSortRecursive(array &$array)
{
foreach ($array as &$current) {
if (is_array($current) &&
$this->kSortRecursive($current) === false
) {
return false;
}
}
return ksort($array);
} | ksort_recursive
@link http://stackoverflow.com/a/2543447/4396537
@param array $array
@return bool | entailment |
public function cron($timeLimit = self::CRON_EXEC_TIME, $workerID = self::WORKER_ID)
{
$start = microtime(true);
$workerID = $this->setWorkerID($workerID);
$log = [];
$lastCount = -1;
while (count($log) > $lastCount &&
(
empty($timeLimit) ||
$timeLimit > (microtime(true) - $start)
)
) {
$lastCount = count($log);
$query = $this->pdo->prepare(<<<SQL
UPDATE robotstxt__cache1
SET worker = :workerID
WHERE worker IS NULL AND nextUpdate <= UNIX_TIMESTAMP()
ORDER BY nextUpdate ASC
LIMIT 1;
SQL
);
$query->bindValue('workerID', $workerID, \PDO::PARAM_INT);
$query->execute();
$query = $this->pdo->prepare(<<<SQL
SELECT base
FROM robotstxt__cache1
WHERE worker = :workerID
ORDER BY nextUpdate DESC
LIMIT 10;
SQL
);
$query->bindValue('workerID', $workerID, \PDO::PARAM_INT);
$query->execute();
while ($baseUri = $query->fetch(\PDO::FETCH_COLUMN)) {
if ((new Base($this->pdo, $baseUri, $this->curlOptions, $this->byteLimit))->refresh()) {
$log[(string)microtime(true)] = $baseUri;
}
}
}
return $log;
} | Process the update queue
@param float|int $timeLimit
@param int|null $workerID
@return string[]
@throws Exceptions\DatabaseException | entailment |
private function setWorkerID($workerID)
{
if ($workerID >= 1 &&
$workerID <= 255
) {
return (int)$workerID;
} elseif ($workerID !== null) {
throw new \InvalidArgumentException('WorkerID out of range (1-255)');
}
return rand(1, 255);
} | Set WorkerID
@param int|null $workerID
@return int
@throws \InvalidArgumentException | entailment |
public function base($baseUri)
{
return new Base($this->pdo, $baseUri, $this->curlOptions, $this->byteLimit);
} | Base class
@param string $baseUri
@return Base | entailment |
public function clean($delay = self::CLEAN_DELAY)
{
$delay += self::CACHE_TIME;
$query = $this->pdo->prepare(<<<SQL
DELETE FROM robotstxt__cache1
WHERE nextUpdate < (UNIX_TIMESTAMP() - :delay);
SQL
);
$query->bindValue('delay', $delay, \PDO::PARAM_INT);
return $query->execute();
} | Clean the cache table
@param int $delay
@return bool | entailment |
protected function _prepareLayout()
{
$this->buttonList->remove('save');
$this->buttonList->remove('delete');
$this->buttonList->remove('reset');
$this->buttonList->add(
'send',
[
'label' => __('Send mail ...'),
'onclick' => "setLocation('{$this->getUrl('*/*/send',
['id' => $this->_mail->getId()]
)}')",
'class' => 'task'
]
);
$this->buttonList->add(
'send_post',
[
'label' => __('Resend mail'),
'onclick' => "setLocation('{$this->getUrl('*/*/sendPost',
[
'id' => $this->_mail->getId()
])}')",
'class' => 'task'
]
);
return parent::_prepareLayout();
} | Prepare the layout.
@return $this | entailment |
public function getBackUrl()
{
if(!empty($this->_mail->getCustomerId())) {
return $this->getUrl('customer/index/edit', array('id' => $this->_mail->getCustomerId()));
}
return $this->getUrl('index/index');
} | Get URL for back (reset) button
@return string | entailment |
public function checkQueue()
{
if ($this->delay == 0) {
return 0;
}
$query = $this->pdo->prepare(<<<SQL
SELECT GREATEST(0, (delayUntil / 1000000) - UNIX_TIMESTAMP(CURTIME(6)))
FROM robotstxt__delay0
WHERE base = :base AND userAgent = :userAgent;
SQL
);
$query->bindValue('base', $this->base, \PDO::PARAM_STR);
$query->bindValue('userAgent', $this->userAgent, \PDO::PARAM_STR);
$query->execute();
return $query->rowCount() > 0 ? floatval($query->fetch(\PDO::FETCH_COLUMN)) : 0;
} | Queue
@return float|int | entailment |
public function reset($newDelay = self::RESET_NEW_DELAY)
{
if (empty($newDelay)) {
$query = $this->pdo->prepare(<<<SQL
DELETE FROM robotstxt__delay0
WHERE base = :base AND userAgent = :userAgent;
SQL
);
$query->bindValue('base', $this->base, \PDO::PARAM_STR);
$query->bindValue('userAgent', $this->userAgent, \PDO::PARAM_STR);
return $query->execute();
}
$query = $this->pdo->prepare(<<<SQL
INSERT INTO robotstxt__delay0 (base, userAgent, delayUntil, lastDelay)
VALUES (:base, :userAgent, (UNIX_TIMESTAMP(CURTIME(6)) + :delay) * 1000000, :delay * 1000000)
ON DUPLICATE KEY UPDATE
delayUntil = (UNIX_TIMESTAMP(CURTIME(6)) + :delay) * 1000000,
lastDelay = :delay * 1000000;
SQL
);
$query->bindValue('base', $this->base, \PDO::PARAM_STR);
$query->bindValue('userAgent', $this->userAgent, \PDO::PARAM_STR);
$query->bindValue('delay', $newDelay, \PDO::PARAM_INT);
return $query->execute();
} | Reset queue
@param float|int $newDelay
@return bool | entailment |
public function getTimeSleepUntil()
{
if ($this->delay == 0) {
return 0;
}
$query = $this->pdo->prepare(<<<SQL
SELECT
delayUntil,
UNIX_TIMESTAMP()
FROM robotstxt__delay0
WHERE base = :base AND userAgent = :userAgent;
SQL
);
$query->bindValue('base', $this->base, \PDO::PARAM_STR);
$query->bindValue('userAgent', $this->userAgent, \PDO::PARAM_STR);
$query->execute();
$this->increment();
if ($query->rowCount() > 0) {
$row = $query->fetch(\PDO::FETCH_ASSOC);
$this->clockSyncCheck($row['UNIX_TIMESTAMP()'], self::OUT_OF_SYNC_TIME_LIMIT);
return $row['delayUntil'] / 1000000;
}
return 0;
} | Timestamp with milliseconds
@return float|int
@throws Exceptions\OutOfSyncException | entailment |
private function increment()
{
$query = $this->pdo->prepare(<<<SQL
INSERT INTO robotstxt__delay0 (base, userAgent, delayUntil, lastDelay)
VALUES (:base, :userAgent, (UNIX_TIMESTAMP(CURTIME(6)) + :delay) * 1000000, :delay * 1000000)
ON DUPLICATE KEY UPDATE
delayUntil = GREATEST((UNIX_TIMESTAMP(CURTIME(6)) + :delay) * 1000000, delayUntil + (:delay * 1000000)),
lastDelay = :delay * 1000000;
SQL
);
$query->bindValue('base', $this->base, \PDO::PARAM_STR);
$query->bindValue('userAgent', $this->userAgent, \PDO::PARAM_STR);
$query->bindValue('delay', $this->delay, \PDO::PARAM_INT);
return $query->execute();
} | Set new delayUntil timestamp
@return bool | entailment |
public function get( $key, $default = null ) {
$post = wp_get_custom_css_post( $this->stylesheet );
if ( $post ) {
return $post->post_content;
}
} | {@inheritdoc} | entailment |
public function set( $key, $value ) {
$r = wp_update_custom_css_post( $value, [
'stylesheet' => $this->stylesheet,
] );
if ( is_wp_error( $r ) ) {
return false;
}
// Cache post ID in theme mod for performance to avoid additional DB query.
if ( get_stylesheet() === $this->stylesheet ) {
set_theme_mod( 'custom_css_post_id', $r->ID );
}
return true;
} | {@inheritdoc} | entailment |
public function execute($cronjobId)
{
$cronjob = $this->cronjobTable->get($cronjobId);
if (empty($cronjob)) {
throw new StatusCode\NotFoundException('Could not find cronjob');
}
if ($cronjob['status'] == Table\Cronjob::STATUS_DELETED) {
throw new StatusCode\GoneException('Cronjob was deleted');
}
$exitCode = null;
try {
$this->executorService->execute(
$cronjob['action'],
'GET',
null,
null,
null,
null
);
$exitCode = Table\Cronjob::CODE_SUCCESS;
} catch (\Throwable $e) {
$this->errorTable->create([
'cronjob_id' => $cronjob['id'],
'message' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
'file' => $e->getFile(),
'line' => $e->getLine(),
]);
$exitCode = Table\Cronjob::CODE_ERROR;
}
// set execute date
$record = [
'id' => $cronjob['id'],
'execute_date' => new \DateTime(),
'exit_code' => $exitCode,
];
$this->cronjobTable->update($record);
} | Executes a specific cronjob
@param integer $cronjobId | entailment |
private function writeCronFile()
{
if (empty($this->cronFile)) {
return false;
}
if (!is_file($this->cronFile)) {
return false;
}
if (!is_writable($this->cronFile)) {
return false;
}
return file_put_contents($this->cronFile, $this->generateCron());
} | Writes the cron file
@return bool|int | entailment |
protected function registerBindings()
{
$this->app->bind('dropbox.connection', function (Container $app) {
$manager = $app['dropbox'];
return $manager->connection();
});
$this->app->alias('dropbox.connection', Client::class);
} | Register the bindings.
@return void | entailment |
protected function manageRedirection()
{
$content = $this->getMainContent();
$code = 301; // default symfony is 302...
if ('Location:' == substr($content, 0, 9)) {
$url = trim(substr($content, 9));
if (preg_match('/ [1-5][0-9]{2}$/', $url, $match)) {
$code = intval(trim($match[0]));
$url = preg_replace('/ [1-5][0-9]{2}$/', '', $url);
}
if (filter_var($url, FILTER_VALIDATE_URL)) {
$this->redirectionUrl = $url;
$this->redirectionCode = $code;
return $url;
}
}
$this->redirectionUrl = false;
} | Check if a content don't start by 'Location: http://valid-url.tld/eg'. | entailment |
public function pay($points, ContextInterface $context)
{
// decrease user points
$this->userTable->payPoints($context->getUser()->getId(), $points);
// add usage entry
$this->usageTable->create([
'route_id' => $context->getRouteId(),
'user_id' => $context->getUser()->getId(),
'app_id' => $context->getApp()->getId(),
'points' => $points,
'insert_date' => new \DateTime(),
]);
// dispatch payed event
$userContext = UserContext::newContext(
$context->getUser()->getId(),
$context->getApp()->getId()
);
$this->eventDispatcher->dispatch(PlanEvents::PAY, new PayedEvent($points, $userContext));
} | Method which is called in case a user visits a route which cost a
specific amount of points. This method decreases the points from the
user account
@param integer $points
@param \Fusio\Engine\ContextInterface $context | entailment |
public function credit($points, UserContext $context)
{
// credit points
$this->userTable->creditPoints($context->getUserId(), $points);
// dispatch credited event
$this->eventDispatcher->dispatch(PlanEvents::CREDIT, new CreditedEvent($points, $context));
} | Method which is called in case the user has bought new points. It adds
the points to the user account
@param integer $points
@param \Fusio\Impl\Authorization\UserContext $context | entailment |
private function resolveSchemasFromRoutes(array $data, $basePath)
{
$schemas = [];
$type = SystemAbstract::TYPE_ROUTES;
if (isset($data[$type]) && is_array($data[$type])) {
foreach ($data[$type] as $name => $row) {
// resolve includes
$row = IncludeDirective::resolve($row, $basePath, $type);
if (isset($row['methods']) && is_array($row['methods'])) {
foreach ($row['methods'] as $method => $config) {
// parameters
if (isset($config['parameters']) && !$this->isName($config['parameters'])) {
$schema = $this->resolveSchema($config['parameters'], $basePath);
$name = NameGenerator::getSchemaNameFromSource($config['parameters']);
$schemas[$name] = $schema;
}
// request
if (isset($config['request']) && !$this->isName($config['request'])) {
$schema = $this->resolveSchema($config['request'], $basePath);
$name = NameGenerator::getSchemaNameFromSource($config['request']);
$schemas[$name] = $schema;
}
// responses
if (isset($config['response']) && !$this->isName($config['response'])) {
$schema = $this->resolveSchema($config['response'], $basePath);
$name = NameGenerator::getSchemaNameFromSource($config['response']);
$schemas[$name] = $schema;
} elseif (isset($config['responses']) && is_array($config['responses'])) {
foreach ($config['responses'] as $code => $response) {
if (!$this->isName($response)) {
$schema = $this->resolveSchema($response, $basePath);
$name = NameGenerator::getSchemaNameFromSource($response);
$schemas[$name] = $schema;
}
}
}
}
}
}
}
return $schemas;
} | In case the routes contains an include as request/response schemas we
automatically create a fitting schema entry
@param array $data
@param string $basePath
@return array | entailment |
protected function setMosaicDefaultListMode(): self
{
if (null !== $this->request) {
if ($mode = $this->request->query->get('_list_mode')) {
$this->setListMode($mode);
} else {
$this->setListMode('mosaic');
}
}
return $this;
} | Must be a cookie to check before to do that
If you click one time to list, stay in liste mode.
Yes it's in the session
TODO. | entailment |
public function getMessage()
{
/** @noinspection IsEmptyFunctionUsageInspection */
/** @noinspection PhpUndefinedMethodInspection */
if (!empty(parent::getMessage())) {
/** @noinspection PhpUndefinedMethodInspection */
return parent::getMessage();
}
return $this->_storage->loadMessage(
$this
);
} | Every mailing is associated to a 'real' message
@return \Shockwavemk\Mail\Base\Model\Mail\Message|null
@throws \Magento\Framework\Exception\MailException | entailment |
public function getAttachments()
{
/** @noinspection IsEmptyFunctionUsageInspection */
/** @noinspection PhpUndefinedMethodInspection */
if (!empty(parent::getAttachments())) {
/** @noinspection PhpUndefinedMethodInspection */
return parent::getAttachments();
}
$attachments = $this->_storage->getAttachments($this);
/** @noinspection PhpUndefinedMethodInspection */
$this->setAttachments($attachments);
return $attachments;
} | A mail can have zero to n associated attachments.
An Attachment is a meta description to get information and access to binary data
@return \Shockwavemk\Mail\Base\Model\Mail\Attachment[] Attachments
@throws \Magento\Framework\Exception\MailException | entailment |
protected function convertPointerToMagentoModels($mailValues)
{
$newMailValues = [];
foreach ($mailValues as $key => $value) {
if (is_array($value)
&& !empty($value['class']) && !empty($value['entity_id'])
) {
$newMailValues[$key] = $this->createAbstractModelFromValue($value);
}
/** @noinspection NotOptimalIfConditionsInspection */
elseif(is_array($value) && !empty($value['class'])) {
$newMailValues[$key] = $this->createObjectFromValue($value);
}
else {
$newMailValues[$key] = $value;
}
}
return $newMailValues;
} | Recover magento models from stored class/ids tuple
@param $mailValues
@return \Magento\Framework\Model\AbstractModel[]|array
@throws \Magento\Framework\Exception\LocalizedException | entailment |
public function getTags()
{
$value = $this->getData('tags');
/** @noinspection IsEmptyFunctionUsageInspection */
if (!empty($decoded = json_decode($value, true))) {
return $decoded;
}
return [];
} | Get tags used for mail
Tags are stored as json string in database
@return mixed | entailment |
public function updateWithTransport($transport)
{
/** @noinspection PhpUndefinedMethodInspection */
/** @noinspection PhpUndefinedMethodInspection */
$this
->setSubject($transport->getMessage()->getSubject())
->setMessage($transport->getMessage())
->setRecipients($transport->getMessage()->getRecipients())
->setId(null);
return $this;
} | Update mail data with information created while transport init
@param \Shockwavemk\Mail\Base\Model\Transports\TransportInterface $transport
@return \Shockwavemk\Mail\Base\Model\Mail | entailment |
public function setAttachments($attachments) {
/** @var AttachmentInterface $attachment */
foreach ($attachments as $attachment) {
$attachment->setMail($this);
}
$this->setData('attachments', $attachments);
return $this;
} | Set reverse link on each attached entity
@var $attachments AttachmentInterface[] | entailment |
public function save()
{
parent::save();
$this->_storage->saveMessage($this);
$this->_storage->saveAttachments($this);
$this->_storage->saveMail($this);
} | Save mail to db, message and attachments to storage
@throws \Magento\Framework\Exception\MailException
@throws \Exception | entailment |
public function jsonSerialize()
{
$data = $this->getData();
$attachmentsSerialized = [];
/** @noinspection IsEmptyFunctionUsageInspection */
if (!empty($this->getAttachments())) {
foreach ($this->getAttachments() as $attachment) {
$attachmentsSerialized[] = $attachment->jsonSerialize();
}
}
$data['attachments'] = $attachmentsSerialized;
return $data;
} | Specify data which should be serialized to JSON
@link http://php.net/manual/en/jsonserializable.jsonserialize.php
@return mixed data which can be serialized by <b>json_encode</b>,
@throws \Magento\Framework\Exception\MailException
which is a value of any type other than a resource.
@since 5.4.0 | entailment |
public function fire() {
$context = Context::guest();
$this->cmb->set_context( $context );
$this->object_type = $this->cmb->mb_object_type();
if ( $this->cmb->prop( 'hookup' ) ) {
$this->universal_hooks();
}
$this->once( 'admin_footer', [ __CLASS__, 'enqueue_scripts' ], 20 );
$this->once( 'admin_enqueue_scripts', [ __CLASS__, 'enqueue_styles' ], 20 );
} | Fire the hooks.
@return void | entailment |
public function column_display( $column_name, $object_id ) {
if ( isset( $this->columns[ $column_name ] ) ) {
$field = $this->columns[ $column_name ]['field']['id'];
/* @var \WPLibs\Form\Box\Builder $builder */
$builder = $this->cmb;
$form = $builder
->set_storage( $builder->get_new_storage( $object_id, $this->object_type ) )
->get_form();
$form->get( $field )->render_column();
}
} | {@inheritdoc} | entailment |
public function handleError($event)
{
$event->handled = true;
$message = $event->message;
if (YII_DEBUG) {
$trace = debug_backtrace();
if (isset($trace[2]) && isset($trace[2]['file']) && isset($trace[2]['line'])) {
$message .= ' (' . $trace[2]['file'] . ':' . $trace[2]['line'] . ')';
}
}
throw new \Exception($message, self::SOAP_ERROR);
} | The PHP error handler.
@param Event $event the PHP error event
@throws \Exception | entailment |
public function renderWsdl()
{
$wsdl = $this->generateWsdl();
$response = Yii::$app->response;
$response->charset = $this->encoding;
$response->format = Response::FORMAT_RAW;
$response->headers->add('Content-Type', 'text/xml');
// header('Content-Length: '.(function_exists('mb_strlen') ? mb_strlen($wsdl,'8bit') : strlen($wsdl)));
return $wsdl;
} | Generates and displays the WSDL as defined by the provider.
@see generateWsdl
@throws \yii\base\InvalidConfigException | entailment |
public function generateWsdl()
{
if (is_object($this->provider)) {
$providerClass = get_class($this->provider);
} else {
$providerClass = $this->provider;
}
if ($this->wsdlCacheDuration > 0 && $this->cacheID !== false && ($cache = Yii::$app->get($this->cacheID, false)) !== null) {
$key = 'Yii.WebService.' . $providerClass . $this->serviceUrl . $this->encoding;
if (($wsdl = $cache->get($key)) !== false) {
return $wsdl;
}
}
$generator = Yii::createObject($this->generatorConfig);
$wsdl = $generator->generateWsdl($providerClass, $this->serviceUrl, $this->encoding);
if (isset($key, $cache)) {
$cache->set($key, $wsdl, $this->wsdlCacheDuration);
}
return $wsdl;
} | Generates the WSDL as defined by the provider.
The cached version may be used if the WSDL is found valid in cache.
@return string the generated WSDL
@throws \yii\base\InvalidConfigException
@see wsdlCacheDuration | entailment |
public function run()
{
$response = Yii::$app->response;
$response->format = Response::FORMAT_RAW;
$response->charset = $this->encoding;
$response->headers->add('Content-Type', 'text/xml');
if (YII_DEBUG) {
ini_set('soap.wsdl_cache_enabled', 0);
}
$server = new \SoapServer($this->wsdlUrl, $this->getOptions());
// \Yii::$app->on($name, $behavior)EventHandler('onError',array($this,'handleError'));
try {
if ($this->persistence !== null) {
$server->setPersistence($this->persistence);
}
if (is_string($this->provider)) {
$provider = Yii::createObject($this->provider);
} else {
$provider = $this->provider;
}
if (method_exists($server, 'setObject')) {
if (is_array($this->generatorConfig) && isset($this->generatorConfig['bindingStyle'])
&& $this->generatorConfig['bindingStyle'] === 'document'
) {
$server->setObject(new DocumentSoapObjectWrapper($provider));
} else {
$server->setObject($provider);
}
} else {
if (is_array($this->generatorConfig) && isset($this->generatorConfig['bindingStyle'])
&& $this->generatorConfig['bindingStyle'] === 'document'
) {
$server->setClass(DocumentSoapObjectWrapper::className(), $provider);
} else {
$server->setClass(SoapObjectWrapper::className(), $provider);
}
}
if ($provider instanceof IWebServiceProvider) {
if ($provider->beforeWebMethod($this)) {
$server->handle();
$provider->afterWebMethod($this);
}
} else {
$server->handle();
}
} catch (\Exception $e) {
// non-PHP error
if ($e->getCode() !== self::SOAP_ERROR) {
// only log for non-PHP-error case because application's error handler already logs it
// php <5.2 doesn't support string conversion auto-magically
Yii::error($e->__toString());
}
$message = $e->getMessage();
if (YII_DEBUG) {
$message .= ' (' . $e->getFile() . ':' . $e->getLine() . ")\n" . $e->getTraceAsString();
}
// We need to end application explicitly because of
// http://bugs.php.net/bug.php?id=49513
Yii::$app->state = Application::STATE_AFTER_REQUEST;
Yii::$app->trigger(Application::EVENT_AFTER_REQUEST);
$reflect = new \ReflectionClass($e);
$server->fault($reflect->getShortName(), $message);
exit(1);
}
} | Handles the web service request.
@throws \ReflectionException | entailment |
public function sleep()
{
$start = microtime(true);
$until = $this->getTimeSleepUntil();
if (microtime(true) > $until) {
return 0;
}
try {
time_sleep_until($until);
} catch (\Exception $warning) {
// Timestamp already in the past
}
return microtime(true) - $start;
} | Sleep
@return float|int
@throws OutOfSyncException | entailment |
public static function is_blank( $value ) {
if ( is_null( $value ) ) {
return true;
}
if ( is_string( $value ) ) {
return trim( $value ) === '';
}
if ( $value instanceof \Countable ) {
return count( $value ) === 0;
}
/* @noinspection TypeUnsafeComparisonInspection */
if ( 0 === $value || '0' === $value ) {
return false;
}
return empty( $value );
} | Determine if the given value is "blank".
Still accepts 0.
@param mixed $value The given value.
@return bool | entailment |
public static function sanitize_recursive( $values, $sanitizer ) {
if ( ! is_array( $values ) ) {
return is_scalar( $values ) ? $sanitizer( $values ) : $values;
}
foreach ( $values as $key => $value ) {
if ( is_array( $value ) ) {
$values[ $key ] = static::sanitize_recursive( $value, $sanitizer );
} else {
$values[ $key ] = is_scalar( $value ) ? $sanitizer( $value ) : $value;
}
}
return $values;
} | Recursive sanitize a given values.
@param mixed $values The values.
@param string $sanitizer The sanitizer callback.
@return mixed | entailment |
public static function esc_html_class( $classes ) {
$classes = array_filter( array_unique( (array) $classes ) );
if ( empty( $classes ) ) {
return '';
}
return implode( ' ', array_map( 'sanitize_html_class', $classes ) );
} | Returns class string by given an array of classes.
@param array $classes The array of class.
@return string | entailment |
public static function build_html_attributes( $attributes ) {
$html = [];
foreach ( (array) $attributes as $key => $value ) {
$element = static::build_attribute_element( $key, $value );
if ( ! is_null( $element ) ) {
$html[] = $element;
}
}
return count( $html ) > 0 ? ' ' . implode( ' ', $html ) : '';
} | Build an HTML attribute string from an array.
@param array $attributes The HTML attributes.
@return string | entailment |
protected static function build_attribute_element( $key, $value ) {
// For numeric keys we will assume that the value is a boolean attribute
// where the presence of the attribute represents a true value and the
// absence represents a false value.
if ( is_numeric( $key ) ) {
return $value;
}
// Treat boolean attributes as HTML properties.
if ( is_bool( $value ) && 'value' !== $key ) {
return $value ? $key : '';
}
if ( is_array( $value ) && 'class' === $key ) {
return 'class="' . static::esc_html_class( $value ) . '"';
}
if ( ! is_null( $value ) ) {
return $key . '="' . esc_attr( $value ) . '"';
}
return null;
} | Build a single attribute element.
@param string $key
@param string $value
@return string|null | entailment |
public function getPermissions(RoleInterface $role)
{
$permissions = new ArrayCollection();
foreach ($role->getPermissions() as $permission) {
$permissions->add($permission);
foreach ($this->getChildPermissions($permission) as $childPermission) {
if (!$permissions->contains($childPermission)) {
$permissions->add($childPermission);
}
}
}
return $permissions;
} | {@inheritdoc} | entailment |
private static function getBaseNamespace()
{
// try to determine the namespace of the
$composerFile = PSX_PATH_SRC . '/../composer.json';
$composer = \json_decode(\file_get_contents($composerFile), true);
if (isset($composer['autoload'])) {
$paths = $composer['autoload']['psr-4'] ?? [];
$base = trim(key($paths), '\\');
if (!empty($base)) {
return $base;
}
}
throw new \RuntimeException('Could not determine the base namespace');
} | This method tries to find the base namespace of the current app. We try
to look at the composer.json file and use the first psr-4 autoload key
@return string | entailment |
public static function getEngine(&$class)
{
$engine = null;
if (($pos = strpos($class, '://')) !== false) {
$proto = substr($class, 0, $pos);
switch ($proto) {
case 'file':
$class = substr($class, $pos + 3);
$engine = self::getEngineByFile($class);
break;
case 'http':
case 'https':
$engine = Resolver\HttpUrl::class;
break;
default:
$class = substr($class, $pos + 3);
$engine = self::getEngineByProto($proto);
}
} elseif (is_file($class)) {
$engine = self::getEngineByFile($class);
} elseif (class_exists($class)) {
$engine = PhpClass::class;
}
if ($engine === null) {
$engine = PhpClass::class;
}
return $engine;
} | This method determines the fitting engine for the provided string. The
provided string gets modified in case it has the uri format
@param string $class
@return string | entailment |
public function add($line)
{
if (!empty($this->version)) {
return false;
}
$this->version = $line;
return true;
} | Add
@param float|int|string $line
@return bool | entailment |
public function render(RenderHandler $handler)
{
if (!empty($this->version)) {
$handler->add(self::DIRECTIVE_ROBOT_VERSION, $this->version);
}
return true;
} | Render
@param RenderHandler $handler
@return bool | entailment |
public function getArrayKeys()
{
$returnValue = [];
foreach (array_keys($this->getArrayCopy()) as $key) {
if ($key != '_type') {
$returnValue[] = $key;
}
}
return $returnValue;
} | Gets key from current array.
Excludes _type from final array.
@return array | entailment |
public function add($line)
{
$host = $this->parse($line);
if ($host === false ||
$host !== $line ||
in_array($host, $this->host)
) {
return false;
}
$this->host[] = $line;
return true;
} | Add
@param string $line
@return bool | entailment |
private function parse($line)
{
$uriParser = new UriParser($line);
$line = $uriParser->encode();
if ($uriParser->validateIP() ||
!$uriParser->validateHost() ||
(
parse_url($line, PHP_URL_SCHEME) !== null &&
!$uriParser->validateScheme()
)
) {
return false;
}
$parts = $this->getParts($line);
return $parts['scheme'] . $parts['host'] . $parts['port'];
} | Parse
@param string $line
@return string|false | entailment |
private function getParts($uri)
{
return ($parsed = parse_url($uri)) === false ? false : [
'scheme' => isset($parsed['scheme']) ? $parsed['scheme'] . '://' : '',
'host' => isset($parsed['host']) ? $parsed['host'] : $parsed['path'],
'port' => isset($parsed['port']) ? ':' . $parsed['port'] : '',
];
} | Get URI parts
@param string $uri
@return string[]|false | entailment |
public function code()
{
$code = $this->language()->code() . '_' . $this->territory()->code();
if ($this->script() != $this->language()->defaultScript()) {
$code .= '@' . strtolower($this->script()->unicodeName());
}
if ($this->variant() !== null) {
if ($this->variant()->code() === 'posix') {
$code = 'POSIX';
} else {
$code .= '@' . $this->variant()->code();
}
}
return $code;
} | Generate a linux locale code for this locale. Examples include
"fr", “en_GB”, “ca_ES@valencia” and “sr@latin”.
@return string | entailment |
public function htmlAttributes()
{
if ($this->direction() === 'rtl' || $this->direction() !== $this->script()->direction()) {
return 'lang="' . $this->languageTag() . '" dir="' . $this->direction() . '"';
} else {
return 'lang="' . $this->languageTag() . '"';
}
} | Markup for an HTML element
@return string e.g. lang="ar" dir="rtl" | entailment |
public function languageTag()
{
$language_tag = $this->language()->code();
if ($this->script() != $this->language()->defaultScript()) {
$language_tag .= '-' . $this->script()->code();
}
if ($this->territory() != $this->language()->defaultTerritory()) {
$language_tag .= '-' . $this->territory()->code();
}
if ($this->variant()) {
$language_tag .= '-' . $this->variant()->code();
}
return $language_tag;
} | The IETF language tag for the locale. Examples include
“fr, “en-GB”, “ca-ES-valencia” and “sr-Latn”.
@return string | entailment |
public function number($number)
{
if ($number < 0) {
$number = -$number;
$negative = self::NEGATIVE;
} else {
$negative = '';
}
$parts = explode(self::DECIMAL, (string) $number, 2);
$integers = $parts[0];
if (strlen($integers) >= $this->digitsFirstGroup() + $this->minimumGroupingDigits()) {
$todo = substr($integers, 0, -$this->digitsFirstGroup());
$integers = self::GROUP . substr($integers, -$this->digitsFirstGroup());
while (strlen($todo) >= $this->digitsGroup() + $this->minimumGroupingDigits()) {
$integers = self::GROUP . substr($todo, -$this->digitsGroup()) . $integers;
$todo = substr($todo, 0, -$this->digitsGroup());
}
$integers = $todo . $integers;
}
if (count($parts) > 1) {
$decimals = self::DECIMAL . $parts[1];
} else {
$decimals = '';
}
return $this->digits($negative . $integers . $decimals);
} | Convert (Hindu-Arabic) digits into a localized form
@param float $number The number to be localized
@return string | entailment |
public function parse( $rules ) {
if ( is_array( $rules ) ) {
return $this->parse_array_rules( $rules );
}
return $this->parse_string_rules( $rules );
} | Parse the rules into an array of rules.
@param string|array $rules The initial rules set.
@return array | entailment |
public function explode( $rules ) {
if ( empty( $rules ) ) {
return [];
}
foreach ( $rules as $key => $_rules ) {
$rules[ $key ] = $this->parse( $_rules );
}
return $rules;
} | Explode the rules into an array of rules.
@param array $rules initial rules set.
@return array | entailment |
public function normalize( $rule ) {
$rule = ucwords( str_replace( [ '-', '_' ], ' ', $rule ) );
$rule = lcfirst( str_replace( ' ', '', $rule ) );
switch ( $rule ) {
case 'creditcard':
return 'creditCard';
case 'int':
return 'integer';
case 'bool':
return 'boolean';
default:
return $rule;
}
} | Normalize a rule name.
@param string $rule Original rule name.
@return string | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.