sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
private function parseLink()
{
$value = $this->RAW();
if (!$value) {
return false;
}
$output = false;
if (preg_match(
'/(https?:\/\/)?(www\.)?(player\.)?vimeo\.com\/([a-z]*\/)*([0-9]{6,11})[?]?.*/i',
$value,
$matches
)) {
foreach ($matches as $match) {
if (preg_match('/^[0-9]{6,12}$/', $match)) {
$output = [
'VideoID' => $match,
'VideoService' => 'Vimeo',
];
}
}
} elseif (preg_match('/https?:\/\/youtu\.be\/([a-z0-9\_\-]+)/i', $value, $matches)) {
$output = [
'VideoID' => $matches[1],
'VideoService' => 'YouTube',
];
} elseif (preg_match('/youtu\.?be/i', $value)) {
$query_string = [];
parse_str(parse_url($value, PHP_URL_QUERY), $query_string);
if (!empty($query_string['v'])) {
$output = [
'VideoID' => $query_string['v'],
'VideoService' => 'YouTube',
];
}
}
return ($output) ? $output : false;
} | Parse video link
@param Null
@return Array|Null | entailment |
public function getParameterValue(\ReflectionParameter $parameter)
{
$class = $parameter->getClass();
if ($class && $class->getName() === Request::class) {
return $this->request;
}
return $this->fallbackResolver->getParameterValue($parameter);
} | {@inheritdoc} | entailment |
public function getPropertyValue(\ReflectionProperty $property)
{
$class = $this->reflectionTools->getPropertyClass($property);
if ($class === Request::class) {
return $this->request;
}
return $this->fallbackResolver->getPropertyValue($property);
} | {@inheritdoc} | entailment |
private function updateValue(): void
{
if ($this->forceEmpty) {
$this->value = "";
} else {
$this->value = $_POST[$this->name] ?? "";
}
} | Private method for updating the parameter's value. Checks if there is an entry in the $_POST superglobal.
If present, the entry is set as a value. Otherwise an empty string is used. If $forceEmpty is set to true the
value is always set as an empty string.
Be aware that no sanitation (htmlspecialchars, etc.) is performed on the values at this point. This is (expected
to be) done by the template engine in the View class. | entailment |
public function buildUrl(string $url, array $parameters = []) : string
{
if ($parameters) {
foreach ($parameters as $key => $value) {
if ($value === null) {
unset($parameters[$key]);
}
if (is_object($value)) {
$packedObject = $this->objectPacker->pack($value);
if ($packedObject === null) {
throw new \RuntimeException('Cannot pack object ' . get_class($value));
}
$parameters[$key] = $packedObject->getData();
}
}
}
$pos = strpos($url, '?');
if ($pos !== false) {
parse_str(substr($url, $pos + 1), $query);
$parameters += $query;
$url = substr($url, 0, $pos);
}
if ($parameters) {
return $url . '?' . http_build_query($parameters);
}
return $url;
} | Builds a URL with the given parameters.
If the URL already contains query parameters, they will be merged, the parameters passed to the method
having precedence over the original query parameters.
If any of the method parameters is an object, it will be replaced by its packed representation,
as provided by the ObjectPacker implementation.
@param string $url
@param array $parameters
@return string
@throws \RuntimeException If an unsupported object is given as a parameter. | entailment |
public function put(string $key, $value, float $minutes)
{
$this->storage[$key] = $value;
$this->ttl[$key] = $this->time() + 60 * $minutes;
} | Store an item in the cache for a given number of minutes.
@param string $key cache key of the item
@param mixed $value value being stored in cache
@param float $minutes cache ttl | entailment |
public function has(string $key): bool
{
if (array_key_exists($key, $this->ttl) &&
$this->time() - $this->ttl[$key] > 0
) {
unset($this->ttl[$key]);
unset($this->storage[$key]);
return false;
}
return array_key_exists($key, $this->storage);
} | Determine if an item exists in the cache. This method will also check
if the ttl of the given cache key has been expired and will free the
memory if so.
@param string $key cache key of the item
@return bool has cache key | entailment |
public function loadConfiguration(): void
{
if (!class_exists(Form::class)) {
throw new LogicalException(sprintf('Install nette/application to use %s factory', Form::class));
}
$builder = $this->getContainerBuilder();
$builder->addDefinition($this->prefix('factory'))
->setImplement(IApplicationFormFactory::class);
} | Register services | entailment |
public function getKey($key) {
$out = NULL;
if ($this->hasKey($key)) {
$out = $this->key[$key];
unset($this->key[$key]);
}
return $out;
} | get and clear a flash key, if it's existing
@param $key
@return mixed|null | entailment |
protected function findDefaultDatabase(string $connectionString)
{
preg_match('/\S+\/(\w*)/', $connectionString, $matches);
if ($matches[1] ?? null) {
$this->defaultDatabase = $matches[1];
}
} | Find and stores the default database in the connection string.
@param string $connectionString mongoDB connection string | entailment |
protected function contains($token)
{
return stripos($this->whois, sprintf($token, $this->domain)) !== false;
} | Checks if whois contains given token.
@param string $token
@return bool | entailment |
public function up()
{
$table_name = $this->getTableName();
Schema::create($table_name, function($table)
{
$table->increments('id');
});
DB::statement('ALTER TABLE `'.$table_name.'` ADD `file_object` LONGBLOB NOT NULL');
} | Run the migrations.
@return void | entailment |
public function getErrorName()
{
if (isset(self::$returnCodes[$this->returnCode])) {
return self::$returnCodes[$this->returnCode][0];
}
return 'Error '.$this->returnCode;
} | Returns a string representation of the returned error code.
@return int | entailment |
public function parseNumber()
{
$tel = [
'Original' => $this->value,
];
// remove brackets
$str = str_replace(['(', ')'], '', $this->value);
// replace characters with space
$str = trim(
preg_replace('/\s+/', ' ', preg_replace('/[^a-z0-9\#\+]/i', ' ', strtolower($str)))
);
// try detect if number starts with a + or international dialing code
if (preg_match('/^(\+\d{1,3}\b)/', $str, $matches)) {
$tel['CountryCode'] = substr($matches[1], 1);
$str = trim(substr($str, strlen($matches[0])));
} elseif (preg_match('/^(00|010|011|0011|810|0010|0011|0014)\s?(\d{1,3})\b/', $str, $matches)) {
$tel['CountryCode'] = $matches[2];
$str = trim(substr($str, strlen($matches[0])));
}
// try detect if an extension is included
if (preg_match('/(#|ext|extension)\s?(\d)+$/', $str, $matches)) {
$tel['Extension'] = $matches[2];
$str = trim(preg_replace('/' . preg_quote($matches[0], '/') . '$/', '', $str));
}
// set default country code if none detected
if (empty($tel['CountryCode'])) {
$tel['CountryCode'] = $this->config()->get('default_country_code');
}
// remove leading 0
if (substr($str, 0, 1) == '0') {
$str = trim(substr($str, 1));
}
// remaining number must contain at least 6 digits
if (preg_match('/[a-z]/', $str) || preg_match_all('/\d/', $str) < 6) {
return false;
}
// generate a RFC3966 link
$tel['RFC3966'] = 'tel:+' . $tel['CountryCode'] . '-' . preg_replace('/[^0-9]/', '-', $str);
if (!empty($tel['Extension'])) {
$tel['RFC3966'] .= ';ext=' . $tel['Extension'];
}
return $tel;
} | Basic phone parser
@param null
@return Array
Note that this is a very basic parser | entailment |
public function render() : string
{
$result = '';
foreach ($this->views as $view) {
$result .= $this->partial($view);
}
return $result;
} | {@inheritdoc} | entailment |
public function save($entity, array $options = [])
{
// If the "saving" event returns false we'll bail out of the save and return
// false, indicating that the save failed. This gives an opportunities to
// listeners to cancel save operations if validations fail or whatever.
if (false === $this->fireEvent('saving', $entity, true)) {
return false;
}
$data = $this->parseToDocument($entity);
$queryResult = $this->getCollection()->replaceOne(
['_id' => $data['_id']],
$data,
$this->mergeOptions($options, ['upsert' => true])
);
$result = $queryResult->isAcknowledged() &&
($queryResult->getModifiedCount() || $queryResult->getUpsertedCount());
if ($result) {
$this->afterSuccess($entity);
$this->fireEvent('saved', $entity);
}
return $result;
} | Upserts the given object into database. Returns success if write concern
is acknowledged.
Notice: Saves with Unacknowledged WriteConcern will not fire `saved` event.
@param mixed $entity the entity used in the operation
@param array $options possible options to send to mongo driver
@return bool Success (but always false if write concern is Unacknowledged) | entailment |
public function insert($entity, array $options = [], bool $fireEvents = true): bool
{
if ($fireEvents && false === $this->fireEvent('inserting', $entity, true)) {
return false;
}
$data = $this->parseToDocument($entity);
$queryResult = $this->getCollection()->insertOne(
$data,
$this->mergeOptions($options)
);
$result = $queryResult->isAcknowledged() && $queryResult->getInsertedCount();
if ($result) {
$this->afterSuccess($entity);
if ($fireEvents) {
$this->fireEvent('inserted', $entity);
}
}
return $result;
} | Inserts the given object into database. Returns success if write concern
is acknowledged. Since it's an insert, it will fail if the _id already
exists.
Notice: Inserts with Unacknowledged WriteConcern will not fire `inserted` event.
@param mixed $entity the entity used in the operation
@param array $options possible options to send to mongo driver
@param bool $fireEvents whether events should be fired
@return bool Success (but always false if write concern is Unacknowledged) | entailment |
public function update($entity, array $options = []): bool
{
if (false === $this->fireEvent('updating', $entity, true)) {
return false;
}
if (!$entity->_id) {
if ($result = $this->insert($entity, $options, false)) {
$this->afterSuccess($entity);
$this->fireEvent('updated', $entity);
}
return $result;
}
$data = $this->parseToDocument($entity);
$queryResult = $this->getCollection()->updateOne(
['_id' => $data['_id']],
['$set' => $data],
$this->mergeOptions($options)
);
$result = $queryResult->isAcknowledged() && $queryResult->getModifiedCount();
if ($result) {
$this->afterSuccess($entity);
$this->fireEvent('updated', $entity);
}
return $result;
} | Updates the given object into database. Returns success if write concern
is acknowledged. Since it's an update, it will fail if the document with
the given _id did not exists.
Notice: Updates with Unacknowledged WriteConcern will not fire `updated` event.
@param mixed $entity the entity used in the operation
@param array $options possible options to send to mongo driver
@return bool Success (but always false if write concern is Unacknowledged) | entailment |
public function delete($entity, array $options = []): bool
{
if (false === $this->fireEvent('deleting', $entity, true)) {
return false;
}
$data = $this->parseToDocument($entity);
$queryResult = $this->getCollection()->deleteOne(
['_id' => $data['_id']],
$this->mergeOptions($options)
);
if ($queryResult->isAcknowledged() &&
$queryResult->getDeletedCount()
) {
$this->fireEvent('deleted', $entity);
return true;
}
return false;
} | Removes the given document from the collection.
Notice: Deletes with Unacknowledged WriteConcern will not fire `deleted` event.
@param mixed $entity the entity used in the operation
@param array $options possible options to send to mongo driver
@return bool Success (but always false if write concern is Unacknowledged) | entailment |
public function where(
$query = [],
array $projection = [],
bool $cacheable = false
): Cursor {
$cursorClass = $cacheable ? CacheableCursor::class : Cursor::class;
$cursor = new $cursorClass(
$this->schema,
$this->getCollection(),
'find',
[
$this->prepareValueQuery($query),
['projection' => $this->prepareProjection($projection)],
]
);
return $cursor;
} | Retrieve a database cursor that will return $this->schema->entityClass
objects that upon iteration.
@param mixed $query mongoDB query to retrieve documents
@param array $projection fields to project in Mongo query
@param bool $cacheable retrieves a CacheableCursor instead
@return \Mongolid\Cursor\Cursor | entailment |
public function first(
$query = [],
array $projection = [],
bool $cacheable = false
) {
if ($cacheable) {
return $this->where($query, $projection, true)->first();
}
$document = $this->getCollection()->findOne(
$this->prepareValueQuery($query),
['projection' => $this->prepareProjection($projection)]
);
if (!$document) {
return;
}
$model = $this->getAssembler()->assemble($document, $this->schema);
return $model;
} | Retrieve one $this->schema->entityClass objects that matches the given
query.
@param mixed $query mongoDB query to retrieve the document
@param array $projection fields to project in Mongo query
@param bool $cacheable retrieves the first through a CacheableCursor
@return mixed First document matching query as an $this->schema->entityClass object | entailment |
public function firstOrFail(
$query = [],
array $projection = [],
bool $cacheable = false
) {
if ($result = $this->first($query, $projection, $cacheable)) {
return $result;
}
throw (new ModelNotFoundException())->setModel($this->schema->entityClass);
} | Retrieve one $this->schema->entityClass objects that matches the given
query. If no document was found, throws ModelNotFoundException.
@param mixed $query mongoDB query to retrieve the document
@param array $projection fields to project in Mongo query
@param bool $cacheable retrieves the first through a CacheableCursor
@throws ModelNotFoundException if no document was found
@return mixed First document matching query as an $this->schema->entityClass object | entailment |
protected function parseToDocument($entity)
{
$schemaMapper = $this->getSchemaMapper();
$parsedDocument = $schemaMapper->map($entity);
if (is_object($entity)) {
foreach ($parsedDocument as $field => $value) {
$entity->$field = $value;
}
}
return $parsedDocument;
} | Parses an object with SchemaMapper and the given Schema.
@param mixed $entity the object to be parsed
@return array Document | entailment |
protected function getSchemaMapper()
{
if (!$this->schema) {
$this->schema = Ioc::make($this->schemaClass);
}
return Ioc::makeWith(SchemaMapper::class, ['schema' => $this->schema]);
} | Returns a SchemaMapper with the $schema or $schemaClass instance.
@return SchemaMapper | entailment |
protected function getCollection(): Collection
{
$conn = $this->connPool->getConnection();
$database = $conn->defaultDatabase;
$collection = $this->schema->collection;
return $conn->getRawConnection()->$database->$collection;
} | Retrieves the Collection object.
@return Collection | entailment |
protected function prepareValueQuery($value): array
{
if (!is_array($value)) {
$value = ['_id' => $value];
}
if (isset($value['_id']) &&
is_string($value['_id']) &&
ObjectIdUtils::isObjectId($value['_id'])
) {
$value['_id'] = new ObjectId($value['_id']);
}
if (isset($value['_id']) &&
is_array($value['_id'])
) {
$value['_id'] = $this->prepareArrayFieldOfQuery($value['_id']);
}
return $value;
} | Transforms a value that is not an array into an MongoDB query (array).
This method will take care of converting a single value into a query for
an _id, including when a objectId is passed as a string.
@param mixed $value the _id of the document
@return array Query for the given _id | entailment |
protected function prepareArrayFieldOfQuery(array $value): array
{
foreach (['$in', '$nin'] as $operator) {
if (isset($value[$operator]) &&
is_array($value[$operator])
) {
foreach ($value[$operator] as $index => $id) {
if (ObjectIdUtils::isObjectId($id)) {
$value[$operator][$index] = new ObjectId($id);
}
}
}
}
return $value;
} | Prepares an embedded array of an query. It will convert string ObjectIds
in operators into actual objects.
@param array $value array that will be treated
@return array prepared array | entailment |
protected function getAssembler()
{
if (!$this->assembler) {
$this->assembler = Ioc::make(EntityAssembler::class);
}
return $this->assembler;
} | Retrieves an EntityAssembler instance.
@return EntityAssembler | entailment |
protected function fireEvent(string $event, $entity, bool $halt = false)
{
$event = "mongolid.{$event}: ".get_class($entity);
$this->eventService ? $this->eventService : $this->eventService = Ioc::make(EventTriggerService::class);
return $this->eventService->fire($event, $entity, $halt);
} | Triggers an event. May return if that event had success.
@param string $event identification of the event
@param mixed $entity event payload
@param bool $halt true if the return of the event handler will be used in a conditional
@return mixed event handler return | entailment |
protected function prepareProjection(array $fields)
{
$projection = [];
foreach ($fields as $key => $value) {
if (is_string($key)) {
if (is_bool($value)) {
$projection[$key] = $value;
continue;
}
if (is_int($value)) {
$projection[$key] = ($value >= 1);
continue;
}
}
if (is_int($key) && is_string($value)) {
$key = $value;
if (0 === strpos($value, '-')) {
$key = substr($key, 1);
$value = false;
} else {
$value = true;
}
$projection[$key] = $value;
continue;
}
throw new InvalidArgumentException(
sprintf(
"Invalid projection: '%s' => '%s'",
$key,
$value
)
);
}
return $projection;
} | Converts the given projection fields to Mongo driver format.
How to use:
As Mongo projection using boolean values:
From: ['name' => true, '_id' => false]
To: ['name' => true, '_id' => false]
As Mongo projection using integer values
From: ['name' => 1, '_id' => -1]
To: ['name' => true, '_id' => false]
As an array of string:
From: ['name', '_id']
To: ['name' => true, '_id' => true]
As an array of string to exclude some fields:
From: ['name', '-_id']
To: ['name' => true, '_id' => false]
@param array $fields fields to project
@throws InvalidArgumentException if the given $fields are not a valid projection
@return array | entailment |
public function check($domain)
{
return $this->client
->query($domain)
->then(function ($result) use ($domain) {
return Factory::create($domain, $result)->isAvailable();
});
} | Checks domain availability.
@param string $domain | entailment |
public function checkAll(array $domains)
{
return When::map($domains, array($this, 'check'))
->then(function ($statuses) use ($domains) {
ksort($statuses);
return array_combine($domains, $statuses);
});
} | Checks domain availability of multiple domains.
@param array $domains | entailment |
public static function convert($path, &$keys = array(), $options = array()) {
$strict = is_array($options) && array_key_exists("strict", $options) ? $options["strict"] : false;
$end = is_array($options) && array_key_exists("end", $options) ? $options["end"] : true;
$flags = is_array($options) && !empty($options["sensitive"]) ? "" : "i";
$index = 0;
if(is_array($path)) {
// Map array parts into regexps and return their source. We also pass
// the same keys and options instance into every generation to get
// consistent matching groups before we join the sources together.
$path = array_map(function($value) use(&$keys, &$options) {
return self::getRegexpSource(self::convert($value, $keys, $options));
}, $path);
// Generate a new regexp instance by joining all the parts together.
return '/(?:' . implode("|", $path) . ')/' . $flags;
}
$pathRegexps = array(
// Match already escaped characters that would otherwise incorrectly appear
// in future matches. This allows the user to escape special characters that
// shouldn't be transformed.
'(\\\\.)',
// Match Express-style parameters and un-named parameters with a prefix
// and optional suffixes. Matches appear as:
//
// "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?"]
// "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined]
'([\\/.])?(?:\\:(\\w+)(?:\\(((?:\\\\.|[^)])*)\\))?|\\(((?:\\\\.|[^)])*)\\))([+*?])?',
// Match regexp special characters that should always be escaped.
'([.+*?=^!:${}()[\\]|\\/])'
);
$pathRegexp = "/" . implode("|", $pathRegexps) . "/";
// Alter the path string into a usable regexp.
$path = preg_replace_callback($pathRegexp, function($matches) use(&$keys, &$index) {
if(count($matches) > 1) {
$escaped = $matches[1];
}
if(count($matches) > 2) {
$prefix = $matches[2];
}
if(count($matches) > 3) {
$key = $matches[3];
}
if(count($matches) > 4) {
$capture = $matches[4];
}
if(count($matches) > 5) {
$group = $matches[5];
}
if(count($matches) > 6) {
$suffix = $matches[6];
} else {
$suffix = "";
}
if(count($matches) > 7) {
$escape = $matches[7];
}
// Avoiding re-escaping escaped characters.
if(!empty($escaped)) {
return $escaped;
}
// Escape regexp special characters.
if(!empty($escape)) {
return '\\' . $escape;
}
$repeat = $suffix === '+' || $suffix === '*';
$optional = $suffix === '?' || $suffix === '*';
array_push($keys, array(
"name" => (string) (!empty($key) ? $key : $index++),
"delimiter" => !empty($prefix) ? $prefix : '/',
"optional" => $optional,
"repeat" => $repeat
));
// Escape the prefix character.
$prefix = !empty($prefix) ? '\\' . $prefix : '';
// Match using the custom capturing group, or fallback to capturing
// everything up to the next slash (or next period if the param was
// prefixed with a period).
$subject = (!empty($capture) ? $capture : (!empty($group) ? $group : '[^' . (!empty($prefix) ? $prefix : '\\/') . ']+?'));
$capture = preg_replace('/([=!:$\/()])/', '\1', $subject);
// Allow parameters to be repeated more than once.
if(!empty($repeat)) {
$capture = $capture . '(?:' . $prefix . $capture . ')*';
}
// Allow a parameter to be optional.
if(!empty($optional)) {
return '(?:' . $prefix . '(' . $capture . '))?';
}
// Basic parameter support.
return $prefix . '(' . $capture . ')';
}, $path);
// Check whether the path ends in a slash as it alters some match behaviour.
$endsWithSlash = substr($path, -1, 1) === "/";
// In non-strict mode we allow an optional trailing slash in the match. If
// the path to match already ended with a slash, we need to remove it for
// consistency. The slash is only valid at the very end of a path match, not
// anywhere in the middle. This is important for non-ending mode, otherwise
// "/test/" will match "/test//route".
if(!$strict) {
$path = ($endsWithSlash ? substr($path, 0, -2) : $path) . '(?:\\/(?=$))?';
}
// In non-ending mode, we need prompt the capturing groups to match as much
// as possible by using a positive lookahead for the end or next path segment.
if(!$end) {
$path .= $strict && $endsWithSlash ? '' : '(?=\\/|$)';
}
return '/^' . $path . ($end ? '$' : '') . '/' . $flags;
} | Normalize the given path string, returning a regular expression.
An empty array should be passed in, which will contain the placeholder key
names. For example `/user/:id` will then contain `["id"]`.
@param {(String)} path
@param {Array} keys
@param {Object} options
@return {RegExp} | entailment |
public function getData()
{
$this->validate('checkoutId', 'amount', 'currency', 'description', 'transactionId');
$return = [
'ik_co_id' => $this->getCheckoutId(),
'ik_am' => $this->getAmount(),
'ik_pm_no' => $this->getTransactionId(),
'ik_desc' => $this->getDescription(),
'ik_cur' => $this->getCurrency(),
];
if ($ik_pnd_u = $this->getReturnUrl()) {
$return['ik_pnd_u'] = $ik_pnd_u;
if ($ik_pnd_m = $this->getReturnMethod()) {
$return['ik_pnd_m'] = $ik_pnd_m;
}
}
if ($ik_suc_u = $this->getReturnUrl()) {
$return['ik_suc_u'] = $ik_suc_u;
if ($ik_suc_m = $this->getReturnMethod()) {
$return['ik_suc_m'] = $ik_suc_m;
}
}
if ($ik_fal_u = $this->getCancelUrl()) {
$return['ik_fal_u'] = $ik_fal_u;
if ($ik_fal_m = $this->getCancelMethod()) {
$return['ik_fal_m'] = $ik_fal_m;
}
}
if ($ik_ia_u = $this->getNotifyUrl()) {
$return['ik_ia_u'] = $ik_ia_u;
if ($ik_ia_m = $this->getNotifyMethod()) {
$return['ik_ia_m'] = $ik_ia_m;
}
}
if ($signKey = $this->getSignKey()) {
$return['ik_sign'] = $this->calculateSign($return, $signKey);
}
return $return;
} | {@inheritdoc} | entailment |
public function parse($content)
{
$this->parser
->setSafeMode(config('markdown.safe-mode', false))
->setUrlsLinked(config('markdown.urls', true))
->setMarkupEscaped(config('markdown.markups', true));
if (config('markdown.xss', true)) {
$content = preg_replace('/(\[.*\])\(javascript:.*\)/', '$1(#)', $content);
}
return $this->parser->text($content);
} | Parses a markdown string to HTML.
@param string $content
@return string | entailment |
public function end()
{
if ($this->buffering === false) {
throw new ParserBufferingException('Markdown buffering have not been started.');
}
$markdown = ob_get_clean();
$this->buffering = false;
return $this->parse($markdown);
} | Stop buffering output & return the parsed markdown string.
@return string
@throws \Arcanedev\LaravelMarkdown\Exceptions\ParserBufferingException | entailment |
public function run($name)
{
$fileName = sprintf('%s_%s.sql',
date('Ymd_His'),
trim($name)
);
$migration = new Migration(null, $fileName);
$migration->setSql(Migration::TAG_TRANSACTION . PHP_EOL
. Migration::TAG_UP . PHP_EOL
. PHP_EOL
. Migration::TAG_DOWN . PHP_EOL
. PHP_EOL
);
$this->repository->insert($migration);
return $fileName;
} | Run
@param string $name
@return string - Название файла Миграции | entailment |
private function registerBladeDirectives()
{
/** @var \Illuminate\View\Compilers\BladeCompiler $blade */
$blade = $this->app['view']->getEngineResolver()->resolve('blade')->getCompiler();
$blade->directive('parsedown', function ($markdown) {
return "<?php echo markdown()->parse($markdown); ?>";
});
$blade->directive('markdown', function () {
return '<?php markdown()->begin(); ?>';
});
$blade->directive('endmarkdown', function () {
return '<?php echo markdown()->end(); ?>';
});
} | Register Blade directives. | entailment |
protected static function bootLogsActivity()
{
self::created(function ($model) {
if (auth()->check()
&& collect($model->getLoggedEvents())->contains('created')) {
(new Logger($model))->onCreated();
}
});
self::updated(function ($model) {
if (auth()->check()
&& collect($model->getLoggedEvents())->contains('updated')) {
(new Logger($model))->onUpdated();
}
});
self::deleted(function ($model) {
if (auth()->check()
&& collect($model->getLoggedEvents())->contains('deleted')) {
(new Logger($model))->onDeleted();
}
});
} | protected $loggedEvents = ['created'] // optional, default ['created', 'updated', 'deleted']; | entailment |
public function setEventLayout($flag, $value, array $layout)
{
$value = (string) $value;
$this->eventLayout[$flag][$value] = $layout;
} | @link http://www.graphviz.org/doc/info/attrs.html
@param string $flag
@param scalar $value
@param array $layout | entailment |
public function setStateLayout($flag, $value, array $layout)
{
$value = (string) $value;
$this->stateLayout[$flag][$value] = $layout;
} | @link http://www.graphviz.org/doc/info/attrs.html
@param string $flag
@param scalar $value
@param array $layout | entailment |
protected function getLayoutOptions(\ArrayAccess $flaggedObject, array $layout)
{
$result = array();
foreach ($layout as $flag => $options) {
if ($flaggedObject->offsetExists($flag)) {
$value = $flaggedObject->offsetGet($flag);
$value = (string) $value;
if (isset($options[$value])) {
$result += $options[$value];
}
}
}
/* @var $callback callable */
foreach ($this->layoutCallback as $callback) {
$result = $callback($flaggedObject, $result);
}
return $result;
} | @param \ArrayAccess $flaggedObject
@param array $layout
@return array | entailment |
public function createStatusVertex(StateInterface $state)
{
$stateName = $state->getName();
$vertex = $this->graph->createVertex($stateName, true);
if ($state instanceof \ArrayAccess) {
$layout = $this->getLayoutOptions($state, $this->stateLayout);
if (method_exists($vertex, 'setLayout')) {
$vertex->setLayout($layout);
} else {
foreach ($layout as $name => $value) {
$vertex->setAttribute('graphviz.' . $name, $value);
}
}
}
return $vertex;
} | @param StateInterface $state
@return \Fhaculty\Graph\Vertex | entailment |
protected function convertObserverToString(EventInterface $event)
{
$observers = array();
foreach ($event->getObservers() as $observer) {
$observers[] = $this->stringConverter->convertToString($observer);
}
return implode(', ', $observers);
} | @param EventInterface $event
@return string | entailment |
protected function getTransitionLabel(StateInterface $state, TransitionInterface $transition)
{
$labelParts = array();
$eventName = $transition->getEventName();
if ($eventName) {
$labelParts[] = 'E: ' . $eventName;
$event = $state->getEvent($eventName);
$observerName = $this->convertObserverToString($event);
if ($observerName) {
$labelParts[] = 'C: ' . $observerName;
}
}
$conditionName = $transition->getConditionName();
if ($conditionName) {
$labelParts[] = 'IF: ' . $conditionName;
}
if ($transition instanceof WeightedInterface) {
$labelParts[] = 'W: ' . $transition->getWeight();
}
$label = implode(PHP_EOL, $labelParts);
return $label;
} | @param TransitionInterface $transition
@return string | entailment |
public function pack($object) : ?PackedObject
{
if ($object instanceof Duration) {
return new PackedObject(Duration::class, (string) $object);
}
if ($object instanceof LocalDate) {
return new PackedObject(LocalDate::class, (string) $object);
}
if ($object instanceof LocalTime) {
return new PackedObject(LocalTime::class, (string) $object);
}
if ($object instanceof LocalDateTime) {
return new PackedObject(LocalDateTime::class, (string) $object);
}
if ($object instanceof TimeZoneOffset) {
return new PackedObject(TimeZoneOffset::class, (string) $object);
}
if ($object instanceof TimeZoneRegion) {
return new PackedObject(TimeZoneRegion::class, (string) $object);
}
if ($object instanceof YearMonth) {
return new PackedObject(YearMonth::class, (string) $object);
}
if ($object instanceof ZonedDateTime) {
return new PackedObject(ZonedDateTime::class, (string) $object);
}
return null;
} | {@inheritdoc} | entailment |
public function unpack(PackedObject $packedObject)
{
$class = $packedObject->getClass();
$data = $packedObject->getData();
try {
switch ($class) {
case Duration::class:
return Duration::parse($data);
case LocalDate::class:
return LocalDate::parse($data);
case LocalTime::class:
return LocalTime::parse($data);
case LocalDateTime::class:
return LocalDateTime::parse($data);
case TimeZoneOffset::class:
return TimeZoneOffset::parse($data);
case TimeZoneRegion::class:
return TimeZoneRegion::parse($data);
case YearMonth::class:
return YearMonth::parse($data);
case ZonedDateTime::class:
return ZonedDateTime::parse($data);
}
} catch (DateTimeParseException $e) {
throw new Exception\ObjectNotConvertibleException($e->getMessage(), 0, $e);
}
return null;
} | {@inheritdoc} | entailment |
protected function referencesOne(string $entity, string $field, bool $cacheable = true)
{
$referenced_id = $this->$field;
if (is_array($referenced_id) && isset($referenced_id[0])) {
$referenced_id = $referenced_id[0];
}
$entityInstance = Ioc::make($entity);
if ($entityInstance instanceof Schema) {
$dataMapper = Ioc::make(DataMapper::class);
$dataMapper->setSchema($entityInstance);
return $dataMapper->first(['_id' => $referenced_id], [], $cacheable);
}
return $entityInstance::first(['_id' => $referenced_id], [], $cacheable);
} | Returns the referenced documents as objects.
@param string $entity class of the entity or of the schema of the entity
@param string $field the field where the _id is stored
@param bool $cacheable retrieves a CacheableCursor instead
@return mixed | entailment |
protected function referencesMany(string $entity, string $field, bool $cacheable = true)
{
$referencedIds = (array) $this->$field;
if (ObjectIdUtils::isObjectId($referencedIds[0] ?? '')) {
foreach ($referencedIds as $key => $value) {
$referencedIds[$key] = new ObjectId($value);
}
}
$query = ['_id' => ['$in' => array_values($referencedIds)]];
$entityInstance = Ioc::make($entity);
if ($entityInstance instanceof Schema) {
$dataMapper = Ioc::make(DataMapper::class);
$dataMapper->setSchema($entityInstance);
return $dataMapper->where($query, [], $cacheable);
}
return $entityInstance::where($query, [], $cacheable);
} | Returns the cursor for the referenced documents as objects.
@param string $entity class of the entity or of the schema of the entity
@param string $field the field where the _ids are stored
@param bool $cacheable retrieves a CacheableCursor instead
@return array | entailment |
protected function embedsOne(string $entity, string $field)
{
if (is_subclass_of($entity, Schema::class)) {
$entity = (new $entity())->entityClass;
}
$items = (array) $this->$field;
if (false === empty($items) && false === array_key_exists(0, $items)) {
$items = [$items];
}
return Ioc::make(CursorFactory::class)
->createEmbeddedCursor($entity, $items)->first();
} | Return a embedded documents as object.
@param string $entity class of the entity or of the schema of the entity
@param string $field field where the embedded document is stored
@return Model|null | entailment |
public function unembed(string $field, &$obj)
{
$embedder = Ioc::make(DocumentEmbedder::class);
$embedder->unembed($this, $field, $obj);
} | Removes an embedded document from the given field. It does that by using
the _id of the given $obj.
@param string $field name of the field where the $obj is embeded
@param mixed $obj document, model instance or _id | entailment |
public function register(EventDispatcher $dispatcher) : void
{
$dispatcher->addListener(RouteMatchedEvent::class, function(RouteMatchedEvent $event) {
$controller = $event->getRouteMatch()->getControllerReflection();
$request = $event->getRequest();
$secure = $this->hasControllerAnnotation($controller, Secure::class);
if ($secure && ! $request->isSecure()) {
$url = preg_replace('/^http/', 'https', $request->getUrl());
throw new HttpRedirectException($url, 301);
}
});
$dispatcher->addListener(ResponseReceivedEvent::class, function (ResponseReceivedEvent $event) {
$controller = $event->getRouteMatch()->getControllerReflection();
/** @var Secure|null $secure */
$secure = $this->getControllerAnnotation($controller, Secure::class);
if ($secure && $secure->hsts !== null && $event->getRequest()->isSecure()) {
$event->getResponse()->setHeader('Strict-Transport-Security', $secure->hsts);
}
});
} | {@inheritdoc} | entailment |
public function getData()
{
$this->validate('checkoutId', 'amount', 'currency', 'description', 'transactionId');
$return = [
'ik_shop_id' => $this->getCheckoutId(),
'ik_payment_amount' => $this->getAmount(),
'ik_payment_id' => $this->getTransactionId(),
'ik_payment_desc' => $this->getDescription(),
];
if ($ik_success_url = $this->getReturnUrl()) {
$return['ik_success_url'] = $ik_success_url;
$return['ik_success_method'] = $this->getReturnMethod();
}
if ($ik_fail_method = $this->getCancelUrl()) {
$return['ik_fail_url'] = $ik_fail_method;
$return['ik_fail_method'] = $this->getCancelMethod();
}
if ($ik_status_url = $this->getNotifyUrl()) {
$return['ik_status_url'] = $ik_status_url;
$return['ik_status_method'] = $this->getNotifyMethod();
}
return $return;
} | {@inheritdoc} | entailment |
public function validate(NavitiaConfigurationInterface $config)
{
$required = $config::getRequiredProperties();
foreach ($required as $property => $getter) {
if (is_null($config->$getter())) {
throw new BadParametersException(
sprintf(
'The configuration parameter "%s" is required',
$property
)
);
}
}
return true;
} | {@inheritDoc} | entailment |
public function render(Form $form, $mode = null): string
{
$usedPrimary = false;
$form->getElementPrototype()->setNovalidate(true);
foreach ($form->getControls() as $control) {
if ($control instanceof Controls\BaseControl
&& !($control instanceof Controls\Checkbox)
&& !($control instanceof Controls\CheckboxList)
&& !($control instanceof Controls\RadioList)) {
$control->getLabelPrototype()->addClass('col-form-label col col-sm-3');
}
switch (true) {
case $control instanceof Controls\Button:
/** @var string|null $class */
$class = $control->getControlPrototype()->getAttribute('class');
if ($class === null || mb_strpos($class, 'btn') === false) {
$control->getControlPrototype()->addClass($usedPrimary === false ? 'btn btn-primary' : 'btn btn-secondary');
$usedPrimary = true;
}
break;
case $control instanceof Controls\TextBase:
case $control instanceof Controls\SelectBox:
case $control instanceof Controls\MultiSelectBox:
$control->getControlPrototype()->addClass('form-control');
break;
case $control instanceof Controls\Checkbox:
case $control instanceof Controls\CheckboxList:
case $control instanceof Controls\RadioList:
$control->getSeparatorPrototype()->setName('div')->addClass('form-check');
$control->getControlPrototype()->addClass('form-check-input');
$control->getLabelPrototype()->addClass('form-check-label');
break;
}
}
return parent::render($form, $mode);
} | Provides complete form rendering.
@param string|null $mode 'begin', 'errors', 'ownerrors', 'body', 'end' or empty to render all
@phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingParameterTypeHint | entailment |
private function renderErrors(Base $base) : string
{
if (! $base->hasErrors()) {
return '';
}
$html = '';
foreach ($base->getErrors() as $error) {
$li = new Tag('li');
$li->setTextContent($error);
$html .= $li->render();
}
$ul = new Tag('ul');
$ul->setHtmlContent($html);
return $ul->render();
} | Renders the errors of a Form or an Element as an unordered list.
@param \Brick\Form\Base $base
@return string | entailment |
private function renderElement(Element $element) : string
{
$label = $element->getLabel();
if ($label->isEmpty()) {
return $element->render();
}
return $label->render() . $element->render();
} | Renders an element, along with its label.
@param \Brick\Form\Element $element
@return string | entailment |
private function renderForm(Form $form) : string
{
$html = '';
foreach ($form->getComponents() as $component) {
$html .= $this->renderErrors($component);
if ($component instanceof Element) {
$html .= $this->renderElement($component);
} elseif ($component instanceof Group) {
foreach ($component->getElements() as $element) {
$html .= $this->renderElement($element);
}
}
}
return $html;
} | @param \Brick\Form\Form $form
@return string | entailment |
public function render() : string
{
return
$this->renderErrors($this->form) .
$this->form->open() .
$this->renderForm($this->form) .
$this->form->close();
} | {@inheritdoc} | entailment |
public function reduce( $p, $r )
{
$p = (double)$p;
$r = (double)$r;
$key = 0;
while ( $key < $this->lastKey(-3) ) {
$out = $key + 2;
while (
$out < $this->lastKey()
&& $this->_shortest($out, $key) < $p
&& $this->_distance($out, $key) < $r
) {
$out++;
}
for ( $i = $key+1, $l = $out - 1; $i < $l; $i++ ) {
unset($this->points[$i]);
}
$this->reindex();
$key++;
}
return $this->points;
} | Reduce points with Opheim algorithm.
@param double $p Defined Perpendicular tolerance
@param double $r Defined Radial tolerance
@return array Reduced set of points | entailment |
private function _distance( $out, $key )
{
return $this->distanceBetweenPoints(
$this->points[$out],
$this->points[$key]
);
} | Short-cut function for distanceBetweenPoints method
@param integer $out Test point-index
@param integer $key Index point-index (what???)
@return double | entailment |
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('dcs_rating');
$rootNode
->children()
->scalarNode('db_driver')->isRequired()->end()
->scalarNode('base_security_role')->defaultValue('IS_AUTHENTICATED_FULLY')->end()
->scalarNode('base_path_to_redirect')->defaultValue('/')->end()
->booleanNode('unique_vote')->defaultTrue()->end()
->integerNode('max_value')->cannotBeEmpty()->defaultValue(5)->end()
->end()
->append($this->buildModelConfiguration())
->append($this->buildServiceConfiguration())
;
return $treeBuilder;
} | {@inheritDoc} | entailment |
public function updateOne(
$filter,
array $dataToSet,
array $options = ['upsert' => true],
string $operator = '$set'
) {
$filter = is_array($filter) ? $filter : ['_id' => $filter];
return $this->getBulkWrite()->update(
$filter,
[$operator => $dataToSet],
$options
);
} | Add an `update` operation to the Bulk, where only one record is updated, by `_id` or `query`.
Be aware that working with multiple levels of nesting on `$dataToSet` may have
an undesired behavior that could lead to data loss on a specific key.
@see https://docs.mongodb.com/manual/reference/operator/update/set/#set-top-level-fields
@param ObjectId|string|array $id
@param array $dataToSet
@param array $options
@param string $operator | entailment |
public function execute($writeConcern = 1)
{
$connection = Ioc::make(Pool::class)->getConnection();
$manager = $connection->getRawManager();
$namespace = $connection->defaultDatabase.'.'.$this->schema->collection;
return $manager->executeBulkWrite(
$namespace,
$this->getBulkWrite(),
['writeConcern' => new WriteConcern($writeConcern)]
);
} | Execute the BulkWrite, using a connection from the Pool.
The collection is inferred from entity's collection name.
@param int $writeConcern
@return \MongoDB\Driver\WriteResult | entailment |
public function push($data)
{
$this->buffer->write($data);
$result = [];
while ($this->buffer->getRemainingBytes() > 0) {
$type = $this->buffer->readByte() >> 4;
try {
$packet = $this->factory->build($type);
} catch (UnknownPacketTypeException $e) {
$this->handleError($e);
continue;
}
$this->buffer->seek(-1);
$position = $this->buffer->getPosition();
try {
$packet->read($this->buffer);
$result[] = $packet;
$this->buffer->cut();
} catch (EndOfStreamException $e) {
$this->buffer->setPosition($position);
break;
} catch (MalformedPacketException $e) {
$this->handleError($e);
}
}
return $result;
} | Appends the given data to the internal buffer and parses it.
@param string $data
@return Packet[] | entailment |
private function handleError($exception)
{
if ($this->errorCallback !== null) {
$callback = $this->errorCallback;
$callback($exception);
}
} | Executes the registered error callback.
@param \Throwable $exception | entailment |
public function transform($request, $params)
{
$params = ltrim($params, "?");
$actionParameters = explode("&", $params);
foreach ($actionParameters as $parameters) {
$parameter = explode("=", $parameters);
$property = Utils::deleteUnderscore($parameter[0]);
$setter = 'set'.ucfirst($property);
if (method_exists($request, $setter)) {
$request->$setter($parameter[1]);
} else {
throw new NavitiaCreationException(
sprintf(
'Neither property "%s" nor method "%s"'.
'nor method "%s" exist.',
$property,
'get'.ucfirst($property),
$setter
)
);
}
}
return $request;
} | {@inheritDoc} | entailment |
final public function partial(View $view) : string
{
if ($this->injector) {
$this->injector->inject($view);
}
return $view->render();
} | Renders a partial View.
@param \Brick\App\View\View $view The View object to render.
@return string The rendered View. | entailment |
final public function buildUrl(string $url, array $parameters = []) : string
{
if (! $this->builder) {
throw new \RuntimeException('No URL builder has been registered');
}
return $this->builder->buildUrl($url, $parameters);
} | @param string $url
@param array $parameters
@return string
@throws \RuntimeException | entailment |
protected function printFormNew(){
$prev_data = Session::get($this->exchange_key);
$str = parent::printFormNew();
$str.= "<h3>Step2: fill save settings</h3>".
$prev_data["preview"];
// config form
$str.="<h4>Fill the form below:</h4>";
$str.= Form::open(array( 'url' => $this->getProcessUrl(), "role" => "form", "class" => "form-horizontal") );
$str.= "<h5>Write the name of each column to export (\"__empty\"=don't export)</h5>";
$columns = $prev_data["column_names"];
foreach( $columns as $key => $column)
{
$str.= "<div class=\"form-group\">".
Form::label("{$column}", "{$column}: ", array("class"=>"control-label col-lg-2")).
"<div class=\"col-lg-10\">".
Form::text("{$column}", $column ,array("class"=>"form-control") ).
"</div>".
"</div>";
}
$str.= "<div class=\"form-group\">".
"<div class=\"col-lg-offset-2 col-lg-10\">".
Form::submit('Export' , array('class'=>'btn btn-success') ).
"</div>".
"</div>";
$str.= Form::close();
return $str;
} | Return the form that needs to be processed | entailment |
public function processForm(array $input = null, $validator = null, CsvFileHandler $handler = null)
{
if($input)
{
$this->form_input = $input;
}
else
{
$this->fillFormInput();
}
$validator = ($validator) ? $validator : new ValidatorFormInputModel($this);
$handler = $handler ? $handler : new CsvFileHandler();
if ( $validator->validateInput() )
{
$builder_config = array(
"columns" => $this->form_input["attributes"],
"table" => $this->form_input["table_name"],
);
try
{
$handler->openFromDb($builder_config);
}
catch(\PDOException $e)
{
$this->appendError("DbException" , $e->getMessage() );
return $this->getIsExecuted();
}
catch(\Exception $e)
{
$this->appendError("DbException" , $e->getMessage() );
return $this->getIsExecuted();
}
try
{
$exchange_data = Session::get($this->exchange_key);
$separator = $exchange_data["separator"];
$success = $handler->saveCsvFile($this->csv_path,$separator);
if($success)
{
Session::put($this->exchange_key,$this->csv_path);
$this->is_executed = true;
}
else
{
$this->appendError("Permission" , "Cannot save temporary data: please set write permission on public folder");
return $this->getIsExecuted();
}
}
catch(NoDataException $e)
{
$this->appendError("NoData" , "No data to save");
return $this->getIsExecuted();
}
}
else
{
$this->appendError("fileEmpty" , "No data found in the file" );
}
return $this->getIsExecuted();
} | Process the form
@return Boolean $is_executed if the state is executed successfully | entailment |
public function register(EventDispatcher $dispatcher) : void
{
$dispatcher->addListener(ControllerReadyEvent::class, static function(ControllerReadyEvent $event) {
$controller = $event->getControllerInstance();
if ($controller instanceof OnRequestInterface) {
$response = $controller->onRequest($event->getRequest());
if ($response instanceof Response) {
$event->setResponse($response);
}
}
});
$dispatcher->addListener(ResponseReceivedEvent::class, static function(ResponseReceivedEvent $event) {
$controller = $event->getControllerInstance();
if ($controller instanceof OnResponseInterface) {
$controller->onResponse($event->getRequest(), $event->getResponse());
}
});
} | {@inheritdoc} | entailment |
public static function pruneByID($RecordID)
{
$keep_versions = Config::inst()->get(VersionTruncator::class, 'keep_versions');
$keep_drafts = Config::inst()->get(VersionTruncator::class, 'keep_drafts');
$keep_redirects = Config::inst()->get(VersionTruncator::class, 'keep_redirects');
$keep_old_page_types = Config::inst()->get(VersionTruncator::class, 'keep_old_page_types');
$query = new SQLSelect();
$query->setFrom('SiteTree_Versions');
$query->addWhere('RecordID = ' . $RecordID);
$query->setOrderBy('LastEdited DESC');
$result = $query->execute();
$publishedCount = 0;
$draftCount = 0;
$seen_url_segments = [];
$versionsToDelete = [];
foreach ($result as $row) {
$ID = $row['ID'];
$RecordID = $row['RecordID'];
$ClassName = $row['ClassName'];
$Version = $row['Version'];
$WasPublished = $row['WasPublished'];
$URLSegment = $row['ParentID'] . $row['URLSegment'];
$live_version = SiteTree::get()->byID($row['RecordID']);
if ( // automatically delete versions of old page types
!$keep_old_page_types &&
$live_version &&
$live_version->ClassName != $ClassName
) {
array_push($versionsToDelete, [
'RecordID' => $RecordID,
'Version' => $Version,
'ClassName' => $ClassName,
]);
} elseif (!$WasPublished && $keep_drafts) { // draft
$draftCount++;
if ($draftCount > $keep_drafts) {
array_push($versionsToDelete, [
'RecordID' => $RecordID,
'Version' => $Version,
'ClassName' => $ClassName,
]);
}
} elseif ($keep_versions) { // published
$publishedCount++;
if ($publishedCount > $keep_versions) {
if (!$keep_redirects || in_array($URLSegment, $seen_url_segments)) {
array_push($versionsToDelete, [
'RecordID' => $RecordID,
'Version' => $Version,
'ClassName' => $ClassName,
]);
}
}
// add page to "seen URLs" if $preserve_redirects
if ($keep_redirects && !in_array($URLSegment, $seen_url_segments)) {
array_push($seen_url_segments, $URLSegment);
}
}
}
$affected_rows = 0;
if (count($versionsToDelete) > 0) {
$table_list = DB::table_list();
$affected_tables = [];
$doschema = new DataObjectSchema();
foreach ($versionsToDelete as $d) {
$subclasses = ClassInfo::dataClassesFor($d['ClassName']);
foreach ($subclasses as $subclass) {
$table_name = strtolower($doschema->tableName($subclass));
if (!empty($table_list[$table_name . '_versions'])) {
DB::query('DELETE FROM "' . $table_list[$table_name . '_versions'] . '" WHERE
"RecordID" = ' . $d['RecordID'] . ' AND "Version" = ' . $d['Version']);
$affected_rows = $affected_rows + DB::affected_rows();
}
}
}
}
return $affected_rows;
} | Prune SiteTree by ID
@param Int
@return Int | entailment |
public static function deleteAllButLive()
{
$query = new SQLSelect();
$query->setFrom('SiteTree_Versions');
$versionsToDelete = [];
$results = $query->execute();
foreach ($results as $row) {
$ID = $row['ID'];
$RecordID = $row['RecordID'];
$Version = $row['Version'];
$ClassName = $row['ClassName'];
// is record is live?
$query = new SQLSelect();
$query->setSelect('Count(*) as Count');
$query->setFrom('SiteTree_Live');
$query->addWhere('ID = ' . $RecordID);
$query->addWhere('Version = ' . $Version);
$is_live = $query->execute()->value();
if (!$is_live) {
array_push($versionsToDelete, [
'RecordID' => $RecordID,
'Version' => $Version,
'ClassName' => $ClassName,
]);
}
}
$affected_rows = 0;
if (count($versionsToDelete) > 0) {
$table_list = DB::table_list();
$affected_tables = [];
$doschema = new DataObjectSchema();
foreach ($versionsToDelete as $d) {
$subclasses = ClassInfo::dataClassesFor($d['ClassName']);
foreach ($subclasses as $subclass) {
$table_name = strtolower($doschema->tableName($subclass));
if (!empty($table_list[$table_name . '_versions'])) {
DB::query('DELETE FROM "' . $table_list[$table_name . '_versions'] . '" WHERE
"RecordID" = ' . $d['RecordID'] . ' AND "Version" = ' . $d['Version']);
$affected_rows = $affected_rows + DB::affected_rows();
}
}
}
}
return $affected_rows;
} | Remove ALL previous versions of a SiteTree record
@param Null
@return Int | entailment |
function get($countryCode = false, $separator = '')
{
if ($countryCode == false) {
$formattedNumber = '0' . $this->msisdn;
if ( ! empty($separator)) {
$formattedNumber = substr_replace($formattedNumber, $separator, 4, 0);
$formattedNumber = substr_replace($formattedNumber, $separator, 8, 0);
}
return $formattedNumber;
} else {
$formattedNumber = $this->countryPrefix . $this->msisdn;
if ( ! empty($separator)) {
$formattedNumber = substr_replace($formattedNumber, $separator, strlen($this->countryPrefix), 0);
$formattedNumber = substr_replace($formattedNumber, $separator, 7, 0);
$formattedNumber = substr_replace($formattedNumber, $separator, 11, 0);
}
return $formattedNumber;
}
} | Returns a formatted mobile number
@param bool|false $countryCode
@param string $separator
@return mixed|string | entailment |
public function getPrefix()
{
if ($this->prefix == null) {
$this->prefix = substr($this->msisdn, 0, 3);
}
return $this->prefix;
} | Returns the prefix of the MSISDN number.
@return string The prefix of the MSISDN number | entailment |
public function getOperator()
{
$this->setPrefixes();
if ( ! empty($this->operator)) {
return $this->operator;
}
if (in_array($this->getPrefix(), $this->smartPrefixes)) {
$this->operator = 'SMART';
} else if (in_array($this->getPrefix(), $this->globePrefixes)) {
$this->operator = 'GLOBE';
} else if (in_array($this->getPrefix(), $this->sunPrefixes)) {
$this->operator = 'SUN';
} else {
$this->operator = 'UNKNOWN';
}
return $this->operator;
} | Determines the operator of this number
@return string The operator of this number | entailment |
public static function validate($mobileNumber)
{
$mobileNumber = Msisdn::clean($mobileNumber);
return ! empty($mobileNumber) &&
strlen($mobileNumber) === 10 &&
is_numeric($mobileNumber);
} | Validate a given mobile number
@param string $mobileNumber
@return bool | entailment |
private static function clean($msisdn)
{
$msisdn = preg_replace("/[^0-9]/", "", $msisdn);
// We remove the 0 or 63 from the number
if (substr($msisdn, 0, 1) == '0') {
$msisdn = substr($msisdn, 1, strlen($msisdn));
} else if (substr($msisdn, 0, 2) == '63') {
$msisdn = substr($msisdn, 2, strlen($msisdn));
}
return $msisdn;
} | Cleans the string
@param string $msisdn
@return string The clean MSISDN | entailment |
public function connect()
{
$socket = stream_socket_client("tcp://{$this->ip}:{$this->port}", $errno, $errstr);
stream_set_timeout($socket, 2, 500);
if (!$socket) {
throw new RconConnectException("Error while connecting to the Rcon server: {$errstr}");
}
$this->socket = $socket;
$this->write(self::SERVERDATA_AUTH, $this->password);
$read = $this->read();
if ($read[1]['ID'] == -1) {
throw new RconAuthException('Authentication to the Rcon server failed.');
}
$this->connected = true;
return true;
} | Connects and authenticates with the CS:GO server.
@return boolean | entailment |
public function exec($command)
{
if (!$this->connected) {
throw new NotAuthenticatedException('Client has not connected to the Rcon server.');
}
$this->write(self::SERVERDATA_EXECCOMMAND, $command);
return $this->read()[0]['S1'];
} | Executes a command on the server.
@param string $command
@return string | entailment |
public function write($type, $s1 = '', $s2 = '')
{
$id = $this->packetID++;
$data = pack('VV', $id, $type);
$data .= $s1.chr(0).$s2.chr(0);
$data = pack('V', strlen($data)).$data;
fwrite($this->socket, $data, strlen($data));
return $id;
} | Writes to the socket.
@param integer $type
@param string $s1
@param string $s2
@return integer | entailment |
public function read()
{
$rarray = [];
$count = 0;
while ($data = fread($this->socket, 4)) {
$data = unpack('V1Size', $data);
if ($data['Size'] > 4096) {
$packet = '';
for ($i = 0; $i < 8; $i++) {
$packet .= "\x00";
}
$packet .= fread($this->socket, 4096);
} else {
$packet = fread($this->socket, $data['Size']);
}
$rarray[] = unpack('V1ID/V1Response/a*S1/a*S2', $packet);
}
return $rarray;
} | Reads from the socket.
@return array | entailment |
public function close()
{
if (!$this->connected) {
return false;
}
$this->connected = false;
fclose($this->socket);
return true;
} | Closes the socket.
@return boolean | entailment |
public function createTable($name, Array $columns, $safe_create = false)
{
if( (! $safe_create) || ($safe_create && ! Schema::connection($this->connection)->hasTable('users')) )
{
// dtop table if exists
if (Schema::connection($this->connection)->hasTable($name))
{
Schema::connection($this->connection)->drop($name);
}
Schema::connection($this->connection)->create($name, function($table) use ($columns)
{
foreach($columns as $name => $type)
{
$table->$type($name);
}
});
}
} | Create a table schme with the given columns
@param $name table name
@param Array $columns "type" => "name"
@param $safe_create if is enabled doesnt create a table if already exists | entailment |
public function getReturnCodeName($returnCode)
{
if (isset(self::$qosLevels[$returnCode])) {
return self::$qosLevels[$returnCode][0];
}
return 'Unknown '.$returnCode;
} | Indicates if the given return code is an error.
@param int $returnCode
@return bool | entailment |
public function setReturnCodes(array $value)
{
foreach ($value as $returnCode) {
$this->assertValidReturnCode($returnCode, false);
}
$this->returnCodes = $value;
} | Sets the return codes.
@param int[] $value
@throws \InvalidArgumentException | entailment |
private function assertValidReturnCode($returnCode, $fromPacket = true)
{
if (!in_array($returnCode, [0, 1, 2, 128])) {
$this->throwException(
sprintf('Malformed return code %02x.', $returnCode),
$fromPacket
);
}
} | Asserts that a return code is valid.
@param int $returnCode
@param bool $fromPacket
@throws MalformedPacketException
@throws \InvalidArgumentException | entailment |
public function setConfig(array $configs)
{
foreach($configs as $config_key => $config_value)
{
if( property_exists(get_class($this), $config_key) )
{
$this->$config_key = $config_value;
}
else
{
throw new \InvalidArgumentException;
}
}
} | set parameters of the object
@param array $config
@throws InvalidArgumentException | entailment |
protected function createLoggerContext(StatemachineInterface $stateMachine)
{
$context = array();
$context[self::CONTEXT_SUBJECT] = $stateMachine->getSubject();
$context[self::CONTEXT_CURRENT_STATE] = $stateMachine->getCurrentState();
if ($stateMachine instanceof Statemachine) {
$context[self::CONTEXT_LAST_STATE] = $stateMachine->getLastState();
$context[self::CONTEXT_TRANSITION] = $stateMachine->getSelectedTransition();
}
return $context;
} | @param StatemachineInterface $stateMachine
@return array | entailment |
protected function createLoggerMessage(array $context)
{
$message = 'Transition';
if (isset($context[self::CONTEXT_SUBJECT])) {
$message .= ' for "' . $this->stringConverter->convertToString($context[self::CONTEXT_SUBJECT]) . '"';
}
if (isset($context[self::CONTEXT_LAST_STATE])) {
$message .= ' from "' . $this->stringConverter->convertToString($context[self::CONTEXT_LAST_STATE]) . '"';
}
if (isset($context[self::CONTEXT_CURRENT_STATE])) {
$message .= ' to "' . $this->stringConverter->convertToString($context[self::CONTEXT_CURRENT_STATE]) . '"';
}
if (isset($context[self::CONTEXT_TRANSITION])) {
/* @var $transition TransitionInterface */
$transition = $context[self::CONTEXT_TRANSITION];
$eventName = $transition->getEventName();
$condition = $transition->getConditionName();
if ($eventName || $condition) {
$message .= ' with';
if ($eventName) {
$message .= ' event "' . $eventName . '"';
}
if ($eventName) {
$message .= ' condition "' . $condition . '"';
}
}
}
return $message;
} | @param array $context
@return string | entailment |
public function createStatemachine($subject)
{
$process = $this->processDetector->detectProcess($subject);
if ($this->stateNameDetector) {
$stateName = $this->stateNameDetector->detectCurrentStateName($subject);
} else {
$stateName = null;
}
if ($this->mutexFactory) {
$mutex = $this->mutexFactory->createMutex($subject);
} else {
$mutex = null;
}
$statemachine = new Statemachine($subject, $process, $stateName, $this->transitonSelector, $mutex);
foreach ($this->statemachineObserver as $observer) {
$statemachine->attach($observer);
}
return $statemachine;
} | @param object $subject
@return \MetaborStd\Statemachine\StatemachineInterface | entailment |
public function pack($object) : ?PackedObject
{
if ($object instanceof Geometry) {
return new PackedObject(Geometry::class, $object->asText());
}
return null;
} | {@inheritdoc} | entailment |
public function unpack(PackedObject $packedObject)
{
$class = $packedObject->getClass();
$data = $packedObject->getData();
if ($class === Geometry::class || is_subclass_of($class, Geometry::class)) {
try {
$geometry = Geometry::fromText($data, $this->srid);
if (! $geometry instanceof $class) {
throw new Exception\ObjectNotConvertibleException(sprintf(
'Expected instance of %s, got instance of %s.',
$class,
get_class($geometry)
));
}
return $geometry;
} catch (GeometryException $e) {
throw new Exception\ObjectNotConvertibleException($e->getMessage(), 0, $e);
}
}
return null;
} | {@inheritdoc} | entailment |
public function calculateSign($data, $signKey)
{
unset($data['ik_sign']);
ksort($data, SORT_STRING);
array_push($data, $signKey);
$signAlgorithm = $this->getSignAlgorithm();
$signString = implode(':', $data);
return base64_encode(hash($signAlgorithm, $signString, true));
} | Calculates sign for the $data.
@param array $data
@param string $signKey
@return string | entailment |
protected function createDataObjectFrom($value, $className)
{
// If the value is already the correct object, return it unaltered
if ($value instanceof $className) {
return $value;
}
// Convert object to array so it can be used to set attributes in the DataObject
if ($value instanceof Arrayable) {
$value = $value->toArray();
} elseif (is_object($value)) {
$value = json_decode(json_encode($value), true);
}
// Make validation fail if value could not be converted to an array
if ( ! is_array($value)) {
return false;
}
// Build an instance of the DataObject
$dataObjectClass = $className;
try {
$dataObject = new $dataObjectClass($value);
} catch (Throwable $e) {
throw new InvalidArgumentException($dataObjectClass . ' is not instantiable as a DataObject', 0, $e);
}
if ( ! ($dataObject instanceof DataObjectInterface)) {
throw new InvalidArgumentException($dataObjectClass . ' is not a validatable DataObject');
}
return $dataObject;
} | Creates a DataObject with the given class name
@param mixed $value
@param string $className DataObject class to instantiate
@return DataObjectInterface|bool | entailment |
public function messages(): MessageBagContract
{
if ($this->validator === null) {
$this->validate();
}
if ( ! $this->validator->fails()) {
return new MessageBag;
}
return $this->validator->messages();
} | Returns validation errors, if any
@return MessageBagContract | entailment |
public function assemble($document, Schema $schema)
{
$entityClass = $schema->entityClass;
$model = Ioc::make($entityClass);
foreach ($document as $field => $value) {
$fieldType = $schema->fields[$field] ?? null;
if ($fieldType && 'schema.' == substr($fieldType, 0, 7)) {
$value = $this->assembleDocumentsRecursively($value, substr($fieldType, 7));
}
$model->$field = $value;
}
$entity = $this->morphingTime($model);
return $this->prepareOriginalAttributes($entity);
} | Builds an object from the provided data.
@param array|object $document the attributes that will be used to compose the entity
@param Schema $schema schema that will be used to map each field
@return mixed | entailment |
protected function assembleDocumentsRecursively($value, string $schemaClass)
{
$value = (array) $value;
if (empty($value)) {
return;
}
$schema = Ioc::make($schemaClass);
$assembler = Ioc::make(self::class);
if (!isset($value[0])) {
$value = [$value];
}
foreach ($value as $key => $subValue) {
$value[$key] = $assembler->assemble($subValue, $schema);
}
return $value;
} | Assembly multiple documents for the given $schemaClass recursively.
@param mixed $value a value of an embeded field containing entity data to be assembled
@param string $schemaClass the schemaClass to be used when assembling the entities within $value
@return mixed | entailment |
private function destructEventEmitterTrait()
{
$this->emitterBlocked = EventEmitter::EVENTS_FORWARD;
$this->eventPointers = [];
$this->eventListeners = [];
$this->forwardListeners = [];
} | Destruct method. | entailment |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.