sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
private function checkSessionId(string $id) : bool
{
if (preg_match('/^[A-Za-z0-9]+$/', $id) !== 1) {
return false;
}
if (strlen($id) !== $this->idLength) {
return false;
}
return true;
} | Checks the validity of a session ID sent in a cookie.
This is a security measure to avoid forged session cookies,
that could be used for example to hack session adapters.
@param string $id
@return bool | entailment |
public function showPreview($maxwidth = 500, $height = '56%')
{
$this->display_video = $maxwidth;
$this->preview_height = $height;
return $this;
} | Display a video preview
@param Varchar width
@param Varchar height
@return VideoLinkField | entailment |
public function getPreview()
{
$url = trim($this->value);
if (!$this->display_video || !$url) {
return false;
}
$obj = VideoLink::create()->setValue($url);
if ($obj->iFrameURL) {
return $obj->Iframe($this->display_video, $this->preview_height);
}
} | Return video preview
@param Null
@return VideoLink | entailment |
public function getVideoTitle()
{
$url = trim($this->value);
return VideoLink::create()->setValue($url)->Title;
} | Return video title
@param Null
@return String | entailment |
public function validate($validator)
{
parent::validate($validator);
// Don't validate empty fields
if (empty($this->value)) {
return true;
}
// Use the VideoLink object to validate
$obj = VideoLink::create()->setValue($this->value);
if (!$obj->getService()) {
$validator->validationError(
$this->name,
_t(__CLASS__ . '.ValidationError', 'Please enter a valid YouTube or Vimeo link'),
'validation'
);
return false;
}
return true;
} | Return validation result
@param Validator $validator
@return Boolean | entailment |
public function create($type)
{
$name = $this->builClassName($type);
if (class_exists($name)) {
return new $name;
} else {
if (!is_null($this->getDefaultClass())) {
$default = $this->getNamespace().'\\'.$this->getDefaultClass();
if (class_exists($default)) {
return new $default;
}
}
throw new NavitiaCreationException(
sprintf(
'Class "%s" not found',
$name
)
);
}
} | {@inheritDoc} | entailment |
private function builClassName($type)
{
$name = $this->getNamespace().'\\';
if (!is_null($this->getprefix())) {
$name .= $this->getprefix();
}
$name .= ucfirst($type).$this->getSuffix();
return $name;
} | Fonction permettant de créer le nom de la class
@params string
@return string | entailment |
protected function renderAsString(View $view) : string
{
if ($this->injector) {
$this->injector->inject($view);
}
return $view->render();
} | @param \Brick\App\View\View $view
@return string | entailment |
protected function json($data, bool $encode = true) : Response
{
if ($encode) {
$data = json_encode($data);
}
return $this->createResponse($data, 'application/json');
} | Returns a JSON response.
@param mixed $data The data to encode, or a valid JSON string if `$encode` == `false`.
@param bool $encode Whether to JSON-encode the data.
@return \Brick\Http\Response | entailment |
private function createResponse(string $data, string $contentType) : Response
{
return (new Response())
->setContent($data)
->setHeader('Content-Type', $contentType);
} | @param string $data
@param string $contentType
@return Response | entailment |
protected function redirect(string $uri, int $statusCode = 302) : Response
{
return (new Response())
->setStatusCode($statusCode)
->setHeader('Location', $uri);
} | @param string $uri
@param int $statusCode
@return \Brick\Http\Response | entailment |
public function getConnection()
{
if ($chosenConn = $this->connections->pop()) {
$this->connections->push($chosenConn);
return $chosenConn;
}
} | Gets a connection from the pool. It will cycle through the existent
connections.
@return Connection | entailment |
public function validate($validator)
{
// Don't validate empty fields
if (empty($this->value)) {
return true;
}
if (!filter_var($this->value, FILTER_VALIDATE_URL)) {
if (filter_var('http://' . $this->value, FILTER_VALIDATE_URL)) {
$this->value = 'http://' . $this->value;
} else {
$validator->validationError(
$this->name,
_t(__CLASS__ . '.ValidationError', 'Please enter a valid URL including the http:// or https://'),
'validation'
);
return false;
}
}
return true;
} | Return validation result
@param Validator $validator
@return Boolean | entailment |
public function html(string $text, bool $lineBreaks = false) : string
{
$html = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
return $lineBreaks ? nl2br($html) : $html;
} | HTML-escapes a text string.
This is the single most important protection against XSS attacks:
any user-originated data, or more generally any data that is not known to be valid and trusted HTML,
must be escaped before being displayed in a web page.
@param string $text The text to escape.
@param bool $lineBreaks Whether to escape line breaks. Defaults to `false`.
@return string | entailment |
public function createRating($id = null)
{
$class = $this->getClass();
$rating = new $class;
if (null !== $id) {
$rating->setId($id);
}
$this->dispatcher->dispatch(DCSRatingEvents::RATING_CREATE, new Event\RatingEvent($rating));
return $rating;
} | Creates an empty rating instance
@param string $id
@return \DCS\RatingBundle\Model\RatingInterface | entailment |
public function rewind()
{
try {
$this->getCursor()->rewind();
} catch (LogicException $e) {
$this->fresh();
$this->getCursor()->rewind();
}
$this->position = 0;
} | Iterator interface rewind (used in foreach). | entailment |
public function current()
{
$document = $this->getCursor()->current();
if ($document instanceof ActiveRecord) {
$documentToArray = $document->toArray();
$this->entitySchema = $document->getSchema();
} else {
$documentToArray = (array) $document;
}
return $this->getAssembler()->assemble(
$documentToArray,
$this->entitySchema
);
} | Iterator interface current. Return a model object
with cursor document. (used in foreach).
@return mixed | entailment |
public function first()
{
$this->rewind();
$document = $this->getCursor()->current();
if (!$document) {
return;
}
return $this->getAssembler()->assemble($document, $this->entitySchema);
} | Returns the first element of the cursor.
@return mixed | entailment |
protected function getCursor(): Traversable
{
if (!$this->cursor) {
$driverCursor = $this->collection->{$this->command}(...$this->params);
$this->cursor = new IteratorIterator($driverCursor);
$this->cursor->rewind();
}
return $this->cursor;
} | Actually returns a Traversable object with the DriverCursor within.
If it does not exists yet, create it using the $collection, $command and
$params given.
@return Traversable | entailment |
public function serialize()
{
$properties = get_object_vars($this);
$properties['collection'] = $this->collection->getCollectionName();
return serialize($properties);
} | Serializes this object storing the collection name instead of the actual
MongoDb\Collection (which is unserializable).
@return string serialized object | entailment |
public function unserialize($serialized)
{
$attributes = unserialize($serialized);
$conn = Ioc::make(Pool::class)->getConnection();
$db = $conn->defaultDatabase;
$collectionObject = $conn->getRawConnection()->$db->{$attributes['collection']};
foreach ($attributes as $key => $value) {
$this->$key = $value;
}
$this->collection = $collectionObject;
} | Unserializes this object. Re-creating the database connection.
@param mixed $serialized serialized cursor | entailment |
public static function invalidControllerClassMethod(\ReflectionException $e, string $class, string $method) : RoutingException
{
return new self(sprintf(
'Cannot find a controller method called %s::%s().',
$class,
$method
), 0, $e);
} | @param \ReflectionException $e
@param string $class
@param string $method
@return RoutingException | entailment |
public function update(\SplSubject $subject)
{
if (!$subject instanceof EventInterface) {
throw new \InvalidArgumentException('Command can only be attached to an event!');
}
if (method_exists($this, '__invoke')) {
call_user_func_array($this, $subject->getInvokeArgs());
} else {
throw new \Exception('Command should have at least one __invoke method');
}
} | @param \SplSubject $subject
@throws \InvalidArgumentException | entailment |
final protected function getRequiredString(array $values, string $name, bool $isFirst = false) : string
{
$value = $this->getOptionalString($values, $name, $isFirst);
if ($value === null) {
throw new \LogicException(sprintf(
'Attribute "%s" of annotation %s is required.',
$name,
$this->getAnnotationName()
));
}
return $value;
} | @param array $values
@param string $name
@param bool $isFirst
@return string
@throws \LogicException | entailment |
final protected function getOptionalString(array $values, string $name, bool $isFirst = false) : ?string
{
if (isset($values[$name])) {
$value = $values[$name];
} elseif ($isFirst && isset($values['value'])) {
$value = $values['value'];
} else {
return null;
}
if (! is_string($value)) {
throw new \LogicException(sprintf(
'Attribute "%s" of annotation %s expects a string, %s given.',
$name,
$this->getAnnotationName(),
gettype($value)
));
}
return $value;
} | @param array $values
@param string $name
@param bool $isFirst
@return string|null
@throws \LogicException | entailment |
final protected function getRequiredStringArray(array $values, string $name, bool $isFirst = false) : array
{
$values = $this->getOptionalStringArray($values, $name, $isFirst);
if (! $values) {
throw new \LogicException(sprintf(
'Attribute "%s" of annotation %s must not be empty.',
$name,
$this->getAnnotationName()
));
}
return $values;
} | @param array $values
@param string $name
@param bool $isFirst
@return string[]
@throws \LogicException | entailment |
final protected function getOptionalStringArray(array $values, string $name, bool $isFirst = false) : array
{
if (isset($values[$name])) {
$value = $values[$name];
} elseif ($isFirst && isset($values['value'])) {
$value = $values['value'];
} else {
return [];
}
if (is_string($value)) {
return [$value];
}
if (is_array($value)) {
foreach ($value as $item) {
if (! is_string($item)) {
throw new \LogicException(sprintf(
'Attribute "%s" of annotation %s expects an array of strings, %s found in array.',
$name,
$this->getAnnotationName(),
gettype($item)
));
}
}
return $value;
}
throw new \LogicException(sprintf(
'Attribute "%s" of annotation %s expects a string or array of strings, %s given.',
$name,
$this->getAnnotationName(),
gettype($value)
));
} | @param array $values
@param string $name
@param bool $isFirst
@return string[]
@throws \LogicException | entailment |
public function register(EventDispatcher $dispatcher) : void
{
$dispatcher->addListener(ControllerReadyEvent::class, function (ControllerReadyEvent $event) {
$controller = $event->getControllerInstance();
if ($controller === null) {
return;
}
foreach ($this->onBefore as $class => $functions) {
if ($controller instanceof $class) {
foreach ($functions as $function) {
$parameters = $this->getFunctionParameters('onBefore', $function, [
$class => $controller,
Request::class => $event->getRequest()
]);
$result = $function(...$parameters);
if ($result instanceof Response) {
$event->setResponse($result);
}
}
}
}
});
$dispatcher->addListener(ResponseReceivedEvent::class, function (ResponseReceivedEvent $event) {
$controller = $event->getControllerInstance();
if ($controller === null) {
return;
}
foreach ($this->onAfter as $class => $functions) {
if ($controller instanceof $class) {
foreach ($functions as $function) {
$parameters = $this->getFunctionParameters('onAfter', $function, [
$class => $controller,
Request::class => $event->getRequest(),
Response::class => $event->getResponse()
]);
$function(...$parameters);
}
}
}
});
} | {@inheritdoc} | entailment |
private function getFunctionParameters(string $onEvent, callable $function, array $objects) : array
{
$parameters = [];
$reflectionFunction = $this->reflectionTools->getReflectionFunction($function);
foreach ($reflectionFunction->getParameters() as $reflectionParameter) {
$parameterClass = $reflectionParameter->getClass();
if ($parameterClass !== null) {
$parameterClassName = $parameterClass->getName();
if (isset($objects[$parameterClassName])) {
$parameters[] = $objects[$parameterClassName];
continue;
}
}
throw $this->cannotResolveParameter($onEvent, array_keys($objects), $reflectionParameter);
}
return $parameters;
} | Resolves the parameters to call the given function.
@param string $onEvent 'onBefore' or 'onAfter'.
@param callable $function The function to resolve.
@param object[] $objects An associative array of available objects, indexed by their class or interface name.
@return array
@throws HttpInternalServerErrorException If the function requires a parameter that is not available. | entailment |
private function cannotResolveParameter(string $onEvent, array $types, \ReflectionParameter $parameter) : HttpInternalServerErrorException
{
$message = 'Cannot resolve ' . $onEvent . ' function parameter $' . $parameter->getName() . ': ';
$parameterClass = $parameter->getClass();
if ($parameterClass === null) {
$message .= 'parameter is not typed.';
} else {
$message .= 'type ' . $parameterClass->getName() . ' is not in available types (' . implode(', ', $types) . ').';
}
return new HttpInternalServerErrorException($message);
} | @param string $onEvent
@param string[] $types
@param \ReflectionParameter $parameter
@return HttpInternalServerErrorException | entailment |
public function createCursor(
Schema $entitySchema,
Collection $collection,
string $command,
array $params,
bool $cacheable = false
): Cursor {
$cursorClass = $cacheable ? CacheableCursor::class : Cursor::class;
return new $cursorClass($entitySchema, $collection, $command, $params);
} | Creates a new instance of a non embedded Cursor.
@param Schema $entitySchema schema that describes the entity that will be retrieved from the database
@param Collection $collection the raw collection object that will be used to retrieve the documents
@param string $command the command that is being called in the $collection
@param array $params the parameters of the $command
@param bool $cacheable retrieves a CacheableCursor instead
@return Cursor | entailment |
public function reduce( $tolerance )
{
$key = 0;
while ( $key < $this->lastKey(-3) ) {
$out = $key + 2;
$pd = $this->shortestDistanceToSegment(
$this->points[$out],
$this->points[$key],
$this->points[$key + 1]
);
while ( $out < $this->lastKey() && $pd < $tolerance ) {
$pd = $this->shortestDistanceToSegment(
$this->points[++$out],
$this->points[$key],
$this->points[$key + 1]
);
}
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 mixed $tolerance Defined threshold to reduce by
@return array Reduced set of points | entailment |
public function read(string $id, string $key, Lock $lock = null) : ?string
{
$path = $this->getPath($id, $key);
if (! file_exists($path)) {
return null;
}
if (fileatime($path) < time() - $this->accessGraceTime) {
touch($path);
}
$fp = fopen($path, $lock ? 'cb+' : 'rb');
flock($fp, LOCK_EX);
$data = stream_get_contents($fp);
if ($lock) {
// Keep the file open & locked, and remember the resource.
$lock->context = $fp;
} else {
// Unlock immediately and close the file.
flock($fp, LOCK_UN);
fclose($fp);
}
return $data;
} | {@inheritdoc} | entailment |
public function write(string $id, string $key, string $value, Lock $lock = null) : void
{
if ($lock) {
$fp = $lock->context;
if ($fp !== null) {
ftruncate($fp, 0);
fseek($fp, 0);
fwrite($fp, $value);
flock($fp, LOCK_UN);
fclose($fp);
return;
}
}
$path = $this->getPath($id, $key);
file_put_contents($path, $value, LOCK_EX);
} | {@inheritdoc} | entailment |
public function unlock(Lock $lock) : void
{
$fp = $lock->context;
if ($fp !== null) {
flock($fp, LOCK_UN);
fclose($fp);
}
} | {@inheritdoc} | entailment |
public function remove(string $id, string $key) : void
{
$path = $this->getPath($id, $key);
if (file_exists($path)) {
unlink($path);
}
} | {@inheritdoc} | entailment |
public function clear(string $id) : void
{
$files = glob($this->directory . DIRECTORY_SEPARATOR . $this->prefix . $id . '_*');
foreach ($files as $file) {
unlink($file);
}
} | {@inheritdoc} | entailment |
public function expire(int $lifetime) : void
{
$files = new \DirectoryIterator($this->directory);
foreach ($files as $file) {
if (! $file->isFile()) {
continue;
}
if ($file->getATime() >= time() - $lifetime) {
continue;
}
if ($this->prefix !== '' && strpos($file->getFilename(), $this->prefix) !== 0) {
continue;
}
unlink($file->getPathname());
}
} | {@inheritdoc} | entailment |
public function updateId(string $oldId, string $newId) : bool
{
$prefix = $this->directory . DIRECTORY_SEPARATOR . $this->prefix;
$prefixOldId = $prefix . $oldId;
$prefixNewId = $prefix . $newId;
$prefixOldIdLength = strlen($prefixOldId);
$files = glob($prefixOldId . '_*');
foreach ($files as $file) {
$newFile = $prefixNewId . substr($file, $prefixOldIdLength);
rename($file, $newFile);
}
return true;
} | {@inheritdoc} | entailment |
private function getPath(string $id, string $key) : string
{
// Sanitize the session key: it may contain characters that could conflict with the filesystem.
// We only allow the resulting file name to contain ASCII letters & digits, dashes, underscores and dots.
// All other chars are hex-encoded, dot is used as an escape character.
$key = preg_replace_callback('/[^A-Za-z0-9\-_]/', static function ($matches) {
return '.' . bin2hex($matches[0]);
}, $key);
return $this->directory . DIRECTORY_SEPARATOR . $this->prefix . $id . '_' . $key;
} | @param string $id
@param string $key
@return string | entailment |
public function reduce( $target )
{
$kill = count($this) - $target;
while ( $kill-- > 0 ) {
$idx = 1;
$minArea = $this->areaOfTriangle(
$this->points[0],
$this->points[1],
$this->points[2]
);
foreach (range(2, $this->lastKey(-2)) as $segment) {
$area = $this->areaOfTriangle(
$this->points[$segment - 1],
$this->points[$segment],
$this->points[$segment + 1]
);
if ( $area < $minArea ) {
$minArea = $area;
$idx = $segment;
}
}
array_splice($this->points, $idx, 1);
}
return $this->points;
} | Reduce points with Visvalingam-Whyatt algorithm.
@param integer $target Desired count of points
@return array Reduced set of points | entailment |
public function isRemove($newValue = null)
{
if (null !== $newValue) {
$this->isRemove = (bool) $newValue;
}
return $this->isRemove;
} | Миграция требует удаления
@param null $newValue
@return bool | entailment |
public function isTransaction($newValue = null)
{
if (null !== $newValue) {
$this->isTransaction = (bool) $newValue;
}
return $this->isTransaction;
} | Выполняется в транзакции
@param bool $newValue
@return bool | entailment |
private function _parseSql($sql)
{
return array_values(array_filter(array_map(function ($value) { return trim(rtrim($value, $this->separator)); },
preg_split(sprintf("/%s[\s]*\n/", preg_quote($this->separator)), rtrim(trim($sql), $this->separator)))));
} | Разобрать SQL на массив запросов
@param string $sql - SQL разделенный ";"
@return array - Массив SQL-запросов | entailment |
public function limit(int $amount)
{
$this->items = array_slice($this->items, 0, $amount);
return $this;
} | Limits the number of results returned.
@param int $amount the number of results to return
@return EmbeddedCursor returns this cursor | entailment |
public function sort(array $fields)
{
foreach (array_reverse($fields) as $key => $direction) {
// Uses usort with a function that will access the $key and sort in
// the $direction. It mimics how the mongodb does sorting internally.
usort(
$this->items,
function ($a, $b) use ($key, $direction) {
$a = is_object($a)
? ($a->$key ?? null)
: ($a[$key] ?? null);
$b = is_object($b)
? ($b->$key ?? null)
: ($b[$key] ?? null);
return ($a <=> $b) * $direction;
}
);
}
return $this;
} | Sorts the results by given fields.
@param array $fields An array of fields by which to sort.
Each element in the array has as key the field name,
and as value either 1 for ascending sort, or -1 for descending sort.
@return EmbeddedCursor returns this cursor | entailment |
public function skip(int $amount)
{
$this->items = array_slice($this->items, $amount);
return $this;
} | Skips a number of results.
@param int $amount the number of results to skip
@return EmbeddedCursor returns this cursor | entailment |
public function current()
{
if (!$this->valid()) {
return;
}
$document = $this->items[$this->position];
if ($document instanceof $this->entityClass) {
return $document;
}
$schema = $this->getSchemaForEntity();
$entityAssembler = Ioc::makeWith(EntityAssembler::class, compact('schema'));
return $entityAssembler->assemble($document, $schema);
} | Iterator interface current. Return a model object
with cursor document. (used in foreach).
@return mixed | entailment |
protected function getSchemaForEntity(): Schema
{
if ($this->entityClass instanceof Schema) {
return $this->entityClass;
}
$model = new $this->entityClass();
if ($model instanceof ActiveRecord) {
return $model->getSchema();
}
return new DynamicSchema();
} | Retrieve a schema based on Entity Class.
@return Schema | entailment |
protected function printFormNew(){
$str = parent::printFormNew();
$csv_handler = new CsvFileHandler();
$csv_file = $csv_handler->getTemporary();
$str.= "<div class=\"row\">".
"<div class=\"col-md-12\">".
"<h3>Step2: Configure import data</h3>".
"<h5>Sample data from csv file:</h5>";
try
{
$str.= $this->getCsvTableStr($csv_handler, $csv_file);
}
catch(NoDataException $e)
{
}
$str.= "<h4>Fill the form below:</h4>";
$exchange_data = Session::get($this->exchange_key);
$setSchema = $exchange_data["create_table"];
$str.= $this->getConfigForm($csv_handler, $csv_file, $setSchema);
$str.= "</div>". // col-md-12
"</div>"; // row
return $str;
} | Return the form that needs to be processed | entailment |
protected function getSelectSchema($name)
{
$data_types = array(
"string" => "string",
"integer" => "integer",
"increments" => "increments",
"bigIncrements" => "bigIncrements",
"bigInteger" => "bigInteger",
"smallInteger" => "smallInteger",
"float" => "float",
"double" => "double",
"decimal" => "decimal",
"boolean" => "boolean",
"date" => "date",
"dateTime" => "dateTime",
"time" => "time",
"blob" => "binary",
);
$select =Form::label($name,'Type: ', array("class"=>"control-label col-lg-2") ).
"<div class=\"col-lg-10\">".
Form::select($name , $data_types, '', array("class" => "form-control") ).
"</div>";
return $select;
} | Return a select for the type of data to create
@param $name select name and id
@return String $select | entailment |
protected function getCsvTableStr(CsvFileHandler $csv_handler, CsvFile $csv_file)
{
if(! $csv_file)
{
throw new NoDataException();
}
$table = new Table();
// set the configuration
$table->setConfig(array(
"table-hover"=>true,
"table-condensed"=>false,
"table-responsive" => true,
"table-striped" => true,
));
// set header
if( $csv_header = $csv_file->getCsvHeader() )
{
$table->setHeader( $csv_header );
}
// set content
$exchange_data = Session::get($this->exchange_key);
$max_num_lines = $exchange_data["max_lines"];
foreach( $csv_file as $csv_line_key => $csv_line)
{
if($csv_line_key >= $max_num_lines)
break;
// add data table row
$table->addRows( $csv_line->getElements() );
}
return $table->getHtml();
} | Return the table rappresenting the csv data
@throws NoDataException
@return String $table | entailment |
public function processForm(array $input = null, $validator = null, $csv_handler = null)
{
if($input)
{
$this->form_input = $input;
}
else
{
$this->fillFormInput();
}
$validator = ($validator) ? $validator : new ValidatorFormInputModel($this);
$csv_handler = ($csv_handler) ? $csv_handler : new CsvFileHandler();
if ( $validator->validateInput() && $this->checkColumns() )
{
// process form
$csv_file = $csv_handler->getTemporary();
if($csv_file)
{
try
{
$csv_handler->updateHeaders($csv_file, $this->form_input["columns"], $this->form_input["table_name"]);
}
catch(UnalignedArrayException $e)
{
$this->appendError("No_temporary", "Invalid Column names." );
return $this->getIsExecuted();
}
try
{
$csv_handler->saveToDb($this->form_input['types']);
$this->is_executed = true;
}
catch( HeadersNotSetException $e)
{
$this->appendError("Save_err", "Cannot save data: check if dmbs support transaction.");
}
catch( PDOException $e)
{
$this->appendError("Save_err", $e->getMessage() );
}
catch( Exception $e)
{
$this->appendError("Save_err", $e->getMessage() );
}
}
else
{
$this->appendError("No_temporary","No data available to save");
}
}
return $this->getIsExecuted();
} | Process the form and return the next state
@return Boolean $is_executed | entailment |
protected function checkColumns()
{
$success = false;
if ( ! empty($this->form_input['columns']) )
{
$success = true;
}
else
{
$this->appendError("No_columns","No column name setted: you need to fill atleast one \"column_\" field");
}
return $success;
} | Check the column field if atleast one exists
@return Boolean $success | entailment |
public function map($data)
{
$data = $this->parseToArray($data);
$this->clearDynamic($data);
// Parse each specified field
foreach ($this->schema->fields as $key => $fieldType) {
$data[$key] = $this->parseField($data[$key] ?? null, $fieldType);
}
return $data;
} | Maps the input $data to the schema specified in the $schema property.
@param array|object $data array or object with the fields that should
be mapped to $this->schema specifications
@return array | entailment |
protected function clearDynamic(array &$data)
{
if (!$this->schema->dynamic) {
$data = array_intersect_key($data, $this->schema->fields);
}
} | If the schema is not dynamic, remove all non specified fields.
@param array $data Reference of the fields. The passed array will be modified. | entailment |
public function parseField($value, string $fieldType)
{
// Uses $fieldType method of the schema to parse the value
if (method_exists($this->schema, $fieldType)) {
return $this->schema->$fieldType($value);
}
// Returns null or an empty array
if (null === $value || is_array($value) && empty($value)) {
return $value;
}
// If fieldType is castable (Ex: 'int')
if (in_array($fieldType, $this->castableTypes)) {
return $this->cast($value, $fieldType);
}
// If the field type points to another schema.
if ('schema.' == substr($fieldType, 0, 7)) {
return $this->mapToSchema($value, substr($fieldType, 7));
}
return $value;
} | Parse a value based on a field yype of the schema.
@param mixed $value value to be parsed
@param string $fieldType description of how the field should be treated
@return mixed $value Value parsed to match $type | entailment |
protected function mapToSchema($value, string $schemaClass)
{
$value = (array) $value;
$schema = Ioc::make($schemaClass);
$mapper = Ioc::makeWith(self::class, compact('schema'));
if (!isset($value[0])) {
$value = [$value];
}
foreach ($value as $key => $subValue) {
$value[$key] = $mapper->map($subValue);
}
return $value;
} | Instantiate another SchemaMapper with the given $schemaClass and maps
the given $value.
@param mixed $value value that will be mapped
@param string $schemaClass class that will be passed to the new SchemaMapper constructor
@return mixed | entailment |
protected function parseToArray($object): array
{
if (!is_array($object)) {
$attributes = method_exists($object, 'getAttributes')
? $object->getAttributes()
: get_object_vars($object);
return $attributes;
}
return $object;
} | Parses an object to an array before sending it to the SchemaMapper.
@param mixed $object the object that will be transformed into an array
@return array | entailment |
public function getData()
{
if ($this->getTestMode()) {
$this->validate('testKey');
} else {
$this->validate('signKey');
}
$result = [];
$vars = array_merge($this->httpRequest->query->all(), $this->httpRequest->request->all());
foreach ($vars as $key => $parameter) {
if (strpos($key, 'ik_') === 0) {
$result[$key] = $parameter;
}
}
return $result;
} | Get the data for this request.
@throws InvalidResponseException
@throws \Omnipay\Common\Exception\InvalidRequestException
@return array request data | entailment |
protected function getDsn(array $config)
{
extract($config);
// First we will create the basic DSN setup as well as the port if it is in
// in the configuration options. This will give us the basic DSN we will
// need to establish the PDO connections and return them back for use.
if (in_array('dblib', $this->getAvailableDrivers())) {
$port = isset($config['port']) ? ':'.$port : '';
return "dblib:host={$hostname}{$port};dbname={$database}";
}
$port = isset($config['port']) ? ','.$port : '';
$dbName = $database != '' ? ";Database={$database}" : '';
return "sqlsrv:Server={$hostname}{$port}{$dbName}";
} | Create a DSN string from a configuration.
@param array $config
@return string | entailment |
public function view($view, array $data = array())
{
$this->view = $view;
$this->viewData = $data;
return $this;
} | Set the view for the mail message.
@param string $view
@param array $data
@return $this | entailment |
public function isPublic()
{
if ($this->getIsActive() && ($this->getPublishAt()->getTimestamp() < time()) && (!$this->getExpiresAt() || $this->getExpiresAt()->getTimestamp() > time())) {
return true;
}
return false;
} | Is visible for user?
@return boolean | entailment |
public function handle()
{
if (! $this->confirmToProceed()) {
return;
}
$slug = $this->argument('slug');
if (! $this->packages->exists($slug)) {
return $this->error('Package does not exist.');
}
$this->call('package:migrate:reset', array(
'slug' => $slug,
'--database' => $this->option('database'),
'--force' => $this->option('force'),
'--pretend' => $this->option('pretend'),
));
$this->call('package:migrate', array(
'slug' => $slug,
'--database' => $this->option('database'),
));
if ($this->needsSeeding()) {
$this->runSeeder($slug, $this->option('database'));
}
$this->info('Package has been refreshed.');
} | Execute the console command.
@return mixed | entailment |
public function render($view = null, $data = array())
{
if (is_null($view)) {
$view = static::$defaultSimpleView;
}
$data = array_merge($data, array(
'paginator' => $this,
));
return new HtmlString(
static::viewFactory()->make($view, $data)->render()
);
} | Render the paginator using the given view.
@param string|null $view
@param array $data
@return string | entailment |
public function send($notifiable, Notification $notification)
{
if (! $notifiable->routeNotificationFor('mail')) {
return;
}
$mail = $notification->toMail($notifiable);
$this->mailer->send($mail->view, $mail->data(), function ($message) use ($notifiable, $notification, $mail)
{
$recipients = empty($mail->to) ? $notifiable->routeNotificationFor('mail') : $mail->to;
if (! empty($mail->from)) {
$message->from($mail->from[0], isset($mail->from[1]) ? $mail->from[1] : null);
}
if (is_array($recipients)) {
$message->bcc($recipients);
} else {
$message->to($recipients);
}
if (! empty($mail->cc)) {
$message->cc($mail->cc);
}
if (! empty($mail->replyTo)) {
$message->replyTo($mail->replyTo[0], isset($mail->replyTo[1]) ? $mail->replyTo[1] : null);
}
$message->subject($mail->subject ?: Str::title(
Str::snake(class_basename($notification), ' ')
));
foreach ($mail->attachments as $attachment) {
$message->attach($attachment['file'], $attachment['options']);
}
foreach ($mail->rawAttachments as $attachment) {
$message->attachData($attachment['data'], $attachment['name'], $attachment['options']);
}
if (! is_null($mail->priority)) {
$message->setPriority($mail->priority);
}
});
} | Send the given notification.
@param mixed $notifiable
@param \Notifications\Notification $notification
@return void | entailment |
public function load(array $configs, ContainerBuilder $container)
{
$processor = new Processor();
$configuration = new Configuration();
$config = $processor->processConfiguration($configuration, $configs);
$config = $this->addDefaults($config);
if ('orm' !== $config['manager_type']) {
throw new \RuntimeException('Only ORM manager is implemented');
}
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('timeline.xml');
$loader->load(sprintf('timeline_%s.xml', $config['manager_type']));
// NEXT_MAJOR: Go back to simple xml configuration when bumping requirements to SF 2.6+
if (interface_exists('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')) {
$tokenStorageReference = new Reference('security.token_storage');
} else {
$tokenStorageReference = new Reference('security.context');
}
$container
->getDefinition('sonata.timeline.admin.extension')
->replaceArgument(1, $tokenStorageReference)
;
$container
->getDefinition('sonata.timeline.block.timeline')
->replaceArgument(4, $tokenStorageReference)
;
$this->configureClass($config, $container);
$this->registerDoctrineMapping($config);
} | Loads the url shortener configuration.
@param array $configs An array of configuration settings
@param ContainerBuilder $container A ContainerBuilder instance | entailment |
public function addDefaults(array $config)
{
if ('orm' === $config['manager_type']) {
$modelType = 'Entity';
} elseif ('mongodb' === $config['manager_type']) {
$modelType = 'Document';
}
$defaultConfig['class']['timeline'] = sprintf('Application\\Sonata\\TimelineBundle\\%s\\Timeline', $modelType);
$defaultConfig['class']['action'] = sprintf('Application\\Sonata\\TimelineBundle\\%s\\Action', $modelType);
$defaultConfig['class']['action_component'] = sprintf('Application\\Sonata\\TimelineBundle\\%s\\ActionComponent', $modelType);
$defaultConfig['class']['component'] = sprintf('Application\\Sonata\\TimelineBundle\\%s\\Component', $modelType);
return array_replace_recursive($defaultConfig, $config);
} | @param array $config
@return array | entailment |
public function processColumnListing($results)
{
return array_values(array_map(function ($result)
{
$result = (object) $result;
return $result->name;
}, $results));
} | Process the results of a column listing query.
@param array $results
@return array | entailment |
protected function tokensMatch($request)
{
$sessionToken = $request->session()->token();
$token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN');
if (is_null($token) && ! is_null($header = $request->header('X-XSRF-TOKEN'))) {
$token = $this->encrypter->decrypt($header);
}
if (! is_string($sessionToken) || ! is_string($token)) {
return false;
}
return Str::equals($sessionToken, $token);
} | Determine if the session and input CSRF tokens match.
@param \Nova\Http\Request $request
@return bool | entailment |
protected function addCookieToResponse($request, $response)
{
$config = $this->app['config']['session'];
$cookie = new Cookie(
'XSRF-TOKEN',
$request->session()->token(),
time() + 60 * 120,
$config['path'],
$config['domain'],
$config['secure'], false
);
$response->headers->setCookie($cookie);
return $response;
} | Add the CSRF token to the response cookies.
@param \Nova\Http\Request $request
@param \Nova\Http\Response $response
@return \Nova\Http\Response | entailment |
public function bulk($jobs, $data = '', $queue = null)
{
$queue = $this->getQueue($queue);
$availableAt = $this->getAvailableAt(0);
$records = array_map(function ($job) use ($queue, $data, $availableAt)
{
return $this->buildDatabaseRecord(
$queue, $this->createPayload($job, $data), $availableAt
);
}, (array) $jobs);
return $this->database->table($this->table)->insert($records);
} | Push an array of jobs onto the queue.
@param array $jobs
@param mixed $data
@param string $queue
@return mixed | entailment |
protected function pushToDatabase($delay, $queue, $payload, $attempts = 0)
{
$attributes = $this->buildDatabaseRecord(
$this->getQueue($queue), $payload, $this->getAvailableAt($delay), $attempts
);
return $this->database->table($this->table)->insertGetId($attributes);
} | Push a raw payload to the database with a given delay.
@param \DateTime|int $delay
@param string|null $queue
@param string $payload
@param int $attempts
@return mixed | entailment |
public function pop($queue = null)
{
$queue = $this->getQueue($queue);
return $this->database->transaction(function () use ($queue)
{
if (! is_null($job = $this->getNextAvailableJob($queue))) {
$this->markJobAsReserved($job->id, $job->attempts);
return new DatabaseJob(
$this->container, $this, $job, $queue
);
}
});
} | Pop the next job off of the queue.
@param string $queue
@return \Nova\Contracts\Queue\Job|null | entailment |
protected function getNextAvailableJob($queue)
{
$job = $this->database->table($this->table)
->lockForUpdate()
->where('queue', $this->getQueue($queue))
->where(function ($query)
{
$this->isAvailable($query);
$this->isReservedButExpired($query);
})
->orderBy('id', 'asc')
->first();
if (! is_null($job)) {
return (object) $job;
}
} | Get the next available job for the queue.
@param string|null $queue
@return \StdClass|null | entailment |
protected function isAvailable($query)
{
$query->where(function ($query)
{
$query->whereNull('reserved_at')->where('available_at', '<=', $this->getTime());
});
} | Modify the query to check for available jobs.
@param \Illuminate\Database\Query\Builder $query
@return void | entailment |
public function deleteReserved($queue, $id)
{
$this->database->transaction(function () use ($id)
{
$record = $this->database->table($this->table)->lockForUpdate()->find($id);
if (! is_null($record)) {
$this->database->table($this->table)->where('id', $id)->delete();
}
});
} | Delete a reserved job from the queue.
@param string $queue
@param string $id
@return void | entailment |
protected function getAvailableAt($delay)
{
$availableAt = ($delay instanceof DateTime) ? $delay : Carbon::now()->addSeconds($delay);
return $availableAt->getTimestamp();
} | Get the "available at" UNIX timestamp.
@param \DateTime|int $delay
@return int | entailment |
public function validAuthenticationResponse(Request $request, $result)
{
$channel = $request->input('channel_name');
$socketId = $request->input('socket_id');
if (Str::startsWith($channel, 'presence-')) {
$user = $request->user();
$result = $this->pusher->presence_auth(
$channel, $socketId, $user->getAuthIdentifier(), $result
);
} else {
$result = $this->pusher->socket_auth($channel, $socketId);
}
return json_decode($result, true);
} | Return the valid authentication response.
@param \Nova\Http\Request $request
@param mixed $result
@return mixed | entailment |
public function broadcast(array $channels, $event, array $payload = array())
{
$socket = Arr::pull($payload, 'socket');
$event = str_replace('\\', '.', $event);
$response = $this->pusher->trigger($this->formatChannels($channels), $event, $payload, $socket, true);
if (($response['status'] >= 200) && ($response['status'] <= 299)) {
return;
}
throw new BroadcastException($response['body']);
} | {@inheritdoc} | entailment |
public function socket($request = null)
{
if (is_null($request) && ! $this->app->bound('request')) {
return;
}
$request = $request ?: $this->app['request'];
if ($request->hasHeader('X-Socket-ID')) {
return $request->header('X-Socket-ID');
}
} | Get the socket ID for the given request.
@param \Nova\Http\Request|null $request
@return string|null | entailment |
public function driver($name = null)
{
$name = $name ?: $this->getDefaultDriver();
if (isset($this->drivers[$name])) {
return $this->drivers[$name];
}
return $this->drivers[$name] = $this->resolve($name);
} | Get a driver instance.
@param string $name
@return mixed | entailment |
protected function callCustomCreator(array $config)
{
$driver = $config['driver'];
return call_user_func($this->customCreators[$driver], $this->app, $config);
} | Call a custom driver creator.
@param array $config
@return mixed | entailment |
protected function createPusherDriver(array $config)
{
$options = Arr::get($config, 'options', array());
// Create a Pusher instance.
$pusher = new Pusher($config['key'], $config['secret'], $config['app_id'], $options);
return new PusherBroadcaster($this->app, $pusher);
} | Create an instance of the driver.
@param array $config
@return \Nova\Broadcasting\BroadcasterInterface | entailment |
protected function createRedisDriver(array $config)
{
$connection = Arr::get($config, 'connection');
// Create a Redis Database instance.
$redis = $this->app->make('redis');
return new RedisBroadcaster($this->app, $redis, $connection);
} | Create an instance of the driver.
@param array $config
@return \Nova\Broadcasting\BroadcasterInterface | entailment |
protected function createLogDriver(array $config)
{
$logger = $this->app->make('Psr\Log\LoggerInterface');
return new LogBroadcaster($this->app, $logger);
} | Create an instance of the driver.
@param array $config
@return \Nova\Broadcasting\BroadcasterInterface | entailment |
public function appends($keys, $value = null)
{
if (! is_array($keys)) {
return $this->addQuery($keys, $value);
}
foreach ($keys as $key => $value) {
$this->addQuery($key, $value);
}
return $this;
} | Add a set of query string values to the paginator.
@param array|string $keys
@param string|null $value
@return $this | entailment |
public function getUrlGenerator()
{
if (isset($this->urlGenerator)) {
return $this->urlGenerator;
}
// Check if an URL Generator resolver was set.
else if (! isset(static::$urlGeneratorResolver)) {
throw new RuntimeException("URL Generator resolver not set on Paginator.");
}
return $this->urlGenerator = call_user_func(static::$urlGeneratorResolver, $this);
} | Get the URL Generator instance.
@return \Nova\Pagination\UrlGenerator | entailment |
public function setItems($items)
{
$this->items = ($items instanceof Collection) ? $items : Collection::make($items);
return $this;
} | Set the paginator's underlying collection.
@param mixed $items
@return $this | entailment |
protected function addWhere(QueryBuilder $query, $key, $extraValue)
{
if ($extraValue === 'NULL') {
$query->whereNull($key);
} elseif ($extraValue === 'NOT_NULL') {
$query->whereNotNull($key);
} else {
$query->where($key, $extraValue);
}
} | Add a "WHERE" clause to the given query.
@param \Nova\Database\Query\Builder $query
@param string $key
@param string $extraValue
@return void | entailment |
protected function setListenerOptions()
{
$this->listener->setEnvironment($this->container->environment());
$this->listener->setSleep($this->option('sleep'));
$this->listener->setMaxTries($this->option('tries'));
$this->listener->setOutputHandler(function($type, $line)
{
$this->output->write($line);
});
} | Set the options on the queue listener.
@return void | entailment |
public function addTwigAssets()
{
if (!$this->twig instanceof \Twig_Environment) {
throw new \LogicException('Twig environment not set');
}
$twigNamespaces = $this->loader->getNamespaces();
foreach ($twigNamespaces as $ns) {
if ( count($this->loader->getPaths($ns)) > 0 ) {
$iterator = Finder::create()->files()->in($this->loader->getPaths($ns));
foreach ($iterator as $file) {
$resource = new TwigResource($this->loader, '@' . $ns . '/' . $file->getRelativePathname());
$this->lam->addResource($resource, 'twig');
}
}
}
} | Locates twig templates and adds their defined assets to the lazy asset manager | entailment |
public function handle()
{
$slug = $this->parseSlug($this->argument('slug'));
$name = $this->parseName($this->argument('name'));
if (! $this->packages->exists($slug)) {
return $this->error('Package ['.$this->data['slug'].'] does not exist.');
}
$this->packageInfo = collect(
$this->packages->where('slug', $slug)
);
// Check for a proper type of the
$type = $this->packageInfo->get('type');
if (($type != 'package') && ($type != 'module')) {
return $this->error('Package [' .$this->data['slug'] .'] has no generator of this type.');
}
$this->packagesPath = ($type == 'module')
? $this->packages->getModulesPath()
: $this->packages->getPackagesPath();
$this->data['slug'] = $slug;
$this->data['name'] = $name;
return $this->generate();
} | Execute the console command.
@return mixed | entailment |
protected function generate()
{
foreach ($this->listFiles as $key => $file) {
$filePath = $this->makeFilePath($this->listFolders[$key], $this->data['name']);
$this->resolveByPath($filePath);
$file = $this->formatContent($file);
//
$find = basename($filePath);
$filePath = strrev(preg_replace(strrev("/$find/"), '', strrev($filePath), 1));
$filePath = $filePath .$file;
if ($this->files->exists($filePath)) {
return $this->error($this->type .' already exists!');
}
$this->makeDirectory($filePath);
foreach ($this->signOption as $option) {
if ($this->option($option)) {
$stubFile = $this->listStubs[$option][$key];
$this->resolveByOption($this->option($option));
break;
}
}
if (! isset($stubFile)) {
$stubFile = $this->listStubs['default'][$key];
}
$this->files->put($filePath, $this->getStubContent($stubFile));
}
return $this->info($this->type.' created successfully.');
} | generate the console command.
@return mixed | entailment |
protected function parseName($name)
{
if (str_contains($name, '\\')) {
$name = str_replace('\\', '/', $name);
}
if (str_contains($name, '/')) {
$formats = collect(explode('/', $name))->map(function ($name)
{
return Str::studly($name);
});
$name = $formats->implode('/');
} else {
$name = Str::studly($name);
}
return $name;
} | Parse class name of the Package.
@param string $slug
@return string | entailment |
protected function makeFilePath($folder, $name)
{
$folder = ltrim($folder, '\/');
$folder = rtrim($folder, '\/');
$name = ltrim($name, '\/');
$name = rtrim($name, '\/');
if ($this->packageInfo->get('type') == 'module') {
return $this->packagesPath .DS .$this->packageInfo->get('basename') .DS .$folder .DS .$name;
}
return $this->packagesPath .DS .$this->packageInfo->get('basename') .DS .'src' .DS .$folder .DS .$name;
} | Make FilePath.
@param string $folder
@param string $name
@return string | entailment |
protected function getNamespace($file)
{
$basename = $this->packageInfo->get('basename');
if ($this->packageInfo->get('type') == 'module') {
$namespace = str_replace($this->packagesPath .DS .$basename, '', $file);
} else {
$namespace = str_replace($this->packagesPath .DS .$basename .DS .'src', '', $file);
}
$find = basename($namespace);
$namespace = strrev(preg_replace(strrev("/$find/"), '', strrev($namespace), 1));
$namespace = $this->packageInfo->get('namespace') .'\\' .trim($namespace, '\\/');
return str_replace('/', '\\', $namespace);
} | Get Namespace of the current file.
@param string $file
@return string | entailment |
protected function getBaseNamespace()
{
if ($this->packageInfo->get('type') == 'module') {
return $this->packages->getModulesNamespace();
}
return $this->packages->getPackagesNamespace();
} | Get the configured Package base namespace.
@return string | entailment |
protected function getStubContent($stubName)
{
$stubPath = $this->getStubsPath() .$stubName;
$content = $this->files->get($stubPath);
return $this->formatContent($content);
} | Get stub content by key.
@param int $key
@return string | entailment |
public function handle()
{
if (! $this->confirmToProceed()) {
return;
}
$slug = $this->argument('slug');
if (! empty($slug)) {
if (! $this->packages->exists($slug)) {
return $this->error('Package does not exist.');
}
if ($this->packages->isEnabled($slug)) {
return $this->reset($slug);
}
return;
}
$packages = $this->packages->enabled()->reverse();
foreach ($packages as $package) {
$this->comment('Resetting the migrations of Package: ' .$package['name']);
$this->reset($package['slug']);
}
} | Execute the console command.
@return mixed | 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.