sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function updateVersion($contentId, $versionNumber, Request $request)
{
if (!$this->isUserContent($contentId)) {
return parent::updateVersion($contentId, $versionNumber, $request);
}
$updatedUser = $this->repository->getUserService()->updateUser(
$this->repository->getUserService()->loadUser($contentId),
$this->mapRequestToUserUpdateStruct($request)
);
return $this->mapUserToVersion($updatedUser, $request);
} | If the updated content is a user, update it using the user API, and return a Version object.
@param mixed $contentId
@param int $versionNumber
@param \Symfony\Component\HttpFoundation\Request $request
@return \eZ\Publish\Core\REST\Server\Values\Version | entailment |
public function publishVersion($contentId, $versionNumber)
{
if (!$this->isUserContent($contentId)) {
parent::publishVersion($contentId, $versionNumber);
}
return new NoContent();
} | If the published content is a user, return directly without publishing.
@param mixed $contentId
@param int $versionNumber
@return \eZ\Publish\Core\REST\Server\Values\NoContent | entailment |
private function isUserContent($contentId)
{
try {
$this->repository->getUserService()->loadUser($contentId);
return true;
} catch (NotFoundException $e) {
return false;
}
} | Checks if $contentId is an existing User content.
@param mixed $contentId
@return bool | entailment |
private function mapRequestToParentGroups(Request $request)
{
$groupId = $this->repository->getLocationService()->loadLocation(
$this->parseContentRequest($request)->locationCreateStruct->parentLocationId
)->contentId;
$group = $this->repository->getUserService()->loadUserGroup($groupId);
return [$group];
} | @param \Symfony\Component\HttpFoundation\Request $request
@return \eZ\Publish\API\Repository\Values\User\UserGroup[] | entailment |
private function mapUserToCreatedContent(User $user)
{
return new CreatedContent([
'content' => new RestContent(
$user->contentInfo,
$this->repository->getLocationService()->loadLocation($user->contentInfo->mainLocationId),
$this->repository->getContentService()->loadContentByContentInfo($user->contentInfo),
$this->repository->getContentTypeService()->loadContentType($user->contentInfo->contentTypeId),
$this->repository->getContentService()->loadRelations($user->versionInfo)
),
]);
} | @param User $user
@return \eZ\Publish\Core\REST\Server\Values\CreatedContent | entailment |
private function mapRequestToUserUpdateStruct($request)
{
$contentUpdateStruct = $this->parseContentRequest($request);
$userUpdateStruct = new UserUpdateStruct();
foreach ($contentUpdateStruct->fields as $field) {
if ($field->value instanceof UserFieldValue) {
$userUpdateStruct->email = $field->value->email;
$userUpdateStruct->password = $field->value->passwordHash ?: null;
$field->value->passwordHash = null;
}
}
$userUpdateStruct->contentUpdateStruct = $contentUpdateStruct;
return $userUpdateStruct;
} | @param \Symfony\Component\HttpFoundation\Request $request
@return \eZ\Publish\API\Repository\Values\User\UserUpdateStruct | entailment |
private function mapUserToVersion(User $user, Request $request)
{
$content = $this->repository->getContentService()->loadContent($user->id);
$request->headers->set('Url', $request->getPathInfo());
return new Version(
$content,
$this->repository->getContentTypeService()->loadContentType($content->contentInfo->contentTypeId),
$this->repository->getContentService()->loadRelations($content->getVersionInfo()),
$request->getPathInfo()
);
} | @param \eZ\Publish\API\Repository\Values\User\User $user
@param \Symfony\Component\HttpFoundation\Request $request
@return \eZ\Publish\Core\REST\Server\Values\Version | entailment |
public function getValidationMessage($attribute, $rule, $data = [], $type = null)
{
$path = Str::snake($rule);
if ($type !== null) {
$path .= '.' . $type;
}
if ($this->translator->has('validation.custom.' . $attribute . '.' . $path)) {
$path = 'custom.' . $attribute . '.' . $path;
}
$niceName = $this->getValidationAttribute($attribute);
return $this->translator->get('validation.' . $path, $data + ['attribute' => $niceName]);
} | Get user friendly validation message.
@param string $attribute
@param string $rule
@param array $data
@param string $type
@return string
@see Illuminate\Validation\Validator::getMessage() | entailment |
public function handle()
{
$this->line('Generating new asset hash. Environment: <comment>' . $this->laravel->make('env') . '</comment>');
$hash = $this->hashReplacer->replaceHash();
$this->config->set('assetcachebuster.hash', $hash);
$msg = "New hash {$hash} generated.";
$this->info($msg);
} | Execute the console command.
@return void | entailment |
public function count()
{
if (is_null($this->_count)) {
$this->_count = $this->_builder
->getQuery()
->count();
}
return $this->_count;
} | TODO : fait la même requete que getItems !!!! | entailment |
public function dataSet()
{
$base = $this->storeManager->getStore(0)->getBaseUrl();
$modules = $this->_moduleList->getNames();
foreach ($modules as $module) {
if (strpos($module, self::EADESIGN) !== false) {
$this->connect([
'url' => $base,
'version' => $this->moduleResource->getDbVersion($module),
'extension' => $module,
'mversion' => 2
]);
}
}
} | Prepare the data to send to the connector | entailment |
public function insert(string $table, array $data)
{
$statement = $this->buildInsertQuery($table, $data);
$this->execute($statement);
return $this->pdo->lastInsertId();
} | {@inheritdoc} | entailment |
public function setHash($hash)
{
if (!preg_match("/[0-9a-f]{32}/", $hash)) {
throw new InvalidArgumentException("Asset cache buster hash must be a valid md5 hash.");
}
$hash = trim($hash, '/');
$this->hash = $hash;
} | Sets the hash
@param string $hash The hash to use to bust the cache | entailment |
public function setPrefix($prefix = null)
{
$prefix = trim($prefix, '/');
$this->prefix = ($prefix) ? trim($prefix, '/') . '/' : '';
} | Sets the asset prefix path
@param string $prefix A prefix containing assets | entailment |
public function url($path = '')
{
$path = trim($path, '/');
if ($this->enabled) {
$hash = ($this->hash) ? trim($this->hash, '/') . '/' : '';
return $this->cdn . $this->prefix . $hash . $path;
} else {
return $this->cdn . $path;
}
} | Generates an asset url
@param string $path The path to the asset
@return string The asset url with the cache busting hash | entailment |
public function register()
{
$this->mergeConfigFrom(
dirname(dirname(__DIR__)) . '/config/assetcachebuster.php', 'assetcachebuster'
);
$this->app->singleton('assetcachebuster', function () {
$options = [
'enable' => $this->app['config']->get('assetcachebuster.enable'),
'hash' => $this->app['config']->get('assetcachebuster.hash'),
'cdn' => $this->app['config']->get('assetcachebuster.cdn'),
'prefix' => $this->app['config']->get('assetcachebuster.prefix'),
];
return new Assetcachebuster($options);
});
$this->app->bind('Spekkionu\Assetcachebuster\Writer\ConfigWriter', function(){
return new ConfigWriter($this->app->make('Illuminate\Filesystem\Filesystem'), $this->app->make('path.config'));
});
$this->app->bind('Spekkionu\Assetcachebuster\Writer\WriterInterface', 'Spekkionu\Assetcachebuster\Writer\ConfigWriter');
$this->app->bind('Spekkionu\Assetcachebuster\HashReplacer\ConfigHashReplacer', function(){
return new ConfigHashReplacer($this->app->make('assetcachebuster'), $this->app->make('Spekkionu\Assetcachebuster\Writer\WriterInterface'));
});
$this->app->bind('Spekkionu\Assetcachebuster\HashReplacer\HashReplacerInterface', 'Spekkionu\Assetcachebuster\HashReplacer\ConfigHashReplacer');
// Register artisan command
$this->app->singleton(
'command.assetcachebuster.generate',
function () {
return new Console\GenerateCommand($this->app->make('Spekkionu\Assetcachebuster\HashReplacer\HashReplacerInterface'), $this->app->make('Illuminate\Contracts\Config\Repository'));
}
);
$this->commands(
'command.assetcachebuster.generate'
);
} | Register the service provider.
@return void | entailment |
public function setCurrentConfig($content)
{
if (!$this->configExists()) {
throw new \InvalidArgumentException('The config file does not exist. Did you run the vendor:publish command?');
}
$this->filesystem->put($this->getConfigFile(), $content);
} | Saves config as current config
@param string $content
@return void | entailment |
public function model($model, array $options = [], $rules = null)
{
$this->setValidation($rules, isset($options['name']) ? $options['name'] : null);
return parent::model($model, $options);
} | {@inheritdoc}
@param array $rules Laravel validation rules | entailment |
public function input($type, $name, $value = null, $options = [])
{
$options += $this->getValidationAttributes($name, $type);
return parent::input($type, $name, $value, $options);
} | {@inheritdoc} | entailment |
public function textarea($name, $value = null, $options = [])
{
$options += $this->getValidationAttributes($name);
return parent::textarea($name, $value, $options);
} | {@inheritdoc} | entailment |
public function select($name, $list = [], $selected = null, array $selectAttributes = [], array $optionsAttributes = [], array $optgroupsAttributes = [])
{
$selectAttributes += $this->getValidationAttributes($name);
return parent::select($name, $list, $selected, $selectAttributes, $optionsAttributes, $optgroupsAttributes);
} | {@inheritdoc} | entailment |
public function parse(\Twig_Token $token)
{
$lineno = $token->getLine();
$stream = $this->parser->getStream();
$crud = $this->parser->getExpressionParser()->parseExpression();
$resources = array();
do {
$resources[] = $this->parser->getExpressionParser()->parseExpression();
} while (!$stream->test(\Twig_Token::BLOCK_END_TYPE));
$stream->expect(\Twig_Token::BLOCK_END_TYPE);
return new CrudThemeNode($crud, new \Twig_Node($resources), $lineno, $this->getTag());
} | Parses a token and returns a node.
@param \Twig_Token $token A Twig_Token instance
@return \Twig_NodeInterface A Twig_NodeInterface instance | entailment |
public function beforeAction($action)
{
if (in_array($this->action->id, ['notify', 'return', 'cancel', 'proxy-notification'], true)) {
Yii::$app->controller->enableCsrfValidation = false;
}
return parent::beforeAction($action);
} | Disable CSRF validation for POST requests we receive from outside
{@inheritdoc} | entailment |
public function actionReturn(string $transactionId = null)
{
$transaction = $this->checkNotify($transactionId);
if ($transaction === null) {
return $this->actionCancel();
}
return $this->render('return', [
'transactionId' => $transaction->getId(),
]);
} | @param string|null $transactionId
Parameters are NOT required because some merchants may NOT send them, or send in POST or JSON bode.
The main purpose of these parameters is handling of special routes using UrlManager
@return string
@throws InvalidConfigException | entailment |
public function actionNotify(string $transactionId = null)
{
$transaction = $this->checkNotify($transactionId);
if ($transaction === null) {
return 'Unknown transaction';
}
Yii::$app->response->format = Response::FORMAT_RAW;
return $transaction->isConfirmed() ? 'OK' : $transaction->getParameter('error');
} | Action handles notifications from payment systems,
processes them and report success or error for the payment system.
@param string|null $transactionId Parameters is NOT required because some merchants may NOT send it, or send in POST or JSON body.
The main purpose of these parameters is handling of special routes using UrlManager
@return null|string
@throws InvalidConfigException | entailment |
public function renderDeposit($form)
{
$request = new DepositRequest();
$request->amount = $form->amount;
$request->currency = $form->currency;
$request->finishUrl = $form->finishUrl;
$requests = $this->getMerchantModule()->getPurchaseRequestCollection($request)->getItems();
return $this->render('deposit', [
'requests' => $requests,
'depositForm' => $form
]);
} | Renders depositing buttons for given request data.
@param DepositForm $form request data
@return \yii\web\Response | entailment |
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$begin = microtime(true);
$response = $handler->handle($request);
$end = microtime(true);
$message = $this->format;
$message = $this->replaceConstantDirectives($message, $request, $response, $begin, $end);
$message = $this->replaceVariableDirectives($message, $request, $response, $begin, $end);
$context = [];
if ($this->context !== null) {
$contextFunction = $this->context;
$context = $contextFunction($request, $response);
}
$statusCode = $response->getStatusCode();
if ($statusCode >= 400 && $statusCode < 500) {
$this->logger->warning($message, $context);
} elseif ($statusCode >= 500 && $statusCode < 600) {
$this->logger->error($message, $context);
} else {
$this->logger->info($message, $context);
}
return $response;
} | Process a server request and return a response. | entailment |
private function replaceVariableDirectives(
string $format,
ServerRequestInterface $request,
ResponseInterface $response,
float $begin,
float $end
): string {
return preg_replace_callback(
'/%(?:[<>])?{([^}]+)}([aCeinopPtT])/',
function (array $matches) use ($request, $response, $begin, $end) {
switch ($matches[2]) {
case 'a':
return Format::getClientIp($request, $this->ipAttribute);
case 'C':
return Format::getCookie($request, $matches[1]);
case 'e':
return Format::getEnv($matches[1]);
case 'i':
return Format::getHeader($request, $matches[1]);
case 'n':
return Format::getAttribute($request, $matches[1]);
case 'o':
return Format::getHeader($response, $matches[1]);
case 'p':
return Format::getPort($request, $matches[1]);
case 't':
return Format::getRequestTime($begin, $end, $matches[1]);
case 'T':
return Format::getRequestDuration($begin, $end, $matches[1]);
//NOT IMPLEMENTED
case 'P':
default:
return '-';
}
},
$format
);
} | @param string $format
@param ServerRequestInterface $request
@param ResponseInterface $response
@param float $begin
@param float $end
@return string | entailment |
protected function getServiceDescription($baseUrl)
{
return new Description(
array(
'baseUrl' => $baseUrl,
'operations' => array(
'lookup' => array(
'uri' => 'postcodes/{postcode}',
'httpMethod' => 'GET',
'responseModel' => 'getResponse',
'parameters' => array(
'postcode' => array(
'location' => 'uri',
'description' => 'The postcode to look up.',
'required' => true
)
)
),
'bulkLookup' => array(
'uri' => 'postcodes',
'httpMethod' => 'POST',
'responseModel' => 'getResponse',
'parameters' => array(
'postcodes' => array(
'location' => 'postField',
'description' => 'The postcodes to look up (max 100).',
'required' => true
)
)
),
'reverseGeocode' => array(
'uri' => 'postcodes/lon/{longitude}/lat/{latitude}',
'httpMethod' => 'GET',
'responseModel' => 'getResponse',
'parameters' => array(
'longitude' => array(
'location' => 'uri',
'description' => 'The longitude to look up.',
'required' => true
),
'latitude' => array(
'location' => 'uri',
'description' => 'The latitude to look up.',
'required' => true
),
'limit' => array(
'location' => 'query',
'description' => 'Limit the number of postcodes returned (default 10, max 100).',
'required' => true
),
'radius' => array(
'location' => 'query',
'description' => 'Limit the postcodes returned in metres (default 100, max 1000).',
'required' => true
)
)
),
'bulkReverseGeocode' => array(
'uri' => 'postcodes',
'httpMethod' => 'POST',
'responseModel' => 'getResponse',
'parameters' => array(
'geolocations' => array(
'location' => 'postField',
'description' => 'The latitude and longitude coordinates to look up.',
'required' => true
)
)
),
'matching' => array(
'uri' => 'postcodes',
'httpMethod' => 'GET',
'responseModel' => 'getResponse',
'parameters' => array(
'query' => array(
'location' => 'query',
'description' => 'The postcode query.'
),
'limit' => array(
'location' => 'query',
'description' => 'Limit the number of postcodes returned (default 10, max 100).'
)
)
),
'validate' => array(
'uri' => 'postcodes/{postcode}/validate',
'httpMethod' => 'GET',
'responseModel' => 'getResponse',
'parameters' => array(
'postcode' => array(
'location' => 'uri',
'description' => 'The postcode to validate.',
'required' => true
)
)
),
'autocomplete' => array(
'uri' => 'postcodes/{postcode}/autocomplete',
'httpMethod' => 'GET',
'responseModel' => 'getResponse',
'parameters' => array(
'postcode' => array(
'location' => 'uri',
'description' => 'The partial postcode to autocomplete.',
'required' => true
),
'limit' => array(
'location' => 'query',
'description' => 'Limit the number of postcodes returned (default 10, max 100).'
)
)
),
'random' => array(
'uri' => 'random/postcodes',
'httpMethod' => 'GET',
'responseModel' => 'getResponse',
),
'outwardCodeLookup' => array(
'uri' => 'outcodes/{outcode}',
'httpMethod' => 'GET',
'responseModel' => 'getResponse',
'parameters' => array(
'outcode' => array(
'location' => 'uri',
'description' => 'The outward code (first half of postcode) to get location data for.',
'required' => true
)
)
)
),
'models' => array(
'getResponse' => array(
'type' => 'object',
'properties' => array(
'statusCode' => array(
'location' => 'statusCode'
)
),
'additionalProperties' => array(
'location' => 'json'
)
)
)
)
);
} | Get the service description.
@param string $baseUrl The base URL.
@return GuzzleServiceDescription The service description. | entailment |
public function addPrimary($primaryColumn): MigrationTable
{
if ($primaryColumn === true) {
$primaryColumn = new Column('id', Column::TYPE_INTEGER, [ColumnSettings::SETTING_AUTOINCREMENT => true]);
return $this->addPrimary($primaryColumn);
}
if ($primaryColumn instanceof Column) {
$this->columns = array_merge([$primaryColumn->getName() => $primaryColumn], $this->columns);
$this->primaryColumnNames = array_merge([$primaryColumn->getName()], $this->primaryColumnNames);
return $this;
}
if (is_string($primaryColumn)) {
$this->primaryColumnNames = array_merge([$primaryColumn], $this->primaryColumnNames);
return $this;
}
if (is_array($primaryColumn)) {
foreach (array_reverse($primaryColumn) as $column) {
$this->addPrimary($column);
}
}
return $this;
} | add primary key(s) to table
@param mixed $primaryColumn
true - if you want classic autoincrement integer primary column with name id
Column - if you want to define your own column (column is added to list of columns)
string - name of column in list of columns
array of strings - names of columns in list of columns
array of Column - list of own columns (all columns are added to list of columns)
other (false, null) - if your table doesn't have primary key | entailment |
public static function getClientIp(ServerRequestInterface $request, string $ipAttribute = null): string
{
if (!empty($ipAttribute)) {
return self::getAttribute($request, $ipAttribute);
}
return self::getLocalIp($request);
} | Client IP address of the request (%a) | entailment |
public static function getRemoteHostname(ServerRequestInterface $request, bool $hostnameLookups = false): string
{
$ip = self::getServerParamIp($request, 'REMOTE_ADDR');
if ($ip !== '-' && $hostnameLookups) {
return gethostbyaddr($ip);
}
return $ip;
} | Remote hostname (%h)
Will log the IP address if hostnameLookups is false. | entailment |
public static function getCookie(ServerRequestInterface $request, string $name): string
{
$cookies = $request->getCookieParams();
return isset($cookies[$name]) ? $cookies[$name] : '-';
} | Returns a cookie value (%{VARNAME}C) | entailment |
public static function getPort(ServerRequestInterface $request, string $format): string
{
switch ($format) {
case 'canonical':
case 'local':
return (string) ($request->getUri()->getPort()
?: ('https' === $request->getUri()->getScheme() ? 443 : 80));
default:
return '-';
}
} | The canonical port of the server serving the request. (%p) | entailment |
public static function getQuery(ServerRequestInterface $request): string
{
$query = $request->getUri()->getQuery();
return '' !== $query ? '?'.$query : '';
} | The query string (%q)
(prepended with a ? if a query string exists, otherwise an empty string). | entailment |
public static function getHost(ServerRequestInterface $request): string
{
$host = $request->hasHeader('Host') ? $request->getHeaderLine('Host') : $request->getUri()->getHost();
return $host ?: '-';
} | The canonical ServerName of the server serving the request. (%v) | entailment |
public static function getServerName(ServerRequestInterface $request): string
{
$name = self::getServerParam($request, 'SERVER_NAME');
if ($name === '-') {
return self::getHost($request);
}
return $name;
} | The server name according to the UseCanonicalName setting. (%V) | entailment |
public static function getRequestLine(ServerRequestInterface $request): string
{
return sprintf(
'%s %s%s %s',
self::getMethod($request),
self::getPath($request),
self::getQuery($request),
self::getProtocol($request)
);
} | First line of request. (%r) | entailment |
public static function getResponseLine(ResponseInterface $response): string
{
return sprintf(
'%s %d%s',
self::getProtocol($response),
self::getStatus($response),
($response->getReasonPhrase() ? ' '.$response->getReasonPhrase() : '')
);
} | Returns the response status line | entailment |
public static function getTransferredSize(ServerRequestInterface $request, ResponseInterface $response): string
{
return (string) (self::getMessageSize($request, 0) + self::getMessageSize($response, 0)) ?: '-';
} | Bytes transferred (received and sent), including request and headers (%S) | entailment |
public static function getMessageSize(MessageInterface $message, $default = null)
{
$bodySize = $message->getBody()->getSize();
if (null === $bodySize) {
return $default;
}
$firstLine = '';
if ($message instanceof ServerRequestInterface) {
$firstLine = self::getRequestLine($message);
} elseif ($message instanceof ResponseInterface) {
$firstLine = self::getResponseLine($message);
}
$headers = [];
foreach ($message->getHeaders() as $header => $values) {
foreach ($values as $value) {
$headers[] = sprintf('%s: %s', $header, $value);
}
}
$headersSize = strlen(implode("\r\n", $headers));
return strlen($firstLine) + 2 + $headersSize + 4 + $bodySize;
} | Get the message size (including first line and headers)
@param MessageInterface $message
@param mixed $default
@return int|null | entailment |
public static function getRequestTime(float $begin, float $end, string $format): string
{
$time = $begin;
if (strpos($format, 'begin:') === 0) {
$format = substr($format, 6);
} elseif (strpos($format, 'end:') === 0) {
$time = $end;
$format = substr($format, 4);
}
switch ($format) {
case 'sec':
return sprintf('[%s]', round($time));
case 'msec':
return sprintf('[%s]', round($time * 1E3));
case 'usec':
return sprintf('[%s]', round($time * 1E6));
default:
return sprintf('[%s]', strftime($format, (int) $time));
}
} | Returns the request time (%t, %{format}t) | entailment |
public static function getRequestDuration(float $begin, float $end, string $format): string
{
switch ($format) {
case 'us':
return (string) round(($end - $begin) * 1E6);
case 'ms':
return (string) round(($end - $begin) * 1E3);
default:
return (string) round($end - $begin);
}
} | The time taken to serve the request. (%T, %{format}T) | entailment |
private static function getServerParam(ServerRequestInterface $request, string $key, string $default = '-'): string
{
$server = $request->getServerParams();
return empty($server[$key]) ? $default : $server[$key];
} | Returns an server parameter value | entailment |
private static function getServerParamIp(ServerRequestInterface $request, string $key): string
{
$ip = self::getServerParam($request, $key);
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6)) {
return $ip;
}
return '-';
} | Returns an ip from the server params | entailment |
public function getPagesRange()
{
$pageRange = $this->getPageRange();
$pageNumber = $this->getCurrentPageNumber();
$pageCount = $this->getNumberOfPages();
if ($pageRange > $pageCount) {
$pageRange = $pageCount;
}
$delta = ceil($pageRange / 2 );
if ($pageNumber - $delta > $pageCount - $pageRange) {
$lowerBound = $pageCount - $pageRange + 1;
$upperBound = $pageCount;
} else {
if ($pageNumber - $delta < 0) {
$delta = $pageNumber;
}
$offset = $pageNumber - $delta;
$lowerBound = $offset + 1;
$upperBound = $offset + $pageRange;
}
$pages = array();
for ($pageNumber = $lowerBound; $pageNumber <= $upperBound; $pageNumber++) {
$pages[$pageNumber] = $pageNumber;
}
return $pages;
} | From Zend\Paginator\Paginator | entailment |
public function set($rules, $formName = null)
{
if (isset($rules)) {
// set form name in order to get related validation rules
$this->currentFormName = $formName;
$this->validationRules[$formName] = (array)$rules;
}
} | Set rules for validation.
@param array $rules Laravel validation rules
@param string $formName | entailment |
public function reset($formName = false)
{
if (is_bool($formName))
$formName = $this->currentFormName;
if (array_key_exists($formName, $this->validationRules)) {
$this->validationRules[$formName] = [];
}
} | Reset validation rules.
@param string|bool $formName Form name | entailment |
public function getValidationRules($formName = false)
{
if (is_bool($formName))
$formName = $this->currentFormName;
if (array_key_exists($formName, $this->validationRules)) {
return $this->validationRules[$formName];
}
return [];
} | Get all given validation rules.
@param string|bool $formName
@return array Laravel validation rules | entailment |
protected function getValidationRule($inputName)
{
$rules = $this->getValidationRules();
return is_array($rules[$inputName]) ? $rules[$inputName] : explode('|', $rules[$inputName]);
} | Returns validation rules for given input name.
@param string $inputName
@return array | entailment |
protected function getTypeOfInput($rulesOfInput)
{
foreach ($rulesOfInput as $key => $rule) {
$parsedRule = $this->parseValidationRule($rule);
if (in_array($parsedRule['name'], static::$numericRules)) {
return 'numeric';
} elseif ($parsedRule['name'] === 'array') {
return 'array';
} elseif (in_array($parsedRule['name'], static::$fileRules)) {
return 'file';
}
}
return 'string';
} | Get all rules and return type of input if rule specifies type
@param array
@return string | entailment |
protected function parseValidationRule($rule)
{
$ruleArray = array();
$explodedRule = explode(':', $rule, 2);
$ruleArray['name'] = array_shift($explodedRule);
if (empty($explodedRule) || !in_array(strtolower($ruleArray['name']), static::$multiParamRules)) {
$ruleArray['parameters'] = $explodedRule;
} else {
$ruleArray['parameters'] = str_getcsv($explodedRule[0]);
}
return $ruleArray;
} | Parses validation rule of laravel.
@param string
@return array | entailment |
protected function getDefaultErrorMessage($laravelRule, $attribute)
{
// getting user friendly validation message
$message = $this->message()->getValidationMessage($attribute, $laravelRule);
return ['data-msg-'.$laravelRule => $message];
} | Gets default error message.
@param string $laravelRule
@param string $attribute
@return string | entailment |
public function getItems($offset, $itemCountPerPage)
{
if ($offset >= $this->count()) {
return array();
}
$remainItemCount = $this->count() - $offset;
$currentItemCount = $remainItemCount > $itemCountPerPage ? $itemCountPerPage : $remainItemCount;
return array_fill(0, $currentItemCount, null);
} | From Zend\Paginator\Adapter\Null | entailment |
public function addParameter($parameter, $value)
{
if (isset($this->parameters[$parameter])) {
return;
}
$this->parameters[$parameter] = $value;
} | Adds parameter $parameter with value $value to the parameters
@param string $parameter
@param mixed $value | entailment |
public function getSymbol($locale = null): string
{
if (null === $locale) {
$locale = Yii::$app->formatter->locale;
}
$fmt = new NumberFormatter($locale . "@currency={$this->code}", NumberFormatter::CURRENCY);
$symbol = $fmt->getSymbol(NumberFormatter::CURRENCY_SYMBOL);
return $symbol;
} | Returns the symbol used for a currency.
@param string|null $locale optional
@return string|null the currency symbol or NULL if not found
@see https://stackoverflow.com/questions/13897516/get-currency-symbol-in-php | entailment |
public function replaceHash()
{
$currentHash = $this->cacheBuster->getHash();
$hash = $this->cacheBuster->generateHash();
$this->writeHash($currentHash, $hash);
$this->cacheBuster->setHash($hash);
return $hash;
} | Generate and save new hash
@return string New Hash
@throws \Exception | entailment |
final protected function insert(string $table, array $data): AbstractMigration
{
$this->execute($this->adapter->buildInsertQuery($table, $data));
return $this;
} | adds insert query to list of queries to execute | entailment |
final protected function update(string $table, array $data, array $conditions = [], string $where = ''): AbstractMigration
{
$this->execute($this->adapter->buildUpdateQuery($table, $data, $conditions, $where));
return $this;
} | adds update query to list of queries to execute
@param string $table
@param array $data
@param array $conditions key => value conditions to generate WHERE part of query, imploded with AND
@param string $where additional where added to generated WHERE as is
@return AbstractMigration | entailment |
final protected function delete(string $table, array $conditions = [], string $where = ''): AbstractMigration
{
$this->execute($this->adapter->buildDeleteQuery($table, $conditions, $where));
return $this;
} | adds delete query to list of queries to exectue
@param string $table
@param array $conditions key => value conditions to generate WHERE part of query, imploded with AND
@param string $where additional where added to generated WHERE as is
@return AbstractMigration | entailment |
public function prepareRequestData($depositRequest)
{
$depositRequest->username = $this->getUsername();
$depositRequest->notifyUrl = $this->buildUrl('notify', $depositRequest);
$depositRequest->returnUrl = $this->buildUrl('return', $depositRequest);
$depositRequest->cancelUrl = $this->buildUrl('cancel', $depositRequest);
$depositRequest->finishUrl = $this->buildUrl('finish', $depositRequest);
} | Method builds data for merchant request.
@param DepositRequest $depositRequest
@return array | entailment |
public function getUsername()
{
if (isset($this->_username)) {
return $this->_username;
} elseif (($identity = Yii::$app->user->identity) !== null) {
if ($identity->hasProperty('username')) {
$this->_username = $identity->username;
} else {
$this->_username = $identity->getId();
}
return $this->_username;
}
throw new InvalidConfigException('Unable to determine username');
} | Gets [[_username]] when defined, otherwise - `Yii::$app->user->identity->username`,
otherwise `Yii::$app->user->identity->getId()`.
@throws InvalidConfigException
@return string | entailment |
public function buildUrl($destination, DepositRequest $depositRequest)
{
$page = [
$this->getPage($destination, $depositRequest),
'username' => $depositRequest->username,
'merchant' => $depositRequest->merchant,
'transactionId' => $depositRequest->id,
];
if (is_array($page)) {
$page[0] = $this->localizePage($page[0]);
} else {
$page = $this->localizePage($page);
}
return Url::to($page, true);
} | Builds URLs that will be passed in the request to the merchant.
@param string $destination `notify`, `return`, `cancel`
@param DepositRequest $depositRequest
@return string URL | entailment |
public function getPayController()
{
if ($this->_payController === null) {
$this->_payController = $this->createControllerById('pay');
}
return $this->_payController;
} | @throws InvalidConfigException
@return PayController | entailment |
protected function createRealValue($value): ?string
{
if ($value === false) {
return 'false';
} elseif ($value === true) {
return 'true';
}
return is_array($value) ? '{' . implode(',', $value) . '}' : $value;
} | {@inheritdoc} | entailment |
public function init()
{
parent::init();
PaymentIconsAsset::register(Yii::$app->getView());
$this->registerMerchantCss();
} | {@inheritdoc} | entailment |
public function renderButton()
{
return $this->render('pay-button', [
'widget' => $this,
'request' => $this->request,
'depositRequest' => new DepositRequest([
'id' => $this->request->id,
'amount' => $this->depositForm->amount,
'currency' => $this->depositForm->currency,
'merchant' => $this->getMerchantName(),
'finishUrl' => $this->depositForm->finishUrl,
])
]);
} | Renders the payment button.
@return string | entailment |
public function boot()
{
/* @var $app \Illuminate\Contracts\Foundation\Application|\ArrayAccess */
$app = $this->app;
$this->publishes([
__DIR__ . '/../../../config/config.php' => $app['path.config'] . '/laravalid.php',
], 'config');
$this->publishes([
__DIR__ . '/../../../public' => $app['path.public'] . '/vendor/laravalid',
], 'public');
// register routes for `remote` validations
$routeName = $app['config']['laravalid.route'];
$app['router']->any($routeName . '/{rule}', function ($rule) use ($app) {
return $app['laravalid']->converter()->route()->convert($rule, [$app['request']->all()]);
})->where('rule', '[\w-]+');
} | Perform post-registration booting of services.
@return void | entailment |
public function register()
{
$this->mergeConfigFrom(
__DIR__ . '/../../../config/config.php', 'laravalid'
);
if (!isset($this->app['html'])) {
$this->app->singleton('html', function ($app) {
return new HtmlBuilder($app['url'], $app['view']);
});
}
$this->app->singleton('laravalid', function ($app) {
$plugin = $app['config']['laravalid.plugin'];
$converterClass = (strpos($plugin, '\\') === false ? 'Bllim\Laravalid\Converter\\' : '') . $plugin . '\Converter';
/* @var $session \Illuminate\Session\Store */
$session = $app['session.store'];
$form = new FormBuilder($app['html'], $app['url'], $app['view'], $session->token(), new $converterClass($app), $app['request']);
return $form->setSessionStore($session);
});
} | Register bindings in the container.
@return void | entailment |
public function getToken()
{
if (!isset($this->token)) {
$this->token = $this->csrf->getToken();
}
return $this->token;
} | Returns the generated token.
The token is generated the first time this method is called. Further
calls to this method will always return the same token.
@return string The generated token | entailment |
public function beforeFilter(\Cake\Event\Event $event)
{
parent::beforeFilter($event);
$this->loadModel('Settings.Configurations');
$this->prefixes = Configure::read('Settings.Prefixes');
$this->Menu->active('ca.settings');
$this->Menu->area('navbar');
foreach ($this->prefixes as $prefix => $alias) {
$this->Menu->add($alias, [
'url' => [
'action' => 'index', $prefix,
]
]);
}
} | beforeFilter
beforeFilter event.
@param \Cake\Event\Event $event Event.
@return void | entailment |
public function index($key = null)
{
if (!$key) {
$key = 'App';
}
$this->Menu->active($this->prefixes[$key]);
if (!$this->__prefixExists($key)) {
throw new NotFoundException("The prefix-setting " . $key . " could not be found");
}
$prefix = Hash::get($this->prefixes, ucfirst($key));
$settings = $this->Configurations->find('all')->where([
'name LIKE' => $key . '%',
'editable' => 1,
])->order(['weight', 'id']);
if ($this->request->is(['patch', 'post', 'put'])) {
$settings = $this->Configurations->patchEntities($settings, $this->request->data);
foreach ($settings as $setting) {
$this->Flash->success('The settings has been saved.');
if (!$this->Configurations->save($setting)) {
$this->Flash->error('The settings could not be saved. Please, try again.');
}
}
Setting::clear(true);
Setting::autoLoad();
return $this->redirect([]);
}
$this->set(compact('prefix', 'settings'));
} | index action
Shows all settings with the specific prefix.
@param string $key The prefix.
@return void|\Cake\Network\Respose
@throws NotFoundException | entailment |
protected function __prefixExists($prefix)
{
if (Hash::get($this->prefixes, ucfirst($prefix)) == null) {
return false;
}
return true;
} | Checks if a prefix exists.
@param string $prefix The prefix.
@return bool | entailment |
public function setSources(array $sources)
{
$this->sources = array_map(function (Source\TokenSource $source) {
return $source;
}, $sources);
} | Sets the possible sources for submitted token.
Multiple sources can be added using an array. The handler will look for
the token from the sources in the order they appear in the array.
@param Source\TokenSource[] $sources List of token sources. | entailment |
public function validateRequest($throw = false)
{
// Ensure that the actual token is generated and stored
$this->getTrueToken();
if (!$this->isValidatedRequest()) {
return true;
}
if (!$this->validateRequestToken()) {
if ($throw) {
throw new InvalidCSRFTokenException('Invalid CSRF token');
}
$this->killScript();
}
return true;
} | Validates the csrf token in the HTTP request.
This method should be called in the beginning of the request. By default,
POST, PUT and DELETE requests will be validated for a valid CSRF token.
If the request does not provide a valid CSRF token, this method will
kill the script and send a HTTP 400 (bad request) response to the
browser.
This method also accepts a single parameter than can be either true or
false. If the parameter is set to true, this method will throw an
InvalidCSRFTokenException instead of killing the script if no valid CSRF
token was provided in the request.
This method will always trigger the token storage. If you are using the
cookie storage, this method must be called before the headers have been
sent. If you are using the session storage instead, you must start the
session before calling this method.
@param bool $throw True to throw an exception on invalid token, false to kill the script
@return bool This method always returns true
@throws InvalidCSRFTokenException If throwing is enabled and there is no valid csrf token
@throws Storage\TokenStorageException If the secret token cannot be loaded or stored | entailment |
public function validateToken($token)
{
if (!is_string($token)) {
return false;
}
$token = base64_decode($token, true);
if (strlen($token) !== self::TOKEN_LENGTH * 2) {
return false;
}
list($key, $encrypted) = str_split($token, self::TOKEN_LENGTH);
return call_user_func(
$this->compare,
$this->encryptToken($this->getTrueToken(), $key),
$encrypted
);
} | Validates the csrf token.
The token must be provided as a base64 encoded string which also includes
the token encryption key. In other words, you should pass this method the
exact same string that has been returned by the `getToken()` method.
@param string $token The base64 encoded token provided by getToken()
@return bool True if the token is valid, false if it is not
@throws Storage\TokenStorageException If the secret token cannot be loaded or stored | entailment |
public function getToken()
{
$key = $this->getGenerator()->getBytes(self::TOKEN_LENGTH);
return base64_encode($key . $this->encryptToken($this->getTrueToken(), $key));
} | Generates a new secure base64 encoded csrf token.
This method returns a new string every time it is called, because it
always generates a new encryption key for the token. Of course, each of
these tokens is a valid CSRF token, unless the `regenerateToken()` method
is called.
@return string Base64 encoded CSRF token
@throws Storage\TokenStorageException If the secret token cannot be loaded or stored | entailment |
public function regenerateToken()
{
do {
$token = $this->getGenerator()->getBytes(self::TOKEN_LENGTH);
} while ($token === $this->token);
$this->token = $token;
$this->storage->storeToken($this->token);
return $this;
} | Regenerates the actual CSRF token.
After this method has been called, any token that has been previously
generated by `getToken()` is no longer considered valid. It is highly
recommended to regenerate the CSRF token after any user authentication.
@return CSRFHandler Returns self for call chaining
@throws Storage\TokenStorageException If the secret token cannot be stored | entailment |
public function getTrueToken()
{
if (!isset($this->token)) {
$token = $this->storage->getStoredToken();
$this->token = is_string($token) ? $token : '';
}
if (strlen($this->token) !== self::TOKEN_LENGTH) {
$this->regenerateToken();
}
return $this->token;
} | Returns the current actual CSRF token.
This returns the current actual 32 byte random string that is used to
validate the CSRF tokens submitted in requests.
@return string The current actual CSRF token
@throws Storage\TokenStorageException If the secret token cannot be loaded or stored | entailment |
public function getRequestToken()
{
$token = false;
foreach ($this->sources as $source) {
if (($token = $source->getRequestToken()) !== false) {
break;
}
}
return $token;
} | Returns the token sent in the request.
@return string|false The token sent in the request or false if there is none | entailment |
private function compareStrings($knownString, $userString)
{
$result = "\x00";
for ($i = 0, $length = strlen($knownString); $i < $length; $i++) {
$result |= $knownString[$i] ^ $userString[$i];
}
return $result === "\x00";
} | Compares two string in constant time.
@param string $knownString String known to be correct by the system
@param string $userString String submitted by the user for comparison
@return bool True if the strings are equal, false if not | entailment |
public function validationDefault(Validator $validator)
{
$validator
->add('id', 'valid', ['rule' => 'numeric'])
->allowEmpty('id', 'create');
$validator
->add('email', 'valid', ['rule' => 'email'])
->notEmpty('email');
$validator
->notEmpty('password');
$validator
->allowEmpty('new_password');
$validator
->allowEmpty('confirm_password');
$validator
->add('new_password', 'custom', [
'rule' => function ($value, $context) {
if (!array_key_exists('confirm_password', $context['data'])) {
return false;
}
if ($value !== $context['data']['confirm_password']) {
return false;
}
return true;
},
'message' => __d('CakeAdmin', 'Passwords are not equal.')]);
$validator
->add('confirm_password', 'custom', ['rule' => function ($value, $context) {
if (!array_key_exists('new_password', $context['data'])) {
return false;
}
if ($value !== $context['data']['new_password']) {
return false;
}
return true;
},
'message' => __d('CakeAdmin', 'Passwords are not equal.')]);
return $validator;
} | Default validation rules.
@param \Cake\Validation\Validator $validator Validator instance.
@return \Cake\Validation\Validator | entailment |
public function beforeSave($event, $entity, $options)
{
$entity->set('cakeadmin', true);
$newPassword = $entity->get('new_password');
if (!empty($newPassword)) {
$entity->set('password', $entity->new_password); // set for password-changes
}
} | beforeSave event
@param \Cake\Event\Event $event Event.
@param \Cake\ORM\Entity $entity Entity.
@param array $options Options.
@return void | entailment |
public function afterSave($event, $entity, $options)
{
if ($entity->isNew()) {
NotificationManager::instance()->notify([
'recipientLists' => ['administrators'],
'template' => 'newAdministrator',
'vars' => [
'email' => $entity->get('email'),
'created' => $entity->get('created'),
]
]);
}
} | afterSave event
@param \Cake\Event\Event $event Event.
@param \Cake\ORM\Entity $entity Entity.
@param array $options Options.
@return void | entailment |
public function generateRequestKey()
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$requestKey = '';
for ($i = 0; $i < 40; $i++) {
$requestKey .= $characters[rand(0, $charactersLength - 1)];
}
return $requestKey;
} | generateRequestKey
This method generates a request key for an user.
It returns a generated string.
@return string | entailment |
public static function init($id, $temp_dir = ''){
if( !preg_match('/\A[a-zA-Z0-9\-_\.]+\z/', $id) ){
throw new SettingException(sprintf('ID %s should be ready for directory name.', $id));
}
// Check ZipArchive
if( !class_exists('ZipArchive') ){
throw new EnvironmentException('Class ZipArchive doesn\'t exist.');
}
if( !isset( static::$ids[$id] ) ){
static::$ids[$id] = new static($id, $temp_dir);
}
return static::$ids[$id];
} | Initialize factory
@param $id
@param string $temp_dir
@return static
@throws EnvironmentException
@throws SettingException | entailment |
public function beforeFilter(\Cake\Event\Event $event)
{
// notifications for index-action have to be loaded here because of the loaded count of unread notifications.
$this->set('notifications', $this->Notifier->getNotifications());
$this->Notifier->markAsRead();
parent::beforeFilter($event);
} | beforeFilter event.
@param \Cake\Event\Event $event Event.
@return void | entailment |
function toRaw()
{
$result = File_MARC::SUBFIELD_INDICATOR.$this->code.$this->data;
return (string)$result;
} | Return the USMARC representation of the subfield
@return string USMARC representation | entailment |
public function initialize()
{
parent::initialize();
$this->loadComponent('Flash');
$this->loadComponent('CakeAdmin.CakeAdmin');
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'authenticate' => [
'Basic' => [
'userModel' => 'CakeAdmin.Administrators'
],
'Form' => [
'userModel' => 'CakeAdmin.Administrators',
'fields' => Configure::read('CA.fields'),
'scope' => ['Administrators.cakeadmin' => true]
],
],
'loginAction' => [
'prefix' => 'admin',
'plugin' => 'CakeAdmin',
'controller' => 'Users',
'action' => 'login'
],
'loginRedirect' => [
'prefix' => 'admin',
'plugin' => 'CakeAdmin',
'controller' => 'Dashboard',
'action' => 'index'
],
'logoutRedirect' => [
'prefix' => 'admin',
'plugin' => 'CakeAdmin',
'controller' => 'Users',
'action' => 'login'
]
]);
$this->Auth->sessionKey = 'Auth.CakeAdmin';
$this->authUser = $this->Auth->user();
$this->loadComponent('Utils.GlobalAuth');
$this->loadComponent('Csrf');
$this->loadComponent('Utils.Menu');
$this->loadComponent('CakeAdmin.PostTypes');
$this->loadComponent('Notifier.Notifier');
$event = new Event('CakeAdmin.Controller.afterInitialize', $this);
EventManager::instance()->dispatch($event);
} | Initialize AppController
@return void | entailment |
public function beforeFilter(Event $event)
{
$this->viewBuilder()->className(Configure::read('CA.viewClass'))->theme(Configure::read('CA.theme'));
if ($this->authUser) {
$this->viewBuilder()->layout(Configure::read('CA.layout.default'));
} else {
$this->viewBuilder()->layout(Configure::read('CA.layout.login'));
}
$this->_addNotificationMenu();
$event = new Event('CakeAdmin.Controller.beforeFilter', $this);
EventManager::instance()->dispatch($event);
} | beforeFilter event.
@param Event $event Event.
@return void | entailment |
public function beforeRender(Event $event)
{
$this->set('authUser', $this->authUser);
$this->set('title', $this->name);
$event = new Event('CakeAdmin.Controller.beforeRender', $this);
EventManager::instance()->dispatch($event);
} | beforeRender event.
@param Event $event Event.
@return void | entailment |
public function initMenuItems()
{
$this->Menu->area('headerLeft');
$this->Menu->add('ca.user', [
'title' => $this->authUser[Configure::read('CA.fields.username')],
'url' => '#'
]);
$this->Menu->add('ca.logout', [
'parent' => 'ca.user',
'title' => __d('CakeAdmin', 'Logout'),
'url' => [
'prefix' => 'admin',
'plugin' => 'CakeAdmin',
'controller' => 'Users',
'action' => 'logout',
]
]);
$this->Menu->area('main');
$this->Menu->add('ca.dashboard', [
'title' => __d('CakeAdmin', 'Dashboard'),
'url' => [
'prefix' => 'admin',
'plugin' => 'CakeAdmin',
'controller' => 'Dashboard',
'action' => 'index',
],
'weight' => 0,
]);
$this->Menu->add('ca.settings', [
'title' => __d('CakeAdmin', 'Settings'),
'url' => [
'prefix' => 'admin',
'plugin' => 'CakeAdmin',
'controller' => 'Settings',
'action' => 'index',
],
'weight' => 50
]);
foreach (Configure::read('CA.Menu.main') as $key => $value) {
$this->Menu->add($key, $value);
}
} | Initializes all admin menu-items.
@return void | entailment |
protected function _addNotificationMenu()
{
$this->Menu->area('headerLeft');
$this->Menu->add('notifier.notifications', [
'title' => __d('CakeAdmin', 'Notifications ({0})', $this->Notifier->countNotifications(null, true)),
'url' => '#',
'weight' => 5
]);
$notifications = $this->Notifier->getNotifications(null, true);
foreach ($notifications as $not) {
$this->Menu->add('notifier.notifications.' . $not->id, [
'parent' => 'notifier.notifications',
'title' => $not->title,
'url' => [
'prefix' => 'admin',
'plugin' => 'CakeAdmin',
'controller' => 'Notifications',
'action' => 'index'
]
]);
}
$this->Menu->add('notifier.notifications.url', [
'parent' => 'notifier.notifications',
'title' => '> ' . __d('CakeAdmin', 'All Notifications'),
'url' => [
'prefix' => 'admin',
'plugin' => 'CakeAdmin',
'controller' => 'Notifications',
'action' => 'index'
]
]);
} | Adds the notification-menu-item to the header menu.
@return void | entailment |
public function login()
{
if ($this->authUser) {
return $this->redirect($this->Auth->redirectUrl());
}
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$user['CakeAdmin'] = $user;
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__d('CakeAdmin', 'Invalid username or password, try again'));
} else {
$this->request->data['email'] = $this->request->query('email');
}
} | Login action
Login action for administrators. Here you are able to login into your admin-panel.
@return \Cake\Network\Response|void | entailment |
public function logout()
{
$this->Flash->success(__d('CakeAdmin', 'You are now logged out.'));
return $this->redirect($this->Auth->logout());
} | Logout action
Via this action you will be logged out and redirected to the login-page.
@return \Cake\Network\Response|void | entailment |
public function forgot()
{
// Redirect if user is already logged in
if ($this->authUser) {
return $this->redirect('/login');
}
$this->Flash->success(__d('CakeAdmin', 'Check your e-mail to change your password.'));
if ($this->request->is('post')) {
$user = $this->Administrators->findByEmail($this->request->data('email'));
if ($user->count()) {
$user = $user->first();
$user->set('request_key', $this->Administrators->generateRequestKey());
if ($this->Users->save($user)) {
$event = new Event('Controller.Admin.Users.afterForgotPassword', $this, [
'user' => $user
]);
EventManager::instance()->dispatch($event);
$this->getMailer('CakeAdmin.CakeAdmin')->send('resetPassword', [$user]);
return $this->redirect($this->Auth->config('loginAction') + ['email' => $user->email]);
}
}
return $this->redirect($this->Auth->config('loginAction'));
}
} | Forgot password action
Via this action you are able to request a new password.
After the post it will send a mail with a link.
This link will redirect to the action 'reset'.
This action always gives a success-message.
That's because else hackers (or other bad-guys) will be able
to see if an e-mail is registered or not.
@return void|\Cake\Network\Response | entailment |
public function reset($email, $requestKey = null)
{
// Redirect if user is already logged in
if ($this->authUser) {
$this->Flash->error(__d('CakeAdmin', 'Your account could not be reset.'));
return $this->redirect($this->Auth->config('loginAction') + ['email' => $email]);
}
// If the email and key doesn't match
if (!$this->Administrators->validateRequestKey($email, $requestKey)) {
$this->Flash->error(__d('CakeAdmin', 'Your account could not be reset.'));
return $this->redirect($this->Auth->config('loginAction') + ['email' => $email]);
}
// If we passed and the POST isset
if ($this->request->is('post')) {
$user = $this->Administrators->find()->where([
'email' => $email,
'request_key' => $requestKey,
])->first();
if ($user) {
$user = $this->Administrators->patchEntity($user, $this->request->data);
$user->set('active', 1);
$user->set('request_key', null);
if ($this->Administrators->save($user)) {
$this->Flash->success(__d('CakeAdmin', 'Your password has been changed.'));
return $this->redirect($this->Auth->config('loginAction') + ['email' => $email]);
}
}
$this->Flash->error(__d('CakeAdmin', 'Your account could not be activated.'));
}
} | Reset password action
Users will reach this action when they need to set a new password for their account.
This action will set a new password and redirect to the login page
@param string $email The e-mailaddress from the user.
@param string $requestKey The refering activation key.
@return void|\Cake\Network\Response | entailment |
public function header($options = [])
{
$_options = [
'before' => '<h3>',
'after' => '</h3>'
];
$options = array_merge($_options, $options);
return $options['before'] . h($this->_type['alias']) . $options['after'];
} | header
Header of the page.
### Options
- `before` - Html before the header.
- `after` - Html after the header.
@param array $options Options.
@return string | entailment |
public function indexButton($options = [])
{
$_options = [
'before' => 'All ',
'after' => '',
];
$options = array_merge($_options, $options);
$string = $options['before'] . h(Inflector::singularize($this->_type['alias'])) . $options['after'];
return $this->Html->link($string, ['action' => 'add', 'type' => $this->_type['slug']]);
} | indexButton
An `index`-button with a link to the PostType List.
### Options
- `before` - Html before the button.
- `after` - Html after the button.
The link will be created via the HtmlHelper.
@param array $options Options.
@return string | entailment |
public function searchFilter($searchFilters, $options = [])
{
$_options = [];
$options = array_merge($_options, $options);
return ($searchFilters ? $this->Search->filterForm($searchFilters) : null);
} | searchFilter
Filter-form to search with.
@param array $searchFilters Filter-data.
@param array $options Options.
@return null|string | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.