sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
public function getTemporary()
{
// disable query logging
$connection_name = Config::get('laravel-import-export::baseconf.connection_name');
DB::connection($connection_name)->disableQueryLog();
$temporary = TemporaryModel::whereRaw("1")->orderBy("id","DESC")->first();
if($temporary)
{
$this->csv_file =... | Get data from the temporary table
@return Mixed $data
@throws Exception | entailment |
public function saveTemporary($csv_file = null, $temporary_model = null)
{
$csv_file = $csv_file ? $csv_file : $this->csv_file;
if( $csv_file )
{
$temporary_model = ($temporary_model) ? $temporary_model : new TemporaryModel();
$temporary_model->fill(array("file_object"=>$csv_file));
// disable query l... | Put data in the temporary table
@return Boolean $success
@throws Exception | entailment |
public function updateHeaders(CsvFile $csv_file, array $columns, $table_name)
{
$this->csv_file = $csv_file ? $csv_file : $this->csv_file;
foreach($this->csv_file as $csv_line)
{
$this->updateHeader($csv_line, $columns, $table_name);
}
} | Update headers of the csv_file
@param CsvFile $csv_line
@param Array $columns $key=column name, $value=column index
@param Sring $table_name name of the table
@throws UnalignedArrayException | entailment |
protected function updateHeader(CsvLine $csv_line, array $columns, $table_name)
{
$model_attributes = $csv_line->getAttributes();
$new_attributes = array();
foreach($columns as $key_column => $column)
{
if( isset($model_attributes[$key_column]) )
{
// append data to new attributes
$new_attributes... | Update headers of the csv_line
@param CsvLine $csv_line
@param Array $columns $key=column name, $value=column index
@param Sring $table_name name of the table
@return Boolean
@throws UnalignedArrayException | entailment |
public function openFromCsv(array $config, CsvFileBuilder $builder = null)
{
$builder = $builder ? $builder : new CsvFileBuilder();
$builder->setConfigModel($config["model"]);
$builder->setConfigFileParse($config["file_parse"]);
$builder->setConfig($config["builder"]);
$builder->buildFromCsv();
$this->csv... | This method build the CsvFile from a csv file
@param $config
'model' for RunTimeModel
'file' for ParseCsv
'builder' for CsvFileBuilder
@throws FileNotFoundException
@throws InvalidArgumentException
@throws NoDataException
@throws UnalignedArrayException
@throws DomainException
@return CsvFile | entailment |
public function openFromDb(array $config, DbFileBuilder $builder = null)
{
$builder = $builder ? $builder : new DbFileBuilder();
$builder->setConfig($config);
$builder->build();
$this->csv_file = $builder->getCsvFile();
return $this->getCsvFile();
} | Build the csvFile from Db
@throws Exception
@throws PDOException
@return CsvFile | entailment |
public function getMaxLength($csv_file = null)
{
$csv_file = $csv_file ? $csv_file : $this->csv_file;
$sizes = array(0);
if( ! $csv_file )
{
throw new NoDataException();
}
foreach($csv_file as $line)
{
$sizes[]=count($line->getElements() );
}
return max($sizes);
} | Get the max lenght of a csv_line
@return Integer | entailment |
public function getCsvString($separator, CsvFile $csv_file = null)
{
$csv_file = $csv_file ? $csv_file : $this->csv_file;
$csv = '';
if( ! isset($csv_file) )
{
throw new NoDataException;
}
else
{
foreach($csv_file as $key => $csv_line)
{
if($key == 0)
{
$csv.=$csv_line->getCsvHeader... | Create the csv string rappresenting the CsvFile
@return String $csv
@throws NoDataException | entailment |
public function run(callable $confirmationCallback = null, $migrationId = null, $loadFromFile = false)
{
if ($this->logger) {
$this->service->setLogger($this->logger);
}
// Выбрать миграцию
if ($migrationId) {
if ($next = $this->service->getDbRepository()->fi... | Run
@param callable|null $confirmationCallback - Спросить подтверждение у пользователя перед запуском каждой миграции
функция должна вернуть true/false
принимает $migrationTitle
@param int $migrationId - ID конкретной миграции, которую надо накатить
@param bool $loadFromFile - Загру... | entailment |
public function pack($object) : ?PackedObject
{
$uow = $this->em->getUnitOfWork();
if (! $uow->isInIdentityMap($object)) {
return null;
}
$identity = $uow->getEntityIdentifier($object);
$count = count($identity);
if ($count === 0) {
return ... | {@inheritdoc} | entailment |
public function unpack(PackedObject $packedObject)
{
$class = $packedObject->getClass();
if ($this->em->getMetadataFactory()->isTransient($class)) {
return null;
}
return $this->em->getReference($class, $packedObject->getData());
} | {@inheritdoc} | entailment |
public function buildFromCsv(CsvLine $csv_line_base = null)
{
$this->csv_line_base = $csv_line_base ? $csv_line_base : new CsvLine;
$this->csv_parser->setConfig($this->config_file_parse);
$this->csv_line_base->setConfig($this->config_model);
$this->updateCsvHeader();
// Csv loop
while ( ($csv_line_array ... | This method build the CsvFile from a csv file
@throws FileNotFoundException
@throws InvalidArgumentException
@throws UnalignedArrayException
@throws DomainException | entailment |
protected function updateCsvHeader()
{
if( $this->config['first_line_headers'] )
{
$csv_line_array = $this->csv_parser->parseCsvFile();
$this->csv_file->setCsvHeader($csv_line_array);
}
} | Update the csv header with first row of the file
if "first_line_headers" is enabled | entailment |
public function match(Request $request) : ?RouteMatch
{
$path = $request->getPath();
foreach ($this->prefixes as $prefix) {
if (strpos($path, $prefix) === 0) {
return $this->route->match($request);
}
}
return null;
} | {@inheritdoc} | entailment |
protected function generateIdentifier()
{
if ($this->identifier === null) {
++self::$nextIdentifier;
self::$nextIdentifier &= 0xFFFF;
$this->identifier = self::$nextIdentifier;
}
return $this->identifier;
} | Returns the identifier or generates a new one.
@return int | entailment |
public function setIdentifier($value)
{
if ($value !== null && ($value < 0 || $value > 0xFFFF)) {
throw new \InvalidArgumentException(
sprintf(
'Expected an identifier between 0x0000 and 0xFFFF but got %x',
$value
)
... | Sets the identifier.
@param int|null $value
@throws \InvalidArgumentException | entailment |
public function approvedWithPending(): ActiveQuery
{
return $this->andWhere([$this->statusAttribute => [Status::APPROVED, Status::PENDING]]);
} | Get a new active query object that includes approved and pending resources.
@return ActiveQuery | entailment |
public function process(Request $request, Handler $handler): Response
{
try {
$symfonyRequest = (new HttpFoundationFactory())
->createRequest($request);
$this->router->getContext()->fromRequest($symfonyRequest);
$route = $this->router
->mat... | Process a request and return a response. | entailment |
public function channel($channel) {
if (!isset($channel['link'])) {
$channel['link'] = '/';
}
if (!isset($channel['title'])) {
$channel['title'] = '';
}
if (!isset($channel['description'])) {
$channel['description'] = '';
}
$channel = $this->_prepareOutput($channel);
return $channel;
} | Prepares the channel and sets default values.
@param array $channel
@return array Channel | entailment |
public function render($view = null, $layout = null) {
if (isset($this->viewVars['_serialize'])) {
return $this->_serialize($this->viewVars['_serialize']);
}
if ($view !== false && $this->_getViewFileName($view)) {
return parent::render($view, false);
}
} | Render a RSS view.
Uses the special '_serialize' parameter to convert a set of
view variables into a XML response. Makes generating simple
XML responses very easy. You can omit the '_serialize' parameter,
and use a normal view + layout as well.
@param string|null $view The view being rendered.
@param string|null $lay... | entailment |
protected function _serialize($serialize) {
$rootNode = isset($this->viewVars['_rootNode']) ? $this->viewVars['_rootNode'] : 'channel';
if (is_array($serialize)) {
$data = [$rootNode => []];
foreach ($serialize as $alias => $key) {
if (is_numeric($alias)) {
$alias = $key;
}
$data[$rootNode][... | Serialize view vars.
@param string|array $serialize The viewVars that need to be serialized.
@return string The serialized data
@throws \RuntimeException When the prefix is not specified | entailment |
protected function _prepareOutput($item) {
foreach ($item as $key => $val) {
$prefix = null;
// The cast prevents a PHP bug for switch case and false positives with integers
$bareKey = (string)$key;
// Detect namespaces
if (strpos($key, ':') !== false) {
list($prefix, $bareKey) = explode(':', $key... | RssView::_prepareOutput()
@param array $item
@return array | entailment |
protected function _newCdata($content) {
$i = count($this->_cdata);
$this->_cdata[$i] = $content;
return '###CDATA-' . $i . '###';
} | RssView::_newCdata()
@param string $content
@return string | entailment |
protected function _replaceCdata($content) {
foreach ($this->_cdata as $n => $data) {
$data = '<![CDATA[' . $data . ']]>';
$content = str_replace('###CDATA-' . $n . '###', $data, $content);
}
return $content;
} | RssView::_replaceCdata()
@param string $content
@return string | entailment |
public function match(Request $request) : ?RouteMatch
{
$path = $request->getPath();
$httpMethod = $request->getMethod();
foreach ($this->routes as $values) {
[$regexp] = $values;
if (preg_match($regexp, $path, $matches) === 1) {
[, $httpMethods] = $... | {@inheritdoc} | entailment |
public function embed($parent, string $field, &$entity): bool
{
// In order to update the document if it exists inside the $parent
$this->unembed($parent, $field, $entity);
$fieldValue = $parent->$field;
$fieldValue[] = $entity;
$parent->$field = array_values($fieldValue);
... | Embeds the given $entity into $field of $parent. This method will also
consider the _id of the $entity in order to update it if it is already
present in $field.
@param mixed $parent the object where the $entity will be embedded
@param string $field name of the field of the object where the document will be embedded
... | entailment |
public function unembed($parent, string $field, &$entity): bool
{
$fieldValue = (array) $parent->$field;
$id = $this->getId($entity);
foreach ($fieldValue as $key => $document) {
if ($id == $this->getId($document)) {
unset($fieldValue[$key]);
}
... | Removes the given $entity from $field of $parent. This method will
consider the _id of the $entity in order to remove it.
@param mixed $parent the object where the $entity will be removed
@param string $field name of the field of the object where the document is
@param mixed $entity entity that will be removed from... | entailment |
public function attach($parent, string $field, &$entity): bool
{
$fieldValue = (array) $parent->$field;
$newId = $this->getId($entity);
foreach ($fieldValue as $id) {
if ($id == $newId) {
return true;
}
}
$fieldValue[] = $newId;
... | Attach a new _id reference into $field of $parent.
@param mixed $parent the object where $entity will be referenced
@param string $field the field where the _id reference of $entity will be stored
@param object|array $entity the object that is being attached
@return bool Success | entailment |
public function detach($parent, string $field, &$entity): bool
{
$fieldValue = (array) $parent->$field;
$newId = $this->getId($entity);
foreach ($fieldValue as $key => $id) {
if ($id == $newId) {
unset($fieldValue[$key]);
}
}
$parent-... | Removes an _id reference from $field of $parent.
@param mixed $parent the object where $entity reference will be removed
@param string $field the field where the _id reference of $entity is stored
@param mixed $entity the object being detached or its _id
@return bool Success | entailment |
protected function getId(&$object)
{
if (is_array($object)) {
if (isset($object['_id']) && $object['_id']) {
return $object['_id'];
}
return $object['_id'] = new ObjectId();
}
if (is_object($object) && !$object instanceof ObjectId) {
... | Gets the _id of the given object or array. If there is no _id in it a new
_id will be generated and set on the object (while still returning it).
@param mixed $object the object|array that the _id will be retrieved from
@return ObjectId|mixed | entailment |
public static function forMethod(string $class, string $method, array $classParameters = [], array $methodParameters = []) : RouteMatch
{
try {
$controller = new \ReflectionMethod($class, $method);
} catch (\ReflectionException $e) {
throw RoutingException::invalidControllerC... | Returns a RouteMatch for the given class and method.
@param string $class
@param string $method
@param array $classParameters
@param array $methodParameters
@return RouteMatch The route match.
@throws RoutingException If the class or method does not exist. | entailment |
public static function forFunction($function, array $functionParameters = []) : RouteMatch
{
try {
$controller = new \ReflectionFunction($function);
} catch (\ReflectionException $e) {
throw RoutingException::invalidControllerFunction($e, $function);
}
return... | Returns a RouteMatch for the given function or closure.
@param string|\Closure $function
@param array $functionParameters
@return RouteMatch The route match.
@throws RoutingException If the function is invalid. | entailment |
public function withClassParameters(array $parameters) : RouteMatch
{
$routeMatch = clone $this;
$routeMatch->classParameters = $parameters + $this->classParameters;
return $routeMatch;
} | Returns a copy of this RouteMatch, with additional class parameters.
Parameters with the same name will override current parameters.
This RouteMatch instance is immutable, and unaffected by this method call.
@param array $parameters An associative array of class parameters.
@return RouteMatch | entailment |
public function withFunctionParameters(array $parameters) : RouteMatch
{
$routeMatch = clone $this;
$routeMatch->functionParameters = $parameters + $this->functionParameters;
return $routeMatch;
} | Returns a copy of this RouteMatch, with additional function parameters.
Parameters with the same name will override current parameters.
This RouteMatch instance is immutable, and unaffected by this method call.
@param array $parameters An associative array of function parameters.
@return RouteMatch | entailment |
protected function printFormNew(){
$str = parent::printFormNew();
$str .=
"<div class=\"row\">".
"<div class=\"col-md-12\">".
"<h3>Step1: Upload file</h3>".
// "<span class=\"glyphicon glyphicon-upload pull-right icon-medium\"></span>".
Form::open(array( 'url' => $this->getProcessUrl(), 'files' ... | Return the form that needs to be processed | 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 C... | Process the form
@return Boolean $is_executed if the state is executed successfully | entailment |
protected function getConfigFromInput()
{
$config_file_parse['separator'] = $this->form_input['separator'];
$config_file_parse['file_path'] = $this->form_input['file_csv']->getRealPath();
$config["file_parse"] = $config_file_parse;
$config_builder['first_line_headers'] = ( $this->form_input['headers'] != '' )... | get the config from form input | entailment |
public function convertToString($source)
{
if (is_object($source)) {
if ($source instanceof NamedInterface) {
return $source->getName();
} elseif (method_exists($source, '__toString')) {
return (string) $source;
} else {
ret... | @param mixed $source
@return string | entailment |
public function convertToObjectRequest($query)
{
$factory = new RequestFactory();
$request = $factory->create($query['api']);
if (isset($query['parameters'])) {
try {
$request = Utils::setter($request, $query['parameters']);
} catch (NavitiaCreationExc... | {@inheritDoc} | entailment |
private function assertValidClientID($value, $fromPacket)
{
if (strlen($value) > 23) {
$this->throwException(
sprintf(
'Expected client id shorter than 24 bytes but got "%s".',
$value
),
$fromPacket
... | Asserts that a client id is shorter than 24 bytes and only contains characters 0-9, a-z or A-Z.
@param string $value
@param bool $fromPacket
@throws MalformedPacketException
@throws \InvalidArgumentException | entailment |
public function getAttribute(string $key)
{
$inAttributes = array_key_exists($key, $this->attributes);
if ($inAttributes) {
return $this->attributes[$key];
} elseif ('attributes' == $key) {
return $this->attributes;
}
} | Get an attribute from the model.
@param string $key the attribute to be accessed
@return mixed | entailment |
public function fill(array $input, bool $force = false)
{
foreach ($input as $key => $value) {
if ($force) {
$this->setAttribute($key, $value);
continue;
}
if ((empty($this->fillable) || in_array($key, $this->fillable)) && !in_array($key,... | Set the model attributes using an array.
@param array $input the data that will be used to fill the attributes
@param bool $force force fill | entailment |
protected function hasMutatorMethod($key, $prefix)
{
$method = $this->buildMutatorMethod($key, $prefix);
return method_exists($this, $method);
} | Verify if model has a mutator method defined.
@param mixed $key attribute name
@param mixed $prefix method prefix to be used
@return bool | entailment |
protected function calculcateScore(TransitionInterface $transition)
{
$score = 0;
if ($transition->getEventName()) {
$score += 2;
}
if ($transition->getConditionName()) {
++$score;
}
return $score;
} | @param TransitionInterface $transition
@return int | entailment |
public static function create(Container $container = null) : Application
{
if ($container !== null) {
$valueResolver = $container->getValueResolver();
$injectionPolicy = $container->getInjectionPolicy();
} else {
$valueResolver = new DefaultValueResolver();
... | Creates an application.
If a dependency injection container is provided, it is used to automatically inject dependencies in controllers.
@param Container|null $container
@return Application | entailment |
public function run() : void
{
$request = Request::getCurrent();
$response = $this->handle($request);
$response->send();
} | Runs the application.
@return void | entailment |
public function handle(Request $request) : Response
{
try {
return $this->handleRequest($request);
} catch (HttpException $e) {
return $this->handleHttpException($e, $request);
} catch (\Throwable $e) {
return $this->handleUncaughtException($e, $request);
... | @param \Brick\Http\Request $request
@return \Brick\Http\Response | entailment |
private function handleHttpException(HttpException $exception, Request $request) : Response
{
$response = new Response();
$response->setContent($exception);
$response->setStatusCode($exception->getStatusCode());
$response->setHeaders($exception->getHeaders());
$response->set... | Converts an HttpException to a Response.
@param \Brick\Http\Exception\HttpException $exception
@param \Brick\Http\Request $request
@return \Brick\Http\Response | entailment |
private function handleUncaughtException(\Throwable $exception, Request $request) : Response
{
$httpException = new HttpInternalServerErrorException('Uncaught exception', $exception);
return $this->handleHttpException($httpException, $request);
} | Wraps an uncaught exception in an HttpInternalServerErrorException, and converts it to a Response.
@param \Throwable $exception
@param \Brick\Http\Request $request
@return \Brick\Http\Response | entailment |
private function handleRequest(Request $request) : Response
{
$event = new IncomingRequestEvent($request);
$this->eventDispatcher->dispatch(IncomingRequestEvent::class, $event);
$match = $this->route($request);
$event = new RouteMatchedEvent($request, $match);
$this->eventD... | @param \Brick\Http\Request $request The request to handle.
@return \Brick\Http\Response The generated response.
@throws \Brick\Http\Exception\HttpException If a route throws such an exception, or no route matches the request.
@throws \UnexpectedValueException If a route or controller returned an invalid val... | entailment |
private function route(Request $request) : RouteMatch
{
foreach ($this->routes as $route) {
try {
$match = $route->match($request);
}
catch (RoutingException $e) {
throw new HttpNotFoundException($e->getMessage(), $e);
}
... | Routes the given Request.
@param Request $request The request.
@return RouteMatch The route match.
@throws HttpNotFoundException If no route matches the request.
@throws \UnexpectedValueException If a route returns an invalid value. | entailment |
private function invalidReturnValue(string $what, string $expected, $actual) : \UnexpectedValueException
{
$message = 'Invalid return value from %s: expected %s, got %s.';
$actual = is_object($actual) ? get_class($actual) : gettype($actual);
return new \UnexpectedValueException(sprintf($me... | @param string $what The name of the expected resource.
@param string $expected The expected return value type.
@param mixed $actual The actual return value.
@return \UnexpectedValueException | entailment |
public static function nameCase($string = '', array $options = [])
{
if ($string == '') return $string;
self::$options = array_merge(self::$options, $options);
// Do not do anything if string is mixed and lazy option is true.
if (self::$options['lazy'] && self::skipMixed($string)) ... | Main function for NameCase.
@param string $string
@param array $options
@return string | entailment |
private static function capitalize($string)
{
$string = mb_strtolower($string);
$string = mb_ereg_replace_callback('\b\w', function ($matches) {
return mb_strtoupper($matches[0]);
}, $string);
// Lowercase 's
$string = mb_ereg_replace_callback('\'\w\b', function... | Capitalize first letters.
@param string $string
@return string | entailment |
private static function skipMixed($string)
{
$firstLetterLower = $string[0] == mb_strtolower($string[0]);
$allLowerOrUpper = (mb_strtolower($string) == $string || mb_strtoupper($string) == $string);
return ! ($firstLetterLower || $allLowerOrUpper);
} | Skip if string is mixed case.
@param string $string
@return bool | entailment |
private static function updateIrish($string)
{
if ( ! self::$options['irish']) return $string;
if (mb_ereg_match('.*?\bMac[A-Za-z]{2,}[^aciozj]\b', $string) || mb_ereg_match('.*?\bMc', $string)) {
$string = self::updateMac($string);
}
return mb_ereg_replace('Macmurdo', ... | Update for Irish names.
@param string $string
@return string | entailment |
private static function fixConjunction($string)
{
if ( ! self::$options['spanish']) return $string;
foreach (self::$conjunctions as $conjunction) {
$string = mb_ereg_replace('\b' . $conjunction . '\b', mb_strtolower($conjunction), $string);
}
return $string;
} | Fix Spanish conjunctions.
@param string $string
@return string | entailment |
private static function updateMac($string)
{
$string = mb_ereg_replace_callback('\b(Ma?c)([A-Za-z]+)', function ($matches) {
return $matches[1] . mb_strtoupper(mb_substr($matches[2], 0, 1)) . mb_substr($matches[2], 1);
}, $string);
// Now fix "Mac" exceptions
foreach (se... | Updates irish Mac & Mc.
@param string $string
@return string | entailment |
public function send(TransactionInterface $transaction)
{
return $this->requestFactory->create(
static::transformRequest($transaction),
[],
$this->httpClient,
$this->loop
)->then(function (ResponseInterface $response) {
return \React\Promis... | @param TransactionInterface $transaction
@return \React\Promise\Promise | entailment |
public function has(string $key) : bool
{
return $this->session->has($this->getKey($key));
} | {@inheritdoc} | entailment |
public function set(string $key, $value) : void
{
$this->session->set($this->getKey($key), $value);
} | {@inheritdoc} | entailment |
public function remove(string $key) : void
{
$this->session->remove($this->getKey($key));
} | {@inheritdoc} | entailment |
public function reduce( $tolerance )
{
$this->points = $this->_reduce($this->points, (double)$tolerance);
return $this->points;
} | Public visible method to reduce points.
@param mixed $tolerance Defined threshold to reduce by
@return array Reduced set of points | entailment |
private function _reduce( $points, $tolerance )
{
$distanceMax = $index = 0;
// Can't user $this->lastkey, as this is a reclusive method.
$pointsEnd = key(array_slice($points, -1, 1, true));
for ( $i = 1; $i < $pointsEnd; $i++ ) {
$distance = $this->shortestDistanceToSegm... | Reduce points with Ramer-Douglas-Peucker algorithm.
@param array $points Finite set of points
@param mixed $tolerance Defined threshold to reduce by
@return array Reduced set of points | entailment |
public function reduce( $tolerance, $lookAhead=null )
{
if ($lookAhead) {
$this->lookAhead = (int)$lookAhead;
}
$key = 0;
$endPoint = min($this->lookAhead, $this->lastKey());
do {
if ( $key + 1 == $endPoint ) {
if ( $endPoint != $this... | Reduce points with Lang algorithm.
@param mixed $tolerance Defines threshold to reduce by.
@param integer $lookAhead Defines the segment size per iteration.
@return array Reduced set of points
@updated v1.2.0 Introduced `lookAhead` concept to allow user to control
performance & accuracy. | entailment |
public function resetState()
{
parent::resetState();
// clean temporary db
$table_name = Config::get('laravel-import-export::baseconf.table_prefix');
$connection_name = Config::get('laravel-import-export::baseconf.connection_name');
DB::connection($connection_name)->table($table_name)->truncate();
} | Reset the session_array state | entailment |
public function initializeState()
{
if (Session::has($this->session_key))
{
$this->setStateArray( Session::get($this->session_key) );
}
else
{
$this->resetState();
}
return $this->getStateArray();
} | Initialize starting import state from session | entailment |
public function resetState()
{
// clean states
$this->setStateArray( new StateArray() );
$state_array = $this->getStateArray();
$state_array->append( new $this->initial_state );
Session::put($this->session_key,$state_array);
} | Reset the session_array state | entailment |
public function setContent($layout)
{
$content = '';
$state_array = $this->getStateArray();
foreach($state_array as $state_key => $state)
{
$content.=$state->getForm();
}
$layout->content = $content;
} | Fill layout content with forms | entailment |
public function processForm()
{
$current_state = $this->getCurrent();
$executed_process = $current_state->processForm();
// set next state
$executed_next_state = $this->setNextState($current_state,$executed_process);
// return success
return ( $executed_process && $executed_next_state );
} | Process the current form
@return $executed if success
@throws ClassNotFoundException | entailment |
protected function setNextState($current_state, $executed)
{
try
{
$next_state = $current_state->getNextState();
}
catch(ClassNotFoundException $e)
{
Session::put('Errors', new MessageBag( array("Class" => "Class not found") ) );
return false;
}
if($executed)
{
// append next state
$thi... | Set the next state
@return Boolean $success | entailment |
public function replaceCurrent($value)
{
$key = $this->getLastKey();
if($key >= 0)
{
$this->getStateArray()->offsetSet($key,$value);
}
else
{
throw new NoDataException;
}
} | Replace the current state | entailment |
private function copy($variable, bool $pack, array & $visited = [], int $level = 0)
{
if (is_object($variable)) {
$hash = spl_object_hash($variable);
if (isset($visited[$hash])) {
return $visited[$hash];
}
if ($pack) {
$packed... | @param mixed $variable The variable to copy.
@param bool $pack True to pack, false to unpack.
@param array $visited The visited objects, for recursive calls.
@param int $level The nesting level.
@return mixed | entailment |
public function validateInput()
{
$v = Validator::make ( $this->model->getFormInput() , $this->model->getRules() );
$success = true;
if ( $v->fails() )
{
$this->model->setErrors( $v->messages() );
$success = false;
}
return $success;
} | Validate form_input with $rules
@return Boolean | entailment |
public function check(\ArrayAccess $keyvalue)
{
foreach ($this as $key => $value) {
if (!($keyvalue->offsetExists($key) && ($keyvalue->offsetGet($key) === $value))) {
return false;
}
}
return true;
} | @param \ArrayAccess $keyvalue
@return bool | entailment |
public function setVoter(\Symfony\Component\Security\Core\User\UserInterface $voter)
{
$this->voter = $voter;
return $this;
} | Set voter
@param \Symfony\Component\Security\Core\User\UserInterface $voter
@return VoteInterface | entailment |
protected function checkAttributeAssignable($attribute): void
{
if (empty($this->assignable)) {
return;
}
if (is_array($attribute)) {
foreach ($attribute as $singleAttribute) {
$this->checkAttributeAssignable($singleAttribute);
}
... | Checks whether attribute key(s) may be assigned values
@param string|array $attribute array key name or array of key names
@throws UnassignableAttributeException | entailment |
protected function &getAttributeValue(string $key)
{
if (isset($this->attributes[$key])) {
return $this->attributes[ $key ];
}
$null = null;
return $null;
} | Get a plain attribute
@param string $key
@return mixed | entailment |
public function setAttribute(string $key, $value): DataObjectInterface
{
$this->checkAttributeAssignable($key);
$this->attributes[$key] = $value;
return $this;
} | Get attribute
@param string $key
@param mixed $value
@return $this|DataObjectInterface | entailment |
public function setAttributes(array $attributes): void
{
$this->checkAttributeAssignable(array_keys($attributes));
$this->setRawAttributes($attributes);
} | Mass assignment of attributes
@param array $attributes associative | entailment |
public function __isset($key)
{
return (isset($this->attributes[$key]) && null !== $this->getAttributeValue($key));
} | Determine if an attribute exists on the model.
@param string $key
@return bool | entailment |
public function toArray(): array
{
if ( ! count($this->attributes)) {
return [];
}
// make this work recursively
$array = [];
foreach ($this->attributes as $key => $attribute) {
if ($attribute instanceof Arrayable) {
$attribute = $a... | ------------------------------------------------------------------------------ | entailment |
protected function recursiveToArray($item)
{
if (is_array($item)) {
foreach ($item as &$subitem) {
$subitem = $this->recursiveToArray($subitem);
}
unset($subitem);
return $item;
}
if ($item instanceof Arrayable) {
... | Recursively converts parameter to array
@param mixed $item
@return array|string | entailment |
protected function arrayToObject(array $array)
{
$obj = (object) [];
foreach ($array as $k => $v) {
if (strlen($k)) {
if (is_array($v)) {
$obj->{$k} = $this->arrayToObject($v);
} else {
$obj->{$k} = $v;
... | Warning: doesn't work with empty array keys!
@param array $array
@return object | entailment |
public function offsetSet($offset, $value)
{
if ( ! $this->magicAssignment) {
throw new UnassignableAttributeException("Not allowed to assign value by magic with array access");
}
$this->checkAttributeAssignable($offset);
$this->attributes[ $offset ] = $value;
} | Set the value for a given offset.
@param mixed $offset
@param mixed $value
@return void | entailment |
public function getNested(?string $key, $default = null)
{
if (null === $key) {
return $this;
}
if (isset($this->attributes[$key])) {
return $this->getAttribute($key);
}
$keys = explode('.', $key);
$part = $this->getAttribute( array_shift($ke... | Returns nested content by dot notation, similar to Laravel's Arr::get()
Works with nested arrays and data objects
@param string|null $key dot-notation representation of keys, null to return self
@param mixed $default default value to return if nothing found, may be a callback
@return mixed | entailment |
public function reduce( $tolerance )
{
$this->_tolerance = $tolerance;
$sentinelKey = 0;
while ($sentinelKey < $this->count()-1) {
$testKey = $sentinelKey + 1;
while ( $sentinelKey < $this->count()-1
&& $this->_isInTolerance($sentinelKey, $testKey) ) {... | Remove points with a distance under a given tolerance.
@param double $tolerance Maximum radial distance between points.
@return array Reduced set of points | entailment |
private function _isInTolerance($basePointIndex, $subjectPointIndex)
{
$radius = $this->distanceBetweenPoints(
$this->points[$basePointIndex],
$this->points[$subjectPointIndex]
);
return $radius < $this->_tolerance;
} | Helper method to ensure clean code.
@param integer $basePointIndex Sentinel point index.
@param integer $subjectPointIndex Test point index.
@return bool True if subject point is under tolerance, false otherwise. | entailment |
public function objectId($value = null)
{
if (null === $value) {
return new ObjectId();
}
if (is_string($value) && ObjectIdUtils::isObjectId($value)) {
$value = new ObjectId($value);
}
return $value;
} | Filters any field in the $fields that has it's value specified as a
'objectId'. It will wraps the $value, if any, into a ObjectId object.
@param mixed $value value that may be converted to ObjectId
@return ObjectId|mixed | entailment |
public function sequence(int $value = null)
{
if ($value) {
return $value;
}
return Ioc::make(SequenceService::class)
->getNextValue($this->collection ?: $this->entityClass);
} | Prepares the field to have a sequence. If $value is zero or not defined
a new auto-increment number will be "generated" for the collection of
the schema. The sequence generation is done by the SequenceService.
@param int|null $value value that will be evaluated
@return int | entailment |
public function createVote(RatingInterface $rating, UserInterface $voter)
{
$class = $this->getClass();
$vote = new $class;
$vote->setRating($rating);
$vote->setVoter($voter);
$this->dispatcher->dispatch(DCSRatingEvents::VOTE_CREATE, new Event\VoteEvent($vote));
ret... | Creates an empty vote instance
@param RatingInterface $rating
@param UserInterface $voter
@return \DCS\RatingBundle\Model\VoteInterface | entailment |
public function onDispatcherReady()
{
if ($this->dispatcher && $this->dispatcher->isReady()) {
$context = $this->currentContext;
$event = $this->currentEvent;
$this->dispatcher = null;
$this->currentContext = null;
$this->currentEvent = null;
... | is called after dispatcher was executed. | entailment |
public function dispatchEvent(DispatcherInterface $dispatcher, $name, \ArrayAccess $context = null)
{
if ($this->dispatcher) {
throw new \RuntimeException('Event dispatching is still running!');
} else {
if ($this->currentState->hasEvent($name)) {
$this->acqui... | @param DispatcherInterface $dispatcher
@param string $name
@param \ArrayAccess $context
@throws \RuntimeException | entailment |
public function setPathFilter($path_filter)
{
if (empty($path_filter)) {
$this->clearPathFilter();
} else {
$this->path_filter = $path_filter.'/';
}
return $this;
} | Set Path Filter
@param string $path_filter
@return self | entailment |
public function buildUrl($base)
{
$url = $base.self::getApiName().'/';
$parameters = http_build_query($this->getParams());
$region = $this->getRegion(). '/';
if (!is_null($region)) {
$url .= $region;
$path_filter = $this->getPathFilter();
if (!is_n... | {@inheritDoc} | entailment |
public function getIframeURL()
{
$info = $this->parseLink();
if (!$info) {
return false;
}
$params = $this->Config()->get('service');
if ($this->Service == 'Vimeo') {
$url = 'https://player.vimeo.com/video/' . $this->VideoID;
if ($params ... | Return the iframe URL
@param Null
@return String | entailment |
public function iFrame($maxwidth = '100%', $height = '56%')
{
$url = $this->getIFrameURL();
if (!$url) {
return false;
}
if (is_numeric($maxwidth)) {
$maxwidth .= 'px';
}
if (is_numeric($height)) {
$height .= 'px';
}
... | Return populated iframe template
@param Varchar max width
@param Varchar height in proportion
@return String | entailment |
public function getTitle()
{
if ($this->getService() == 'YouTube') {
$data = $this->getCachedJsonResponse(
'https://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=' .
$this->VideoID .
'&format=json'
);
if ($data &... | Scrape Video information from hosting sites
@param Null
@return String | entailment |
public function thumbnailURL($size = 'large')
{
if (!in_array($size, ['large', 'medium', 'small'])) {
return false;
}
$info = $this->parseLink();
$service = $this->getService();
if (!$info || !$service) {
return false;
}
if ($service... | Return thumbnail URL
@param Null
@return String | entailment |
private function getCachedJsonResponse($url)
{
if (!class_exists('GuzzleHttp\Client')) {
return false;
}
$cache_seconds = $this->config()->get('cache_seconds');
if (!is_numeric($cache_seconds)) {
$cache_seconds = 604800;
}
$cache = Injector::... | Return cached json response
@param String url
@return Array|null | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.