_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q244700 | GenericRouter.add | validation | public function add(Route $route): void
{
if ($route instanceof Route) {
$name = $route->getName();
} else {
$name = Route::generateNameFromPath($route->getPath());
}
$baseRoute = new SymfonyRoute($route->getPath());
$baseRoute->setMethods($route->getMethods());
$this->routeCollection->add($name, $baseRoute);
$this->routes[$name] = $route;
} | php | {
"resource": ""
} |
q244701 | GenericRouter.find | validation | public function find(string $method, string $path): Route
{
$matcher = new UrlMatcher($this->routeCollection, new RequestContext('/', $method));
try {
$route = $matcher->match($path);
} catch (ResourceNotFoundException $exception) {
throw RouterException::noRouteMatchesRequestedUri($path, $method);
} catch (SymfonyMethodNotAllowedException $exception) {
throw RouterException::methodNotAllowed($path, $exception->getAllowedMethods());
}
$routeName = $route['_route'];
unset($route['_route']);
return $this->routes[$routeName]->withAttributes($route);
} | php | {
"resource": ""
} |
q244702 | HttpApplication.use | validation | public function use($middleware): void
{
if (!is_subclass_of($middleware, MiddlewareInterface::class)) {
if (!is_callable($middleware)) {
throw new ApplicationException(sprintf(
'Middleware must be either class or object that implements `%s`',
MiddlewareInterface::class
));
}
$middleware = new CallableMiddleware($middleware);
}
$this->middleware[] = $middleware;
} | php | {
"resource": ""
} |
q244703 | HttpApplication.process | validation | public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
{
/** @var Route $route */
$route = $this->router->find(
$request->getMethod(),
$request->getUri()->getPath()
);
$controller = $route->getController();
if ($request instanceof ServerRequest) {
$request = $request->withAttributes($route->getAttributes());
}
if (is_string($controller) &&
class_exists($controller) &&
is_subclass_of($controller, Controller::class)
) {
/** @var Controller $instance */
$instance = $this->resolver->resolve($controller);
return $instance($request);
}
if (is_callable($controller)) {
$response = $controller($request);
if (!$response instanceof ResponseInterface) {
throw ControllerException::forInvalidReturnValue();
}
return $response;
}
throw ControllerException::forMissingController($route->getPath());
} | php | {
"resource": ""
} |
q244704 | HttpApplication.handle | validation | public function handle(ServerRequestInterface $request): ResponseInterface
{
$response = $this->getMiddlewarePipe()->handle($request);
return $response;
} | php | {
"resource": ""
} |
q244705 | HttpApplication.get | validation | public function get(string $route, callable $controller): void
{
$this->register($controller, Route::get($route));
} | php | {
"resource": ""
} |
q244706 | HttpApplication.post | validation | public function post(string $route, callable $controller): void
{
$this->register($controller, Route::post($route));
} | php | {
"resource": ""
} |
q244707 | HttpApplication.put | validation | public function put(string $route, callable $controller): void
{
$this->register($controller, Route::put($route));
} | php | {
"resource": ""
} |
q244708 | HttpApplication.patch | validation | public function patch(string $route, callable $controller): void
{
$this->register($controller, Route::patch($route));
} | php | {
"resource": ""
} |
q244709 | HttpApplication.delete | validation | public function delete(string $route, callable $controller): void
{
$this->register($controller, Route::delete($route));
} | php | {
"resource": ""
} |
q244710 | HttpApplication.options | validation | public function options(string $route, callable $controller): void
{
$this->register($controller, Route::options($route));
} | php | {
"resource": ""
} |
q244711 | HttpApplication.head | validation | public function head(string $route, callable $controller): void
{
$this->register($controller, Route::head($route));
} | php | {
"resource": ""
} |
q244712 | Config.merge | validation | public function merge(Config $config): Config
{
$this->config = array_merge_recursive($this->config, $config->config);
return $this;
} | php | {
"resource": ""
} |
q244713 | Config.extract | validation | public function extract(string $namespace): Config
{
$extracted = $this->get($namespace);
if (!is_array($extracted)) {
throw ConfigException::forExtractionFailure($namespace);
}
return new self($extracted);
} | php | {
"resource": ""
} |
q244714 | Config.set | validation | public function set(string $key, $value): void
{
$key = explode('.', $key);
$last = array_pop($key);
$result = &$this->config;
foreach ($key as $part) {
if (!isset($result[$part]) || !is_array($result[$part])) {
$result[$part] = [];
}
$result = &$result[$part];
}
$result[$last] = $value;
} | php | {
"resource": ""
} |
q244715 | SetupCommand.handle | validation | public function handle()
{
if (! $this->token) {
$this->error('You must paste your Discord token (App Bot User token) into your `services.php` config file.');
$this->error('View the README for more info: https://github.com/laravel-notification-channels/discord#installation');
return -1;
}
if (! $this->confirm('Is the bot already added to your server?')) {
$clientId = $this->ask('What is your Discord app client ID?');
$this->warn('Add the bot to your server by visiting this link: https://discordapp.com/oauth2/authorize?&client_id='.$clientId.'&scope=bot&permissions=0');
if (! $this->confirm('Continue?', true)) {
return -1;
}
}
$this->warn("Attempting to identify the bot with Discord's websocket gateway...");
$this->gateway = $this->getGateway();
$this->warn("Connecting to '$this->gateway'...");
$client = $this->getSocket($this->gateway);
// Discord requires all bots to connect via a websocket connection and
// identify at least once before any API requests over HTTP are allowed.
// https://discordapp.com/developers/docs/topics/gateway#gateway-identify
$client->send(json_encode([
'op' => 2,
'd' => [
'token' => $this->token,
'v' => 3,
'compress' => false,
'properties' => [
'$os' => PHP_OS,
'$browser' => 'laravel-notification-channels-discord',
'$device' => 'laravel-notification-channels-discord',
'$referrer' => '',
'$referring_domain' => '',
],
],
]));
$response = $client->receive();
$identified = Arr::get(json_decode($response, true), 'op') === 10;
if (! $identified) {
$this->error("Discord responded with an error while trying to identify the bot: $response");
return -1;
}
$this->info('Your bot has been identified by Discord and can now send API requests!');
} | php | {
"resource": ""
} |
q244716 | SetupCommand.getGateway | validation | public function getGateway()
{
$gateway = $this->gateway;
try {
$response = $this->guzzle->get('https://discordapp.com/api/gateway', [
'headers' => [
'Authorization' => 'Bot '.$this->token,
],
]);
$gateway = Arr::get(json_decode($response->getBody(), true), 'url', $gateway);
} catch (Exception $e) {
$this->warn("Could not get a websocket gateway address, defaulting to '{$gateway}'.");
}
return $gateway;
} | php | {
"resource": ""
} |
q244717 | Discord.request | validation | protected function request($verb, $endpoint, array $data)
{
$url = rtrim($this->baseUrl, '/').'/'.ltrim($endpoint, '/');
try {
$response = $this->httpClient->request($verb, $url, [
'headers' => [
'Authorization' => 'Bot '.$this->token,
],
'json' => $data,
]);
} catch (RequestException $exception) {
if ($response = $exception->getResponse()) {
throw CouldNotSendNotification::serviceRespondedWithAnHttpError($response);
}
throw CouldNotSendNotification::serviceCommunicationError($exception);
} catch (Exception $exception) {
throw CouldNotSendNotification::serviceCommunicationError($exception);
}
$body = json_decode($response->getBody(), true);
if (Arr::get($body, 'code', 0) > 0) {
throw CouldNotSendNotification::serviceRespondedWithAnApiError($body);
}
return $body;
} | php | {
"resource": ""
} |
q244718 | Alert.withLocalizedTitle | validation | public function withLocalizedTitle(Localized $localized): Alert
{
$cloned = clone $this;
$cloned->title = '';
$cloned->titleLocalized = $localized;
return $cloned;
} | php | {
"resource": ""
} |
q244719 | Alert.withBodyLocalized | validation | public function withBodyLocalized(Localized $localized): Alert
{
$cloned = clone $this;
$cloned->body = '';
$cloned->bodyLocalized = $localized;
return $cloned;
} | php | {
"resource": ""
} |
q244720 | Alert.withActionLocalized | validation | public function withActionLocalized(Localized $localized): Alert
{
$cloned = clone $this;
$cloned->actionLocalized = $localized;
return $cloned;
} | php | {
"resource": ""
} |
q244721 | Alert.withLaunchImage | validation | public function withLaunchImage(string $launchImage): Alert
{
$cloned = clone $this;
$cloned->launchImage = $launchImage;
return $cloned;
} | php | {
"resource": ""
} |
q244722 | Demo.includeConfigurationFile | validation | private static function includeConfigurationFile()
{
static $included = false;
if ($included) {
// The configuration file already included
return;
}
$file = __DIR__.'/config.php';
if (!file_exists($file)) {
print sprintf(
'The configuration file "%s" was not found.%sPlease copy %s/config.php.dist to %s/config.php and modify new file for set own parameters.%s',
$file,
PHP_EOL,
__DIR__,
__DIR__,
PHP_EOL
);
exit(1);
}
$included = true;
include_once $file;
} | php | {
"resource": ""
} |
q244723 | Aps.withContentAvailable | validation | public function withContentAvailable(bool $contentAvailable): Aps
{
$cloned = clone $this;
$cloned->contentAvailable = $contentAvailable;
return $cloned;
} | php | {
"resource": ""
} |
q244724 | Aps.withMutableContent | validation | public function withMutableContent(bool $mutableContent): Aps
{
$cloned = clone $this;
$cloned->mutableContent = $mutableContent;
return $cloned;
} | php | {
"resource": ""
} |
q244725 | Aps.withThreadId | validation | public function withThreadId(string $threadId): Aps
{
$cloned = clone $this;
$cloned->threadId = $threadId;
return $cloned;
} | php | {
"resource": ""
} |
q244726 | SignatureGeneratorFactory.resolve | validation | public static function resolve(): SignatureGeneratorInterface
{
self::addDefaultResolvers();
foreach (self::$resolvers as $resolver) {
if ($generator = $resolver()) {
return $generator;
}
}
throw new \LogicException('Cannot resolve available JWT Signature Generator.');
} | php | {
"resource": ""
} |
q244727 | SignatureGeneratorFactory.addDefaultResolvers | validation | private static function addDefaultResolvers(): void
{
static $added = false;
if ($added) {
return;
}
$added = true;
self::addResolver([__CLASS__, 'tryResolveByWebTokenJwtSystem']);
self::addResolver([__CLASS__, 'tryResolveBySpomkyLabsJoseSystem']);
} | php | {
"resource": ""
} |
q244728 | SignatureGeneratorFactory.tryResolveByWebTokenJwtSystem | validation | private static function tryResolveByWebTokenJwtSystem(): ?WebTokenJwtSignatureGenerator
{
$requiredClasses = [
WebTokenComponentJws::class,
WebTokenComponentJwk::class,
WebTokenComponentJWKFactory::class,
];
foreach ($requiredClasses as $requiredClass) {
if (!class_exists($requiredClass)) {
return null;
}
}
return new WebTokenJwtSignatureGenerator();
} | php | {
"resource": ""
} |
q244729 | SignatureGeneratorFactory.tryResolveBySpomkyLabsJoseSystem | validation | private static function tryResolveBySpomkyLabsJoseSystem(): ?SpomkyLabsJoseSignatureGenerator
{
$requiredClasses = [
JWKFactory::class,
JWSFactory::class,
];
foreach ($requiredClasses as $requiredClass) {
if (!class_exists($requiredClass)) {
return null;
}
}
return new SpomkyLabsJoseSignatureGenerator();
} | php | {
"resource": ""
} |
q244730 | ContentJwt.createTemporaryFile | validation | private function createTemporaryFile(): string
{
$tmpDir = $this->tmpDir;
$tmpFileName = md5(uniqid((string) mt_rand(), true)).'.p8';
$tmpFilePath = $tmpDir.'/'.$tmpFileName;
$errorCode = $errorMessage = null;
set_error_handler(function ($errCode, $errMessage) use (&$errorCode, &$errorMessage) {
$errorCode = $errCode;
$errorMessage = $errMessage;
});
if (!file_exists($tmpDir)) {
mkdir($tmpDir, 0600, true);
if ($errorCode || $errorMessage) {
restore_error_handler();
// Error create directory
throw new \RuntimeException(sprintf(
'Can not create temporary directory "%s". Error: %s [%d].',
$tmpDir,
$errorMessage ?: 'Undefined',
$errorCode ?: '0'
));
}
}
touch($tmpFilePath);
if ($errorCode || $errorMessage) {
restore_error_handler();
// Error create file
throw new \RuntimeException(sprintf(
'Can not create temporary certificate file "%s". Error: %s [%d].',
$tmpFilePath,
$errorMessage ?: 'Undefined',
$errorCode ?: '0'
));
}
restore_error_handler();
return $tmpFilePath;
} | php | {
"resource": ""
} |
q244731 | Payload.withCustomData | validation | public function withCustomData(string $name, $value): Payload
{
if ($value && !is_array($value) && !is_scalar($value) && !$value instanceof \JsonSerializable) {
throw new \InvalidArgumentException(sprintf(
'The custom data value should be a scalar or \JsonSerializable instance, but "%s" given.',
is_object($value) ? get_class($value) : gettype($value)
));
}
$cloned = clone $this;
$cloned->customData[$name] = $value;
return $cloned;
} | php | {
"resource": ""
} |
q244732 | Request.withHeader | validation | public function withHeader(string $name, string $value): Request
{
$cloned = clone $this;
$cloned->headers[$name] = $value;
return $cloned;
} | php | {
"resource": ""
} |
q244733 | Request.withHeaders | validation | public function withHeaders(array $headers): Request
{
$cloned = clone $this;
foreach ($headers as $name => $value) {
$cloned = $cloned->withHeader($name, $value);
}
return $cloned;
} | php | {
"resource": ""
} |
q244734 | Request.withCertificate | validation | public function withCertificate(string $certificate): Request
{
$cloned = clone $this;
$cloned->certificate = $certificate;
return $cloned;
} | php | {
"resource": ""
} |
q244735 | Request.withCertificatePassPhrase | validation | public function withCertificatePassPhrase(string $passPhrase): Request
{
$cloned = clone $this;
$cloned->certificatePassPhrase = $passPhrase;
return $cloned;
} | php | {
"resource": ""
} |
q244736 | HttpProtocolChainVisitor.add | validation | public function add(HttpProtocolVisitorInterface $visitor, int $priority = 0): void
{
$this->visitors->insert($visitor, $priority);
} | php | {
"resource": ""
} |
q244737 | HttpProtocol.doSend | validation | private function doSend(Receiver $receiver, Notification $notification, bool $sandbox): void
{
$payloadEncoded = $this->payloadEncoder->encode($notification->getPayload());
$uri = $this->uriFactory->create($receiver->getToken(), $sandbox);
$request = new Request($uri, $payloadEncoded);
$headers = [
'content-type' => 'application/json',
'accept' => 'application/json',
'apns-topic' => $receiver->getTopic(),
];
$request = $request->withHeaders($headers);
$request = $this->authenticator->authenticate($request);
$request = $this->visitor->visit($notification, $request);
$response = $this->httpSender->send($request);
if ($response->getStatusCode() !== 200) {
throw $this->exceptionFactory->create($response);
}
} | php | {
"resource": ""
} |
q244738 | Http20Builder.addDefaultVisitors | validation | public function addDefaultVisitors(): Http20Builder
{
if ($this->addedDefaultVisitors) {
return $this;
}
$this->addedDefaultVisitors = true;
$this->addVisitor(new AddExpirationHeaderVisitor());
$this->addVisitor(new AddPriorityHeaderVisitor());
$this->addVisitor(new AddApnIdHeaderVisitor());
$this->addVisitor(new AddCollapseIdHeaderVisitor());
return $this;
} | php | {
"resource": ""
} |
q244739 | Http20Builder.createChainVisitor | validation | private function createChainVisitor(): HttpProtocolChainVisitor
{
$chainVisitors = new HttpProtocolChainVisitor();
$visitors = clone $this->visitors;
$priority = 0;
foreach ($visitors as $visitor) {
$chainVisitors->add($visitor, ++$priority);
}
return $chainVisitors;
} | php | {
"resource": ""
} |
q244740 | UriFactory.create | validation | public function create(DeviceToken $deviceToken, bool $sandbox): string
{
$uri = 'https://api.push.apple.com/3/device/%s';
if ($sandbox) {
$uri = 'https://api.development.push.apple.com/3/device/%s';
}
return sprintf($uri, $deviceToken);
} | php | {
"resource": ""
} |
q244741 | Notification.withApnId | validation | public function withApnId(ApnId $apnId = null): Notification
{
$cloned = clone $this;
$cloned->apnId = $apnId;
return $cloned;
} | php | {
"resource": ""
} |
q244742 | Notification.withCollapseId | validation | public function withCollapseId(CollapseId $collapseId = null): Notification
{
$cloned = clone $this;
$cloned->collapseId = $collapseId;
return $cloned;
} | php | {
"resource": ""
} |
q244743 | CurlHttpSender.initializeCurlResource | validation | private function initializeCurlResource(): void
{
if (!$this->resource) {
$this->resource = curl_init();
curl_setopt($this->resource, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($this->resource, CURLOPT_POST, 1);
curl_setopt($this->resource, CURLOPT_HTTP_VERSION, 3);
}
} | php | {
"resource": ""
} |
q244744 | CurlHttpSender.prepareCurlResourceByRequest | validation | private function prepareCurlResourceByRequest(Request $request): void
{
curl_setopt($this->resource, CURLOPT_URL, $request->getUrl());
curl_setopt($this->resource, CURLOPT_POSTFIELDS, $request->getContent());
if ($request->getCertificate()) {
curl_setopt($this->resource, CURLOPT_SSLCERT, $request->getCertificate());
curl_setopt($this->resource, CURLOPT_SSLCERTPASSWD, $request->getCertificatePassPhrase());
}
$inlineHeaders = [];
foreach ($request->getHeaders() as $name => $value) {
$inlineHeaders[] = sprintf('%s: %s', $name, $value);
}
curl_setopt($this->resource, CURLOPT_HTTPHEADER, $inlineHeaders);
} | php | {
"resource": ""
} |
q244745 | ExceptionFactory.createByReason | validation | private function createByReason(string $reason, array $json): SendNotificationException
{
$reason = strtolower($reason);
switch ($reason) {
case 'badcollapseid':
return new BadCollapseIdException();
case 'baddevicetoken':
return new BadDeviceTokenException();
case 'badexpirationdate':
return new BadExpirationDateException();
case 'badmessageid':
return new BadMessageIdException();
case 'badpriority':
return new BadPriorityException();
case 'badtopic':
return new BadTopicException();
case 'devicetokennotfortopic':
return new DeviceTokenNotForTopicException();
case 'duplicateheaders':
return new DuplicateHeadersException();
case 'idletimeout':
return new IdleTimeoutException();
case 'missingdevicetoken':
return new MissingDeviceTokenException();
case 'missingtopic':
return new MissingTopicException();
case 'payloadempty':
return new PayloadEmptyException();
case 'topicdisallowed':
return new TopicDisallowedException();
case 'badcertificate':
return new BadCertificateException();
case 'badcertificateenvironment':
return new BadCertificateEnvironmentException();
case 'expiredprovidertoken':
return new ExpiredProviderTokenException();
case 'forbidden':
return new ForbiddenException();
case 'invalidprovidertoken':
return new InvalidProviderTokenException();
case 'missingprovidertoken':
return new MissingProviderTokenException();
case 'badpath':
return new BadPathException();
case 'methodnotallowed':
return new MethodNotAllowedException();
case 'unregistered':
$timestamp = array_key_exists('timestamp', $json) ? $json['timestamp'] : 0;
$lastConfirmed = new \DateTime('now', new \DateTimeZone('UTC'));
$lastConfirmed->setTimestamp($timestamp);
return new UnregisteredException($lastConfirmed);
case 'payloadtoolarge':
return new PayloadTooLargeException();
case 'toomanyprovidertokenupdates':
return new TooManyProviderTokenUpdatesException();
case 'toomanyrequests':
return new TooManyRequestsException();
case 'internalservererror':
return new InternalServerErrorException();
case 'serviceunavailable':
return new ServiceUnavailableException();
case 'shutdown':
return new ShutdownException();
default:
return new UndefinedErrorException();
}
} | php | {
"resource": ""
} |
q244746 | PayloadEncoder.convertApsToArray | validation | private function convertApsToArray(Aps $aps): array
{
$data = [
'alert' => $this->convertAlertToArray($aps->getAlert()),
];
if ($aps->getSound()) {
$data['sound'] = $aps->getSound();
}
if ($aps->getBadge() !== null) {
$data['badge'] = $aps->getBadge();
}
if ($aps->getCategory()) {
$data['category'] = $aps->getCategory();
}
if ($aps->isContentAvailable()) {
$data['content-available'] = 1;
}
if ($aps->isMutableContent()) {
$data['mutable-content'] = 1;
}
if ($aps->getThreadId()) {
$data['thread-id'] = $aps->getThreadId();
}
return $data;
} | php | {
"resource": ""
} |
q244747 | PayloadEncoder.convertAlertToArray | validation | private function convertAlertToArray(Alert $alert): array
{
$data = [];
if ($alert->getBodyLocalized()->getKey()) {
$data['loc-key'] = $alert->getBodyLocalized()->getKey();
$data['loc-args'] = $alert->getBodyLocalized()->getArgs();
} else {
$data['body'] = $alert->getBody();
}
if ($alert->getTitleLocalized()->getKey()) {
$data['title-loc-key'] = $alert->getTitleLocalized()->getKey();
$data['title-loc-args'] = $alert->getTitleLocalized()->getArgs();
} elseif ($alert->getTitle()) {
$data['title'] = $alert->getTitle();
}
if ($alert->getActionLocalized()->getKey()) {
$data['action-loc-key'] = $alert->getActionLocalized()->getKey();
}
if ($alert->getLaunchImage()) {
$data['launch-image'] = $alert->getLaunchImage();
}
return $data;
} | php | {
"resource": ""
} |
q244748 | FineDiff.doDiff | validation | private function doDiff($from_text, $to_text)
{
$this->last_edit = false;
$this->stackpointer = 0;
$this->from_text = $from_text;
$this->from_offset = 0;
// can't diff without at least one granularity specifier
if (empty($this->granularityStack)) {
return;
}
$this->_processGranularity($from_text, $to_text);
} | php | {
"resource": ""
} |
q244749 | FineDiff.doCharDiff | validation | private static function doCharDiff($from_text, $to_text)
{
$result = array();
$jobs = array(array(0, strlen($from_text), 0, strlen($to_text)));
while ($job = array_pop($jobs)) {
// get the segments which must be diff'ed
list($from_segment_start, $from_segment_end, $to_segment_start, $to_segment_end) = $job;
$from_segment_len = $from_segment_end - $from_segment_start;
$to_segment_len = $to_segment_end - $to_segment_start;
// catch easy cases first
if (!$from_segment_len || !$to_segment_len) {
if ($from_segment_len) {
$result[$from_segment_start * 4 + 0] = new FineDiffDeleteOp($from_segment_len);
} else if ($to_segment_len) {
$result[$from_segment_start * 4 + 1] = new FineDiffInsertOp(substr($to_text, $to_segment_start, $to_segment_len));
}
continue;
}
if ($from_segment_len >= $to_segment_len) {
$copy_len = $to_segment_len;
while ($copy_len) {
$to_copy_start = $to_segment_start;
$to_copy_start_max = $to_segment_end - $copy_len;
while ($to_copy_start <= $to_copy_start_max) {
$from_copy_start = strpos(substr($from_text, $from_segment_start, $from_segment_len), substr($to_text, $to_copy_start, $copy_len));
if ($from_copy_start !== false) {
$from_copy_start += $from_segment_start;
break 2;
}
$to_copy_start++;
}
$copy_len--;
}
} else {
$copy_len = $from_segment_len;
while ($copy_len) {
$from_copy_start = $from_segment_start;
$from_copy_start_max = $from_segment_end - $copy_len;
while ($from_copy_start <= $from_copy_start_max) {
$to_copy_start = strpos(substr($to_text, $to_segment_start, $to_segment_len), substr($from_text, $from_copy_start, $copy_len));
if ($to_copy_start !== false) {
$to_copy_start += $to_segment_start;
break 2;
}
$from_copy_start++;
}
$copy_len--;
}
}
// match found
if ($copy_len) {
$jobs[] = array($from_segment_start, $from_copy_start, $to_segment_start, $to_copy_start);
$result[$from_copy_start * 4 + 2] = new FineDiffCopyOp($copy_len);
$jobs[] = array($from_copy_start + $copy_len, $from_segment_end, $to_copy_start + $copy_len, $to_segment_end);
} // no match, so delete all, insert all
else {
$result[$from_segment_start * 4] = new FineDiffReplaceOp($from_segment_len, substr($to_text, $to_segment_start, $to_segment_len));
}
}
ksort($result, SORT_NUMERIC);
return array_values($result);
} | php | {
"resource": ""
} |
q244750 | FineDiff.renderToTextFromOpcode | validation | private static function renderToTextFromOpcode($opcode, $from, $from_offset, $from_len)
{
if ($opcode === 'c' || $opcode === 'i') {
echo substr($from, $from_offset, $from_len);
}
} | php | {
"resource": ""
} |
q244751 | TranslatorRepository.dbValue | validation | public static function dbValue($value, $nullValue = 'NULL')
{
if ($value === null) {
return $nullValue;
}
if (is_string($value)) {
return '\'' . str_replace('\'', '\'\'', $value) . '\'';
}
if (is_bool($value)) {
return $value ? '1' : '0';
}
return $value;
} | php | {
"resource": ""
} |
q244752 | TranslatorRepository.adjustTranslationTable | validation | protected function adjustTranslationTable($sql)
{
$adjustedSql = $this->tableRenameNeeded ? str_replace(' ltm_translations ', ' ' . $this->tableName . ' ', $sql) : $sql;
return $adjustedSql;
} | php | {
"resource": ""
} |
q244753 | TranslatorRepository.getInsertTranslationsElement | validation | public function getInsertTranslationsElement($translation, $timeStamp)
{
return '(' .
self::dbValue($translation->status, Translation::STATUS_SAVED) . ',' .
self::dbValue($translation->locale) . ',' .
self::dbValue($translation->group) . ',' .
self::dbValue($translation->key) . ',' .
self::dbValue($translation->value) . ',' .
self::dbValue($translation->created_at, $timeStamp) . ',' .
self::dbValue($translation->updated_at, $timeStamp) . ',' .
self::dbValue($translation->source) . ',' .
self::dbValue($translation->saved_value) . ',' .
self::dbValue($translation->is_deleted, 0) . ',' .
self::dbValue($translation->was_used, 0) .
')';
} | php | {
"resource": ""
} |
q244754 | Controller.getPublish | validation | public function getPublish($group)
{
if ($group && $group != '*') {
$this->manager->exportTranslations($group);
} else {
$this->manager->exportAllTranslations();
}
$errors = $this->manager->errors();
event(new TranslationsPublished($group, $errors));
return Response::json(array('status' => $errors ? 'errors' : 'ok', 'errors' => $errors));
} | php | {
"resource": ""
} |
q244755 | Controller.postMissingKeys | validation | public function postMissingKeys()
{
$missingKeys = Request::json('missingKeys');
// always on the default connection
$this->manager->setConnectionName('');
/* @var $translator \Vsch\TranslationManager\Translator */
$translator = App::make('translator');
$affectedGroups = [];
foreach ($missingKeys as $key) {
$key = decodeKey($key);
list($namespace, $group, $item) = $translator->parseKey($key);
if ($item && $group) {
if (!in_array($group, $this->manager->config(Manager::EXCLUDE_GROUPS_KEY))) {
$t = $this->manager->missingKey($namespace, $group, $item, null, false, true);
if (!$t->exists) {
$affectedGroups[] = $t->group;
$t->save();
}
}
} else {
// TODO: return error invalid key
}
}
$data = [
'connectionName' => '',
'affectedGroups' => $affectedGroups,
'missingKeys' => [],
];
$pretty = Request::has('pretty-json') ? JSON_PRETTY_PRINT : 0;
return Response::json($data, 200, [], JSON_UNESCAPED_SLASHES | $pretty);
} | php | {
"resource": ""
} |
q244756 | Translator.getLocale | validation | public function getLocale()
{
if (!$this->cookiesLoaded) {
$key = $this->cookiePrefix . 'lang_locale';
$queuedCookieLocale = \Cookie::queued($key, null);
$locale = getSupportedLocale($queuedCookieLocale != null ? $queuedCookieLocale->getValue() : \Cookie::get($key, ''));
parent::setLocale($locale);
// load unpublished translation flag at the same time
$this->getShowUnpublished();
$this->cookiesLoaded = true;
}
return parent::getLocale();
} | php | {
"resource": ""
} |
q244757 | Translator.setLocale | validation | public function setLocale($locale)
{
if ($this->useCookies) {
Cookie::queue($this->cookiePrefix . 'lang_locale', $locale);
}
parent::setLocale($locale);
} | php | {
"resource": ""
} |
q244758 | Translator.getShowUnpublished | validation | public function getShowUnpublished()
{
if (!$this->cookiesLoaded) {
$key = $this->cookiePrefix . 'show_unpublished';
$queuedCookie = \Cookie::queued($key, null);
$showUnpublished = $queuedCookie != null ? $queuedCookie->getValue() : \Cookie::get($key, false);
$this->useDB = $showUnpublished ? 2 : 1;
$this->cookiesLoaded = true;
}
return $this->useDB === 2;
} | php | {
"resource": ""
} |
q244759 | Translator.setShowUnpublished | validation | public function setShowUnpublished($showUnpublished)
{
if ($this->useCookies) {
Cookie::queue($this->cookiePrefix . 'show_unpublished', $showUnpublished);
}
$this->useDB = $showUnpublished ? 2 : 1;
} | php | {
"resource": ""
} |
q244760 | Translator.getWebUITranslations | validation | public function getWebUITranslations()
{
$TITLE_SAVE_CHANGES = $this->get($this->package . '::messages.title-save-changes');
$TITLE_CANCEL_CHANGES = $this->get($this->package . '::messages.title-cancel-changes');
$TITLE_TRANSLATE = $this->get($this->package . '::messages.title-translate');
$TITLE_CONVERT_KEY = $this->get($this->package . '::messages.title-convert-key');
$TITLE_GENERATE_PLURALS = $this->get($this->package . '::messages.title-generate-plurals');
$TITLE_CLEAN_HTML_MARKDOWN = $this->get($this->package . '::messages.title-clean-html-markdown');
$TITLE_CAPITALIZE = $this->get($this->package . '::messages.title-capitalize');
$TITLE_LOWERCASE = $this->get($this->package . '::messages.title-lowercase');
$TITLE_CAPITALIZE_FIRST_WORD = $this->get($this->package . '::messages.title-capitalize-first-word');
$TITLE_SIMULATED_COPY = $this->get($this->package . '::messages.title-simulated-copy');
$TITLE_SIMULATED_PASTE = $this->get($this->package . '::messages.title-simulated-paste');
$TITLE_RESET_EDITOR = $this->get($this->package . '::messages.title-reset-editor');
$TITLE_LOAD_LAST = $this->get($this->package . '::messages.title-load-last');
return <<<HTML
<script>
var TITLE_SAVE_CHANGES = "$TITLE_SAVE_CHANGES";
var TITLE_CANCEL_CHANGES = "$TITLE_CANCEL_CHANGES";
var TITLE_TRANSLATE = "$TITLE_TRANSLATE";
var TITLE_CONVERT_KEY = "$TITLE_CONVERT_KEY";
var TITLE_GENERATE_PLURALS = "$TITLE_GENERATE_PLURALS";
var TITLE_CLEAN_HTML_MARKDOWN = "$TITLE_CLEAN_HTML_MARKDOWN";
var TITLE_CAPITALIZE = "$TITLE_CAPITALIZE";
var TITLE_LOWERCASE = "$TITLE_LOWERCASE";
var TITLE_CAPITALIZE_FIRST_WORD = "$TITLE_CAPITALIZE_FIRST_WORD";
var TITLE_SIMULATED_COPY = "$TITLE_SIMULATED_COPY";
var TITLE_SIMULATED_PASTE = "$TITLE_SIMULATED_PASTE";
var TITLE_RESET_EDITOR = "$TITLE_RESET_EDITOR";
var TITLE_LOAD_LAST = "$TITLE_LOAD_LAST";
</script>
HTML;
} | php | {
"resource": ""
} |
q244761 | Translator.choice | validation | public function choice($key, $number, array $replace = array(), $locale = null, $useDB = null)
{
$inplaceEditMode = $this->manager->config('inplace_edit_mode');
if ($this->inPlaceEditing() && $inplaceEditMode == 2) {
if (!in_array($key, $this->usedKeys)) {
$this->usedKeys[] = $key;
}
}
if (!$this->suspendInPlaceEdit && $this->inPlaceEditing() && $inplaceEditMode == 1) {
return $this->get($key, $replace, $locale, true, $useDB);
} else {
if ($useDB !== null) {
$oldUseDB = $this->useDB;
$this->useDB = $useDB;
$retVal = parent::choice($key, $number, $replace, $locale);
$this->useDB = $oldUseDB;
return $retVal;
} else {
return parent::choice($key, $number, $replace, $locale);
}
}
} | php | {
"resource": ""
} |
q244762 | Auth.login | validation | public static function login($email, $password, $challenge = '', $code = '') {
$requestParams = [
'includePerms' => 'false', // We don't need these here
'token_type' => 'eg1'
];
if (empty($challenge) && empty($code)) {
// Regular login
$requestParams = array_merge($requestParams, [
'grant_type' => 'password',
'username' => $email,
'password' => $password,
]);
} else {
$requestParams = array_merge($requestParams, [
'grant_type' => 'otp',
'otp' => $code,
'challenge' => $challenge,
]);
}
// First, we need to get a token for the Unreal Engine client
$data = FortniteClient::sendUnrealClientPostRequest(FortniteClient::EPIC_OAUTH_TOKEN_ENDPOINT, $requestParams);
if (!isset($data->access_token)) {
if ($data->errorCode === 'errors.com.epicgames.common.two_factor_authentication.required') {
throw new TwoFactorAuthRequiredException($data->challenge);
}
throw new \Exception($data->errorMessage);
}
// Now that we've got our Unreal Client launcher token, let's get an exchange token for Fortnite
$data = FortniteClient::sendUnrealClientGetRequest(FortniteClient::EPIC_OAUTH_EXCHANGE_ENDPOINT, $data->access_token, true);
if (!isset($data->code)) {
throw new \Exception($data->errorMessage);
}
// Should be good. Let's get our tokens for the Fortnite API
$data = FortniteClient::sendUnrealClientPostRequest(FortniteClient::EPIC_OAUTH_TOKEN_ENDPOINT, [
'grant_type' => 'exchange_code',
'exchange_code' => $data->code,
'includePerms' => false, // We don't need these here
'token_type' => 'eg1'
], FortniteClient::FORTNITE_AUTHORIZATION);
if (!isset($data->access_token)) {
throw new \Exception($data->errorMessage);
}
return new self($data->access_token, $data->in_app_id, $data->refresh_token, $data->account_id, $data->expires_in);
} | php | {
"resource": ""
} |
q244763 | Auth.refresh | validation | public static function refresh($refresh_token) {
$data = FortniteClient::sendUnrealClientPostRequest(FortniteClient::EPIC_OAUTH_TOKEN_ENDPOINT, [
'grant_type' => 'refresh_token',
'refresh_token' => $refresh_token,
'includePerms' => "false", // We don't need these here
'token_type' => 'eg1',
], FortniteClient::FORTNITE_AUTHORIZATION);
if (!$data->access_token) {
throw new \Exception($data->errorMessage);
}
return new self($data->access_token, $data->in_app_id, $data->refresh_token, $data->account_id, $data->expires_in);
} | php | {
"resource": ""
} |
q244764 | Items.id | validation | public function id($id) {
foreach ($this->items as $item) {
if ($item->itemId == $id) return $item;
}
return null;
} | php | {
"resource": ""
} |
q244765 | Stats.fetch | validation | private function fetch($account_id) {
if (!$account_id) return null;
$data = FortniteClient::sendFortniteGetRequest(FortniteClient::FORTNITE_API . 'stats/accountId/' . $account_id . '/bulk/window/alltime',
$this->access_token);
// Remove - from account ID and get it's display name
$this->display_name = Account::getDisplayNameFromID(str_replace("-","",$this->account_id), $this->access_token);
//if (!count($data)) throw new StatsNotFoundException('Unable to find any stats for account id '. $account_id);
// Loop over all the stat objects and compile them together cleanly
$compiledStats = [];
foreach ($data as $stat) {
$parsed = $this->parseStatItem($stat);
$compiledStats = array_merge_recursive($compiledStats, $parsed);
}
// Now loop over the compiled stats and create proper objects
$platforms = [];
foreach ($compiledStats as $key => $platform) {
$platforms[$key] = new Platform($platform);
}
return $platforms;
} | php | {
"resource": ""
} |
q244766 | Stats.lookup | validation | public function lookup($username) {
try {
$data = FortniteClient::sendFortniteGetRequest(FortniteClient::FORTNITE_PERSONA_API . 'public/account/lookup?q=' . urlencode($username),
$this->access_token);
return new self($this->access_token, $data->id);
} catch (GuzzleException $e) {
if ($e->getResponse()->getStatusCode() == 404) throw new UserNotFoundException('User ' . $username . ' was not found.');
throw $e; //If we didn't get the user not found status code, just re-throw the error.
}
} | php | {
"resource": ""
} |
q244767 | Stats.parseStatItem | validation | private function parseStatItem($stat): array {
//
// Example stat name:
// br_placetop5_ps4_m0_p10
// {type}_{name}_{platform}_{??}_{mode (squads/solo/duo)}
//
$result = [];
$pieces = explode("_", $stat->name);
$result[$pieces[2]][$pieces[4]][$pieces[1]] = $stat->value;
return $result;
} | php | {
"resource": ""
} |
q244768 | Profile.fetch | validation | private function fetch() {
$data = FortniteClient::sendFortnitePostRequest(FortniteClient::FORTNITE_API . 'game/v2/profile/' . $this->account_id . '/client/QueryProfile?profileId=athena&rvn=-1',
$this->access_token,
new \StdClass());
return $data->profileChanges[0]->profile;
} | php | {
"resource": ""
} |
q244769 | Profile.getFriends | validation | public function getFriends() {
$data = FortniteClient::sendUnrealClientGetRequest(FortniteClient::EPIC_FRIENDS_ENDPOINT . $this->account_id, $this->access_token, true);
return $data;
} | php | {
"resource": ""
} |
q244770 | FortniteClient.sendUnrealClientGetRequest | validation | public static function sendUnrealClientGetRequest($endpoint, $authorization = self::EPIC_LAUNCHER_AUTHORIZATION, $oauth = false) {
$client = new Client();
try {
$response = $client->get($endpoint, [
'headers' => [
'User-Agent' => self::UNREAL_CLIENT_USER_AGENT,
'Authorization' => (!$oauth) ? 'basic ' . $authorization : 'bearer ' . $authorization
]
]);
return json_decode($response->getBody()->getContents());
} catch (GuzzleException $e) {
throw $e; //Throw exception back up to caller
}
} | php | {
"resource": ""
} |
q244771 | FortniteClient.sendUnrealClientPostRequest | validation | public static function sendUnrealClientPostRequest($endpoint, $params = null, $authorization = self::EPIC_LAUNCHER_AUTHORIZATION, $oauth = false) {
$client = new Client(['http_errors' => false]);
try {
$response = $client->post($endpoint, [
'form_params' => $params,
'headers' => [
'User-Agent' => self::UNREAL_CLIENT_USER_AGENT,
'Authorization' => (!$oauth) ? 'basic ' . $authorization : 'bearer ' . $authorization,
'X-Epic-Device-ID' => self::generateDeviceId()
]
]);
return json_decode($response->getBody()->getContents());
} catch (GuzzleException $e) {
throw $e; //Throw exception back up to caller
}
} | php | {
"resource": ""
} |
q244772 | FortniteClient.sendFortniteGetRequest | validation | public static function sendFortniteGetRequest($endpoint, $access_token, $extra_headers = array()) {
$client = new Client();
$headers = [
'User-Agent' => self::FORTNITE_USER_AGENT,
'Authorization' => 'bearer ' . $access_token
];
$headers = array_merge($headers, $extra_headers);
try {
$response = $client->get($endpoint, [
'headers' => $headers
]);
return json_decode($response->getBody()->getContents());
} catch (GuzzleException $e) {
throw $e; //Throw exception back up to caller
}
} | php | {
"resource": ""
} |
q244773 | FortniteClient.sendFortnitePostRequest | validation | public static function sendFortnitePostRequest($endpoint, $access_token, $params = null) {
$client = new Client();
try {
$response = $client->post($endpoint, [
'json' => $params,
'headers' => [
'User-Agent' => self::FORTNITE_USER_AGENT,
'Authorization' => 'bearer ' . $access_token
]
]);
return json_decode($response->getBody()->getContents());
} catch (GuzzleException$e) {
throw $e; //Throw exception back up to caller
}
} | php | {
"resource": ""
} |
q244774 | UserDbLdap.findByAttribute | validation | public static function findByAttribute($attribute, $searchValue) {
if(static::getExtensionOptions('ENABLE_YII2_PROFILING') == true) {
Yii::beginProfile('Attribute: ' . $attribute . '; Value: ' . $searchValue, static::YII2_PROFILE_NAME . 'findByAttribute');
}
$userObjectsFound = static::getAdldapProvider()->search()->select('samaccountname')->where($attribute, '=', $searchValue)->get();
$userObjectReturn = null;
if(count($userObjectsFound) == 1) {
$userObjectReturn = static::findByUsername($userObjectsFound[0]['samaccountname'][0]);
}
if(static::getExtensionOptions('ENABLE_YII2_PROFILING') == true) {
Yii::endProfile('Attribute: ' . $attribute . '; Value: ' . $searchValue, static::YII2_PROFILE_NAME . 'findByAttribute');
}
return $userObjectReturn;
} | php | {
"resource": ""
} |
q244775 | UserDbLdap.createNewUser | validation | public static function createNewUser($username,$individualGroupAssignmentOptions = null) {
if(static::getExtensionOptions('ENABLE_YII2_PROFILING') == true) {
Yii::beginProfile('createNewUser', static::YII2_PROFILE_NAME . 'createNewUser');
}
$userObjectDb = new static();
//Username has to be set before a LDAP query
$userObjectDb->username = $username;
$userObjectDb->setIndividualGroupAssignmentOptions($individualGroupAssignmentOptions);
//Check if user exists in LDAP.
if($userObjectDb->queryLdapUserObject() == null) {
$userObjectDb = null;
} else {
$roles = $userObjectDb->updateGroupAssignment();
//When a group is needed for login and no roles are assigned to user, don't create one
if (count($roles) > 0 || static::getGroupAssigmentOptions('LOGIN_POSSIBLE_WITH_ROLE_ASSIGNED_MATCHING_REGEX',$userObjectDb->individualGroupAssignmentOptions) == null) {
$userObjectDb->generateAuthKey();
$userObjectDb->updateAccountStatus();
$userObjectDb->save();
} else {
$userObjectDb = null;
}
}
if(static::getExtensionOptions('ENABLE_YII2_PROFILING') == true) {
Yii::endProfile('createNewUser', static::YII2_PROFILE_NAME . 'createNewUser');
}
return $userObjectDb;
} | php | {
"resource": ""
} |
q244776 | UserDbLdap.createOrRefreshUser | validation | public static function createOrRefreshUser($username,$individualGroupAssignmentOptions = null) {
if(static::getExtensionOptions('ENABLE_YII2_PROFILING') == true) {
Yii::beginProfile('createOrRefreshUser', static::YII2_PROFILE_NAME . 'createOrRefreshUser');
}
$userObjectDb = static::findOne(['username' => $username]);
//Create user if not found in db
if ($userObjectDb == null) {
$userObjectDb = static::createNewUser($username, $individualGroupAssignmentOptions);
} else {
$userObjectDb->setIndividualGroupAssignmentOptions($individualGroupAssignmentOptions);
$userObjectDb->updateAccountStatus();
$userObjectDb->updateGroupAssignment();
}
if(static::getExtensionOptions('ENABLE_YII2_PROFILING') == true) {
Yii::endProfile('createOrRefreshUser', static::YII2_PROFILE_NAME . 'createOrRefreshUser');
}
return $userObjectDb;
} | php | {
"resource": ""
} |
q244777 | UserDbLdap.updateAccountStatus | validation | public function updateAccountStatus() {
if(static::getExtensionOptions('ENABLE_YII2_PROFILING') == true) {
Yii::beginProfile('LDAP updateAccountStatus function', static::YII2_PROFILE_NAME . 'updateAccountStatus');
}
$ldapUser = $this->queryLdapUserObject();
if ($ldapUser == null) {
//If no user is found in LDAP, disable in database.
$this->status = static::STATUS_DISABLED;
} else {
//Query account status from active directory
$ldapAccountState = $ldapUser->getUserAccountControl();
$disabledUser = ($ldapAccountState & AccountControl::ACCOUNTDISABLE) === AccountControl::ACCOUNTDISABLE;
$lockedUser = ($ldapAccountState & AccountControl::LOCKOUT) === AccountControl::LOCKOUT;
$pwExpired = ($ldapAccountState & AccountControl::PASSWORD_EXPIRED) === AccountControl::PASSWORD_EXPIRED;
if($disabledUser == true || $lockedUser == true || $pwExpired == true) {
$this->status = static::STATUS_DISABLED;
} else {
$this->status = static::STATUS_ENABLED;
}
}
$this->save();
if(static::getExtensionOptions('ENABLE_YII2_PROFILING') == true) {
Yii::endProfile('LDAP updateAccountStatus function', static::YII2_PROFILE_NAME . 'updateAccountStatus');
}
return $this->status;
} | php | {
"resource": ""
} |
q244778 | UserDbLdap.getGroupsAssignedInLdap | validation | public function getGroupsAssignedInLdap() {
if(static::getExtensionOptions('ENABLE_YII2_PROFILING') == true) {
Yii::beginProfile('getGroupsAssignedInLdap', static::YII2_PROFILE_NAME . 'getGroupsAssignedInLdap');
}
$ldapUser = $this->queryLdapUserObject();
$ldapGroupsConverted = []; //start with empty array of groups
if ($ldapUser != null) {
//check for nested groups?
if (static::getGroupAssigmentOptions('SEARCH_NESTED_GROUPS',$this->individualGroupAssignmentOptions) == true) {
//$ldapGroups=$ldapUser->getGroups(['cn'], $recursive=true); //alternate Query, but slower
//1.2.840.113556.1.4.1941 = Specical OID to resolve chains
$ldapGroups = static::getAdldapProvider()->search()->rawFilter('(member:1.2.840.113556.1.4.1941:=' . $ldapUser->getDn() . ')')->select('cn')->raw()->get();
if ($ldapGroups == null) {
$ldapGroups = [];
}
//get cn of each group
foreach ($ldapGroups as $groupDn) {
if (is_array($groupDn) && array_key_exists('cn', $groupDn)) {
array_push($ldapGroupsConverted, $groupDn['cn'][0]);
}
}
} else {
//get attribute memberof
$ldapGroups = $ldapUser->getAttribute('memberof');
if ($ldapGroups == null) {
$ldapGroups = [];
}
//get first part of dn
foreach ($ldapGroups as $groupDn) {
$n = Utilities::explodeDn($groupDn)[0];
array_push($ldapGroupsConverted, $n);
}
}
}
if(static::getExtensionOptions('ENABLE_YII2_PROFILING') == true) {
Yii::endProfile('getGroupsAssignedInLdap', static::YII2_PROFILE_NAME . 'getGroupsAssignedInLdap');
}
return $ldapGroupsConverted;
} | php | {
"resource": ""
} |
q244779 | UserDbLdap.queryLdapUserObject | validation | public function queryLdapUserObject() {
if(static::getExtensionOptions('ENABLE_YII2_PROFILING') == true) {
Yii::beginProfile('queryLdapUserObject', static::YII2_PROFILE_NAME . 'queryLdapUserObject');
}
if ($this->ldapUserObject == null) {
if ($this->username == null) {
throw new \yii\base\Exception('Please set username attribute before calling queryLdapUserObject() function.');
}
$userObjectsFound = static::getAdldapProvider()->search()->where('sAMAccountname', '=', $this->username)->get();
if(count($userObjectsFound) != 1) {
$this->ldapUserObject = null;
} else {
$this->ldapUserObject = $userObjectsFound[0];
}
}
if(static::getExtensionOptions('ENABLE_YII2_PROFILING') == true) {
Yii::endProfile('queryLdapUserObject', static::YII2_PROFILE_NAME . 'queryLdapUserObject');
}
return $this->ldapUserObject;
} | php | {
"resource": ""
} |
q244780 | UserDbLdap.getAdldapProvider | validation | public static function getAdldapProvider() {
if(static::getExtensionOptions('adldap-providername') != '__USE_DEFAULT_PROVIDER__') {
$provider = Yii::$app->ad->getProvider(static::getExtensionOptions('adldap-providername'));
} else {
$provider = Yii::$app->ad->getDefaultProvider();
}
return $provider;
} | php | {
"resource": ""
} |
q244781 | UserDbLdap.getSyncOptions | validation | public static function getSyncOptions($optionName, $individualSyncOptions = null) {
//try object specific settings
if ($individualSyncOptions != null &&
is_array($individualSyncOptions) &&
array_key_exists($optionName, $individualSyncOptions))
{
return $individualSyncOptions[$optionName];
}
//try yii2 params
else if (isset(Yii::$app->params['LDAP-User-Sync-Options']) &&
is_array(Yii::$app->params['LDAP-User-Sync-Options']) &&
array_key_exists($optionName, Yii::$app->params['LDAP-User-Sync-Options']))
{
return Yii::$app->params['LDAP-User-Sync-Options'][$optionName];
}
//default from distribution
else if (array_key_exists($optionName, static::SYNC_OPTIONS_TEMPLATE_WITHOUT_BACKEND_TASK)) {
return static::SYNC_OPTIONS_TEMPLATE_WITHOUT_BACKEND_TASK[$optionName];
}
//Exception
else {
throw new \yii\base\Exception('Sync-option ' . $optionName . ' not found. Please define settings in the config/params.php of the yii2 framework as described on top of the UserDbLdap.php');
}
} | php | {
"resource": ""
} |
q244782 | UserDbLdap.getGroupAssigmentOptions | validation | public static function getGroupAssigmentOptions($optionName, $individualGroupAssignmentOptions = null) {
//try object specific settings
if ($individualGroupAssignmentOptions != null &&
is_array($individualGroupAssignmentOptions) &&
array_key_exists($optionName, $individualGroupAssignmentOptions))
{
return $individualGroupAssignmentOptions[$optionName];
}
//try yii2 params
else if (isset(Yii::$app->params['LDAP-Group-Assignment-Options']) &&
is_array(Yii::$app->params['LDAP-Group-Assignment-Options']) &&
array_key_exists($optionName, Yii::$app->params['LDAP-Group-Assignment-Options']))
{
return Yii::$app->params['LDAP-Group-Assignment-Options'][$optionName];
}
//default from distribution
else if (array_key_exists($optionName, static::GROUP_ASSIGNMENT_TOUCH_ONLY_MATCHING_REGEX)) {
return static::GROUP_ASSIGNMENT_TOUCH_ONLY_MATCHING_REGEX[$optionName];
}
//Exception
else {
throw new \yii\base\Exception('Group-Option ' . $optionName . ' not found. Please define settings in the config/params.php of the yii2 framework as described on top of the UserDbLdap.php');
}
} | php | {
"resource": ""
} |
q244783 | UserDbLdap.getExtensionOptions | validation | public static function getExtensionOptions($optionName) {
//try yii2 params
if (isset(Yii::$app->params['yii2-adldap-extension-Options']) &&
is_array(Yii::$app->params['yii2-adldap-extension-Options']) &&
array_key_exists($optionName, Yii::$app->params['yii2-adldap-extension-Options']))
{
return Yii::$app->params['yii2-adldap-extension-Options'][$optionName];
}
//default from distribution
else if (array_key_exists($optionName, static::EXTENSION_OPTIONS_DEFAULT)) {
return static::EXTENSION_OPTIONS_DEFAULT[$optionName];
}
//Exception
else {
throw new \yii\base\Exception('Extension-Option ' . $optionName . ' not found. Please define settings in the config/params.php of the yii2 framework as described on top of the UserDbLdap.php');
}
} | php | {
"resource": ""
} |
q244784 | LdapController.actionCreateExampleRole | validation | public function actionCreateExampleRole()
{
$auth = Yii::$app->authManager;
// add "permissionDisplayDetailedAbout" permission
$displayDetailedAbout = $auth->createPermission('permissionDisplayDetailedAbout');
$displayDetailedAbout->description = 'Permission to display detailed about informations';
$auth->add($displayDetailedAbout);
// add "permissionToUseContanctPage" permission
$useContactPage = $auth->createPermission('permissionToUseContanctPage');
$useContactPage->description = 'Permission to use the contanct page';
$auth->add($useContactPage);
// add "yii2_example_group" role and give this role the "permissionDisplayDetailedAbout" and "permissionToUseContanctPage" permission
$yii2ExampleGroup = $auth->createRole('yii2_example_group');
$auth->add($yii2ExampleGroup);
$auth->addChild($yii2ExampleGroup, $displayDetailedAbout);
$auth->addChild($yii2ExampleGroup, $useContactPage);
// add "permissionToUseContanctPage" permission
$useHomePage = $auth->createPermission('permissionToSeeHome');
$useHomePage->description = 'Permission to use the home page';
$auth->add($useHomePage);
// add "yii2_see_home_group" role and give this role the "permissionToSeeHome" permission
$yii2HomeGroup = $auth->createRole('yii2_see_home_group');
$auth->add($yii2HomeGroup);
$auth->addChild($yii2HomeGroup, $useHomePage);
echo "\n\n!!!! TODO !!!!\nTow roles with the name yii2_example_group and yii2_see_home_group were created in yii2.\nPlease create the groups with the same name in Active Directory.\nAssign the user you are using for the login to this groups in Active Directory.\n";
} | php | {
"resource": ""
} |
q244785 | GenerateModels.writeable | validation | protected function writeable($file_path)
{
if ($this->option('force')) {
return true;
}
return ( ! file_exists($file_path) || $this->confirmable($file_path));
} | php | {
"resource": ""
} |
q244786 | GenerateModels.write | validation | protected function write($file, $file_path)
{
if (! is_dir(dirname($file_path))) {
mkdir(dirname($file_path), 0755, true);
}
file_put_contents(
$file_path,
file_get_contents(
dirname(__FILE__)
.DIRECTORY_SEPARATOR
.'..'.DIRECTORY_SEPARATOR
.'..'.DIRECTORY_SEPARATOR
.'..'.DIRECTORY_SEPARATOR
.'templates'
.DIRECTORY_SEPARATOR
.$file
.'.txt'
)
);
} | php | {
"resource": ""
} |
q244787 | UserGateway.create | validation | public function create($request)
{
$data = $request->all();
$user = $this->repository->create($data);
$event_class = "Acoustep\EntrustGui\Events\\".ucwords($this->getModelName()).'CreatedEvent';
$event = new $event_class;
$this->dispatcher->fire($event->setModel($user));
return $user;
} | php | {
"resource": ""
} |
q244788 | EntrustGuiServiceProvider.boot | validation | public function boot()
{
$this->loadViewsFrom(realpath(__DIR__.'/../views'), 'entrust-gui');
$this->setupRoutes($this->app->router);
$this->loadTranslationsFrom(realpath(__DIR__.'/../translations'), 'entrust-gui');
// This is for conig
$this->publishes(
[__DIR__.'/../config/entrust-gui.php' => config_path('entrust-gui.php')],
'config'
);
// This is for views
$this->publishes(
[__DIR__.'/../views' => base_path('resources/views/vendor/entrust-gui')],
'views'
);
// This is for translations
$this->publishes(
[__DIR__.'/../translations' => base_path('resources/lang/vendor/entrust-gui')],
'translations'
);
// Register commands
$this->commands('command.entrust-gui.models');
} | php | {
"resource": ""
} |
q244789 | ManyToManyGateway.create | validation | public function create($request)
{
$model = $this->repository->create($request->all());
$model->{$this->getShortRelationName()}()->sync($request->get($this->getRelationName(), []));
$event_class = "Acoustep\EntrustGui\Events\\".ucwords($this->getModelName()).'CreatedEvent';
$event = new $event_class;
$this->dispatcher->fire($event->setModel($model));
return $model;
} | php | {
"resource": ""
} |
q244790 | EmojiServiceProvider.registerRepository | validation | protected function registerRepository()
{
$this->app->singleton(CachingRepository::class, function (Container $app) {
$repo = new GitHubRepository(
GuzzleFactory::make(),
$app->config->get('emoji.token')
);
$cache = $app->cache->store($app->config->get('emoji.connection'));
$key = $app->config->get('emoji.key', 'emoji');
$life = (int) $app->config->get('emoji.life', 10080);
return new CachingRepository($repo, $cache, $key, $life);
});
$this->app->alias(CachingRepository::class, RepositoryInterface::class);
} | php | {
"resource": ""
} |
q244791 | EmojiServiceProvider.registerParser | validation | protected function registerParser()
{
$this->app->singleton(EmojiParser::class, function (Container $app) {
return new EmojiParser($app->make(RepositoryInterface::class));
});
} | php | {
"resource": ""
} |
q244792 | EmojiParser.parse | validation | public function parse(InlineParserContext $inlineContext)
{
$cursor = $inlineContext->getCursor();
$previous = $cursor->peek(-1);
if ($previous !== null && $previous !== ' ') {
return false;
}
$saved = $cursor->saveState();
$cursor->advance();
$handle = $cursor->match('/^[a-z0-9\+\-_]+:/');
if (!$handle) {
$cursor->restoreState($saved);
return false;
}
$next = $cursor->peek(0);
if ($next !== null && $next !== ' ') {
$cursor->restoreState($saved);
return false;
}
$key = substr($handle, 0, -1);
if ($this->map === null) {
$this->map = $this->repo->get();
}
if (!array_key_exists($key, $this->map)) {
$cursor->restoreState($saved);
return false;
}
$inline = new Image($this->map[$key], $key);
$inline->data['attributes'] = ['class' => 'emoji', 'data-emoji' => $key];
$inlineContext->getContainer()->appendChild($inline);
return true;
} | php | {
"resource": ""
} |
q244793 | Attribute.boot | validation | protected static function boot()
{
parent::boot();
if (!isset(static::$attributeMutator)) {
if (function_exists('app') && app()->bound('eloquence.mutator')) {
static::$attributeMutator = app('eloquence.mutator');
} else {
static::$attributeMutator = new Mutator;
}
}
} | php | {
"resource": ""
} |
q244794 | Attribute.set | validation | protected function set($key, $value, $group = 'default')
{
$this->setMetaKey($key);
$this->setValue($value);
$this->setMetaGroup($group);
} | php | {
"resource": ""
} |
q244795 | Attribute.getValue | validation | public function getValue()
{
if ($this->hasMutator($this->attributes['meta_value'], 'getter', $this->attributes['meta_type'])) {
return $this->mutateValue($this->attributes['meta_value'], 'getter');
}
return $this->castValue();
} | php | {
"resource": ""
} |
q244796 | Attribute.castValue | validation | protected function castValue()
{
$value = $this->attributes['meta_value'];
$validTypes = ['boolean', 'integer', 'float', 'double', 'array', 'object', 'null'];
if (in_array($this->attributes['meta_type'], $validTypes)) {
settype($value, $this->attributes['meta_type']);
}
return $value;
} | php | {
"resource": ""
} |
q244797 | Attribute.setMetaGroup | validation | public function setMetaGroup($group = null)
{
if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $group) && $group !== null) {
throw new InvalidArgumentException("Provided group [{$group}] is not valid variable name.");
}
$this->attributes['meta_group'] = $group;
} | php | {
"resource": ""
} |
q244798 | Attribute.setType | validation | protected function setType($value)
{
$this->attributes['meta_type'] = $this->hasMutator($value, 'setter')
? $this->getMutatedType($value, 'setter')
: $this->getValueType($value);
} | php | {
"resource": ""
} |
q244799 | Attribute.setValue | validation | public function setValue($value)
{
$this->setType($value);
if ($this->hasMutator($value, 'setter')) {
$value = $this->mutateValue($value, 'setter');
} elseif (!$this->isStringable($value) && !is_null($value)) {
throw new InvalidTypeException(
"Unsupported meta value type [{$this->getValueType($value)}]."
);
}
$this->attributes['meta_value'] = $value;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.