_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q260900 | ActivateCommand.validateProvidedTheme | test | protected function validateProvidedTheme(string $group, $id, $theme): bool
{
if (! \in_array($group, $this->type)) {
throw new InvalidArgumentException("Invalid theme name [{$group}], should either be 'frontend' or 'backend'.");
}
if (\is_null($theme)) {
throw new InvalidArgumentException("Invalid Theme ID [{$id}], or is not available for '{$group}'.");
}
return true;
} | php | {
"resource": ""
} |
q260901 | ActivateCommand.getAvailableTheme | test | protected function getAvailableTheme(string $type): Collection
{
$themes = $this->finder->detect();
return $themes->filter(function (Manifest $manifest) use ($type) {
$group = $manifest->get('type');
if (! empty($group) && ! \in_array($type, $group)) {
return;
}
return $manifest;
});
} | php | {
"resource": ""
} |
q260902 | Decorator.render | test | public function render(string $name, ...$parameters)
{
if (! isset($this->macros[$name])) {
throw new BadMethodCallException("Method [$name] does not exist.");
}
return $this->macros[$name](...$parameters);
} | php | {
"resource": ""
} |
q260903 | DateToDateTime.filter | test | public function filter($value)
{
/**
* We try to create a \DateTime according to the format
* If the creation fails, we return the string itself
* so it's treated by Validate\Date
*/
$date = (is_int($value))
? date_create("@$value") // from timestamp
: DateTime::createFromFormat($this->format, $value);
// Invalid dates can show up as warnings (ie. "2007-02-99")
// and still return a DateTime object
$errors = DateTime::getLastErrors();
if ($errors['warning_count'] > 0 || $date === false) {
return $value;
}
return $date;
} | php | {
"resource": ""
} |
q260904 | StatusChecker.verifyStatus | test | protected function verifyStatus(): void
{
$config = $this->config->get('orchestra/extension::mode', 'normal');
$input = $this->request->input('_mode', $config);
if ($input == 'safe') {
$this->enableSafeMode();
} else {
$this->disableSafeMode();
}
} | php | {
"resource": ""
} |
q260905 | Finder.addPath | test | public function addPath(string $path)
{
$path = \rtrim($path, '/');
if (! \in_array($path, $this->paths)) {
$this->paths[] = $path;
}
return $this;
} | php | {
"resource": ""
} |
q260906 | Finder.detect | test | public function detect()
{
$extensions = [];
$packages = $this->getComposerLockData();
// Loop each path to check if there orchestra.json available within
// the paths. We would only treat packages that include orchestra.json
// as an Orchestra Platform extension.
foreach ($this->paths as $key => $path) {
$manifests = $this->files->glob($this->resolveExtensionPath("{$path}/orchestra.json"));
// glob() method might return false if there an errors, convert
// the result to an array.
\is_array($manifests) || $manifests = [];
foreach ($manifests as $manifest) {
$name = \is_numeric($key)
? $this->guessExtensionNameFromManifest($manifest, $path)
: $key;
if (! \is_null($name)) {
$lockContent = $packages->firstWhere('name', $name);
$extensions[$name] = $this->getManifestContents($manifest, $lockContent);
}
}
}
return new Collection($extensions);
} | php | {
"resource": ""
} |
q260907 | Finder.getManifestContents | test | protected function getManifestContents(string $manifest, ?array $lockContent): array
{
$path = $sourcePath = $this->guessExtensionPath($manifest);
$jsonable = \json_decode($this->files->get($manifest), true);
// If json_decode fail, due to invalid json format. We going to
// throw an exception so this error can be fixed by the developer
// instead of allowing the application to run with a buggy config.
if (\is_null($jsonable)) {
throw new ManifestRuntimeException("Cannot decode file [{$manifest}]");
}
if (\is_array($lockContent)) {
foreach (['description', 'version'] as $type) {
$jsonable[$type] = $lockContent[$type] ?? $jsonable[$type] ?? null;
}
}
$path = $jsonable['path'] ?? $path;
$paths = [
'path' => \rtrim($path, '/'),
'source-path' => \rtrim($sourcePath, '/'),
];
// Generate a proper manifest configuration for the extension. This
// would allow other part of the application to use this configuration
// to migrate, load service provider as well as preload some
// configuration.
return \array_merge($paths, $this->generateManifestConfig($jsonable));
} | php | {
"resource": ""
} |
q260908 | Finder.generateManifestConfig | test | protected function generateManifestConfig(array $config): array
{
// Assign extension manifest option or provide the default value.
return Collection::make($this->manifestOptions)->mapWithKeys(function ($default, $key) use ($config) {
return [$key => ($config[$key] ?? $default)];
})->all();
} | php | {
"resource": ""
} |
q260909 | Finder.getComposerLockData | test | protected function getComposerLockData(): Collection
{
$json = [];
if ($this->files->exists($this->config['path.composer'])) {
$json = \json_decode($this->files->get($this->config['path.composer']), true);
}
return Collection::make($json['packages'] ?? []);
} | php | {
"resource": ""
} |
q260910 | Finder.guessExtensionNameFromManifest | test | public function guessExtensionNameFromManifest(string $manifest, string $path): ?string
{
if (\rtrim($this->config['path.app'], '/') === \rtrim($path, '/')) {
return 'app';
}
list($vendor, $package) = $namespace = $this->resolveExtensionNamespace($manifest);
if (\is_null($vendor) && \is_null($package)) {
return null;
}
// Each package should have vendor/package name pattern.
$name = \trim(\implode('/', $namespace));
return $this->validateExtensionName($name);
} | php | {
"resource": ""
} |
q260911 | Finder.guessExtensionPath | test | public function guessExtensionPath(string $path): string
{
$path = \str_replace('orchestra.json', '', $path);
$app = \rtrim($this->config['path.app'], '/');
$base = \rtrim($this->config['path.base'], '/');
return \str_replace(
["{$app}/", "{$base}/vendor/", "{$base}/"],
['app::', 'vendor::', 'base::'],
$path
);
} | php | {
"resource": ""
} |
q260912 | Finder.resolveExtensionNamespace | test | public function resolveExtensionNamespace(string $manifest): array
{
$vendor = null;
$package = null;
$manifest = \str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $manifest);
$fragment = \explode(DIRECTORY_SEPARATOR, $manifest);
// Remove orchestra.json from fragment as we are only interested with
// the two segment before it.
if (\array_pop($fragment) == 'orchestra.json') {
$package = \array_pop($fragment);
$vendor = \array_pop($fragment);
}
return [$vendor, $package];
} | php | {
"resource": ""
} |
q260913 | Finder.validateExtensionName | test | public function validateExtensionName(string $name): string
{
if (\in_array($name, $this->reserved)) {
throw new RuntimeException("Unable to register reserved name [{$name}] as extension.");
}
return $name;
} | php | {
"resource": ""
} |
q260914 | ViewServiceProvider.registerViewFinder | test | public function registerViewFinder()
{
$this->app->bind('view.finder', function (Application $app) {
$paths = $app->make('config')->get('view.paths', []);
return new FileViewFinder($app->make('files'), $paths);
});
} | php | {
"resource": ""
} |
q260915 | ViewServiceProvider.registerTheme | test | protected function registerTheme(): void
{
$this->app->singleton('orchestra.theme', function (Application $app) {
return new ThemeManager($app);
});
$this->app->singleton('orchestra.theme.finder', function (Application $app) {
return new Finder($app->make('files'), $app->publicPath());
});
} | php | {
"resource": ""
} |
q260916 | Finder.detect | test | public function detect(): Collection
{
$path = \rtrim($this->publicPath, '/').'/themes/';
return Collection::make($this->files->directories($path))->mapWithKeys(function ($folder) {
return [
$this->parseThemeNameFromPath($folder) => new Manifest($this->files, \rtrim($folder, '/').'/'),
];
});
} | php | {
"resource": ""
} |
q260917 | LoadCurrentTheme.setCurrentTheme | test | protected function setCurrentTheme(Application $app, Theme $theme): void
{
$memory = $app->make('orchestra.memory')->makeOrFallback();
$events = $app->make('events');
// By default, we should consider all request to use "frontend"
// theme and only convert to use "backend" routing when certain
// event is fired.
$theme->setTheme($memory->get('site.theme.frontend'));
$events->listen('orchestra.started: admin', function () use ($theme, $memory) {
$theme->setTheme($memory->get('site.theme.backend'));
});
$events->listen('composing: *', function () use ($theme) {
$theme->boot();
});
} | php | {
"resource": ""
} |
q260918 | LoadCurrentTheme.setThemeResolver | test | protected function setThemeResolver(Application $app, Theme $theme): void
{
// The theme is only booted when the first view is being composed.
// This would prevent multiple theme being booted in the same
// request.
if ($app->resolved('view')) {
$theme->resolving();
} else {
$app->resolving('view', function () use ($theme) {
$theme->resolving();
});
}
} | php | {
"resource": ""
} |
q260919 | ExtensionServiceProvider.registerExtension | test | protected function registerExtension(): void
{
$this->app->singleton('orchestra.extension', function (Application $app) {
$config = $app->make('config');
$events = $app->make('events');
$files = $app->make('files');
$finder = $app->make('orchestra.extension.finder');
$status = $app->make('orchestra.extension.status');
$provider = $app->make('orchestra.extension.provider');
return new Factory(
$app, new Dispatcher($app, $config, $events, $files, $finder, $provider), $status
);
});
} | php | {
"resource": ""
} |
q260920 | ExtensionServiceProvider.registerExtensionConfigManager | test | protected function registerExtensionConfigManager(): void
{
$this->app->singleton('orchestra.extension.config', function (Application $app) {
return new Config\Repository($app->make('config'), $app->make('orchestra.memory'));
});
} | php | {
"resource": ""
} |
q260921 | ExtensionServiceProvider.registerExtensionFinder | test | protected function registerExtensionFinder(): void
{
$this->app->singleton('orchestra.extension.finder', function (Application $app) {
$config = [
'path.app' => $app->path(),
'path.base' => $app->basePath(),
'path.composer' => $app->basePath('/composer.lock'),
];
return new Finder($app->make('files'), $config);
});
} | php | {
"resource": ""
} |
q260922 | ExtensionServiceProvider.registerExtensionStatusChecker | test | protected function registerExtensionStatusChecker(): void
{
$this->app->singleton('orchestra.extension.status', function (Application $app) {
return new StatusChecker($app->make('config'), $app->make('request'));
});
} | php | {
"resource": ""
} |
q260923 | Processor.execute | test | protected function execute($listener, $type, Fluent $extension, Closure $callback)
{
$name = $extension->get('name');
try {
// Check if folder is writable via the web instance, this would
// avoid issue running Orchestra Platform with debug as true where
// creating/copying the directory would throw an ErrorException.
if (! $this->factory->permission($name)) {
throw new FilePermissionException("[{$name}] is not writable.");
}
$callback($this->factory, $name);
} catch (FilePermissionException $e) {
return $listener->{"{$type}HasFailed"}($extension, ['error' => $e->getMessage()]);
}
return $listener->{"{$type}HasSucceed"}($extension);
} | php | {
"resource": ""
} |
q260924 | UrlGenerator.getScheme | test | protected function getScheme(?bool $secure): string
{
if (\is_null($secure)) {
return $this->forceSchema ?: $this->request->getScheme().'://';
}
return $secure ? 'https://' : 'http://';
} | php | {
"resource": ""
} |
q260925 | UrlGenerator.handle | test | public function handle(string $handles)
{
// If the handles doesn't start as "//some.domain.com/foo" we should
// assume that it doesn't belong to any subdomain, otherwise we
// need to split the value to "some.domain.com" and "foo".
if (\is_null($handles) || ! Str::startsWith($handles, ['//', 'http://', 'https://'])) {
$this->prefix = $handles;
} else {
$handles = \substr(\str_replace(['http://', 'https://'], '//', $handles), 2);
$fragments = \explode('/', $handles, 2);
$this->domain = \array_shift($fragments);
$this->prefix = \array_shift($fragments);
}
// It is possible that prefix would be null, in this case assume
// it handle the main path under the domain.
! \is_null($this->prefix) || $this->prefix = '/';
return $this;
} | php | {
"resource": ""
} |
q260926 | UrlGenerator.domain | test | public function domain(bool $forceBase = false): ?string
{
$pattern = $this->domain;
$baseUrl = $this->getBaseUrl();
if (\is_null($pattern) && $forceBase === true) {
$pattern = $baseUrl;
} elseif (Str::contains($pattern, '{{domain}}')) {
$pattern = \str_replace('{{domain}}', $baseUrl, $pattern);
}
return $pattern;
} | php | {
"resource": ""
} |
q260927 | UrlGenerator.group | test | public function group(bool $forceBase = false): array
{
$group = [
'prefix' => $this->prefix($forceBase),
];
if (! \is_null($domain = $this->domain($forceBase))) {
$group['domain'] = $domain;
}
return $group;
} | php | {
"resource": ""
} |
q260928 | UrlGenerator.is | test | public function is(string $pattern): bool
{
$path = $this->path();
$prefix = $this->prefix();
foreach (\func_get_args() as $pattern) {
$pattern = ($pattern === '*' ? "{$prefix}*" : "{$prefix}/{$pattern}");
$pattern = \trim($pattern, '/');
empty($pattern) && $pattern = '/';
if (Str::is($pattern, $path)) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q260929 | UrlGenerator.prefix | test | public function prefix(bool $forceBase = false): string
{
$pattern = \trim($this->prefix, '/');
if (\is_null($this->domain) && $forceBase === true) {
$pattern = \trim($this->basePrefix, '/')."/{$pattern}";
$pattern = \trim($pattern, '/');
}
empty($pattern) && $pattern = '/';
return $pattern;
} | php | {
"resource": ""
} |
q260930 | UrlGenerator.root | test | public function root(): string
{
$scheme = $this->getScheme(null);
$domain = \trim($this->domain(true), '/');
$prefix = $this->prefix(true);
return \trim("{$scheme}{$domain}/{$prefix}", '/');
} | php | {
"resource": ""
} |
q260931 | UrlGenerator.getBaseUrl | test | public function getBaseUrl(): string
{
if (\is_null($this->baseUrl)) {
$this->resolveBaseUrlFrom($this->request->root());
}
return $this->baseUrl;
} | php | {
"resource": ""
} |
q260932 | UrlGenerator.resolveBaseUrlFrom | test | protected function resolveBaseUrlFrom(?string $root): void
{
// Build base URL and prefix.
$baseUrl = \ltrim(\str_replace(['https://', 'http://'], '', $root), '/');
$base = \explode('/', $baseUrl, 2);
if (\count($base) > 1) {
$this->basePrefix = \array_pop($base);
}
$this->baseUrl = \array_shift($base);
} | php | {
"resource": ""
} |
q260933 | YamlUtils.safeParse | test | public static function safeParse($input, $validateDuplicateKeys = true)
{
if (method_exists('Symfony\Component\Yaml\Yaml', 'setPhpParsing')) {
Yaml::setPhpParsing(false);
}
if ($validateDuplicateKeys) {
self::validateDuplicatedKey($input);
}
return (new Parser())->parse($input, true, false);
} | php | {
"resource": ""
} |
q260934 | YamlUtils.validateDuplicatedKey | test | private static function validateDuplicatedKey($input)
{
$lines = explode("\n", $input);
$data = array();
$nbSpacesOfLastLine = 0;
foreach ($lines as $linenumber => $line) {
$trimmedLine = ltrim($line, ' ');
if ($trimmedLine === '' || $trimmedLine[0] === '#') {
continue;
}
$nbSpacesOfCurrentLine = strlen($line) - strlen($trimmedLine);
if ($nbSpacesOfCurrentLine < $nbSpacesOfLastLine) {
foreach ($data as $nbSpaces => $keys) {
if ($nbSpaces > $nbSpacesOfCurrentLine) {
unset($data[$nbSpaces]);
}
}
}
if ($trimmedLine[0] === '-' || false === $pos = strpos($trimmedLine, ':')) {
continue;
}
$key = substr($trimmedLine, 0, $pos);
if (isset($data[$nbSpacesOfCurrentLine][$key])) {
throw new ParseException(sprintf('Duplicate key "%s" detected on line %s whilst parsing YAML.', $key, $linenumber));
}
$data[$nbSpacesOfCurrentLine][$key] = array();
$nbSpacesOfLastLine = $nbSpacesOfCurrentLine;
}
} | php | {
"resource": ""
} |
q260935 | Dispatcher.activating | test | public function activating(string $name, array $options): void
{
$this->register($name, $options);
$this->fireEvent($name, $options, 'activating');
$this->provider->writeFreshManifest();
} | php | {
"resource": ""
} |
q260936 | Dispatcher.deactivating | test | public function deactivating(string $name, array $options): void
{
$this->fireEvent($name, $options, 'deactivating');
$this->provider->writeFreshManifest();
} | php | {
"resource": ""
} |
q260937 | Dispatcher.registerExtensionProviders | test | protected function registerExtensionProviders(array $options): void
{
$services = $options['provides'] ?? [];
! empty($services) && $this->provider->provides($services);
} | php | {
"resource": ""
} |
q260938 | Dispatcher.registerExtensionPlugin | test | protected function registerExtensionPlugin(array $options): void
{
$plugin = $options['plugin'] ?? null;
! \is_null($plugin) && $this->app->make($plugin)->bootstrap($this->app);
} | php | {
"resource": ""
} |
q260939 | Dispatcher.boot | test | public function boot(): void
{
foreach ($this->extensions as $name => $options) {
$this->fireEvent($name, $options, 'booted');
}
$this->provider->writeManifest();
} | php | {
"resource": ""
} |
q260940 | Dispatcher.start | test | public function start(string $name, array $options): void
{
$basePath = \rtrim($options['path'], '/');
$sourcePath = \rtrim($options['source-path'] ?? $basePath, '/');
$search = ['source-path::', 'app::/'];
$replacement = ["{$sourcePath}/", 'app::'];
// By now, extension should already exist as an extension. We should
// be able start orchestra.php start file on each package.
$this->getAutoloadFiles(Collection::make($options['autoload'] ?? []))
->each(function ($path) use ($search, $replacement) {
$this->loadAutoloaderFile(\str_replace($search, $replacement, $path));
});
$this->fireEvent($name, $options, 'started');
} | php | {
"resource": ""
} |
q260941 | Dispatcher.fireEvent | test | protected function fireEvent(string $name, array $options, string $type = 'started'): void
{
$this->dispatcher->dispatch("extension.{$type}", [$name, $options]);
$this->dispatcher->dispatch("extension.{$type}: {$name}", [$options]);
} | php | {
"resource": ""
} |
q260942 | Dispatcher.getAutoloadFiles | test | protected function getAutoloadFiles(Collection $autoload): Collection
{
return $autoload->map(function ($path) {
return Str::contains($path, '::') ? $path : 'source-path::'.\ltrim($path, '/');
})->merge(['source-path::src/orchestra.php', 'source-path::orchestra.php']);
} | php | {
"resource": ""
} |
q260943 | Dispatcher.loadAutoloaderFile | test | protected function loadAutoloaderFile(string $filePath): void
{
$filePath = $this->finder->resolveExtensionPath($filePath);
if ($this->files->isFile($filePath)) {
$this->files->getRequire($filePath);
}
} | php | {
"resource": ""
} |
q260944 | Ongr_Sniffs_Commenting_FunctionCommentSniff.processDeprecated | test | protected function processDeprecated(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $commentStart)
{
$tokens = $phpcsFile->getTokens();
foreach ($tokens[$commentStart]['comment_tags'] as $pos => $tag) {
if ($tokens[$tag]['content'] !== '@deprecated') {
continue;
}
$content = $tokens[($tag + 2)]['content'];
if (empty($content) === true || $tokens[($tag + 2)]['code'] !== T_DOC_COMMENT_STRING) {
$error = 'Deprecated type missing for @deprecated tag in function comment';
$phpcsFile->addError($error, $tag, 'MissingDeprecatedType');
} else {
//ONGR Validate that return comment begins with capital letter and ends with full stop.
if ($content !== null) {
$firstChar = $content{0};
if (preg_match('|\p{Lu}|u', $firstChar) === 0) {
$error = 'Deprecated comment must start with a capital letter';
$fix = $phpcsFile->addFixableError($error, ($tag + 2), 'DeprecatedCommentNotCapital');
if ($fix === true) {
$newComment = ucfirst($content);
$tokenLength = strlen($tokens[($tag + 2)]['content']);
$commentLength = strlen($content);
$tokenWithoutComment
= substr($tokens[($tag + 2)]['content'], 0, $tokenLength - $commentLength);
$phpcsFile->fixer->replaceToken(($tag + 2), $tokenWithoutComment . $newComment);
}
}
$lastChar = substr($content, -1);
if ($lastChar !== '.') {
$error = 'Deprecated comment must end with a full stop';
$fix = $phpcsFile->addFixableError($error, ($tag + 2), 'DeprecatedCommentFullStop');
if ($fix === true) {
$phpcsFile->fixer->addContent(($tag + 2), '.');
}
}
}
}
}
} | php | {
"resource": ""
} |
q260945 | ErrorCatcher.start | test | public static function start(): void // TODO - not this.
{
ini_set('display_errors', 1);
ini_set('track_errors', 1);
error_reporting(self::$level);
if (TEST) {
return;
}
/**
* if you return true from here it will continue script execution from the point of the error..
* this is not wanted. Die and Exit are equivalent in execution. I ran across a post once that
* explained how die should signify a complete error with no resolution, while exit has resolution
* returning 1 rather than 0 in both cases will signify an error occurred
* @param array $argv
* @internal param TYPE_NAME $closure
*/
$closure = function (...$argv) {
static $count;
if (empty($count)) {
$count = 0;
}
$count++;
self::generateLog($argv);
if (!SOCKET && !APP_LOCAL && CarbonPHP::$setupComplete) { // TODO - do we really want to reset?
if ($count > 1) {
print 'A recursive error has occurred in (or at least affecting) your $app->defaultRoute();';
die(1);
}
startApplication(true);
exit(1);
}
/** @noinspection ForgottenDebugOutputInspection
* TODO - fix this? */
print_r($argv);
print "\n\nCarbonPHP Caught This Error.\n\n";
die(1);
};
set_error_handler($closure);
set_exception_handler($closure);
} | php | {
"resource": ""
} |
q260946 | ErrorCatcher.generateLog | test | public static function generateLog($e = null, string $level = 'log'): string
{
if (ob_get_status()) {
// Attempt to remove any previous in-progress output buffers
ob_end_clean();
}
ob_start(null, null, PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_FLUSHABLE | PHP_OUTPUT_HANDLER_REMOVABLE); // start a new buffer for saving errors
if ($e instanceof \Throwable) {
$trace = self::generateCallTrace($e);
if (!$e instanceof PublicAlert) {
print '(set_error_handler || set_exception_handler) caught this error. #Bubbled up#' . PHP_EOL;
} else {
print 'Public Alert Thrown!' . PHP_EOL;
}
print PHP_EOL . $e->getMessage() . PHP_EOL;
} else {
$trace = self::generateCallTrace();
if (\is_array($e) && \count($e) >= 4) {
print PHP_EOL . 'Carbon caught this Message: ' . $e[1] . PHP_EOL . 'line: ' . $e[2] . '(' . $e[3] . ')' . PHP_EOL;
}
}
print PHP_EOL . $trace . PHP_EOL;
$output = ob_get_contents();
ob_end_clean();
/** @noinspection ForgottenDebugOutputInspection */
error_log($output);
if (self::$printToScreen) {
print "<h1>You have the print to screen Error Catching option turned on!</h1><h2> Turn it off to suppress this reporting.</h2><pre>$output</pre>";
}
if (self::$storeReport === true || self::$storeReport === 'file') { // TODO - store to file?
if (!is_dir(REPORTS) && !mkdir($concurrentDirectory = REPORTS) && !is_dir($concurrentDirectory)) {
PublicAlert::danger('Failed Storing Log');
} else {
$file = fopen(REPORTS . '/Log_' . time() . '.log', 'ab');
if (!\is_resource($file) || !fwrite($file, $output)) {
PublicAlert::danger('Failed Storing Log');
}
fclose($file);
}
}
if (self::$storeReport === true || self::$storeReport === 'database') { // TODO - store to file?
$sql = 'INSERT INTO carbon_reports (log_level, report, call_trace) VALUES (?, ?, ?)';
$sql = Database::database()->prepare($sql);
if (!$sql->execute([$level, $output, $trace])) {
print 'Failed to store error log, nothing works... Why does nothing work?' and die(1);
}
}
return $output;
} | php | {
"resource": ""
} |
q260947 | ErrorCatcher.generateCallTrace | test | public static function generateCallTrace(\Throwable $e = null): string
{
ob_start();
if (null === $e) {
$e = new \Exception();
$trace = explode("\n", $e->getTraceAsString());
$args = array_reverse($e->getTrace());
$trace = array_reverse($trace);
array_shift($trace); // remove {main}
array_pop($args); // remove call to this method
array_pop($args); // remove call to this method
array_pop($trace); // remove call to this method
array_pop($trace); // remove call to this method
} else {
$trace = explode("\n", $e->getTraceAsString());
$args = array_reverse($e->getTrace());
$trace = array_reverse($trace);
array_shift($trace); // remove {main}
}
$length = \count($trace);
$result = array();
for ($i = 0; $i < $length; $i++) {
$result[] = ($i + 1) . ') ' . implode(' (', explode('(', substr($trace[$i], strpos($trace[$i], ' ')))) . PHP_EOL . "\t\t\t\t" . json_encode($args[$i]['args']) . PHP_EOL;
}
print "\n\t" . implode("\n\t", $result);
$output = ob_get_contents();
ob_end_clean();
return $output;
} | php | {
"resource": ""
} |
q260948 | PublicAlert.alert | test | private static function alert(string $message, string $code) {
global $json;
if ($code !== 'success' && $code !== 'info') {
$message .= ' Contact us if problem persists.';
}
$json['alert'][$code][] = $message;
} | php | {
"resource": ""
} |
q260949 | Fork.become_daemon | test | public static function become_daemon(callable $call = null) : int // do not use this unless you know what you are doing
{
if (!\extension_loaded('pcntl')) {
print 'You must have the PCNTL extencion installed. See Carbon PHP for documentation.' and die;
}
if ($pid = pcntl_fork()) { // Parent
if (\is_callable($call)) {
return 1;
}
exit;
}
if ($pid < 0) {
throw new \RuntimeException('Failed to fork');
}
\define('FORK', TRUE);
/* child becomes our daemon */
posix_setsid();
chdir('/'); // What does this do ?
umask(0); // Give access to nothing
register_shutdown_function(function () {
session_abort();
posix_kill(posix_getpid(), SIGHUP);
exit(1);
});
if (\is_callable($call)) {
$call();
exit(1);
}
return posix_getpid();
} | php | {
"resource": ""
} |
q260950 | Fork.safe | test | public static function safe(callable $closure = null) : int
{
if (!\extension_loaded('pcntl')) {
if ($closure !== null) {
$closure();
}
return 0;
}
if ($pid = pcntl_fork()) { // return child id for parent and 0 for child
return $pid; // Parent
}
if ($pid < 0) {
throw new \RuntimeException('Failed to fork');
}
\define('FORK', true);
// Database::resetConnection();
// fclose(STDIN); -- unset
register_shutdown_function(function () {
session_abort();
posix_kill(posix_getpid(), SIGHUP);
exit(1);
});
if ($closure !== null) {
$closure();
}
exit;
} | php | {
"resource": ""
} |
q260951 | Slug.getSlug | test | public function getSlug($forceRegeneration = false)
{
$owner = $this->getOwner();
$field = $this->fieldToSlug;
$unfilteredSlug = $owner->URLSlug;
if (!$unfilteredSlug || $forceRegeneration) {
$unfilteredSlug = $owner->$field;
}
return URLSegmentFilter::create()->filter($unfilteredSlug);
} | php | {
"resource": ""
} |
q260952 | Slug.onBeforeWrite | test | public function onBeforeWrite()
{
$owner = $this->getOwner();
$slugHasChanged = $owner->isChanged('URLSlug');
$fieldToSlugHasChanged = $owner->isChanged($this->fieldToSlug);
$updateSlug = (
empty($owner->URLSlug)
|| ($this->enforceParity && $fieldToSlugHasChanged)
|| (!$this->enforceParity && $slugHasChanged)
);
if ($updateSlug) {
$owner->URLSlug = $this->getSlug($this->enforceParity);
$collisionList = DataObject::get(get_class($owner))->exclude('ID', $owner->ID);
$filter = ['URLSlug' => $owner->URLSlug];
if ($this->relationName) {
$parentIDField = $this->relationName . 'ID';
$filter[$parentIDField] = $owner->$parentIDField;
// Also handle polymorphic relationships
$parentClassName = DataObject::getSchema()->hasOneComponent(get_class($owner), $this->relationName);
if ($parentClassName === DataObject::class) {
$parentClassField = $this->relationName . 'Class';
$filter[$parentClassField] = $owner->$parentClassField;
}
}
$count = 1;
while ($collisionList->filter($filter)->exists()) {
$owner->URLSlug = $owner->URLSlug . $count++;
$filter['URLSlug'] = $owner->URLSlug;
}
} elseif ($slugHasChanged) {
// enforceParity is set, and the slug has changed... but the
// field to slug has not. We need to reset to keep parity.
// Ideally we could do this via the $original property through
// {@see DataObject::getChangedFields}, however the returned
// 'before' value for a changed field is unreliable :(
// https://github.com/silverstripe/silverstripe-framework/issues/8443
throw new UnexpectedValueException(
'URLSlug has been updated independently of the tracked field, ' .
'but this has been disabled via Slug::enforceParity'
);
}
} | php | {
"resource": ""
} |
q260953 | Request.sendHeaders | test | public static function sendHeaders(): void
{
if (!(SOCKET || headers_sent())) {
if (isset($_SESSION['Cookies']) && \is_array($_SESSION['Cookies'])) {
foreach ($_SESSION['Cookies'] as $key => $array) {
if ($array[1] ?? false) {
static::setCookie($key, $array[0] ?? null, $array[1]);
} else {
static::setCookie($key, $array[0] ?? null);
}
}
}
if (isset($_SESSION['Headers']) && \is_array($_SESSION['Headers'])) {
foreach ($_SESSION['Headers'] as $value) {
static::setHeader($value);
}
}
unset($_SESSION['Cookies'], $_SESSION['Headers']);
}
} | php | {
"resource": ""
} |
q260954 | Request.setCookie | test | public static function setCookie(string $key, $value = null, int $time = 604800): void // Week?
{
if (headers_sent()) {
$_SESSION['Cookies'][] = [$key => [$value, $time]];
} else {
setcookie($key, $value, time() + $time, '/', SITE, HTTPS, true);
}
} | php | {
"resource": ""
} |
q260955 | Request.clearCookies | test | public function clearCookies(): void
{
$all = array_keys(\is_array($_COOKIE) ? $_COOKIE : []);
foreach ($all as $key => $value) {
static::setCookie($value);
}
} | php | {
"resource": ""
} |
q260956 | Request.request | test | private function request(array $argv, array &$array, bool $removeHTML = false): self
{
$this->storage = null;
$closure = function ($key) use ($removeHTML, &$array) {
if (array_key_exists($key, $array)) {
$this->storage[] = $removeHTML ? htmlspecialchars($array[$key]) : $array[$key];
$array[$key] = null; // by reference, if we validate it then we should ensure no one uses it
} else {
$this->storage[] = false;
}
};
if (\count($argv) === 0 || !array_walk($argv, $closure)) {
$this->storage = [];
}
return $this;
} | php | {
"resource": ""
} |
q260957 | Request.storeFiles | test | public function storeFiles(string $location = 'Data/Uploads/Temp/')
{
$storagePath = array();
return $this->closure_array_walk(function ($file) use ($location, &$storagePath) {
$storagePath[] = Files::uploadFile($file, $location);
})($storagePath);
} | php | {
"resource": ""
} |
q260958 | Request.except | test | public function except(...$argv): self
{
array_walk($argv, function ($key) {
if (array_key_exists($key, $this->storage)) {
unset($this->storage[$key]);
}
});
return $this;
} | php | {
"resource": ""
} |
q260959 | Request.regex | test | public function regex(string $condition)
{
$array = [];
return $this->closure_array_walk(function ($key) use ($condition, &$array) {
return $array[] = (preg_match($condition, $key) ? $key : false);
})($array);
} | php | {
"resource": ""
} |
q260960 | Request.noHTML | test | public function noHTML($complete = false)
{ // Disallow: $, ", ', <, >
$array = [];
$fn = $this->closure_array_walk(function ($key) use (&$array) {
return $array[] = htmlspecialchars($key);
});
if ($complete) {
return $fn($array);
}
return $this;
} | php | {
"resource": ""
} |
q260961 | Request.int | test | public function int(int $min = null, int $max = null) // inclusive max and min
{
$array = [];
return $this->closure_array_walk(function ($key) use (&$array, $min, $max) {
if (($key = (int)$key) === false) {
return $array[] = false;
}
if ($max !== null) {
$key = ($key <= $max ? $key : false);
}
if ($min !== null) {
$key = ($key >= $min ? $key : false);
}
return $array[] = $key;
})($array);
} | php | {
"resource": ""
} |
q260962 | LessCompiler.flush | test | public static function flush()
{
if (!self::$already_flushed && file_exists(self::getCacheDir())) {
$paths = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator(self::getCacheDir(), FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($paths as $path) {
$path->isDir() && !$path->isLink() ? rmdir($path->getPathname()) : unlink($path->getPathname());
}
// make sure we only flush once per request and not for each *.less
self::$already_flushed = true;
}
} | php | {
"resource": ""
} |
q260963 | LessCompiler.combineFiles | test | public function combineFiles($combinedFileName, $files, $options = array())
{
$new_files = [];
foreach ($files as $file) {
$new_files[] = $this->processLessFile($file);
}
return parent::combineFiles($combinedFileName, $new_files, $options);
} | php | {
"resource": ""
} |
q260964 | SshDeployer.connect | test | protected function connect(ServerInterface $server)
{
if (false === function_exists('ssh2_connect')) {
throw new \RuntimeException('The "ssh2_connect" function does not exist.');
}
$con = ssh2_connect($server->getHost(), $server->getPort());
if (false === $con) {
throw new SshException(sprintf('Cannot connect to server "%s"', $server->getHost()));
}
if (false === ssh2_auth_password($con, $server->getUser(), $server->getPassword())) {
throw new SshException(sprintf('Authorization failed for user "%s"', $server->getUser()));
}
$this->con = $con;
} | php | {
"resource": ""
} |
q260965 | SshDeployer.exec | test | protected function exec($cmd)
{
if (false === $stream = ssh2_exec($this->con, $cmd)) {
throw new SshException(sprintf('"%s" : SSH command failed', $cmd));
}
stream_set_blocking($stream, true);
$data = '';
while ($buf = fread($stream, 4096)) {
$data .= $buf;
}
fclose($stream);
return $data;
} | php | {
"resource": ""
} |
q260966 | CarbonPHP.isClientServer | test | private function isClientServer()
{
if (PHP_SAPI === 'cli-server' || PHP_SAPI === 'cli' || \in_array($_SERVER['REMOTE_ADDR'] ?? [], ['127.0.0.1', 'fe80::1', '::1'], false)) {
if (SOCKET && $ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
\define('IP', $ip);
return false;
}
\define('IP', '127.0.0.1');
return IP;
}
return false;
} | php | {
"resource": ""
} |
q260967 | CarbonPHP.IP_FILTER | test | private function IP_FILTER()
{
$ip_keys = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR');
foreach ($ip_keys as $key) {
if (array_key_exists($key, $_SERVER) === true) {
foreach (explode(',', $_SERVER[$key]) as $ip) {
// trim for safety measures
$ip = trim($ip);
if ($ip = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
\define('IP', $ip);
return IP;
}
}
}
} // TODO - log invalid ip addresses
print 'Could not establish an IP address.';
die(1);
} | php | {
"resource": ""
} |
q260968 | Pipe.named | test | public static function named(string $fifoPath) // Arbitrary)
{
if (file_exists($fifoPath)) {
unlink($fifoPath); // We are always the master, hopefully we'll catch the kill this time
}
umask(0000);
if (!posix_mkfifo($fifoPath, 0666)) {
print 'Failed to create named Pipe' . PHP_EOL;
return false;
} # create a named pipe 0644
#$user = get_current_user(); // get current process user
#exec("chown -R {$user} $fifoPath"); // We need to modify the permissions so users can write to it
$fifoFile = fopen($fifoPath, 'rb+'); // Now we open the named pipe we Already created
stream_set_blocking($fifoFile, false); // setting to true (resource heavy) activates the handshake feature, aka timeout
return $fifoFile; // File descriptor
} | php | {
"resource": ""
} |
q260969 | Plum.registerDeployer | test | public function registerDeployer(DeployerInterface $deployer)
{
if (null !== $deployer) {
$this->deployers[$deployer->getName()] = $deployer;
}
return $this;
} | php | {
"resource": ""
} |
q260970 | Plum.getDeployer | test | public function getDeployer($deployer)
{
if (false === isset($this->deployers[$deployer])) {
throw new \InvalidArgumentException(sprintf('The deployer "%s" is not registered.', $deployer));
}
return $this->deployers[$deployer];
} | php | {
"resource": ""
} |
q260971 | Plum.addServer | test | public function addServer($name, ServerInterface $server)
{
if (null === $server) {
throw new \InvalidArgumentException('The server can not be null.');
}
if (true === isset($this->servers[$name])) {
throw new \InvalidArgumentException(sprintf('The server "%s" is already registered.', $name));
}
$this->servers[$name] = $server;
return $this;
} | php | {
"resource": ""
} |
q260972 | Plum.setServers | test | public function setServers(array $servers)
{
foreach ($servers as $name => $server) {
$this->addServer($name, $server);
}
return $this;
} | php | {
"resource": ""
} |
q260973 | Plum.getServer | test | public function getServer($server)
{
if (!isset($this->servers[$server])) {
throw new \InvalidArgumentException(sprintf('The server "%s" is not registered.', $server));
}
return $this->servers[$server];
} | php | {
"resource": ""
} |
q260974 | Plum.deploy | test | public function deploy($server, $deployer)
{
$server = $this->getServer($server);
$deployer = $this->getDeployer($deployer);
return $deployer->deploy($server, $this->options);
} | php | {
"resource": ""
} |
q260975 | Plum.getOptions | test | public function getOptions($server = null)
{
if (null === $server) {
return $this->options;
}
$server = $this->getServer($server);
return array_merge($this->options, $server->getOptions());
} | php | {
"resource": ""
} |
q260976 | Ongr_Sniffs_Classes_ClassDeclarationSniff.processOpen | test | public function processOpen(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
parent::processOpen($phpcsFile, $stackPtr);
$tokens = $phpcsFile->getTokens();
if ($tokens[($stackPtr - 1)]['code'] === T_WHITESPACE) {
$prevContent = $tokens[($stackPtr - 1)]['content'];
if ($prevContent !== $phpcsFile->eolChar) {
$blankSpace = substr($prevContent, strpos($prevContent, $phpcsFile->eolChar));
$spaces = strlen($blankSpace);
if ($tokens[($stackPtr - 2)]['code'] !== T_ABSTRACT
&& $tokens[($stackPtr - 2)]['code'] !== T_FINAL
) {
if ($spaces !== 0) {
$type = strtolower($tokens[$stackPtr]['content']);
$error = 'Expected 0 spaces before %s keyword; %s found';
$data = array(
$type,
$spaces,
);
$fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceBeforeKeyword', $data);
if ($fix === true) {
$phpcsFile->fixer->replaceToken(($stackPtr - 1), '');
}
}
}
}//end if
}//end if
//ONGR we do not allow blank line after an opening brace.
$curlyBrace = $tokens[$stackPtr]['scope_opener'];
$i = 1;
while ($tokens[($curlyBrace + $i)]['code'] === T_WHITESPACE && $i < count($tokens)) {
$i++;
}
$blankLineCount = ($tokens[($curlyBrace + $i)]['line'] - $tokens[$curlyBrace]['line']) - 1;
if ($blankLineCount > 0) {
$data = [$blankLineCount];
$error = 'Expected no blank lines after an opening brace, %s found';
$phpcsFile->addError($error, $curlyBrace, 'OpenBraceBlankLines', $data);
}
} | php | {
"resource": ""
} |
q260977 | Ajaxer.ajax_slug | test | protected function ajax_slug( $action ) {
$slug = $action;
if ( ! empty( $this->action_prefix ) ) {
$slug = $this->action_prefix . '_' . $slug;
}
if ( ! empty( $this->action_surfix ) ) {
$slug .= '_' . $this->action_surfix;
}
return $slug;
} | php | {
"resource": ""
} |
q260978 | Ajaxer.ajax_request_single | test | public function ajax_request_single() {
$action = false;
$action_key = ( true === $this->is_single ) ? $this->action : $this->is_single;
if ( isset( $_REQUEST[ $action_key . '-action' ] ) && ! empty( $_REQUEST[ $action_key . '-action' ] ) ) {
$action = $_REQUEST[ $action_key . '-action' ];
} elseif ( isset( $_REQUEST[ $action_key ] ) && ! empty( $_REQUEST[ $action_key ] ) ) {
$action = $_REQUEST[ $action_key ];
}
$_action = $this->extract_action_slug( $action );
if ( false !== $action && isset( $this->actions[ $_action ] ) ) {
if ( false === \is_user_logged_in() && true === $this->actions[ $_action ] ) {
$this->trigger_ajax_callback( $action );
} elseif ( \is_user_logged_in() === true ) {
$this->trigger_ajax_callback( $action );
}
}
\wp_die( 0 );
} | php | {
"resource": ""
} |
q260979 | Ajaxer.trigger_ajax_callback | test | protected function trigger_ajax_callback( $action ) {
$_function_action = $this->extract_action_slug( $action );
if ( method_exists( $this, $this->function_name( $_function_action ) ) ) {
$function = $this->function_name( $_function_action );
\do_action( 'ajax_before_' . $action );
$this->$function();
\do_action( 'ajax_after_' . $action );
} else {
\do_action( 'ajax_' . $action );
}
} | php | {
"resource": ""
} |
q260980 | Ajaxer.ajax_request | test | public function ajax_request() {
$action = ( isset( $_REQUEST['action'] ) && ! empty( $_REQUEST['action'] ) ) ? $_REQUEST['action'] : false;
$_action = $this->extract_action_slug( $action );
if ( false !== $action && isset( $this->actions[ $_action ] ) ) {
if ( is_array( $this->actions[ $_action ] ) && isset( $this->actions[ $_action ]['callback'] ) ) {
call_user_func( $this->actions[ $_action ]['callback'] );
\wp_die();
} else {
$this->trigger_ajax_callback( $_action );
}
}
\wp_die( 0 );
} | php | {
"resource": ""
} |
q260981 | Ajaxer.get_post_request | test | private function get_post_request( $key, $default, $type ) {
$return = $default;
if ( false !== $this->has( $key, $type ) ) {
switch ( $type ) {
case 'GET':
case 'get':
$return = $_GET[ $key ];
break;
case 'POST':
case 'post':
$return = $_POST[ $key ];
break;
case 'REQUEST':
case 'request':
$return = $_REQUEST[ $key ];
break;
default:
$return = $default;
break;
}
}
return $return;
} | php | {
"resource": ""
} |
q260982 | Bcrypt.genRandomHex | test | public static function genRandomHex($bitLength = 40)
{
$sudoRandom = 1;
for ($i=0;$i<=$bitLength;$i++) $sudoRandom = ($sudoRandom<<1)|rand(0,1);
return dechex($sudoRandom);
} | php | {
"resource": ""
} |
q260983 | Serialized.start | test | public static function start(...$argv) : void
{
//TODO - make base64 optional
self::$sessionVar = $argv;
foreach (self::$sessionVar as $value){
if (isset($_SESSION[__CLASS__][$value])) {
$GLOBALS[$value] = $_SESSION[__CLASS__][$value];
#self::is_serialized( base64_decode( $_SESSION[__CLASS__][$value] ), $GLOBALS[$value] );
}
}
// You CAN register multiple shutdown functions
register_shutdown_function( function () use ($argv) {
$last_error = error_get_last();
if ($last_error['type'] === E_ERROR) {
sortDump($last_error);
} else {
foreach ($argv as $value) {
if (isset($GLOBALS[$value])) {
$_SESSION[__CLASS__][$value] = $GLOBALS[$value];
#$_SESSION[__CLASS__][$value] = base64_encode( serialize( $GLOBALS[$value] ) );
}
}
}
} );
} | php | {
"resource": ""
} |
q260984 | Serialized.clear | test | public static function clear() : void
{
if (!empty(self::$sessionVar)) {
foreach (self::$sessionVar as $value) {
$GLOBALS[$value] = $_SESSION[$value] = null;
}
}
} | php | {
"resource": ""
} |
q260985 | Serialized.is_serialized | test | public static function is_serialized($value, &$result = null) : bool
{
// Bit of a give away this one
if (!\is_string( $value )) {
return false;
}
// Serialized false, return true. unserialize() returns false on an
// invalid string or it could return false if the string is serialized
// false, eliminate that possibility.
if ($value === 'b:0;') {
$result = false;
return true;
}
$length = \strlen( $value );
$end = '';
switch ($value[0]) {
case 's':
if ($value[$length - 2] !== '"') {
return false;
}
case 'b':
case 'i':
case 'd':
// This looks odd but it is quicker than isset()ing
$end .= ';';
case 'a':
case 'O':
$end .= '}';
if ($value[1] !== ':') {
return false;
}
switch ($value[2]) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
break;
default:
return false;
}
case 'N':
$end .= ';';
if ($value[$length - 1] !== $end[0]) {
return false;
}
break;
default:
return false;
}
if (($result = @unserialize( $value, true )) === false) {
$result = null;
return false;
}
return true;
} | php | {
"resource": ""
} |
q260986 | SlugHandler.handleSlug | test | public function handleSlug(HTTPRequest $request)
{
$item = $this->findSlug();
if (!$item) {
$owner = $this->getOwner();
$owner->httpError(404);
}
$item->setSlugActive(Slug::ACTIVE_CURRENT);
return ['ActiveSlug' => $item];
} | php | {
"resource": ""
} |
q260987 | Singleton.addMethod | test | private function addMethod(string $name, callable $closure): void
{
$this->methods[$name] = \Closure::bind($closure, $this, static::class);
} | php | {
"resource": ""
} |
q260988 | Session.update | test | public static function update($clear = false)
{
global $user;
static $count = 0;
$count++;
if ($clear || !($_SESSION['id'] ?? false)) {
Serialized::clear();
}
if (!\is_array($user)) {
$user = array();
}
if (static::$user_id = $_SESSION['id'] = $_SESSION['id'] ?? false) {
$_SESSION['X_PJAX_Version'] = 'v' . SITE_VERSION . 'u' . $_SESSION['id'];
} // force reload occurs when X_PJAX_Version changes between requests
if (!isset($_SESSION['X_PJAX_Version'])) {
$_SESSION['X_PJAX_Version'] = SITE_VERSION; // static::$user_id, keep this static
}
Request::setHeader('X-PJAX-Version: ' . $_SESSION['X_PJAX_Version']);
/* If the session variable changes from the constant we will
* send the full html page and notify the pjax js to reload
* everything
* */
if (\is_callable(self::$callback)) {
/** @noinspection OnlyWritesOnParameterInspection */
($lambda = self::$callback)($clear); // you must have callable in a variable in fn scope
}
if (!\defined('X_PJAX_VERSION')) {
\define('X_PJAX_VERSION', $_SESSION['X_PJAX_Version']);
}
Request::sendHeaders(); // Send any stored headers
} | php | {
"resource": ""
} |
q260989 | Session.clear | test | public static function clear()
{
try {
$id = session_id();
$_SESSION = array();
session_write_close();
# $db = Database::database();
# $db->prepare('DELETE FROM sessions WHERE session_id = ?')->execute([$id]);
sessions::Delete($_SESSION,$id,[]);
session_start();
} catch (\PDOException $e) {
sortDump($e);
}
} | php | {
"resource": ""
} |
q260990 | Session.verifySocket | test | private function verifySocket($ip)
{
if ($ip) {
$_SERVER['REMOTE_ADDR'] = $ip;
}
preg_match ('#PHPSESSID=([^;\s]+)#', $_SERVER['HTTP_COOKIE'] ?? false, $array, PREG_OFFSET_CAPTURE);
$session_id = $array[1][0] ?? false;
if (!$session_id) {
print 'Failed to capture PHPSESSID' . PHP_EOL;
die(1);
}
$db = Database::database();
$sql = 'SELECT count(*) FROM sessions WHERE user_ip = ? AND session_id = ? LIMIT 1';
$stmt = $db->prepare($sql);
$stmt->execute([$_SERVER['REMOTE_ADDR'], $session_id]);
$session = $stmt->fetchColumn();
self::$session_id = $session_id;
if (!$session) {
if (SOCKET) {
print 'BAD ADDRESS :: ' . $_SERVER['REMOTE_ADDR'] . "\n\n";
}
die(0);
}
session_id($session_id);
} | php | {
"resource": ""
} |
q260991 | Session.open | test | public function open($savePath, $sessionName)
{
try {
Database::database()->prepare('SELECT count(*) FROM sessions LIMIT 1')->execute();
} catch (\PDOException $e) {
if ($e->getCode()) {
print "<h1>Setting up database {$e->getCode()}</h1>";
Database::setUp();
exit(1);
}
}
return true;
} | php | {
"resource": ""
} |
q260992 | Session.gc | test | public function gc($maxLife)
{
$db = Database::database();
return $db->prepare('DELETE FROM sessions WHERE (UNIX_TIMESTAMP(session_expires) + ? ) < UNIX_TIMESTAMP(?)')->execute([$maxLife, date('Y-m-d H:i:s')]) ?
true : false;
} | php | {
"resource": ""
} |
q260993 | RoutingResolver.matchRule | test | private function matchRule($route, RoutingRuleAbstract &$rule) {
list($regex, $inputs) = $this->getRegexProperties($rule);
$matches = array();
preg_match($regex, $route, $matches);
if (count($matches) > 0) {
//Substract the first element of the array, which is the complete URL
array_splice($matches, 0, 1);
for ($i = 0; $i < count($inputs); $i++) {
$key = $inputs[$i];
$value = $matches[$i];
$rule->getInput()->setInput($key, $value);
}
return true;
}
return false;
} | php | {
"resource": ""
} |
q260994 | Page.getDataPage | test | public function getDataPage()
{
return array(
'title' => $this->getTitle(),
'slug' => $this->getSlug(),
'language' => $this->getLanguage(),
'menu_title' => $this->getMenuTitle(),
'is_in_navigation' => $this->getIsInNavigation(),
'forced_url' => $this->getForcedUrl(),
'left' => $this->getLeft(),
'right' => $this->getRight(),
'root' => $this->getRoot(),
'level' => $this->getLevel(),
'hasChildren' => $this->getHasChildren()
);
} | php | {
"resource": ""
} |
q260995 | Page.isPage | test | public function isPage(Page $page = null)
{
return null !== $page && $this->getId() === $page->getId();
} | php | {
"resource": ""
} |
q260996 | MetadataFactory.loadClassMetadata | test | public function loadClassMetadata(string $className)
{
$metadata = new ClassMetadata();
$reflection = new \ReflectionClass($className);
$this->processClassAnnotations($reflection, $metadata);
$this->processPropertyAnnotations($reflection, $metadata);
return $metadata;
} | php | {
"resource": ""
} |
q260997 | CreatePropertyConditionListener.createCondition | test | public function createCondition(CreatePropertyConditionEvent $event)
{
$meta = $event->getData();
if ('conditionpropertyvalueis' !== $meta['type']) {
return;
}
$metaModel = $event->getMetaModel();
$attribute = $metaModel->getAttributeById($meta['attr_id']);
if (!($attribute instanceof TranslatedCheckbox)) {
return;
}
if ((bool) $meta['value']) {
$event->setInstance(new PropertyTrueCondition($attribute->getColName()));
return;
}
$event->setInstance(new PropertyFalseCondition($attribute->getColName()));
} | php | {
"resource": ""
} |
q260998 | PluginManager.initPluginInstalled | test | public function initPluginInstalled() {
try {
foreach ($this->pluginPaths as $path) {
//Get the installed plugins
$newPluginInstalled = $this->pluginLocator->getInstalledPlugins($this->autoloader->getURLBase().$path);
$listOfPluginsInstalled = $this->createPluginInstances($newPluginInstalled, true);
foreach ($listOfPluginsInstalled as $newPlugin) {
$this->pluginList[] = $newPlugin['plugin'];
}
}
return $this->pluginList;
} catch (Exception $e) {
throw new PluginException('Plugin Manager: Can not init all plugins. '
. 'Please find attach the error from the '
. 'initialization:'. $e->getMessage());
}
} | php | {
"resource": ""
} |
q260999 | PluginManager.getPluginList | test | public function getPluginList() {
$arrayPluginList = array();
try {
//Iterate over the plugins paths
foreach ($this->pluginPaths as $path) {
//Search new plugins
$newPluginsDiscover = $this->pluginLocator->discoverPlugins($this->autoloader->getURLBase().$path);
//Instantiate the plugins
$listOfPluginsDiscover = $this->createPluginInstances($newPluginsDiscover);
foreach ($listOfPluginsDiscover as $newPlugin) {
$arrayPluginList[] = array('plugin'=>$newPlugin['plugin'], 'enabled'=>$newPlugin['enabled']);
}
}
} catch (\Exception $e) {
throw new PluginException('Plugin Manager: Can not init all plugins. '
. 'Please find attach the error from the '
. 'initialization:'. $e->getMessage());
}
return (array)$arrayPluginList;
} | php | {
"resource": ""
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.