sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function register(EventDispatcher $dispatcher) : void
{
$dispatcher->addListener(RouteMatchedEvent::class, function (RouteMatchedEvent $event) {
$annotation = $this->getTransactionalAnnotation($event->getRouteMatch());
if ($annotation) {
$this->connection->setTransactionIsolation($annotation->getIsolationLevel());
$this->connection->beginTransaction();
}
});
$dispatcher->addListener(ControllerInvocatedEvent::class, function (ControllerInvocatedEvent $event) {
$annotation = $this->getTransactionalAnnotation($event->getRouteMatch());
if ($annotation) {
if ($this->connection->isTransactionActive()) {
$this->connection->rollBack();
}
}
});
} | {@inheritdoc} | entailment |
private function getTransactionalAnnotation(RouteMatch $routeMatch) : ?Transactional
{
$method = $routeMatch->getControllerReflection();
if ($method instanceof \ReflectionMethod) {
$annotations = $this->annotationReader->getMethodAnnotations($method);
foreach ($annotations as $annotation) {
if ($annotation instanceof Transactional) {
return $annotation;
}
}
}
return null;
} | Returns the Transactional annotation for the controller.
@param \Brick\App\RouteMatch $routeMatch
@return Transactional|null The annotation, or NULL if the controller is not transactional.
@todo add support for annotations on functions when Doctrine will handle them | entailment |
public function register(EventDispatcher $dispatcher) : void
{
$dispatcher->addListener(ControllerReadyEvent::class, function(ControllerReadyEvent $event) {
$event->addParameters($this->getParameters(
$event->getRequest(),
$event->getRouteMatch()->getControllerReflection()
));
});
} | {@inheritdoc} | entailment |
private function getParameters(Request $request, \ReflectionFunctionAbstract $controller) : array
{
if ($controller instanceof \ReflectionMethod) {
$annotations = $this->annotationReader->getMethodAnnotations($controller);
} else {
// @todo annotation reading on generic functions is not available yet
return [];
}
$parameters = [];
foreach ($controller->getParameters() as $parameter) {
$parameters[$parameter->getName()] = $parameter;
}
$result = [];
foreach ($annotations as $annotation) {
if ($annotation instanceof RequestParam) {
$result[$annotation->getBindTo()] = $this->getParameter(
$annotation,
$controller,
$parameters,
$request
);
}
}
return $result;
} | @param \Brick\Http\Request $request
@param \ReflectionFunctionAbstract $controller
@return array
@throws HttpException | entailment |
private function getParameter(RequestParam $annotation, \ReflectionFunctionAbstract $controller, array $parameters, Request $request)
{
$requestParameters = $annotation->getRequestParameters($request);
$parameterName = $annotation->getName();
$bindTo = $annotation->getBindTo();
if (! isset($parameters[$bindTo])) {
throw $this->unknownParameterException($controller, $annotation);
}
$parameter = $parameters[$bindTo];
if (! isset($requestParameters[$parameterName])) {
if ($parameter->isDefaultValueAvailable()) {
return $parameter->getDefaultValue();
}
if ($parameter->hasType() && $parameter->allowsNull()) {
return null;
}
if ($parameter->isVariadic()) {
return [];
}
throw $this->missingParameterException($controller, $annotation);
}
$value = $requestParameters[$parameterName];
if ($value === '' && $parameter->getClass() && $parameter->allowsNull()) {
return null;
}
if ($parameter->isArray() && ! is_array($value)) {
throw $this->invalidArrayParameterException($controller, $annotation);
}
if ($parameter->isArray() || $parameter->getClass()) {
return $value;
}
$type = $parameter->getType();
if ($type === null) {
return $value;
}
$type = (string) $type;
if ($value === '') {
if ($parameter->isDefaultValueAvailable()) {
return $parameter->getDefaultValue();
}
}
if ($type === 'bool') {
if ($value === '0' || $value === 'false' || $value === 'off' || $value === 'no') {
return false;
}
if ($value === '1' || $value === 'true' || $value === 'on' || $value === 'yes') {
return true;
}
} elseif ($type === 'int') {
if (ctype_digit($value)) {
return (int) $value;
}
} elseif ($type === 'float') {
if (is_numeric($value)) {
return (float) $value;
}
} elseif ($type === 'string') {
return $value;
} else {
throw $this->unsupportedBuiltinType($controller, $annotation, $type);
}
throw $this->invalidScalarParameterException($controller, $annotation, $type);
} | @param RequestParam $annotation The annotation.
@param \ReflectionFunctionAbstract $controller The reflection of the controller function.
@param \ReflectionParameter[] $parameters An array of ReflectionParameter for the function, indexed by name.
@param Request $request The HTTP Request.
@return mixed The value to assign to the function parameter.
@throws HttpException | entailment |
private function unknownParameterException(\ReflectionFunctionAbstract $controller, RequestParam $annotation) : HttpInternalServerErrorException
{
return new HttpInternalServerErrorException(sprintf(
'%s() does not have a $%s parameter, please check your annotation.',
$this->reflectionTools->getFunctionName($controller),
$annotation->getBindTo()
));
} | @param \ReflectionFunctionAbstract $controller
@param RequestParam $annotation
@return HttpInternalServerErrorException | entailment |
private function missingParameterException(\ReflectionFunctionAbstract $controller, RequestParam $annotation) : HttpBadRequestException
{
return new HttpBadRequestException(sprintf(
'%s() requires a %s parameter "%s" which is missing in the request.',
$this->reflectionTools->getFunctionName($controller),
$annotation->getParameterType(),
$annotation->getName()
));
} | @param \ReflectionFunctionAbstract $controller
@param RequestParam $annotation
@return HttpBadRequestException | entailment |
private function invalidArrayParameterException(\ReflectionFunctionAbstract $controller, RequestParam $annotation) : HttpBadRequestException
{
return new HttpBadRequestException(sprintf(
'%s() expects an array for %s parameter "%s" (bound to $%s), string given.',
$this->reflectionTools->getFunctionName($controller),
$annotation->getParameterType(),
$annotation->getName(),
$annotation->getBindTo()
));
} | @param \ReflectionFunctionAbstract $controller
@param RequestParam $annotation
@return HttpBadRequestException | entailment |
private function invalidScalarParameterException(\ReflectionFunctionAbstract $controller, RequestParam $annotation, string $type) : HttpBadRequestException
{
return new HttpBadRequestException(sprintf(
'%s() received an invalid %s value for %s parameter "%s" (bound to $%s).',
$this->reflectionTools->getFunctionName($controller),
$type,
$annotation->getParameterType(),
$annotation->getName(),
$annotation->getBindTo()
));
} | @param \ReflectionFunctionAbstract $controller
@param RequestParam $annotation
@param string $type
@return HttpBadRequestException | entailment |
private function unsupportedBuiltinType(\ReflectionFunctionAbstract $controller, RequestParam $annotation, string $type) : HttpInternalServerErrorException
{
return new HttpInternalServerErrorException(sprintf(
'%s() requests an unsupported type (%s) for %s parameter "%s" (bound to $%s).',
$this->reflectionTools->getFunctionName($controller),
$type,
$annotation->getParameterType(),
$annotation->getName(),
$annotation->getBindTo()
));
} | @param \ReflectionFunctionAbstract $controller
@param RequestParam $annotation
@param string $type
@return HttpInternalServerErrorException | entailment |
public function getAuthUrl()
{
if (! $oauthConfig = $this->client->getConfig("oauth2")) {
throw new \Exception('OAuth2 authorisation not registered');
}
$command = $this->client->getCommand('GetAuthUrl', (array) $oauthConfig)->prepare();
return $command->getUrl();
} | @return string
@throws \Exception | entailment |
public function getTokens($code)
{
if (! $oauthConfig = $this->client->getConfig("oauth2")) {
throw new \Exception('OAuth2 authorisation not registered');
}
$tokens = $this->executeCommand('GetAuthToken',
array_merge((array) $oauthConfig, array(
'code' => $code
)
));
return $tokens;
} | @param $code
@return array
@throws \Exception | entailment |
public function executeCommand($command, $arguments = array())
{
$command = $this->client->getCommand($command, $arguments);
return $this->client->execute($command);/*$command->getResponse()->json();*/
} | @param $command
@param array $arguments
@return array | entailment |
public function build($type)
{
if (!isset(self::$mapping[$type])) {
throw new UnknownPacketTypeException(sprintf('Unknown packet type %d.', $type));
}
$class = self::$mapping[$type];
return new $class();
} | Builds a packet object for the given type.
@param int $type
@throws UnknownPacketTypeException
@return Packet | entailment |
private function renderCell(string $tagName, string $html) : string
{
$td = new Tag($tagName);
$td->setHtmlContent($html);
return $td->render();
} | @param string $tagName
@param string $html
@return string | entailment |
private function renderElementAsRow(Element $element) : string
{
$tr = new Tag('tr');
$html = $this->renderCell('th', $element->getLabel()->render() . $this->renderErrors($element));
$html .= $this->renderCell('td', $element->render());
$tr->setHtmlContent($html);
return $tr->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) {
if ($component instanceof Element) {
$html .= $this->renderElementAsRow($component);
} elseif ($component instanceof Group) {
foreach ($component->getElements() as $element) {
$html .= $this->renderElementAsRow($element);
}
}
}
$table = new Tag('table');
$table->setAttribute('class', $this->class);
$table->setHtmlContent($html);
return $table->render();
} | @param \Brick\Form\Form $form
@return string
@throws \RuntimeException | entailment |
public function create($httpCode, $errorId = '', $message = '')
{
switch ($httpCode) {
case 0:
return new $this->httpCodes[$httpCode](
'Navitia timeout',
$httpCode
);
break;
case 404:
return new $this->errorIds[$errorId](
'Navitia error message: ' . $message,
$httpCode,
$errorId
);
break;
case 400:
case 401:
case 403:
return new $this->httpCodes[$httpCode](
'Navitia access error',
$httpCode
);
break;
default:
return new NavitiaException(
'Navitia error message: ' . $message,
$httpCode
);
}
} | {@inheritDoc} | entailment |
public function getNextState()
{
if( $this->getIsExecuted() )
{
if ( class_exists( $next = $this->getNextStateClass() ) )
{
return (new $next );
}
else
{
throw new ClassNotFoundException;
}
}
else
{
return $this;
}
} | Return the next state
@throws Jacopo\LaravelImportExport\Exception\ClassNotFoundException
@return ImportState | entailment |
public function getErrorHeader()
{
$err_str = '';
$error_class = $this->getErrors();
$error_session = Session::get($this->errors_key);
if( $error_class )
{
foreach ($error_class->all() as $error_key => $error) {
$err_str.="<div class=\"alert alert-danger\">{$error}</div>";
}
}
if( $error_session)
{
foreach ($error_session->all() as $error_key => $error) {
$err_str.="<div class=\"alert alert-danger\">{$error}</div>";
}
}
$this->resetErrors();
return $err_str;
} | Print the form errors if exists
@return String|null | entailment |
public function appendError($error_key, $error_string)
{
if($this->getErrors())
{
// append
$this->errors->add( $error_key, $error_string );
}
else
{
// new MessageBag
$this->errors = new MessageBag( array($error_key => $error_string) );
}
} | Append error to the MessageBag | entailment |
public function setProtocolLevel($value)
{
if ($value < 3 || $value > 4) {
throw new \InvalidArgumentException(sprintf('Unknown protocol level %d.', $value));
}
$this->protocolLevel = $value;
if ($this->protocolLevel === 3) {
$this->protocolName = 'MQIsdp';
} elseif ($this->protocolLevel === 4) {
$this->protocolName = 'MQTT';
}
} | Sets the protocol level.
@param int $value
@throws \InvalidArgumentException | entailment |
public function setWill($topic, $message, $qosLevel = 0, $isRetained = false)
{
$this->assertValidString($topic, false);
if ($topic === '') {
throw new \InvalidArgumentException('The topic must not be empty.');
}
$this->assertValidStringLength($message, false);
if ($message === '') {
throw new \InvalidArgumentException('The message must not be empty.');
}
$this->assertValidQosLevel($qosLevel, false);
$this->willTopic = $topic;
$this->willMessage = $message;
$this->flags |= 4;
$this->flags |= ($qosLevel << 3);
if ($isRetained) {
$this->flags |= 32;
} else {
$this->flags &= ~32;
}
} | Sets the will.
@param string $topic
@param string $message
@param int $qosLevel
@param bool $isRetained
@throws \InvalidArgumentException | entailment |
public function setUsername($value)
{
$this->assertValidString($value, false);
$this->username = $value;
if ($this->username !== '') {
$this->flags |= 64;
} else {
$this->flags &= ~64;
}
} | Sets the username.
@param string $value
@throws \InvalidArgumentException | entailment |
public function setPassword($value)
{
$this->assertValidStringLength($value, false);
$this->password = $value;
if ($this->password !== '') {
$this->flags |= 128;
} else {
$this->flags &= ~128;
}
} | Sets the password.
@param string $value
@throws \InvalidArgumentException | entailment |
private function assertValidWill()
{
if ($this->hasWill()) {
$this->assertValidQosLevel($this->getWillQosLevel(), true);
} else {
if ($this->getWillQosLevel() > 0) {
$this->throwException(
sprintf(
'Expected a will quality of service level of zero but got %d.',
$this->getWillQosLevel()
),
true
);
}
if ($this->isWillRetained()) {
$this->throwException('There is not will but the will retain flag is set.', true);
}
}
} | Asserts that all will flags and quality of service are correct.
@throws MalformedPacketException | entailment |
public function setParameter(ParameterInterface $param): void
{
$paramName = $param->getName();
foreach ($this->params as &$arg) {
if ($arg->getName() === $paramName) {
$arg = $param;
return;
}
}
$this->params[] = $param;
} | Allows to add or redefine parameters when the view object already exists. This avoids having to create a
completely new view object just because one parameter has changed or needs to be added. This method first checks
if a parameter with the given name is already stored within the view. If so, it updates its value with the one
supplied in $param. If the parameter is not present in the view, it is being added.
@param ParameterInterface $param The parameter to be added or updated. | entailment |
public function display(): void
{
$templateParameters = [];
foreach ($this->params as $param) {
if ($param instanceof PostParameter) {
$templateParameters[$param->getName()] = $param;
} else {
if ($param instanceof GenericParameter) {
$templateParameters[$param->getName()] = $param->getValue();
}
}
}
try {
$this->twig->display($this->templateName, $templateParameters);
} catch (LoaderError $e) {
trigger_error($e->getMessage(), E_USER_ERROR);
error_log($e->getMessage());
} catch (RuntimeError $e) {
trigger_error($e->getMessage(), E_USER_ERROR);
error_log($e->getMessage());
} catch (SyntaxError $e) {
trigger_error($e->getMessage(), E_USER_ERROR);
error_log($e->getMessage());
}
} | Displays the current view. Iterates over all the parameters and stores them in a temporary, associative array.
Twig then displays the main template, using the array with the parameters.
Exceptions generated by Twig are shown as errors and logged accordingly for simplification. | entailment |
public static function redirectTo(string $location, array $queryParameters = null): void
{
if (isset($queryParameters)) {
header("Location: $location" . "?" . http_build_query($queryParameters));
} else {
header("Location: $location");
}
exit();
} | Performs a generic redirect using header(). GET-Parameters may optionally be supplied as an associative array.
@param string $location The target location for the redirect.
@param array $queryParameters GET-Parameters for HTTP-Request | entailment |
public function pack($object) : ?PackedObject
{
foreach ($this->objectPackers as $objectPacker) {
$packedObject = $objectPacker->pack($object);
if ($packedObject !== null) {
return $packedObject;
}
}
return null;
} | {@inheritdoc} | entailment |
public function unpack(PackedObject $packedObject)
{
foreach ($this->objectPackers as $objectPacker) {
$object = $objectPacker->unpack($packedObject);
if ($object !== null) {
return $object;
}
}
return null;
} | {@inheritdoc} | entailment |
public function call($call, $format = null, $timeout = 6000, $pagination = true)
{
$service = $this->getService();
$service->setLogger($this->getLogger());
return $service->process($call, $format, $timeout, $pagination);
} | Facade d'appel Navitia
@param mixed $call
@return type | entailment |
public function setConfiguration($config)
{
$this->config = $config;
$service = $this->getService();
return $service->processConfiguration($this->config);
} | Facade de setter de la configuration
@param mixed $config
@return NavitiaService | entailment |
public function match(Request $request) : ?RouteMatch
{
$path = $request->getPath();
if ($path === '') {
return null;
}
if ($path[0] !== '/') {
return null;
}
$lastSlashPos = strrpos($path, '/');
$prefix = substr($path, 0, $lastSlashPos + 1);
$action = substr($path, $lastSlashPos + 1);
if (! isset($this->routes[$prefix])) {
return null;
}
$class = $this->routes[$prefix];
if ($action === 'index') {
return null;
}
if ($action === '') {
$action = 'index';
}
$method = $this->capitalize($action) . 'Action';
$classParameters = $this->getClassParameters($request);
if ($classParameters === null) {
return null;
}
$functionParameters = $this->getFunctionParameters($request);
if ($functionParameters === null) {
return null;
}
return RouteMatch::forMethod($class, $method, $classParameters, $functionParameters);
} | {@inheritdoc} | entailment |
public function beforeModeration(): bool
{
if (method_exists($this->owner, 'beforeModeration')) {
if (!$this->owner->beforeModeration()) {
return false;
}
}
$event = new ModelEvent();
$this->owner->trigger(self::EVENT_BEFORE_MODERATION, $event);
return $event->isValid;
} | This method is invoked before moderating a record.
@return bool | entailment |
public function markApproved(): bool
{
$this->owner->{$this->statusAttribute} = Status::APPROVED;
if ($this->beforeModeration()) {
return $this->owner->save();
}
return false;
} | Change model status to Approved
@return bool | entailment |
public function markRejected(): bool
{
$this->owner->{$this->statusAttribute} = Status::REJECTED;
if ($this->beforeModeration()) {
return $this->owner->save();
}
return false;
} | Change model status to Rejected
@return bool | entailment |
public function markPostponed(): bool
{
$this->owner->{$this->statusAttribute} = Status::POSTPONED;
if ($this->beforeModeration()) {
return $this->owner->save();
}
return false;
} | Change model status to Postponed
@return bool | entailment |
public function markPending(): bool
{
$this->owner->{$this->statusAttribute} = Status::PENDING;
if ($this->beforeModeration()) {
return $this->owner->save();
}
return false;
} | Change model status to Pending
@return bool | entailment |
protected function fillModeratedByAttribute(): void
{
if ($this->moderatedByAttribute !== false) {
$this->owner->{$this->moderatedByAttribute} = $this->getModeratedByAttributeValue();
}
} | Fill `moderatedByAttribute`
return void | entailment |
protected function getModeratedByAttributeValue(): ?int
{
$user = Yii::$app->get('user', false);
return $user && !$user->isGuest ? $user->id : null;
} | Get value for `moderatedByAttribute`
@return int|null | entailment |
public function build(CsvLine $csv_line_base = null)
{
$csv_line_base = $csv_line_base ? $csv_line_base : new CsvLine;
$stdclass_lines = $this->getAttributesFromDb();
foreach($stdclass_lines as $key => $line)
{
$csv_line = clone $csv_line_base;
$csv_line->forceSetAttributes((Array)$line);
$this->appendLine($csv_line);
}
} | Build the CsvFile
@throws Exception
@throws PDOException | entailment |
protected function getAttributesFromDb()
{
$connection_name = Config::get('laravel-import-export::baseconf.connection_name');
return DB::connection($connection_name)
->table($this->config["table"])
->select($this->createSelect() )
->get();
} | Get the data from db
@return Array | entailment |
protected function createSelect($config = null)
{
$config = $config ? $config : $this->config;
$select = array();
if( ($columns = $config["columns"]) )
{
foreach($columns as $db_key => $export_key)
{
$select[]= "{$db_key} as {$export_key}";
}
}
return $select;
} | Create select to make the CsvFile attributes
to export
@return String | entailment |
public function URL()
{
$p = $this->parse();
$link = '';
$link .= (!empty($p['scheme'])) ? $p['scheme'] . '://' : false;
$link .= (!empty($p['user'])) ? $p['user'] . ':' : false;
$link .= (!empty($p['pass'])) ? $p['pass'] . '@' : false;
$link .= (!empty($p['host'])) ? $p['host'] : false;
$link .= (!empty($p['path'])) ? $p['path'] : false;
if (!empty($p['query'])) {
parse_str($p['query'], $get_array);
$link .= '?' . http_build_query($get_array, '', '&');
}
$link .= (!empty($p['fragment'])) ? '#' . $p['fragment'] : false;
return $link;
} | Return constructed URL
@param Null
@return String | entailment |
public function parse($component = false)
{
$parts = parse_url($this->RAW());
if (!$component) {
return $parts;
} elseif (!empty($parts[$component])) {
return $parts[$component];
} else {
return false;
}
} | Parse the URL string.
@param Boolean optional component
@return string eg: x=1&y=2 | entailment |
protected function createTransition(TransitionInterface $sourceTransition)
{
$targetStateName = $sourceTransition->getTargetState()->getName();
$targetState = $this->findOrCreateState($targetStateName);
$this->mergeMetadata($sourceTransition->getTargetState(), $targetState);
$eventName = $sourceTransition->getEventName();
$condition = $this->createCondition($sourceTransition);
$transition = new Transition($targetState, $eventName, $condition);
if ($sourceTransition instanceof WeightedInterface) {
$transition->setWeight($sourceTransition->getWeight());
}
return $transition;
} | @param TransitionInterface $sourceTransition
@throws \InvalidArgumentException
@return \Metabor\Statemachine\Transition | entailment |
protected function mergeMetadata($source, $target)
{
if ($source instanceof \ArrayAccess) {
if ($target instanceof \ArrayAccess) {
if ($source instanceof MetadataInterface) {
$metadata = $source->getMetadata();
foreach ($metadata as $offset => $value) {
$target->offsetSet($offset, $value);
}
} else {
throw new \RuntimeException('Source had to make all metadata available!');
}
} else {
throw new \RuntimeException('Source metadata can not be merged!');
}
}
} | @param object $source
@param object $target
@throws \RuntimeException | entailment |
protected function addState(StateInterface $state)
{
if ($this->targetCollection instanceof StateCollection) {
$this->targetCollection->addState($state);
} else {
throw new \InvalidArgumentException('TargetCollection has to be a StateCollection. Overwrite this method to implement a different type!');
}
} | @param StateInterface $state
@throws \InvalidArgumentException | entailment |
protected function findOrCreateState($name)
{
$name = $this->stateNamePrefix . $name;
if ($this->targetCollection->hasState($name)) {
$targetState = $this->targetCollection->getState($name);
} else {
$targetState = $this->createState($name);
$this->addState($targetState);
}
return $targetState;
} | @param string $name
@return \MetaborStd\Statemachine\StateInterface | entailment |
protected function mergeState(StateInterface $sourceState)
{
$name = $sourceState->getName();
$targetState = $this->findOrCreateState($name);
$this->mergeMetadata($sourceState, $targetState);
/* @var $transition TransitionInterface */
foreach ($sourceState->getTransitions() as $sourceTransition) {
$targetTransition = $this->createTransition($sourceTransition);
$this->addTransition($targetState, $targetTransition);
}
foreach ($sourceState->getEventNames() as $eventName) {
$sourceEvent = $sourceState->getEvent($eventName);
$targetEvent = $targetState->getEvent($eventName);
$this->mergeMetadata($sourceEvent, $targetEvent);
foreach ($sourceEvent->getObservers() as $observer) {
$targetEvent->attach($observer);
}
}
} | @param StateInterface $sourceState
@throws \InvalidArgumentException | entailment |
protected function getControllerAnnotation(\ReflectionFunctionAbstract $controller, string $annotationClass)
{
if ($controller instanceof \ReflectionMethod) {
$annotations = $this->annotationReader->getMethodAnnotations($controller);
foreach ($annotations as $annotation) {
if ($annotation instanceof $annotationClass) {
return $annotation;
}
}
$class = $controller->getDeclaringClass();
$classes = $this->reflectionTools->getClassHierarchy($class);
foreach ($classes as $class) {
$annotations = $this->annotationReader->getClassAnnotations($class);
foreach ($annotations as $annotation) {
if ($annotation instanceof $annotationClass) {
return $annotation;
}
}
}
}
return null;
} | Finds an annotation on the controller class or method.
If the annotation is found on both the controller class and method, the method annotation is returned.
If the annotation is found on several classes in the hierarchy of controller classes,
the annotation of the child class is returned.
This method does not support controller functions outside a class.
@param \ReflectionFunctionAbstract $controller
@param string $annotationClass
@return object|null The annotation, or null if not found. | entailment |
protected function hasControllerAnnotation(\ReflectionFunctionAbstract $controller, string $annotationClass) : bool
{
return $this->getControllerAnnotation($controller, $annotationClass) !== null;
} | Checks whether a controller has an annotation on the class or method.
@param \ReflectionFunctionAbstract $controller
@param string $annotationClass
@return bool Whether the annotation is present. | entailment |
public function processConfiguration($config)
{
$factory = new ConfigurationProcessorFactory();
$processor = $factory->create(gettype($config));
$config = $processor->convertToObjectConfiguration($config);
$processor->validate($config);
$this->config = $config;
} | processConfiguration
Conversion de la configuration en object NavitiaConfiguration
Validation de la configuration
@param mixed $config | entailment |
public function process($query, $format = null, $timeout = 6000, $pagination = true)
{
$this->timeout = $timeout;
$factory = new RequestProcessorFactory();
$processor = $factory->create(gettype($query));
$request = $processor->convertToObjectRequest($query);
$validation = $this->validate($request);
if ($validation->count() === 0) {
$result = $this->callApi($request, $format);
$pagination_total_result_le_pagination_item_per_page = false;
if (isset($result->pagination)) {
if ($result->pagination->total_result <= $result->pagination->items_per_page) {
$pagination_total_result_le_pagination_item_per_page = true;
}
}
if ($pagination !== false ||
$pagination_total_result_le_pagination_item_per_page) {
return $result;
} else {
return $this->deletePagination($request, $format, $result);
}
} else {
return $validation;
}
} | Conversion de query en object NavitiaRequest
Validation de la requete et appel Navitia si requete valide
@param mixed $query | entailment |
public function deletePagination($request, $format, $result)
{
$parameters = $request->getParameters();
if (isset($result->pagination)) {
$result_pagination_total_result = $result->pagination->total_result;
} else {
$result_pagination_total_result = 0;
}
if (gettype($parameters) === 'string') {
$parameters .= '&count='.$result_pagination_total_result;
}
if (gettype($parameters) === 'array') {
$parameters['count'] = $result_pagination_total_result;
}
$request->setParameters($parameters);
return $this->callApi($request, $format);
} | Function to delete Navitia pagination
Retrieve the result count and call again with count
@param NavitiaRequestInterface $request
@param string $format
@param mixed $result
@return mixed | entailment |
public function validate(NavitiaRequestInterface $request)
{
$validator = Validation::createValidatorBuilder()
->enableAnnotationMapping()
->getValidator();
$violations = $validator->validate($request->processParameters());
return $violations;
} | Permet de valider une requete avec les contraintes en annotations
@param \Navitia\Component\Request\NavitiaRequestInterface $request
@return \Symfony\Component\Validator\ConstraintViolationListInterface | entailment |
public function callApi(NavitiaRequestInterface $request, $format)
{
$baseUrl = $this->config->getUrl().'/'.$this->config->getVersion().'/';
$url = $request->buildUrl($baseUrl);
$token = $this->config->getToken();
$this->log(
$url,
$request->getApiName(),
array_merge($request->getParams(), array('token' => $token))
);
$ch = new CurlService($url, $this->timeout, $token, $this->logger);
$curlResponse = $ch->process();
$response = $curlResponse['response'];
$curlError = $curlResponse['curlError'];
$httpCode = $curlResponse['httpCode'];
if ($httpCode !== 200) {
$this->errorProcessor($response, $httpCode);
}
return $this->responseProcessor($response, $format, $curlError);
} | {@inheritDoc} | entailment |
public function responseProcessor($response, $format, $curlError)
{
$format = (is_null($format)) ? $this->config->getFormat() : $format;
switch ($format) {
case 'json':
return $response;
case 'object':
if ('NO_CURL_ERROR' == current($curlError)) {
return json_decode($response);
} else {
$responseError = new \stdClass();
$responseError->error = $curlError;
return $responseError;
}
break;
default:
throw new BadParametersException(
sprintf('the "%s" format is not supported.', $format)
);
}
} | Fonction permettant de fournir la sortie en fonction du format donné
@param string $response
@param mixed $format
@return mixed
@throws BadParametersException | entailment |
public function errorProcessor($response, $httpCode)
{
if ($this->config->getResponseError() === 'exception') {
$exceptionFactory = new NavitiaExceptionFactory();
$errorId = null;
$errorMessage = '';
$responseObject = json_decode($response);
if (isset($responseObject->error)) {
$errorId = $responseObject->error->id;
$errorMessage = $responseObject->error->message;
}
$exception = $exceptionFactory->create($httpCode, $errorId, $errorMessage);
if (isset($responseObject->exceptions)) {
$exception->setExceptions($responseObject->exceptions);
}
if (isset($responseObject->notes)) {
$exception->setNotes($responseObject->notes);
}
throw $exception;
}
return $response;
} | Function throwing an exception containing navitia error message and code.
if response_error in config is 'exception' Function throwing the exception.
else Function return navitia response
Default mode is the exception mode
@link http://doc.navitia.io/documentation.html#Errors
@param string $response
@param string $httpCode
@return void
@throws NavitiaException | entailment |
protected function log($url, $api, $parameters)
{
if ($this->logger !== null) {
$this->logger->debug(
$url,
array(
'api' => $api,
'parameters' => $parameters
)
);
}
} | Appel à la fonction debug du logger LoggerInterface
@param string $url
@param string $api
@param array $parameters | entailment |
public function setPoints( $points )
{
if ( is_array($points) || $points instanceof \Traversable ) {
array_walk(
$points,
function (&$point, $index) {
if ( !$point instanceof PointInterface ) {
if (is_array($point) && count($point) == 2) {
list($x, $y) = array_values($point);
$point = new Point($x, $y);
} else {
$msg = "Point at index #$index does not implement "
. "PointReduction\\Common\\PointInterface";
throw new InvalidArgumentException($msg);
}
}
}
);
$this->points = $points;
} else {
$msg = "All points must be a traversable object, or array. "
. gettype($points)
. " given.";
throw new InvalidArgumentException($msg);
}
} | Set subject points
@param mixed $points Must be array or Traversable
@return null
@throws InvalidArgumentException | entailment |
protected function areaOfTriangle(
PointInterface $a,
PointInterface $b,
PointInterface $c
) {
list( $ax, $ay ) = $a->getCoordinates();
list( $bx, $by ) = $b->getCoordinates();
list( $cx, $cy ) = $c->getCoordinates();
$area = $ax * ( $by - $cy );
$area += $bx * ( $cy - $ay );
$area += $cx * ( $ay - $by );
return abs($area / 2);
} | Calculate the area of a triangle
@param PointInterface $a First point
@param PointInterface $b Middle point
@param PointInterface $c Last point
@return float | entailment |
protected function distanceBetweenPoints(
PointInterface $head,
PointInterface $tail
) {
return sqrt(self::pythagorus($head, $tail));
} | Calculate the distance between to points
@param PointInterface $head First point
@param PointInterface $tail Last point
@return float | entailment |
protected function pythagorus( PointInterface $a, PointInterface $b )
{
list( $ax, $ay ) = $a->getCoordinates();
list( $bx, $by ) = $b->getCoordinates();
return pow($ax - $bx, 2) + pow($ay - $by, 2);
} | Calculate Pythagoras distance.
Pythagorus as described as "a^2 + b^2 = c^2"
@param PointInterface $a First point
@param PointInterface $b Last point
@return float | entailment |
public function setGcProbability(int $dividend, int $divisor) : void
{
$this->gcDividend = $dividend;
$this->gcDivisor = $divisor;
} | Sets the probability for the garbage collection to be triggered on any given request.
For example, setGcProbability(1, 100) gives a 1% chance for the gc to be triggered.
@param int $dividend
@param int $divisor
@return void | entailment |
public function handleRequest(Request $request) : void
{
$this->reset();
$this->readSessionId($request);
if ($this->isTimeToCollectGarbage()) {
$this->collectGarbage();
}
$this->inRequest = true;
} | Reads the session cookie from the request.
@param \Brick\Http\Request $request
@return void | entailment |
public function handleResponse(Response $response) : void
{
if ($this->id === null) {
// The request was not associated with an existing session, and no session writes occurred.
// Sending a session cookie is unnecessary.
return;
}
// Note: we re-send the session cookie even if it was part of the request, to refresh the expiration time.
$this->writeSessionId($response);
$this->reset();
} | Writes the session cookie to the Response.
@param \Brick\Http\Response $response
@return void | entailment |
public function get(string $key)
{
if (isset($this->data[$key])) {
return $this->data[$key];
}
$id = $this->getOptionalId();
if ($id === null) {
return null;
}
$value = $this->storage->read($id, $key);
if ($value !== null) {
$value = $this->unserialize($value);
}
return $this->data[$key] = $value;
} | {@inheritdoc} | entailment |
public function set(string $key, $value) : void
{
if ($value === null) {
$this->remove($key);
return;
}
$id = $this->getId();
$serialized = $this->serialize($value);
$this->storage->write($id, $key, $serialized);
$this->data[$key] = $value;
} | {@inheritdoc} | entailment |
public function remove(string $key) : void
{
$id = $this->getOptionalId();
if ($id === null) {
return;
}
$this->storage->remove($id, $key);
unset($this->data[$key]);
} | {@inheritdoc} | entailment |
public function synchronize(string $key, callable $function)
{
$id = $this->getId();
$lock = new Lock();
$serialized = $this->storage->read($id, $key, $lock);
try {
$value = ($serialized !== null) ? $this->unserialize($serialized) : null;
$value = $function($value);
$serialized = $this->serialize($value);
} catch (\Throwable $e) {
$this->storage->unlock($lock);
throw $e;
}
$this->storage->write($id, $key, $serialized, $lock);
return $this->data[$key] = $value;
} | {@inheritdoc} | entailment |
private function serialize($value) : string
{
if ($this->packer !== null) {
$value = $this->packer->pack($value);
}
return serialize($value);
} | @param mixed $value
@return string | entailment |
private function unserialize(string $data)
{
$value = unserialize($data);
if ($this->packer !== null) {
return $this->packer->unpack($value);
}
return $value;
} | @param string $data
@return mixed | entailment |
private function reset() : void
{
$this->id = null;
$this->data = [];
$this->inRequest = false;
} | Resets the session status.
@return void | entailment |
public static function get(UTCDateTime $date): DateTime
{
$date = $date->toDateTime();
$date->setTimezone(new DateTimeZone(date_default_timezone_get()));
return $date;
} | Retrieves DateTime instance using default timezone.
@param UTCDateTime $date
@return DateTime | entailment |
public static function format(
UTCDateTime $date,
string $format = 'd/m/Y H:i:s'
): string {
return self::get($date)->format($format);
} | Retrieves formated date time using timezone.
@param UTCDateTime $date
@param string $format
@return string | entailment |
public function addConnection(Connection $connection): bool
{
$this->init();
$this->connectionPool->addConnection($connection);
return true;
} | Main entry point to openning a connection and start using Mongolid in
pure PHP. After adding a connection into the Manager you are ready to
persist and query your models.
@param Connection $connection connection instance to be used in database interactions
@return bool Success | entailment |
public function setEventTrigger(EventTriggerInterface $eventTrigger)
{
$this->init();
$eventService = new EventTriggerService();
$eventService->registerEventDispatcher($eventTrigger);
$this->container->instance(EventTriggerService::class, $eventService);
} | Sets the event trigger for Mongolid events.
@param EventTriggerInterface $eventTrigger external event trigger | entailment |
public function getMapper(string $entityClass)
{
if (isset($this->schemas[$entityClass])) {
$dataMapper = Ioc::make(DataMapper::class);
$dataMapper->setSchema($this->schemas[$entityClass] ?? null);
return $dataMapper;
}
} | Retrieves a DataMapper for the given $entityClass. This can only be done
if the Schema for that entity has been previously registered with
registerSchema() method.
@param string $entityClass class of the entity that needs to be mapped
@return DataMapper|null dataMapper configured for the $entityClass | entailment |
protected function init()
{
if ($this->container) {
return;
}
$this->container = new Container();
$this->connectionPool = new Pool();
$this->cacheComponent = new CacheComponent();
$this->container->instance(Pool::class, $this->connectionPool);
$this->container->instance(CacheComponentInterface::class, $this->cacheComponent);
Ioc::setContainer($this->container);
static::$singleton = $this;
} | Initializes the Mongolid manager. | entailment |
public static function deleteUnderscore($param)
{
$parts = explode('_', $param);
$result = array_shift($parts);
foreach ($parts as $part) {
$result .= ucfirst($part);
}
return $result;
} | Fonction permettant de supprimer les underscores
@param string $param
@return string | entailment |
public static function setter($request, $params)
{
if (is_array($params)) {
foreach ($params as $property => $value) {
$property = Utils::deleteUnderscore($property);
$setter = 'set'.ucfirst($property);
if (method_exists($request, $setter)) {
$request->$setter($value);
} else {
throw new NavitiaCreationException(
sprintf(
'Neither property "%s" nor method "%s"'.
'nor method "%s" exist.',
$property,
'get'.ucfirst($property),
$setter
)
);
}
}
} else {
throw new NavitiaCreationException(
sprintf(
'The parameter (type "%s") will be an Array',
gettype($params)
)
);
}
return $request;
} | Fonction permettant de setter
@param object $request
@param array $params
@return object
@throws NavitiaCreationException | entailment |
public function normForm(): void
{
if ($this->isFormSubmission()) {
if ($this->isValid()) {
$this->business();
}
}
if ($this->currentView instanceof View) {
$this->show();
}
} | Main "decision" method for the form processing. This decision tree uses isFormSubmission() to check if the form
is being initially displayed or shown again after a form submission and either calls show() to display the form
(using the supplied View object) or validate the received input in isValid(). If validation failed, show() is
called again. Possible error messages provided as parameters to the View object in isValid() can now be
displayed. Once the submission was correct, business() is called where the data can be processed as needed. | entailment |
protected function isEmptyPostField(string $index): bool
{
return (!isset($_POST[$index]) || strlen(trim($_POST[$index])) === 0);
} | Convenience method to check if a form field is empty, thus contains only an empty string. This is preferred to
PHP's own empty() method which also defines inputs such as "0" as empty.
@param string $index The index in the super global $_POST array.
@return bool Returns true if the form field is empty, otherwise false. | entailment |
protected function getCursor(): Traversable
{
// Returns original (non-cached) cursor
if ($this->ignoreCache || $this->position >= self::DOCUMENT_LIMIT) {
return $this->getOriginalCursor();
}
// Returns cached set of documents
if ($this->documents) {
return $this->documents;
}
// Check if there is a cached set of documents
$cacheComponent = Ioc::make(CacheComponentInterface::class);
$cacheKey = $this->generateCacheKey();
try {
$cachedDocuments = $cacheComponent->get($cacheKey, null);
} catch (ErrorException $error) {
$cachedDocuments = [];
}
if ($cachedDocuments) {
return $this->documents = new ArrayIterator($cachedDocuments);
}
// Stores the original "limit" clause of the query
$this->storeOriginalLimit();
// Stores the documents within the object and cache then for later use
$this->documents = [];
foreach (parent::getCursor() as $document) {
$this->documents[] = $document;
}
$cacheComponent->put($cacheKey, $this->documents, 0.6);
// Drops the unserializable DriverCursor.
$this->cursor = null;
// Return the documents iterator
return $this->documents = new ArrayIterator($this->documents);
} | Actually returns a Traversable object with the DriverCursor within.
If it does not exists yet, create it using the $collection, $command and
$params given.
The difference between the CacheableCursor and the normal Cursor is that
the Cacheable stores all the results within itself and drops the
Driver Cursor in order to be serializable.
@return Traversable | entailment |
protected function generateCacheKey(): string
{
return sprintf(
'%s:%s:%s',
$this->command,
$this->collection->getNamespace(),
md5(serialize($this->params))
);
} | Generates an unique cache key for the cursor in it's current state.
@return string cache key to identify the query of the current cursor | entailment |
protected function storeOriginalLimit()
{
if (isset($this->params[1]['limit'])) {
$this->originalLimit = $this->params[1]['limit'];
}
if ($this->originalLimit > self::DOCUMENT_LIMIT) {
$this->limit(self::DOCUMENT_LIMIT);
}
} | Stores the original "limit" clause of the query. | entailment |
protected function getOriginalCursor(): Traversable
{
if ($this->ignoreCache) {
return parent::getCursor();
}
if ($this->getLimit()) {
$this->params[1]['limit'] = $this->getLimit() - $this->position;
}
$skipped = $this->params[1]['skip'] ?? 0;
$this->skip($skipped + $this->position - 1);
$this->ignoreCache = true;
return $this->getOriginalCursor();
} | Returns the DriverCursor considering the documents that have already
been retrieved from cache.
@return Traversable | entailment |
public function register(EventDispatcher $dispatcher) : void
{
$dispatcher->addListener(RouteMatchedEvent::class, function(RouteMatchedEvent $event) {
$controller = $event->getRouteMatch()->getControllerReflection();
$annotation = $this->getControllerAnnotation($controller, Allow::class);
if ($annotation instanceof Allow) {
$method = $event->getRequest()->getMethod();
$allowedMethods = $annotation->getMethods();
if (! in_array($method, $allowedMethods)) {
throw new HttpMethodNotAllowedException($allowedMethods);
}
}
});
} | {@inheritdoc} | entailment |
public function read(string $id, string $key, Lock $lock = null) : ?string
{
if ($lock) {
$this->pdo->beginTransaction();
}
$query = sprintf(
'SELECT %s, %s FROM %s WHERE %s = ? AND %s = ? FOR UPDATE',
$this->options['value-column'],
$this->options['last-access-column'],
$this->options['table-name'],
$this->options['id-column'],
$this->options['key-column']
);
$statement = $this->pdo->prepare($query);
$statement->execute([$id, $key]);
$data = $statement->fetch(\PDO::FETCH_NUM);
$statement->closeCursor();
if ($data === false) {
return null;
}
if (! $lock) {
// Only update the last access time if it's older than the imprecision allowed.
if (time() - $data[1] > $this->options['last-access-grace']) {
$this->touch($id, $key);
}
}
return $data[0];
} | {@inheritdoc} | entailment |
public function write(string $id, string $key, string $value, Lock $lock = null) : void
{
$this->updateRecord($id, $key, $value) || $this->insertRecord($id, $key, $value);
if ($lock) {
$this->pdo->commit();
}
} | {@inheritdoc} | entailment |
private function updateRecord(string $id, string $key, string $value) : bool
{
$query = sprintf(
'UPDATE %s SET %s = ?, %s = CASE WHEN %s = ? THEN %s + 1 ELSE ? END WHERE %s = ? AND %s = ?',
$this->options['table-name'],
$this->options['value-column'],
$this->options['last-access-column'],
$this->options['last-access-column'],
$this->options['last-access-column'],
$this->options['id-column'],
$this->options['key-column']
);
$statement = $this->pdo->prepare($query);
$statement->execute([$value, $time = time(), $time, $id, $key]);
return $statement->rowCount() !== 0;
} | Updates the record with the given id and key.
The CASE statement is here to ensure that if two updates occur within the same second,
the record will still be updated and the method will return true.
@param string $id
@param string $key
@param string $value
@return bool Whether the record exists and was updated. | entailment |
private function insertRecord(string $id, string $key, string $value) : void
{
$query = sprintf(
'INSERT INTO %s (%s, %s, %s, %s) VALUES(?, ?, ?, ?)',
$this->options['table-name'],
$this->options['id-column'],
$this->options['key-column'],
$this->options['value-column'],
$this->options['last-access-column']
);
$statement = $this->pdo->prepare($query);
$statement->execute([$id, $key, $value, time()]);
} | Creates a new record with the given id and key.
@param string $id
@param string $key
@param string $value
@return void | entailment |
public function clear(string $id) : void
{
$query = sprintf(
'DELETE FROM %s WHERE %s = ?',
$this->options['table-name'],
$this->options['id-column']
);
$statement = $this->pdo->prepare($query);
$statement->execute([$id]);
} | {@inheritdoc} | entailment |
public function expire(int $lifetime) : void
{
$query = sprintf(
'DELETE FROM %s WHERE %s < ?',
$this->options['table-name'],
$this->options['last-access-column']
);
$statement = $this->pdo->prepare($query);
$statement->execute([time() - $lifetime]);
} | {@inheritdoc} | entailment |
public function updateId(string $oldId, string $newId) : bool
{
$query = sprintf(
'UPDATE %s SET %s = ?, %s = ? WHERE %s = ?',
$this->options['table-name'],
$this->options['id-column'],
$this->options['last-access-column'],
$this->options['id-column']
);
$this->executeQuery($query, [
$newId,
time(),
$oldId
]);
return true;
} | {@inheritdoc} | entailment |
private function executeQuery(string $query, array $parameters) : bool
{
$statement = $this->pdo->prepare($query);
$statement->execute($parameters);
return $statement->rowCount() !== 0;
} | @param string $query
@param array $parameters
@return bool | entailment |
protected function generateSessionId() : string
{
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$id = '';
for ($i = 0; $i < $this->idLength; $i++) {
$id .= $chars[random_int(0, 61)];
}
return $id;
} | {@inheritDoc} | entailment |
public function regenerateId() : bool
{
$id = $this->generateSessionId();
if ($this->storage->updateId($this->id, $id)) {
$this->id = $id;
return true;
}
return false;
} | Regenerates the session id.
This is a useful security measure that can be used after user login to even
further limit the risks of session fixation attacks.
Not all storage engines support id regeneration.
If the storage engine supports regeneration, this method returns true.
If the storage engine does not support regeneration, this method will do nothing and return false.
@return bool | 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.