repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
rocketeers/rocketeer
src/Rocketeer/Services/Connections/Shell/Modules/Statuses.php
Statuses.displayStatusMessage
public function displayStatusMessage($error, $output = null, $success = null) { // If all went well if ($this->checkResults($output)) { if ($success) { $this->explainer->success($success); } return $output || true; } // Else display the error $error = sprintf('An error occured: "%s"', $error); if ($output) { $error .= ', while running:'.PHP_EOL.$output; } $this->explainer->error($error); return false; }
php
public function displayStatusMessage($error, $output = null, $success = null) { // If all went well if ($this->checkResults($output)) { if ($success) { $this->explainer->success($success); } return $output || true; } // Else display the error $error = sprintf('An error occured: "%s"', $error); if ($output) { $error .= ', while running:'.PHP_EOL.$output; } $this->explainer->error($error); return false; }
[ "public", "function", "displayStatusMessage", "(", "$", "error", ",", "$", "output", "=", "null", ",", "$", "success", "=", "null", ")", "{", "// If all went well", "if", "(", "$", "this", "->", "checkResults", "(", "$", "output", ")", ")", "{", "if", ...
Check the status of the last run command, return an error if any. @param string $error The message to display on error @param string|null $output The command's output @param string|null $success The message to display on success @return bool
[ "Check", "the", "status", "of", "the", "last", "run", "command", "return", "an", "error", "if", "any", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Services/Connections/Shell/Modules/Statuses.php#L52-L72
train
rocketeers/rocketeer
src/Rocketeer/Services/History/History.php
History.getFlattened
protected function getFlattened($type) { $history = []; foreach ($this->items as $class => $entries) { $history = array_merge($history, $entries[$type]); } ksort($history); return array_values($history); }
php
protected function getFlattened($type) { $history = []; foreach ($this->items as $class => $entries) { $history = array_merge($history, $entries[$type]); } ksort($history); return array_values($history); }
[ "protected", "function", "getFlattened", "(", "$", "type", ")", "{", "$", "history", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "items", "as", "$", "class", "=>", "$", "entries", ")", "{", "$", "history", "=", "array_merge", "(", "$", "...
Get a flattened list of a certain type. @param string $type @return string[]|string[][]
[ "Get", "a", "flattened", "list", "of", "a", "certain", "type", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Services/History/History.php#L62-L72
train
rocketeers/rocketeer
src/Rocketeer/Tasks/Closure.php
Closure.does
public function does($task) { // Store the original task before transformation $this->setStringTask($task); // Wrap string tasks if (is_string($task) || is_array($task)) { $task = $this->builder->wrapStringTasks($task); } $this->setClosure($task); return $this; }
php
public function does($task) { // Store the original task before transformation $this->setStringTask($task); // Wrap string tasks if (is_string($task) || is_array($task)) { $task = $this->builder->wrapStringTasks($task); } $this->setClosure($task); return $this; }
[ "public", "function", "does", "(", "$", "task", ")", "{", "// Store the original task before transformation", "$", "this", "->", "setStringTask", "(", "$", "task", ")", ";", "// Wrap string tasks", "if", "(", "is_string", "(", "$", "task", ")", "||", "is_array",...
Change what the task does. @param string|array|callable $task @return self
[ "Change", "what", "the", "task", "does", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Tasks/Closure.php#L45-L58
train
rocketeers/rocketeer
src/Rocketeer/Tasks/Closure.php
Closure.getDescription
public function getDescription() { $flattened = (array) $this->getStringTask(); $flattened = implode('/', $flattened); return parent::getDescription() ?: $flattened; }
php
public function getDescription() { $flattened = (array) $this->getStringTask(); $flattened = implode('/', $flattened); return parent::getDescription() ?: $flattened; }
[ "public", "function", "getDescription", "(", ")", "{", "$", "flattened", "=", "(", "array", ")", "$", "this", "->", "getStringTask", "(", ")", ";", "$", "flattened", "=", "implode", "(", "'/'", ",", "$", "flattened", ")", ";", "return", "parent", "::",...
Get what the task does. @return string
[ "Get", "what", "the", "task", "does", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Tasks/Closure.php#L93-L99
train
rocketeers/rocketeer
src/Rocketeer/Services/Environment/Modules/ServerPathfinder.php
ServerPathfinder.getHomeFolder
public function getHomeFolder() { $rootDirectory = $this->getRootDirectory(); $appDirectory = $this->config->getContextually('remote.directories.app_directory') ?: $this->config->get('application_name'); return $rootDirectory.$appDirectory; }
php
public function getHomeFolder() { $rootDirectory = $this->getRootDirectory(); $appDirectory = $this->config->getContextually('remote.directories.app_directory') ?: $this->config->get('application_name'); return $rootDirectory.$appDirectory; }
[ "public", "function", "getHomeFolder", "(", ")", "{", "$", "rootDirectory", "=", "$", "this", "->", "getRootDirectory", "(", ")", ";", "$", "appDirectory", "=", "$", "this", "->", "config", "->", "getContextually", "(", "'remote.directories.app_directory'", ")",...
Get the path to the root folder of the application. @return string
[ "Get", "the", "path", "to", "the", "root", "folder", "of", "the", "application", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Services/Environment/Modules/ServerPathfinder.php#L38-L44
train
rocketeers/rocketeer
src/Rocketeer/Services/Environment/Modules/ServerPathfinder.php
ServerPathfinder.getFolder
public function getFolder(...$folder) { $folder = implode('/', $folder); $folder = $this->modulable->replacePatterns($folder); $base = $this->connections->is('local') ? getcwd() : $this->getHomeFolder(); $base = $base.'/'; $stage = $this->connections->getCurrentConnectionKey()->stage; if ($folder && $stage) { $base .= $stage.'/'; } // Replace base and cap it $folder = preg_replace('#^'.$base.'#', null, $folder); $folder = $base.$folder; return $folder; }
php
public function getFolder(...$folder) { $folder = implode('/', $folder); $folder = $this->modulable->replacePatterns($folder); $base = $this->connections->is('local') ? getcwd() : $this->getHomeFolder(); $base = $base.'/'; $stage = $this->connections->getCurrentConnectionKey()->stage; if ($folder && $stage) { $base .= $stage.'/'; } // Replace base and cap it $folder = preg_replace('#^'.$base.'#', null, $folder); $folder = $base.$folder; return $folder; }
[ "public", "function", "getFolder", "(", "...", "$", "folder", ")", "{", "$", "folder", "=", "implode", "(", "'/'", ",", "$", "folder", ")", ";", "$", "folder", "=", "$", "this", "->", "modulable", "->", "replacePatterns", "(", "$", "folder", ")", ";"...
Get the path to a folder, taking into account application name and stage. @param string|null ...$folder @return string
[ "Get", "the", "path", "to", "a", "folder", "taking", "into", "account", "application", "name", "and", "stage", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Services/Environment/Modules/ServerPathfinder.php#L73-L90
train
rocketeers/rocketeer
src/Rocketeer/Services/Bootstrapper/Modules/UserBootstrapper.php
UserBootstrapper.bootstrapPlugins
public function bootstrapPlugins() { $plugins = (array) $this->config->get('plugins.loaded'); $plugins = array_filter($plugins, 'class_exists'); $this->events->onTag('plugins', function () use ($plugins) { foreach ($plugins as $plugin) { $this->container->addServiceProvider($plugin); } }); }
php
public function bootstrapPlugins() { $plugins = (array) $this->config->get('plugins.loaded'); $plugins = array_filter($plugins, 'class_exists'); $this->events->onTag('plugins', function () use ($plugins) { foreach ($plugins as $plugin) { $this->container->addServiceProvider($plugin); } }); }
[ "public", "function", "bootstrapPlugins", "(", ")", "{", "$", "plugins", "=", "(", "array", ")", "$", "this", "->", "config", "->", "get", "(", "'plugins.loaded'", ")", ";", "$", "plugins", "=", "array_filter", "(", "$", "plugins", ",", "'class_exists'", ...
Load any configured plugins.
[ "Load", "any", "configured", "plugins", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Services/Bootstrapper/Modules/UserBootstrapper.php#L50-L60
train
rocketeers/rocketeer
src/Rocketeer/Services/Bootstrapper/Modules/UserBootstrapper.php
UserBootstrapper.bootstrapApp
protected function bootstrapApp() { $namespace = $this->getUserNamespace(); // Load service provider $serviceProvider = $namespace.'\\'.$namespace.'ServiceProvider'; $hasServiceProvider = class_exists($serviceProvider); if ($hasServiceProvider) { $plugins = (array) $this->config->get('plugins.loaded'); $plugins[] = $serviceProvider; $this->config->set('plugins.loaded', $plugins); } return $hasServiceProvider; }
php
protected function bootstrapApp() { $namespace = $this->getUserNamespace(); // Load service provider $serviceProvider = $namespace.'\\'.$namespace.'ServiceProvider'; $hasServiceProvider = class_exists($serviceProvider); if ($hasServiceProvider) { $plugins = (array) $this->config->get('plugins.loaded'); $plugins[] = $serviceProvider; $this->config->set('plugins.loaded', $plugins); } return $hasServiceProvider; }
[ "protected", "function", "bootstrapApp", "(", ")", "{", "$", "namespace", "=", "$", "this", "->", "getUserNamespace", "(", ")", ";", "// Load service provider", "$", "serviceProvider", "=", "$", "namespace", ".", "'\\\\'", ".", "$", "namespace", ".", "'Service...
Bootstrap a PSR4 folder in the user's directory. @return bool
[ "Bootstrap", "a", "PSR4", "folder", "in", "the", "user", "s", "directory", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Services/Bootstrapper/Modules/UserBootstrapper.php#L78-L92
train
rocketeers/rocketeer
src/Rocketeer/Services/Bootstrapper/Modules/UserBootstrapper.php
UserBootstrapper.bootstrapStandaloneFiles
protected function bootstrapStandaloneFiles() { $files = $this->files->listFiles($this->paths->getUserlandPath(), true); // Build queue, placing tasks first, events after $queue = []; foreach ($files as $file) { $path = $this->files->getAdapter()->applyPathPrefix($file['path']); if (mb_strpos($path, 'tasks') !== false) { array_unshift($queue, $path); } else { $queue[] = $path; } } // Include files foreach ($queue as $path) { include $path; } }
php
protected function bootstrapStandaloneFiles() { $files = $this->files->listFiles($this->paths->getUserlandPath(), true); // Build queue, placing tasks first, events after $queue = []; foreach ($files as $file) { $path = $this->files->getAdapter()->applyPathPrefix($file['path']); if (mb_strpos($path, 'tasks') !== false) { array_unshift($queue, $path); } else { $queue[] = $path; } } // Include files foreach ($queue as $path) { include $path; } }
[ "protected", "function", "bootstrapStandaloneFiles", "(", ")", "{", "$", "files", "=", "$", "this", "->", "files", "->", "listFiles", "(", "$", "this", "->", "paths", "->", "getUserlandPath", "(", ")", ",", "true", ")", ";", "// Build queue, placing tasks firs...
Bootstrap the user's standalone files.
[ "Bootstrap", "the", "user", "s", "standalone", "files", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Services/Bootstrapper/Modules/UserBootstrapper.php#L97-L116
train
rocketeers/rocketeer
src/Rocketeer/Services/Bootstrapper/Modules/UserBootstrapper.php
UserBootstrapper.bootstrapUserCode
public function bootstrapUserCode() { // Clean previously registered events $this->tasks->clearRegisteredEvents(); $this->bootstrapPlugins(); // Get the registered events $hooks = (array) $this->config->getContextually('hooks'); $tasks = isset($hooks['tasks']) ? (array) $hooks['tasks'] : []; $roles = isset($hooks['roles']) ? (array) $hooks['roles'] : []; $events = isset($hooks['events']) ? (array) $hooks['events'] : []; // Bind tasks and commands foreach ($tasks as $name => $task) { try { $this->tasks->task($name, $task); } catch (TaskCompositionException $exception) { $this->tasks->command($name, $task); } } // Bind events $this->events->onTag('hooks', function () use ($events) { foreach ($events as $event => $tasks) { foreach ($tasks as $task => $listeners) { $this->tasks->addTaskListeners($task, $event, $listeners, 0); } } }); // Assign roles $this->roles->assignTasksRoles($roles); }
php
public function bootstrapUserCode() { // Clean previously registered events $this->tasks->clearRegisteredEvents(); $this->bootstrapPlugins(); // Get the registered events $hooks = (array) $this->config->getContextually('hooks'); $tasks = isset($hooks['tasks']) ? (array) $hooks['tasks'] : []; $roles = isset($hooks['roles']) ? (array) $hooks['roles'] : []; $events = isset($hooks['events']) ? (array) $hooks['events'] : []; // Bind tasks and commands foreach ($tasks as $name => $task) { try { $this->tasks->task($name, $task); } catch (TaskCompositionException $exception) { $this->tasks->command($name, $task); } } // Bind events $this->events->onTag('hooks', function () use ($events) { foreach ($events as $event => $tasks) { foreach ($tasks as $task => $listeners) { $this->tasks->addTaskListeners($task, $event, $listeners, 0); } } }); // Assign roles $this->roles->assignTasksRoles($roles); }
[ "public", "function", "bootstrapUserCode", "(", ")", "{", "// Clean previously registered events", "$", "this", "->", "tasks", "->", "clearRegisteredEvents", "(", ")", ";", "$", "this", "->", "bootstrapPlugins", "(", ")", ";", "// Get the registered events", "$", "h...
Register the user's tasks, events and roles.
[ "Register", "the", "user", "s", "tasks", "events", "and", "roles", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Services/Bootstrapper/Modules/UserBootstrapper.php#L121-L153
train
rocketeers/rocketeer
src/Rocketeer/Binaries/AbstractBinary.php
AbstractBinary.getBinary
public function getBinary() { $default = $this->binary; // Resolve true path to binary if (!$this->resolved) { $paths = $this->getKnownPaths() ?: [$default]; if ($this->connections->getCurrentConnectionKey() && $paths) { $binary = Arr::get($paths, 0); $fallback = Arr::get($paths, 1); $this->setBinary($this->bash->which($binary, $fallback, false)); } elseif ($paths) { $this->setBinary($paths[0]); } } return $this->binary ?: $default; }
php
public function getBinary() { $default = $this->binary; // Resolve true path to binary if (!$this->resolved) { $paths = $this->getKnownPaths() ?: [$default]; if ($this->connections->getCurrentConnectionKey() && $paths) { $binary = Arr::get($paths, 0); $fallback = Arr::get($paths, 1); $this->setBinary($this->bash->which($binary, $fallback, false)); } elseif ($paths) { $this->setBinary($paths[0]); } } return $this->binary ?: $default; }
[ "public", "function", "getBinary", "(", ")", "{", "$", "default", "=", "$", "this", "->", "binary", ";", "// Resolve true path to binary", "if", "(", "!", "$", "this", "->", "resolved", ")", "{", "$", "paths", "=", "$", "this", "->", "getKnownPaths", "("...
Get the current binary name. @return string
[ "Get", "the", "current", "binary", "name", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Binaries/AbstractBinary.php#L94-L111
train
rocketeers/rocketeer
src/Rocketeer/Binaries/AbstractBinary.php
AbstractBinary.getCommand
public function getCommand($command = null, $arguments = [], $flags = [], $environmentVariables = []) { // Format arguments $arguments = $this->buildArguments($arguments); $options = $this->buildOptions($flags); $environmentVariables = $this->buildEnvironmentVariables($environmentVariables); // Build command $binary = $this->getBinary(); $components = [$command, $arguments, $options]; foreach ($components as $component) { if ($component) { $binary .= ' '.$component; } } // If the binary has a parent, wrap the call with it $parent = $this->parent instanceof self ? $this->parent->getBinary() : $this->parent; $command = $environmentVariables.$parent.' '.$binary; return trim($command); }
php
public function getCommand($command = null, $arguments = [], $flags = [], $environmentVariables = []) { // Format arguments $arguments = $this->buildArguments($arguments); $options = $this->buildOptions($flags); $environmentVariables = $this->buildEnvironmentVariables($environmentVariables); // Build command $binary = $this->getBinary(); $components = [$command, $arguments, $options]; foreach ($components as $component) { if ($component) { $binary .= ' '.$component; } } // If the binary has a parent, wrap the call with it $parent = $this->parent instanceof self ? $this->parent->getBinary() : $this->parent; $command = $environmentVariables.$parent.' '.$binary; return trim($command); }
[ "public", "function", "getCommand", "(", "$", "command", "=", "null", ",", "$", "arguments", "=", "[", "]", ",", "$", "flags", "=", "[", "]", ",", "$", "environmentVariables", "=", "[", "]", ")", "{", "// Format arguments", "$", "arguments", "=", "$", ...
Returns a command with the VCS's binary. @param string|null $command @param string|string[] $arguments @param string|string[] $flags @param array $environmentVariables @return string
[ "Returns", "a", "command", "with", "the", "VCS", "s", "binary", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Binaries/AbstractBinary.php#L155-L176
train
rocketeers/rocketeer
src/Rocketeer/Binaries/AbstractBinary.php
AbstractBinary.sanitizeFlags
protected function sanitizeFlags(array $flags) { $flags = (array) $flags; // Flip array if necessary $firstKey = Arr::get(array_keys($flags), 0); if ($firstKey !== null && is_int($firstKey)) { $flags = array_combine( array_values($flags), array_fill(0, count($flags), null) ); } return $flags; }
php
protected function sanitizeFlags(array $flags) { $flags = (array) $flags; // Flip array if necessary $firstKey = Arr::get(array_keys($flags), 0); if ($firstKey !== null && is_int($firstKey)) { $flags = array_combine( array_values($flags), array_fill(0, count($flags), null) ); } return $flags; }
[ "protected", "function", "sanitizeFlags", "(", "array", "$", "flags", ")", "{", "$", "flags", "=", "(", "array", ")", "$", "flags", ";", "// Flip array if necessary", "$", "firstKey", "=", "Arr", "::", "get", "(", "array_keys", "(", "$", "flags", ")", ",...
Sanitize a flags array. @param array $flags @return array
[ "Sanitize", "a", "flags", "array", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Binaries/AbstractBinary.php#L260-L274
train
rocketeers/rocketeer
src/Rocketeer/Services/Ignition/PluginsIgniter.php
PluginsIgniter.publish
public function publish($plugins = null) { $plugins = $this->gatherLoadedPackagesHandles($plugins); foreach ($plugins as $plugin) { // Find the plugin's configuration $paths = $this->findPackageConfiguration($plugin); // Cancel if no valid paths $paths = array_filter($paths, [$this->files, 'isDirectory']); $paths = array_values($paths); if (empty($paths)) { $this->explainer->comment('No configuration found for '.$plugin); continue; } $this->publishConfiguration($paths[0]); } }
php
public function publish($plugins = null) { $plugins = $this->gatherLoadedPackagesHandles($plugins); foreach ($plugins as $plugin) { // Find the plugin's configuration $paths = $this->findPackageConfiguration($plugin); // Cancel if no valid paths $paths = array_filter($paths, [$this->files, 'isDirectory']); $paths = array_values($paths); if (empty($paths)) { $this->explainer->comment('No configuration found for '.$plugin); continue; } $this->publishConfiguration($paths[0]); } }
[ "public", "function", "publish", "(", "$", "plugins", "=", "null", ")", "{", "$", "plugins", "=", "$", "this", "->", "gatherLoadedPackagesHandles", "(", "$", "plugins", ")", ";", "foreach", "(", "$", "plugins", "as", "$", "plugin", ")", "{", "// Find the...
Publishes a package's configuration. @param string|string[] $plugins @return bool|string|null
[ "Publishes", "a", "package", "s", "configuration", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Services/Ignition/PluginsIgniter.php#L49-L66
train
rocketeers/rocketeer
src/Rocketeer/Services/Ignition/PluginsIgniter.php
PluginsIgniter.publishConfiguration
protected function publishConfiguration($path) { // Compute and create the destination folder $destination = $this->paths->getConfigurationPath().'/plugins'; // Export configuration $files = $this->files->listFiles($path, true); foreach ($files as $file) { $fileDestination = $destination.DS.$file['basename']; if ($this->files->has($destination) && !$this->force) { continue; } $this->files->forceCopy($file['path'], $fileDestination); $this->explainer->success('Published <comment>'.str_replace($this->paths->getBasePath(), null, $fileDestination).'</comment>'); } }
php
protected function publishConfiguration($path) { // Compute and create the destination folder $destination = $this->paths->getConfigurationPath().'/plugins'; // Export configuration $files = $this->files->listFiles($path, true); foreach ($files as $file) { $fileDestination = $destination.DS.$file['basename']; if ($this->files->has($destination) && !$this->force) { continue; } $this->files->forceCopy($file['path'], $fileDestination); $this->explainer->success('Published <comment>'.str_replace($this->paths->getBasePath(), null, $fileDestination).'</comment>'); } }
[ "protected", "function", "publishConfiguration", "(", "$", "path", ")", "{", "// Compute and create the destination folder", "$", "destination", "=", "$", "this", "->", "paths", "->", "getConfigurationPath", "(", ")", ".", "'/plugins'", ";", "// Export configuration", ...
Publishes a configuration within a classic application. @param string $path @return bool
[ "Publishes", "a", "configuration", "within", "a", "classic", "application", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Services/Ignition/PluginsIgniter.php#L75-L91
train
rocketeers/rocketeer
src/Rocketeer/Services/Ignition/PluginsIgniter.php
PluginsIgniter.findPackageConfiguration
public function findPackageConfiguration($package) { $paths = [ $this->paths->getBasePath().'vendor/%s/src/config', $this->paths->getBasePath().'vendor/%s/config', $this->paths->getRocketeerPath().'/vendor/%s/src/config', $this->paths->getRocketeerPath().'/vendor/%s/config', $this->paths->getUserHomeFolder().'/.composer/vendor/%s/src/config', $this->paths->getUserHomeFolder().'/.composer/vendor/%s/config', ]; // Check for the first configuration path that exists $paths = array_map(function ($path) use ($package) { return sprintf($path, $package); }, $paths); return $paths; }
php
public function findPackageConfiguration($package) { $paths = [ $this->paths->getBasePath().'vendor/%s/src/config', $this->paths->getBasePath().'vendor/%s/config', $this->paths->getRocketeerPath().'/vendor/%s/src/config', $this->paths->getRocketeerPath().'/vendor/%s/config', $this->paths->getUserHomeFolder().'/.composer/vendor/%s/src/config', $this->paths->getUserHomeFolder().'/.composer/vendor/%s/config', ]; // Check for the first configuration path that exists $paths = array_map(function ($path) use ($package) { return sprintf($path, $package); }, $paths); return $paths; }
[ "public", "function", "findPackageConfiguration", "(", "$", "package", ")", "{", "$", "paths", "=", "[", "$", "this", "->", "paths", "->", "getBasePath", "(", ")", ".", "'vendor/%s/src/config'", ",", "$", "this", "->", "paths", "->", "getBasePath", "(", ")...
Find all the possible locations for a package's configuration. @param string $package @return string[]
[ "Find", "all", "the", "possible", "locations", "for", "a", "package", "s", "configuration", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Services/Ignition/PluginsIgniter.php#L104-L121
train
rocketeers/rocketeer
src/Rocketeer/Services/Ignition/PluginsIgniter.php
PluginsIgniter.gatherLoadedPackagesHandles
protected function gatherLoadedPackagesHandles($packages) { $packages = (array) $packages; if (!$packages) { $plugins = $this->container->getPlugins(); foreach ($plugins as $plugin) { $path = (new ReflectionClass($plugin))->getFileName(); preg_match('/vendor\/([^\/]+)\/([^\/]+)/', $path, $handle); if (count($handle) !== 3) { continue; } $packages[] = $handle[1].'/'.$handle[2]; } } return $packages; }
php
protected function gatherLoadedPackagesHandles($packages) { $packages = (array) $packages; if (!$packages) { $plugins = $this->container->getPlugins(); foreach ($plugins as $plugin) { $path = (new ReflectionClass($plugin))->getFileName(); preg_match('/vendor\/([^\/]+)\/([^\/]+)/', $path, $handle); if (count($handle) !== 3) { continue; } $packages[] = $handle[1].'/'.$handle[2]; } } return $packages; }
[ "protected", "function", "gatherLoadedPackagesHandles", "(", "$", "packages", ")", "{", "$", "packages", "=", "(", "array", ")", "$", "packages", ";", "if", "(", "!", "$", "packages", ")", "{", "$", "plugins", "=", "$", "this", "->", "container", "->", ...
Infer the name of the loaded packages from their service provider. @param string|string[] $packages @return string[]
[ "Infer", "the", "name", "of", "the", "loaded", "packages", "from", "their", "service", "provider", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Services/Ignition/PluginsIgniter.php#L131-L148
train
rocketeers/rocketeer
src/Rocketeer/Services/Builders/Modules/CommandsBuilder.php
CommandsBuilder.buildCommand
public function buildCommand($task, $slug = null) { // Build the task instance try { $instance = $this->modulable->buildTask($task); } catch (TaskCompositionException $exception) { $instance = null; } // Get the command name $name = $instance ? $instance->getName() : null; $command = $this->modulable->findQualifiedName($name, 'commands'); // If no command found, use BaseTaskCommand or task name if ($command === BaseTaskCommand::class) { $name = is_string($task) ? $task : $name; $command = $this->modulable->findQualifiedName($name, 'commands'); } /** @var AbstractCommand $command */ $command = new $command($instance, $slug); $command->setContainer($this->container); return $command; }
php
public function buildCommand($task, $slug = null) { // Build the task instance try { $instance = $this->modulable->buildTask($task); } catch (TaskCompositionException $exception) { $instance = null; } // Get the command name $name = $instance ? $instance->getName() : null; $command = $this->modulable->findQualifiedName($name, 'commands'); // If no command found, use BaseTaskCommand or task name if ($command === BaseTaskCommand::class) { $name = is_string($task) ? $task : $name; $command = $this->modulable->findQualifiedName($name, 'commands'); } /** @var AbstractCommand $command */ $command = new $command($instance, $slug); $command->setContainer($this->container); return $command; }
[ "public", "function", "buildCommand", "(", "$", "task", ",", "$", "slug", "=", "null", ")", "{", "// Build the task instance", "try", "{", "$", "instance", "=", "$", "this", "->", "modulable", "->", "buildTask", "(", "$", "task", ")", ";", "}", "catch", ...
Build the command bound to a task. @param string|\Rocketeer\Tasks\AbstractTask $task @param string|null $slug @return \Rocketeer\Console\Commands\AbstractCommand
[ "Build", "the", "command", "bound", "to", "a", "task", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Services/Builders/Modules/CommandsBuilder.php#L32-L56
train
rocketeers/rocketeer
src/Rocketeer/Console/ConsoleServiceProvider.php
ConsoleServiceProvider.getPredefinedCommands
public function getPredefinedCommands() { $tasks = [ 'check' => 'Check', 'cleanup' => 'Cleanup', 'current' => 'CurrentRelease', 'deploy' => 'Deploy', 'flush' => 'Flush', 'ignite' => 'Ignite', 'ignite-stubs' => 'Ignite\Stubs', 'rollback' => 'Rollback', 'setup' => 'Setup', 'strategies' => 'Strategies', 'teardown' => 'Teardown', 'test' => 'Test', 'update' => 'Update', 'debug-tinker' => 'Development\Tinker', 'debug-config' => 'Development\Configuration', 'self-update' => 'Development\SelfUpdate', 'plugin-publish' => 'Plugins\Publish', 'plugin-list' => 'Plugins\List', 'plugin-install' => 'Plugins\Install', 'plugin-update' => 'Plugins\Updater', ]; // Add user commands $userTasks = (array) $this->config->get('hooks.custom'); $userTasks = array_filter($userTasks); $tasks = array_merge($tasks, $userTasks); return $tasks; }
php
public function getPredefinedCommands() { $tasks = [ 'check' => 'Check', 'cleanup' => 'Cleanup', 'current' => 'CurrentRelease', 'deploy' => 'Deploy', 'flush' => 'Flush', 'ignite' => 'Ignite', 'ignite-stubs' => 'Ignite\Stubs', 'rollback' => 'Rollback', 'setup' => 'Setup', 'strategies' => 'Strategies', 'teardown' => 'Teardown', 'test' => 'Test', 'update' => 'Update', 'debug-tinker' => 'Development\Tinker', 'debug-config' => 'Development\Configuration', 'self-update' => 'Development\SelfUpdate', 'plugin-publish' => 'Plugins\Publish', 'plugin-list' => 'Plugins\List', 'plugin-install' => 'Plugins\Install', 'plugin-update' => 'Plugins\Updater', ]; // Add user commands $userTasks = (array) $this->config->get('hooks.custom'); $userTasks = array_filter($userTasks); $tasks = array_merge($tasks, $userTasks); return $tasks; }
[ "public", "function", "getPredefinedCommands", "(", ")", "{", "$", "tasks", "=", "[", "'check'", "=>", "'Check'", ",", "'cleanup'", "=>", "'Cleanup'", ",", "'current'", "=>", "'CurrentRelease'", ",", "'deploy'", "=>", "'Deploy'", ",", "'flush'", "=>", "'Flush'...
Get an array of all already defined tasks. @return array
[ "Get", "an", "array", "of", "all", "already", "defined", "tasks", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Console/ConsoleServiceProvider.php#L69-L100
train
rocketeers/rocketeer
src/Rocketeer/Rocketeer.php
Rocketeer.getDetectedStage
public static function getDetectedStage($application = 'application', $path = null) { $folderRegex = '[a-zA-Z0-9_-]+'; $current = $path ?: realpath(__DIR__); $pattern = sprintf('/%s\/(%s)\/%s\/([0-9]{14})/', $application, $folderRegex, $folderRegex); preg_match($pattern, $current, $matches); return isset($matches[1]) ? $matches[1] : false; }
php
public static function getDetectedStage($application = 'application', $path = null) { $folderRegex = '[a-zA-Z0-9_-]+'; $current = $path ?: realpath(__DIR__); $pattern = sprintf('/%s\/(%s)\/%s\/([0-9]{14})/', $application, $folderRegex, $folderRegex); preg_match($pattern, $current, $matches); return isset($matches[1]) ? $matches[1] : false; }
[ "public", "static", "function", "getDetectedStage", "(", "$", "application", "=", "'application'", ",", "$", "path", "=", "null", ")", "{", "$", "folderRegex", "=", "'[a-zA-Z0-9_-]+'", ";", "$", "current", "=", "$", "path", "?", ":", "realpath", "(", "__DI...
Returns what stage Rocketeer thinks he's in. @param string $application @param string|null $path @return string|false
[ "Returns", "what", "stage", "Rocketeer", "thinks", "he", "s", "in", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Rocketeer.php#L45-L54
train
rocketeers/rocketeer
src/Rocketeer/Traits/Properties/ConfigurableTrait.php
ConfigurableTrait.setFlags
public function setFlags(array $flags) { // Check types of flags $types = array_filter($flags, 'is_array'); if (count($types) !== count($flags)) { throw new InvalidArgumentException('Flags must be passed as an array'); } $this->options['flags'] = $flags; }
php
public function setFlags(array $flags) { // Check types of flags $types = array_filter($flags, 'is_array'); if (count($types) !== count($flags)) { throw new InvalidArgumentException('Flags must be passed as an array'); } $this->options['flags'] = $flags; }
[ "public", "function", "setFlags", "(", "array", "$", "flags", ")", "{", "// Check types of flags", "$", "types", "=", "array_filter", "(", "$", "flags", ",", "'is_array'", ")", ";", "if", "(", "count", "(", "$", "types", ")", "!==", "count", "(", "$", ...
Set flags on the command. @param array $flags
[ "Set", "flags", "on", "the", "command", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Traits/Properties/ConfigurableTrait.php#L69-L78
train
rocketeers/rocketeer
src/Rocketeer/Traits/Properties/ConfigurableTrait.php
ConfigurableTrait.getFlags
public function getFlags($command = null) { $option = $command ? 'flags.'.$command : 'flags'; return $this->getOption($option, true); }
php
public function getFlags($command = null) { $option = $command ? 'flags.'.$command : 'flags'; return $this->getOption($option, true); }
[ "public", "function", "getFlags", "(", "$", "command", "=", "null", ")", "{", "$", "option", "=", "$", "command", "?", "'flags.'", ".", "$", "command", ":", "'flags'", ";", "return", "$", "this", "->", "getOption", "(", "$", "option", ",", "true", ")...
Get the flags for a command. @param string|null $command @return array
[ "Get", "the", "flags", "for", "a", "command", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Traits/Properties/ConfigurableTrait.php#L87-L92
train
rocketeers/rocketeer
src/Rocketeer/Traits/Properties/ConfigurableTrait.php
ConfigurableTrait.getClosureOption
protected function getClosureOption($option) { $option = array_get($this->options, $option); if (!is_callable($option)) { return; } return $option; }
php
protected function getClosureOption($option) { $option = array_get($this->options, $option); if (!is_callable($option)) { return; } return $option; }
[ "protected", "function", "getClosureOption", "(", "$", "option", ")", "{", "$", "option", "=", "array_get", "(", "$", "this", "->", "options", ",", "$", "option", ")", ";", "if", "(", "!", "is_callable", "(", "$", "option", ")", ")", "{", "return", "...
Get a callable option. @param string $option @return callable|null
[ "Get", "a", "callable", "option", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Traits/Properties/ConfigurableTrait.php#L105-L113
train
rocketeers/rocketeer
src/Rocketeer/Strategies/Deploy/SyncStrategy.php
SyncStrategy.getSyncHandle
protected function getSyncHandle() { $credentials = $this->credentials->getServerCredentials(); $handle = array_get($credentials, 'host'); $explodedHandle = explode(':', $handle); // Extract port if (count($explodedHandle) === 2) { $this->options['port'] = $explodedHandle[1]; $handle = $explodedHandle[0]; } // Add username if ($user = array_get($credentials, 'username')) { $handle = $user.'@'.$handle; } return $handle; }
php
protected function getSyncHandle() { $credentials = $this->credentials->getServerCredentials(); $handle = array_get($credentials, 'host'); $explodedHandle = explode(':', $handle); // Extract port if (count($explodedHandle) === 2) { $this->options['port'] = $explodedHandle[1]; $handle = $explodedHandle[0]; } // Add username if ($user = array_get($credentials, 'username')) { $handle = $user.'@'.$handle; } return $handle; }
[ "protected", "function", "getSyncHandle", "(", ")", "{", "$", "credentials", "=", "$", "this", "->", "credentials", "->", "getServerCredentials", "(", ")", ";", "$", "handle", "=", "array_get", "(", "$", "credentials", ",", "'host'", ")", ";", "$", "explod...
Get the handle to connect with. @return string
[ "Get", "the", "handle", "to", "connect", "with", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Strategies/Deploy/SyncStrategy.php#L72-L90
train
rocketeers/rocketeer
src/Rocketeer/Strategies/Deploy/SyncStrategy.php
SyncStrategy.getTransport
protected function getTransport() { $ssh = 'ssh'; // Get port if ($port = $this->getOption('port', true)) { $ssh .= ' -p '.$port; } // Get key $key = $this->credentials->getServerCredentials(); $key = Arr::get($key, 'key'); if ($key) { $ssh .= ' -i "'.$key.'"'; } return $ssh; }
php
protected function getTransport() { $ssh = 'ssh'; // Get port if ($port = $this->getOption('port', true)) { $ssh .= ' -p '.$port; } // Get key $key = $this->credentials->getServerCredentials(); $key = Arr::get($key, 'key'); if ($key) { $ssh .= ' -i "'.$key.'"'; } return $ssh; }
[ "protected", "function", "getTransport", "(", ")", "{", "$", "ssh", "=", "'ssh'", ";", "// Get port", "if", "(", "$", "port", "=", "$", "this", "->", "getOption", "(", "'port'", ",", "true", ")", ")", "{", "$", "ssh", ".=", "' -p '", ".", "$", "por...
Get the transport to use. @return string
[ "Get", "the", "transport", "to", "use", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Strategies/Deploy/SyncStrategy.php#L97-L114
train
rocketeers/rocketeer
src/Rocketeer/Services/Ignition/RocketeerIgniter.php
RocketeerIgniter.exportDotenv
public function exportDotenv(array $credentials) { // Build dotenv file $dotenv = ''; foreach ($credentials as $credential => $value) { $value = str_replace('"', '\\"', $value); $dotenv .= sprintf('%s="%s"', $credential, $value); $dotenv .= PHP_EOL; } // Write to disk $this->files->append($this->paths->getDotenvPath(), $dotenv); }
php
public function exportDotenv(array $credentials) { // Build dotenv file $dotenv = ''; foreach ($credentials as $credential => $value) { $value = str_replace('"', '\\"', $value); $dotenv .= sprintf('%s="%s"', $credential, $value); $dotenv .= PHP_EOL; } // Write to disk $this->files->append($this->paths->getDotenvPath(), $dotenv); }
[ "public", "function", "exportDotenv", "(", "array", "$", "credentials", ")", "{", "// Build dotenv file", "$", "dotenv", "=", "''", ";", "foreach", "(", "$", "credentials", "as", "$", "credential", "=>", "$", "value", ")", "{", "$", "value", "=", "str_repl...
Export credentials to a dotenv file. @param array $credentials
[ "Export", "credentials", "to", "a", "dotenv", "file", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Services/Ignition/RocketeerIgniter.php#L39-L51
train
rocketeers/rocketeer
src/Rocketeer/Services/Ignition/RocketeerIgniter.php
RocketeerIgniter.exportConfiguration
public function exportConfiguration($format, $consolidated) { $definition = new ConfigurationDefinition(); $definition->setValues($this->config->all()); $this->configurationPublisher->setDefinition($definition); $this->configurationPublisher->publish($format, $consolidated); }
php
public function exportConfiguration($format, $consolidated) { $definition = new ConfigurationDefinition(); $definition->setValues($this->config->all()); $this->configurationPublisher->setDefinition($definition); $this->configurationPublisher->publish($format, $consolidated); }
[ "public", "function", "exportConfiguration", "(", "$", "format", ",", "$", "consolidated", ")", "{", "$", "definition", "=", "new", "ConfigurationDefinition", "(", ")", ";", "$", "definition", "->", "setValues", "(", "$", "this", "->", "config", "->", "all",...
Export Rocketeer's configuration in a given format. @param string $format @param bool $consolidated
[ "Export", "Rocketeer", "s", "configuration", "in", "a", "given", "format", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Services/Ignition/RocketeerIgniter.php#L59-L66
train
rocketeers/rocketeer
src/Rocketeer/Services/Ignition/RocketeerIgniter.php
RocketeerIgniter.exportStubs
public function exportStubs($type, $destination, $namespace = null) { // If we have no stubs for this type, cancel $source = __DIR__.'/../../../stubs/'.$type; if (!$this->files->has($source)) { return; } $this->files->createDir($destination); $files = $this->files->listFiles($source, true); foreach ($files as $file) { $contents = $this->files->read($file['path']); $basename = $file['basename']; $fileDestination = $destination.DS.$basename; if ($namespace) { $namespace = preg_replace("/[^\w]/", '', $namespace); // only words allowed $contents = str_replace('namespace App', 'namespace '.$namespace, $contents); $contents = str_replace('AppServiceProvider', $namespace.'ServiceProvider', $contents); $fileDestination = mb_strpos($basename, 'ServiceProvider') === false ? $destination.DS.basename(dirname($file['path'])).DS.$basename : $destination.DS.$namespace.'ServiceProvider.php'; } $this->files->put($fileDestination, $contents); } }
php
public function exportStubs($type, $destination, $namespace = null) { // If we have no stubs for this type, cancel $source = __DIR__.'/../../../stubs/'.$type; if (!$this->files->has($source)) { return; } $this->files->createDir($destination); $files = $this->files->listFiles($source, true); foreach ($files as $file) { $contents = $this->files->read($file['path']); $basename = $file['basename']; $fileDestination = $destination.DS.$basename; if ($namespace) { $namespace = preg_replace("/[^\w]/", '', $namespace); // only words allowed $contents = str_replace('namespace App', 'namespace '.$namespace, $contents); $contents = str_replace('AppServiceProvider', $namespace.'ServiceProvider', $contents); $fileDestination = mb_strpos($basename, 'ServiceProvider') === false ? $destination.DS.basename(dirname($file['path'])).DS.$basename : $destination.DS.$namespace.'ServiceProvider.php'; } $this->files->put($fileDestination, $contents); } }
[ "public", "function", "exportStubs", "(", "$", "type", ",", "$", "destination", ",", "$", "namespace", "=", "null", ")", "{", "// If we have no stubs for this type, cancel", "$", "source", "=", "__DIR__", ".", "'/../../../stubs/'", ".", "$", "type", ";", "if", ...
Export the provided type of stubs to a certain folder Optionally replace a namespace with a given one. @param string $type @param string $destination @param string|null $namespace
[ "Export", "the", "provided", "type", "of", "stubs", "to", "a", "certain", "folder", "Optionally", "replace", "a", "namespace", "with", "a", "given", "one", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Services/Ignition/RocketeerIgniter.php#L76-L102
train
rocketeers/rocketeer
src/Rocketeer/Services/Connections/Credentials/Modules/ConnectionsKeychain.php
ConnectionsKeychain.syncConnectionCredentials
public function syncConnectionCredentials(ConnectionKey $connection = null, array $credentials = []) { // Store credentials if any if (!$credentials) { return; } $key = 'connections.'.$connection->name.'.servers.'.$connection->server; $filtered = $this->filterUnsavableCredentials($connection, $credentials); $this->localStorage->set($key, $filtered); // Merge and save $current = (array) $this->config->get($key); $credentials = array_replace_recursive($current, $credentials); $this->config->set($key, $credentials); // Reset connections $this->connections->disconnect(); return $credentials; }
php
public function syncConnectionCredentials(ConnectionKey $connection = null, array $credentials = []) { // Store credentials if any if (!$credentials) { return; } $key = 'connections.'.$connection->name.'.servers.'.$connection->server; $filtered = $this->filterUnsavableCredentials($connection, $credentials); $this->localStorage->set($key, $filtered); // Merge and save $current = (array) $this->config->get($key); $credentials = array_replace_recursive($current, $credentials); $this->config->set($key, $credentials); // Reset connections $this->connections->disconnect(); return $credentials; }
[ "public", "function", "syncConnectionCredentials", "(", "ConnectionKey", "$", "connection", "=", "null", ",", "array", "$", "credentials", "=", "[", "]", ")", "{", "// Store credentials if any", "if", "(", "!", "$", "credentials", ")", "{", "return", ";", "}",...
Persists connection credentials to cache. @param ConnectionKey|null $connection @param array $credentials @return array|void
[ "Persists", "connection", "credentials", "to", "cache", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Services/Connections/Credentials/Modules/ConnectionsKeychain.php#L32-L53
train
rocketeers/rocketeer
src/Rocketeer/Services/Connections/Credentials/Modules/ConnectionsKeychain.php
ConnectionsKeychain.createConnectionKey
public function createConnectionKey($connection = null, $server = null, $stage = null) { if ($connection instanceof ConnectionKey) { return $connection; } // Concatenate $handle = new ConnectionKey([ 'name' => $connection, 'server' => (int) $server, 'stage' => $stage, ]); // Populate credentials $handle->servers = $this->getServersCredentials($handle); return $handle; }
php
public function createConnectionKey($connection = null, $server = null, $stage = null) { if ($connection instanceof ConnectionKey) { return $connection; } // Concatenate $handle = new ConnectionKey([ 'name' => $connection, 'server' => (int) $server, 'stage' => $stage, ]); // Populate credentials $handle->servers = $this->getServersCredentials($handle); return $handle; }
[ "public", "function", "createConnectionKey", "(", "$", "connection", "=", "null", ",", "$", "server", "=", "null", ",", "$", "stage", "=", "null", ")", "{", "if", "(", "$", "connection", "instanceof", "ConnectionKey", ")", "{", "return", "$", "connection",...
Build the current connection's handle. @param ConnectionKey|string|null $connection @param int|null $server @param string|null $stage @return ConnectionKey
[ "Build", "the", "current", "connection", "s", "handle", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Services/Connections/Credentials/Modules/ConnectionsKeychain.php#L68-L85
train
rocketeers/rocketeer
src/Rocketeer/Services/Connections/Credentials/Modules/ConnectionsKeychain.php
ConnectionsKeychain.getServersCredentials
public function getServersCredentials($connection = null) { $connection = $this->sanitizeConnection($connection); $available = $this->connections->getAvailableConnections(); // Get and filter servers $servers = Arr::get($available, $connection->name.'.servers'); if ($this->hasCommand() && $allowed = $this->command->option('server')) { $allowed = explode(',', $allowed); $servers = array_intersect_key((array) $servers, array_flip($allowed)); } return $servers; }
php
public function getServersCredentials($connection = null) { $connection = $this->sanitizeConnection($connection); $available = $this->connections->getAvailableConnections(); // Get and filter servers $servers = Arr::get($available, $connection->name.'.servers'); if ($this->hasCommand() && $allowed = $this->command->option('server')) { $allowed = explode(',', $allowed); $servers = array_intersect_key((array) $servers, array_flip($allowed)); } return $servers; }
[ "public", "function", "getServersCredentials", "(", "$", "connection", "=", "null", ")", "{", "$", "connection", "=", "$", "this", "->", "sanitizeConnection", "(", "$", "connection", ")", ";", "$", "available", "=", "$", "this", "->", "connections", "->", ...
Get the credentials for a particular connection. @param ConnectionKey|string|null $connection @return string[][]
[ "Get", "the", "credentials", "for", "a", "particular", "connection", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Services/Connections/Credentials/Modules/ConnectionsKeychain.php#L115-L128
train
rocketeers/rocketeer
src/Rocketeer/Services/Connections/Credentials/Modules/ConnectionsKeychain.php
ConnectionsKeychain.getServerCredentials
public function getServerCredentials($connection = null, $server = 0) { $connection = $this->sanitizeConnection($connection); $servers = $this->getServersCredentials($connection); return (array) Arr::get($servers, $server ?: $connection->server); }
php
public function getServerCredentials($connection = null, $server = 0) { $connection = $this->sanitizeConnection($connection); $servers = $this->getServersCredentials($connection); return (array) Arr::get($servers, $server ?: $connection->server); }
[ "public", "function", "getServerCredentials", "(", "$", "connection", "=", "null", ",", "$", "server", "=", "0", ")", "{", "$", "connection", "=", "$", "this", "->", "sanitizeConnection", "(", "$", "connection", ")", ";", "$", "servers", "=", "$", "this"...
Get the credentials for as server. @param ConnectionKey|string|null $connection @param int $server @return array
[ "Get", "the", "credentials", "for", "as", "server", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Services/Connections/Credentials/Modules/ConnectionsKeychain.php#L138-L144
train
rocketeers/rocketeer
src/Rocketeer/Services/Connections/Credentials/Modules/ConnectionsKeychain.php
ConnectionsKeychain.filterUnsavableCredentials
protected function filterUnsavableCredentials(ConnectionKey $connection, $credentials) { $defined = $this->getServerCredentials($connection); foreach ($credentials as $key => $value) { if (array_get($defined, $key) === true) { unset($credentials[$key]); } } return $credentials; }
php
protected function filterUnsavableCredentials(ConnectionKey $connection, $credentials) { $defined = $this->getServerCredentials($connection); foreach ($credentials as $key => $value) { if (array_get($defined, $key) === true) { unset($credentials[$key]); } } return $credentials; }
[ "protected", "function", "filterUnsavableCredentials", "(", "ConnectionKey", "$", "connection", ",", "$", "credentials", ")", "{", "$", "defined", "=", "$", "this", "->", "getServerCredentials", "(", "$", "connection", ")", ";", "foreach", "(", "$", "credentials...
Filter the credentials and remove the ones that can't be saved to disk. @param ConnectionKey $connection @param array $credentials @return string[]
[ "Filter", "the", "credentials", "and", "remove", "the", "ones", "that", "can", "t", "be", "saved", "to", "disk", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Services/Connections/Credentials/Modules/ConnectionsKeychain.php#L159-L169
train
rocketeers/rocketeer
src/Rocketeer/Services/Config/Files/ConfigurationPublisher.php
ConfigurationPublisher.publishNode
public function publishNode($path, $format = 'php', $node = null) { if ($this->files->isDirectory($path)) { foreach (['config', 'hooks', 'paths', 'remote', 'vcs', 'stages', 'strategies', 'plugins'] as $file) { $this->publishNode($path.'/'.$file.'.'.$format, $format, $file); } return; } // If a single file was passed, infer format from extension $format = $format ?: pathinfo($path, PATHINFO_EXTENSION); $configuration = $this->getDefinition($format, $node); $this->files->put($path, $configuration); }
php
public function publishNode($path, $format = 'php', $node = null) { if ($this->files->isDirectory($path)) { foreach (['config', 'hooks', 'paths', 'remote', 'vcs', 'stages', 'strategies', 'plugins'] as $file) { $this->publishNode($path.'/'.$file.'.'.$format, $format, $file); } return; } // If a single file was passed, infer format from extension $format = $format ?: pathinfo($path, PATHINFO_EXTENSION); $configuration = $this->getDefinition($format, $node); $this->files->put($path, $configuration); }
[ "public", "function", "publishNode", "(", "$", "path", ",", "$", "format", "=", "'php'", ",", "$", "node", "=", "null", ")", "{", "if", "(", "$", "this", "->", "files", "->", "isDirectory", "(", "$", "path", ")", ")", "{", "foreach", "(", "[", "'...
Publish the configuration somewhere. @param string $path @param string $format @param string|null $node
[ "Publish", "the", "configuration", "somewhere", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Services/Config/Files/ConfigurationPublisher.php#L96-L111
train
rocketeers/rocketeer
src/Rocketeer/Services/Config/Files/ConfigurationPublisher.php
ConfigurationPublisher.getDefinition
public function getDefinition($format = 'yml', $node = null) { switch (mb_strtolower($format)) { case 'json': $dumper = new JsonReferenceDumper(); break; case 'yml': case 'yaml': $dumper = new YamlReferenceDumper(); break; case 'php': default: $dumper = new PhpReferenceDumper(); break; } $definition = $this->definition; $definition = $definition->getConfigTreeBuilder()->buildTree(); if ($node && $definition instanceof ArrayNode) { $definition = $definition->getChildren()[$node]; } return $dumper->dumpNode($definition); }
php
public function getDefinition($format = 'yml', $node = null) { switch (mb_strtolower($format)) { case 'json': $dumper = new JsonReferenceDumper(); break; case 'yml': case 'yaml': $dumper = new YamlReferenceDumper(); break; case 'php': default: $dumper = new PhpReferenceDumper(); break; } $definition = $this->definition; $definition = $definition->getConfigTreeBuilder()->buildTree(); if ($node && $definition instanceof ArrayNode) { $definition = $definition->getChildren()[$node]; } return $dumper->dumpNode($definition); }
[ "public", "function", "getDefinition", "(", "$", "format", "=", "'yml'", ",", "$", "node", "=", "null", ")", "{", "switch", "(", "mb_strtolower", "(", "$", "format", ")", ")", "{", "case", "'json'", ":", "$", "dumper", "=", "new", "JsonReferenceDumper", ...
Set the available options and their values. @param string $format @param string|null $node @return string
[ "Set", "the", "available", "options", "and", "their", "values", "." ]
8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0
https://github.com/rocketeers/rocketeer/blob/8a381d5b03a5554c2c0d466bd49c3bdf6a6e20c0/src/Rocketeer/Services/Config/Files/ConfigurationPublisher.php#L121-L146
train
stefangabos/Zebra_Session
Zebra_Session.php
Zebra_Session.stop
public function stop() { // if a cookie is used to pass the session id if (ini_get('session.use_cookies')) { // get session cookie's properties $params = session_get_cookie_params(); // unset the cookie setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'], $params['secure'], $params['httponly']); } // destroy the session session_unset(); session_destroy(); }
php
public function stop() { // if a cookie is used to pass the session id if (ini_get('session.use_cookies')) { // get session cookie's properties $params = session_get_cookie_params(); // unset the cookie setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'], $params['secure'], $params['httponly']); } // destroy the session session_unset(); session_destroy(); }
[ "public", "function", "stop", "(", ")", "{", "// if a cookie is used to pass the session id", "if", "(", "ini_get", "(", "'session.use_cookies'", ")", ")", "{", "// get session cookie's properties", "$", "params", "=", "session_get_cookie_params", "(", ")", ";", "// uns...
Deletes all data related to the session. <i>This method runs the garbage collector respecting your environment's garbage collector-related properties. Read {@link __construct() here} for more information.</i> <code> // first, connect to a database containing the sessions table // include the class require 'path/to/Zebra_Session.php'; // start the session // where $link is a connection link returned by mysqli_connect $session = new Zebra_Session($link, 'sEcUr1tY_c0dE'); // end current session $session->stop(); </code> @since 1.0.1 @return void
[ "Deletes", "all", "data", "related", "to", "the", "session", "." ]
3ab1b09353fc35c37603fa4264f89c963bf35545
https://github.com/stefangabos/Zebra_Session/blob/3ab1b09353fc35c37603fa4264f89c963bf35545/Zebra_Session.php#L630-L647
train
stefangabos/Zebra_Session
Zebra_Session.php
Zebra_Session._manage_flashdata
function _manage_flashdata() { // if there is flashdata to be handled if (!empty($this->flashdata)) { // iterate through all the entries foreach ($this->flashdata as $variable => $counter) { // increment counter representing server requests $this->flashdata[$variable]++; // if we're past the first server request if ($this->flashdata[$variable] > 1) { // unset the session variable unset($_SESSION[$variable]); // stop tracking unset($this->flashdata[$variable]); } } // if there is any flashdata left to be handled if (!empty($this->flashdata)) // store data in a temporary session variable $_SESSION[$this->flashdata_varname] = serialize($this->flashdata); } }
php
function _manage_flashdata() { // if there is flashdata to be handled if (!empty($this->flashdata)) { // iterate through all the entries foreach ($this->flashdata as $variable => $counter) { // increment counter representing server requests $this->flashdata[$variable]++; // if we're past the first server request if ($this->flashdata[$variable] > 1) { // unset the session variable unset($_SESSION[$variable]); // stop tracking unset($this->flashdata[$variable]); } } // if there is any flashdata left to be handled if (!empty($this->flashdata)) // store data in a temporary session variable $_SESSION[$this->flashdata_varname] = serialize($this->flashdata); } }
[ "function", "_manage_flashdata", "(", ")", "{", "// if there is flashdata to be handled", "if", "(", "!", "empty", "(", "$", "this", "->", "flashdata", ")", ")", "{", "// iterate through all the entries", "foreach", "(", "$", "this", "->", "flashdata", "as", "$", ...
Manages flashdata behind the scenes @access private
[ "Manages", "flashdata", "behind", "the", "scenes" ]
3ab1b09353fc35c37603fa4264f89c963bf35545
https://github.com/stefangabos/Zebra_Session/blob/3ab1b09353fc35c37603fa4264f89c963bf35545/Zebra_Session.php#L692-L724
train
stefangabos/Zebra_Session
Zebra_Session.php
Zebra_Session._mysql_query
private function _mysql_query($query) { // call "mysqli_query" $result = mysqli_query($this->link, $query); // stop if there was an error if (!$result) throw new Exception($this->_mysql_error()); // return the result if query was successful return $result; }
php
private function _mysql_query($query) { // call "mysqli_query" $result = mysqli_query($this->link, $query); // stop if there was an error if (!$result) throw new Exception($this->_mysql_error()); // return the result if query was successful return $result; }
[ "private", "function", "_mysql_query", "(", "$", "query", ")", "{", "// call \"mysqli_query\"", "$", "result", "=", "mysqli_query", "(", "$", "this", "->", "link", ",", "$", "query", ")", ";", "// stop if there was an error", "if", "(", "!", "$", "result", "...
Wrapper for PHP's "mysqli_query" function. @access private
[ "Wrapper", "for", "PHP", "s", "mysqli_query", "function", "." ]
3ab1b09353fc35c37603fa4264f89c963bf35545
https://github.com/stefangabos/Zebra_Session/blob/3ab1b09353fc35c37603fa4264f89c963bf35545/Zebra_Session.php#L755-L766
train
spatie/searchindex
src/SearchIndexHandlers/Elasticsearch.php
Elasticsearch.removeFromIndex
public function removeFromIndex(Searchable $subject, $indexName = null) { $indexName = $this->resolveIndexName($indexName); $this->elasticsearch->delete( [ 'index' => $indexName, 'type' => $subject->getSearchableType(), 'id' => $subject->getSearchableId(), ] ); }
php
public function removeFromIndex(Searchable $subject, $indexName = null) { $indexName = $this->resolveIndexName($indexName); $this->elasticsearch->delete( [ 'index' => $indexName, 'type' => $subject->getSearchableType(), 'id' => $subject->getSearchableId(), ] ); }
[ "public", "function", "removeFromIndex", "(", "Searchable", "$", "subject", ",", "$", "indexName", "=", "null", ")", "{", "$", "indexName", "=", "$", "this", "->", "resolveIndexName", "(", "$", "indexName", ")", ";", "$", "this", "->", "elasticsearch", "->...
Remove the given subject from the search index. @param Searchable $subject
[ "Remove", "the", "given", "subject", "from", "the", "search", "index", "." ]
44324c52696dcfcd9083fdbbb2641d4350449c2c
https://github.com/spatie/searchindex/blob/44324c52696dcfcd9083fdbbb2641d4350449c2c/src/SearchIndexHandlers/Elasticsearch.php#L92-L103
train
spatie/searchindex
src/SearchIndexHandlers/Elasticsearch.php
Elasticsearch.removeFromIndexByTypeAndId
public function removeFromIndexByTypeAndId($type, $id, $indexName = null) { $indexName = $this->resolveIndexName($indexName); $this->elasticsearch->delete( [ 'index' => $indexName, 'type' => $type, 'id' => $id, ] ); }
php
public function removeFromIndexByTypeAndId($type, $id, $indexName = null) { $indexName = $this->resolveIndexName($indexName); $this->elasticsearch->delete( [ 'index' => $indexName, 'type' => $type, 'id' => $id, ] ); }
[ "public", "function", "removeFromIndexByTypeAndId", "(", "$", "type", ",", "$", "id", ",", "$", "indexName", "=", "null", ")", "{", "$", "indexName", "=", "$", "this", "->", "resolveIndexName", "(", "$", "indexName", ")", ";", "$", "this", "->", "elastic...
Remove an item from the search index by type and id. @param string $type @param int $id
[ "Remove", "an", "item", "from", "the", "search", "index", "by", "type", "and", "id", "." ]
44324c52696dcfcd9083fdbbb2641d4350449c2c
https://github.com/spatie/searchindex/blob/44324c52696dcfcd9083fdbbb2641d4350449c2c/src/SearchIndexHandlers/Elasticsearch.php#L111-L122
train
spatie/searchindex
src/SearchIndexHandlers/Elasticsearch.php
Elasticsearch.clearIndex
public function clearIndex($indexName = null) { $indexName = $this->resolveIndexName($indexName); $this->elasticsearch->indices()->delete(['index' => $indexName]); }
php
public function clearIndex($indexName = null) { $indexName = $this->resolveIndexName($indexName); $this->elasticsearch->indices()->delete(['index' => $indexName]); }
[ "public", "function", "clearIndex", "(", "$", "indexName", "=", "null", ")", "{", "$", "indexName", "=", "$", "this", "->", "resolveIndexName", "(", "$", "indexName", ")", ";", "$", "this", "->", "elasticsearch", "->", "indices", "(", ")", "->", "delete"...
Remove everything from the index. @return mixed
[ "Remove", "everything", "from", "the", "index", "." ]
44324c52696dcfcd9083fdbbb2641d4350449c2c
https://github.com/spatie/searchindex/blob/44324c52696dcfcd9083fdbbb2641d4350449c2c/src/SearchIndexHandlers/Elasticsearch.php#L129-L134
train
spatie/searchindex
src/Query/Algolia/SearchQuery.php
SearchQuery.aroundLocation
public function aroundLocation($lat, $lng, $aroundRadius = 30000) { $this->lat = $lat; $this->lng = $lng; $this->aroundRadius = $aroundRadius; $this->useLocationAwareSearch = true; return $this; }
php
public function aroundLocation($lat, $lng, $aroundRadius = 30000) { $this->lat = $lat; $this->lng = $lng; $this->aroundRadius = $aroundRadius; $this->useLocationAwareSearch = true; return $this; }
[ "public", "function", "aroundLocation", "(", "$", "lat", ",", "$", "lng", ",", "$", "aroundRadius", "=", "30000", ")", "{", "$", "this", "->", "lat", "=", "$", "lat", ";", "$", "this", "->", "lng", "=", "$", "lng", ";", "$", "this", "->", "around...
Create a location aware search. @param int $lat @param int $lng @param int $aroundRadius @return $this
[ "Create", "a", "location", "aware", "search", "." ]
44324c52696dcfcd9083fdbbb2641d4350449c2c
https://github.com/spatie/searchindex/blob/44324c52696dcfcd9083fdbbb2641d4350449c2c/src/Query/Algolia/SearchQuery.php#L62-L70
train
spatie/searchindex
src/Query/Algolia/SearchQuery.php
SearchQuery.withNumericFilter
public function withNumericFilter($name, $values, $logicalOperator = 'and') { if (!is_array($values)) { $values = [$values]; } $numericalFilterArray = array_map(function ($value) use ($name) { return "{$name}={$value}"; }, $values); $numericalFilter = implode(',', $numericalFilterArray); if ($logicalOperator == self::LOGICAL_OPERATOR_OR) { $numericalFilter = "({$numericalFilter})"; } $this->numericFilters[] = $numericalFilter; return $this; }
php
public function withNumericFilter($name, $values, $logicalOperator = 'and') { if (!is_array($values)) { $values = [$values]; } $numericalFilterArray = array_map(function ($value) use ($name) { return "{$name}={$value}"; }, $values); $numericalFilter = implode(',', $numericalFilterArray); if ($logicalOperator == self::LOGICAL_OPERATOR_OR) { $numericalFilter = "({$numericalFilter})"; } $this->numericFilters[] = $numericalFilter; return $this; }
[ "public", "function", "withNumericFilter", "(", "$", "name", ",", "$", "values", ",", "$", "logicalOperator", "=", "'and'", ")", "{", "if", "(", "!", "is_array", "(", "$", "values", ")", ")", "{", "$", "values", "=", "[", "$", "values", "]", ";", "...
Set a numeric filter. @param string $name @param string|array $values @param string $logicalOperator @return $this
[ "Set", "a", "numeric", "filter", "." ]
44324c52696dcfcd9083fdbbb2641d4350449c2c
https://github.com/spatie/searchindex/blob/44324c52696dcfcd9083fdbbb2641d4350449c2c/src/Query/Algolia/SearchQuery.php#L136-L155
train
spatie/searchindex
src/Query/Algolia/SearchQuery.php
SearchQuery.toArray
public function toArray() { $query = [ 'numericFilters' => '', 'facetFilters' => '', ]; if ($this->query != '') { $query['query'] = $this->query; } if ($this->useLocationAwareSearch) { $query['aroundLatLng'] = $this->lat.','.$this->lng; $query['aroundRadius'] = $this->aroundRadius; } foreach ($this->dateRestrictions as $dateRestriction) { $query['numericFilters'] .= ','. $dateRestriction['dateFieldName']. $dateRestriction['operation']. $dateRestriction['date']->getTimeStamp(); } foreach ($this->numericFilters as $filter) { $query['numericFilters'] .= ','.$filter; } foreach ($this->facets as $facet) { $query['facetFilters'] .= ','.$facet; } $query['page'] = $this->page; $query['hitsPerPage'] = $this->hitsPerPage; return $query; }
php
public function toArray() { $query = [ 'numericFilters' => '', 'facetFilters' => '', ]; if ($this->query != '') { $query['query'] = $this->query; } if ($this->useLocationAwareSearch) { $query['aroundLatLng'] = $this->lat.','.$this->lng; $query['aroundRadius'] = $this->aroundRadius; } foreach ($this->dateRestrictions as $dateRestriction) { $query['numericFilters'] .= ','. $dateRestriction['dateFieldName']. $dateRestriction['operation']. $dateRestriction['date']->getTimeStamp(); } foreach ($this->numericFilters as $filter) { $query['numericFilters'] .= ','.$filter; } foreach ($this->facets as $facet) { $query['facetFilters'] .= ','.$facet; } $query['page'] = $this->page; $query['hitsPerPage'] = $this->hitsPerPage; return $query; }
[ "public", "function", "toArray", "(", ")", "{", "$", "query", "=", "[", "'numericFilters'", "=>", "''", ",", "'facetFilters'", "=>", "''", ",", "]", ";", "if", "(", "$", "this", "->", "query", "!=", "''", ")", "{", "$", "query", "[", "'query'", "]"...
Get the query as an array. @return array
[ "Get", "the", "query", "as", "an", "array", "." ]
44324c52696dcfcd9083fdbbb2641d4350449c2c
https://github.com/spatie/searchindex/blob/44324c52696dcfcd9083fdbbb2641d4350449c2c/src/Query/Algolia/SearchQuery.php#L162-L197
train
spatie/searchindex
src/SearchIndexHandlers/Algolia.php
Algolia.getResults
public function getResults($query) { $parameters = []; if (is_object($query) && $query instanceof SearchQuery) { $query = $query->toArray(); } if (is_array($query)) { $collection = new Collection($query); $query = $collection->pull('query', ''); $parameters = $collection->toArray(); } return $this->index->search($query, $parameters); }
php
public function getResults($query) { $parameters = []; if (is_object($query) && $query instanceof SearchQuery) { $query = $query->toArray(); } if (is_array($query)) { $collection = new Collection($query); $query = $collection->pull('query', ''); $parameters = $collection->toArray(); } return $this->index->search($query, $parameters); }
[ "public", "function", "getResults", "(", "$", "query", ")", "{", "$", "parameters", "=", "[", "]", ";", "if", "(", "is_object", "(", "$", "query", ")", "&&", "$", "query", "instanceof", "SearchQuery", ")", "{", "$", "query", "=", "$", "query", "->", ...
Get the results for the given query. @param string|array|\Spatie\SearchIndex\Query\Algolia\SearchQuery $query @return mixed
[ "Get", "the", "results", "for", "the", "given", "query", "." ]
44324c52696dcfcd9083fdbbb2641d4350449c2c
https://github.com/spatie/searchindex/blob/44324c52696dcfcd9083fdbbb2641d4350449c2c/src/SearchIndexHandlers/Algolia.php#L112-L129
train
phpactor/phpactor
lib/Phpactor.php
Phpactor.normalizePath
public static function normalizePath(string $path): string { if (substr($path, 0, 1) == DIRECTORY_SEPARATOR) { return $path; } return getcwd().DIRECTORY_SEPARATOR.$path; }
php
public static function normalizePath(string $path): string { if (substr($path, 0, 1) == DIRECTORY_SEPARATOR) { return $path; } return getcwd().DIRECTORY_SEPARATOR.$path; }
[ "public", "static", "function", "normalizePath", "(", "string", "$", "path", ")", ":", "string", "{", "if", "(", "substr", "(", "$", "path", ",", "0", ",", "1", ")", "==", "DIRECTORY_SEPARATOR", ")", "{", "return", "$", "path", ";", "}", "return", "g...
If the path is relative we need to use the current working path because otherwise it will be the script path, which is wrong in the context of a PHAR. @deprecated Use webmozart Path instead. @param string $path @return string
[ "If", "the", "path", "is", "relative", "we", "need", "to", "use", "the", "current", "working", "path", "because", "otherwise", "it", "will", "be", "the", "script", "path", "which", "is", "wrong", "in", "the", "context", "of", "a", "PHAR", "." ]
7db7a5c56ef66c288597eba7acb5ae28a7d24d60
https://github.com/phpactor/phpactor/blob/7db7a5c56ef66c288597eba7acb5ae28a7d24d60/lib/Phpactor.php#L154-L161
train
Beaten-Sect0r/yii2-db-manager
src/Module.php
Module.getDbInfo
public function getDbInfo($db) { $info = ArrayHelper::getValue($this->dbInfo, $db, null); if (!$info) { throw new UserException('Database with name ' . $db . ' not configured for dump.'); } return $info; }
php
public function getDbInfo($db) { $info = ArrayHelper::getValue($this->dbInfo, $db, null); if (!$info) { throw new UserException('Database with name ' . $db . ' not configured for dump.'); } return $info; }
[ "public", "function", "getDbInfo", "(", "$", "db", ")", "{", "$", "info", "=", "ArrayHelper", "::", "getValue", "(", "$", "this", "->", "dbInfo", ",", "$", "db", ",", "null", ")", ";", "if", "(", "!", "$", "info", ")", "{", "throw", "new", "UserE...
Get info for selected database. @param $db @return array @throws UserException
[ "Get", "info", "for", "selected", "database", "." ]
56c512f8b23b65f956093c26e97d49d1a558bcc6
https://github.com/Beaten-Sect0r/yii2-db-manager/blob/56c512f8b23b65f956093c26e97d49d1a558bcc6/src/Module.php#L139-L147
train
Beaten-Sect0r/yii2-db-manager
src/commands/DumpController.php
DumpController.actionCreate
public function actionCreate() { $model = new Dump($this->getModule()->dbList); if (ArrayHelper::isIn($this->db, $this->getModule()->dbList)) { $dbInfo = $this->getModule()->getDbInfo($this->db); $dumpOptions = $model->makeDumpOptions(); if ($this->gzip) { $dumpOptions['isArchive'] = true; } $manager = $this->getModule()->createManager($dbInfo); $dumpPath = $manager->makePath($this->getModule()->path, $dbInfo, $dumpOptions); $dumpCommand = $manager->makeDumpCommand($dumpPath, $dbInfo, $dumpOptions); Yii::trace(compact('dumpCommand', 'dumpPath', 'dumpOptions'), get_called_class()); $process = new Process($dumpCommand); $process->run(); if ($process->isSuccessful()) { if ($this->storage) { if (Yii::$app->has('backupStorage')) { $dumpText = fopen($dumpPath, 'r+'); Yii::$app->backupStorage->writeStream(StringHelper::basename($dumpPath), $dumpText); fclose($dumpText); } else { Console::output('Storage component is not configured.'); } } Console::output('Dump successfully created.'); } else { Console::output('Dump failed create.'); } } else { Console::output('Database configuration not found.'); } }
php
public function actionCreate() { $model = new Dump($this->getModule()->dbList); if (ArrayHelper::isIn($this->db, $this->getModule()->dbList)) { $dbInfo = $this->getModule()->getDbInfo($this->db); $dumpOptions = $model->makeDumpOptions(); if ($this->gzip) { $dumpOptions['isArchive'] = true; } $manager = $this->getModule()->createManager($dbInfo); $dumpPath = $manager->makePath($this->getModule()->path, $dbInfo, $dumpOptions); $dumpCommand = $manager->makeDumpCommand($dumpPath, $dbInfo, $dumpOptions); Yii::trace(compact('dumpCommand', 'dumpPath', 'dumpOptions'), get_called_class()); $process = new Process($dumpCommand); $process->run(); if ($process->isSuccessful()) { if ($this->storage) { if (Yii::$app->has('backupStorage')) { $dumpText = fopen($dumpPath, 'r+'); Yii::$app->backupStorage->writeStream(StringHelper::basename($dumpPath), $dumpText); fclose($dumpText); } else { Console::output('Storage component is not configured.'); } } Console::output('Dump successfully created.'); } else { Console::output('Dump failed create.'); } } else { Console::output('Database configuration not found.'); } }
[ "public", "function", "actionCreate", "(", ")", "{", "$", "model", "=", "new", "Dump", "(", "$", "this", "->", "getModule", "(", ")", "->", "dbList", ")", ";", "if", "(", "ArrayHelper", "::", "isIn", "(", "$", "this", "->", "db", ",", "$", "this", ...
Create database dump.
[ "Create", "database", "dump", "." ]
56c512f8b23b65f956093c26e97d49d1a558bcc6
https://github.com/Beaten-Sect0r/yii2-db-manager/blob/56c512f8b23b65f956093c26e97d49d1a558bcc6/src/commands/DumpController.php#L60-L92
train
Beaten-Sect0r/yii2-db-manager
src/commands/DumpController.php
DumpController.actionDeleteAll
public function actionDeleteAll() { Console::output('Do you want to delete all dumps? [yes|no]'); $answer = trim(fgets(STDIN)); if (!strncasecmp($answer, 'y', 1)) { if (!empty($this->getModule()->getFileList())) { $fail = []; foreach ($this->getModule()->getFileList() as $file) { if (!unlink($file)) { $fail[] = $file; } } if (empty($fail)) { Console::output('All dumps successfully removed.'); } else { Console::output('Error deleting dumps.'); } } } }
php
public function actionDeleteAll() { Console::output('Do you want to delete all dumps? [yes|no]'); $answer = trim(fgets(STDIN)); if (!strncasecmp($answer, 'y', 1)) { if (!empty($this->getModule()->getFileList())) { $fail = []; foreach ($this->getModule()->getFileList() as $file) { if (!unlink($file)) { $fail[] = $file; } } if (empty($fail)) { Console::output('All dumps successfully removed.'); } else { Console::output('Error deleting dumps.'); } } } }
[ "public", "function", "actionDeleteAll", "(", ")", "{", "Console", "::", "output", "(", "'Do you want to delete all dumps? [yes|no]'", ")", ";", "$", "answer", "=", "trim", "(", "fgets", "(", "STDIN", ")", ")", ";", "if", "(", "!", "strncasecmp", "(", "$", ...
Deleting all dumps.
[ "Deleting", "all", "dumps", "." ]
56c512f8b23b65f956093c26e97d49d1a558bcc6
https://github.com/Beaten-Sect0r/yii2-db-manager/blob/56c512f8b23b65f956093c26e97d49d1a558bcc6/src/commands/DumpController.php#L172-L191
train
coduo/php-matcher
src/Parser.php
Parser.getNextExpanderNode
private function getNextExpanderNode() { if ($this->endOfPattern()) { return ; } $expander = new AST\Expander($this->getExpanderName()); if ($this->endOfPattern()) { $this->unexpectedEndOfString(')'); } $this->addArgumentValues($expander); if ($this->endOfPattern()) { $this->unexpectedEndOfString(')'); } if (!$this->isNextCloseParenthesis()) { $this->unexpectedSyntaxError($this->lexer->lookahead, ')'); } return $expander; }
php
private function getNextExpanderNode() { if ($this->endOfPattern()) { return ; } $expander = new AST\Expander($this->getExpanderName()); if ($this->endOfPattern()) { $this->unexpectedEndOfString(')'); } $this->addArgumentValues($expander); if ($this->endOfPattern()) { $this->unexpectedEndOfString(')'); } if (!$this->isNextCloseParenthesis()) { $this->unexpectedSyntaxError($this->lexer->lookahead, ')'); } return $expander; }
[ "private", "function", "getNextExpanderNode", "(", ")", "{", "if", "(", "$", "this", "->", "endOfPattern", "(", ")", ")", "{", "return", ";", "}", "$", "expander", "=", "new", "AST", "\\", "Expander", "(", "$", "this", "->", "getExpanderName", "(", ")"...
Try to get next expander, return null if there is no expander left @return AST\Expander|null
[ "Try", "to", "get", "next", "expander", "return", "null", "if", "there", "is", "no", "expander", "left" ]
5ff1924e6362406508006300408ef0aa2f3903ac
https://github.com/coduo/php-matcher/blob/5ff1924e6362406508006300408ef0aa2f3903ac/src/Parser.php#L91-L114
train
coduo/php-matcher
src/Parser.php
Parser.addArgumentValues
private function addArgumentValues(AST\Expander $expander) { while (($argument = $this->getNextArgumentValue()) !== null) { $argument = ($argument === self::NULL_VALUE) ? null : $argument; $expander->addArgument($argument); if (!$this->lexer->isNextToken(Lexer::T_COMMA)) { break; } $this->lexer->moveNext(); if ($this->lexer->isNextToken(Lexer::T_CLOSE_PARENTHESIS)) { $this->unexpectedSyntaxError($this->lexer->lookahead, 'string, number, boolean or null argument'); } } }
php
private function addArgumentValues(AST\Expander $expander) { while (($argument = $this->getNextArgumentValue()) !== null) { $argument = ($argument === self::NULL_VALUE) ? null : $argument; $expander->addArgument($argument); if (!$this->lexer->isNextToken(Lexer::T_COMMA)) { break; } $this->lexer->moveNext(); if ($this->lexer->isNextToken(Lexer::T_CLOSE_PARENTHESIS)) { $this->unexpectedSyntaxError($this->lexer->lookahead, 'string, number, boolean or null argument'); } } }
[ "private", "function", "addArgumentValues", "(", "AST", "\\", "Expander", "$", "expander", ")", "{", "while", "(", "(", "$", "argument", "=", "$", "this", "->", "getNextArgumentValue", "(", ")", ")", "!==", "null", ")", "{", "$", "argument", "=", "(", ...
Add arguments to expander @param AST\Expander $expander
[ "Add", "arguments", "to", "expander" ]
5ff1924e6362406508006300408ef0aa2f3903ac
https://github.com/coduo/php-matcher/blob/5ff1924e6362406508006300408ef0aa2f3903ac/src/Parser.php#L132-L147
train
coduo/php-matcher
src/Parser.php
Parser.getNextArgumentValue
private function getNextArgumentValue() { $validArgumentTypes = [ Lexer::T_STRING, Lexer::T_NUMBER, Lexer::T_BOOLEAN, Lexer::T_NULL ]; if ($this->lexer->isNextToken(Lexer::T_CLOSE_PARENTHESIS)) { return ; } if ($this->lexer->isNextToken(Lexer::T_OPEN_CURLY_BRACE)) { return $this->getArrayArgument(); } if ($this->lexer->isNextToken(Lexer::T_EXPANDER_NAME)) { return $this->getNextExpanderNode(); } if (!$this->lexer->isNextTokenAny($validArgumentTypes)) { $this->unexpectedSyntaxError($this->lexer->lookahead, 'string, number, boolean or null argument'); } $tokenType = $this->lexer->lookahead['type']; $argument = $this->lexer->lookahead['value']; $this->lexer->moveNext(); if ($tokenType === Lexer::T_NULL) { $argument = self::NULL_VALUE; } return $argument; }
php
private function getNextArgumentValue() { $validArgumentTypes = [ Lexer::T_STRING, Lexer::T_NUMBER, Lexer::T_BOOLEAN, Lexer::T_NULL ]; if ($this->lexer->isNextToken(Lexer::T_CLOSE_PARENTHESIS)) { return ; } if ($this->lexer->isNextToken(Lexer::T_OPEN_CURLY_BRACE)) { return $this->getArrayArgument(); } if ($this->lexer->isNextToken(Lexer::T_EXPANDER_NAME)) { return $this->getNextExpanderNode(); } if (!$this->lexer->isNextTokenAny($validArgumentTypes)) { $this->unexpectedSyntaxError($this->lexer->lookahead, 'string, number, boolean or null argument'); } $tokenType = $this->lexer->lookahead['type']; $argument = $this->lexer->lookahead['value']; $this->lexer->moveNext(); if ($tokenType === Lexer::T_NULL) { $argument = self::NULL_VALUE; } return $argument; }
[ "private", "function", "getNextArgumentValue", "(", ")", "{", "$", "validArgumentTypes", "=", "[", "Lexer", "::", "T_STRING", ",", "Lexer", "::", "T_NUMBER", ",", "Lexer", "::", "T_BOOLEAN", ",", "Lexer", "::", "T_NULL", "]", ";", "if", "(", "$", "this", ...
Try to get next argument. Return false if there are no arguments left before ")" @return null|mixed
[ "Try", "to", "get", "next", "argument", ".", "Return", "false", "if", "there", "are", "no", "arguments", "left", "before", ")" ]
5ff1924e6362406508006300408ef0aa2f3903ac
https://github.com/coduo/php-matcher/blob/5ff1924e6362406508006300408ef0aa2f3903ac/src/Parser.php#L154-L188
train
maglnet/ComposerRequireChecker
src/ComposerRequireChecker/FileLocator/LocateComposerPackageDirectDependenciesSourceFiles.php
LocateComposerPackageDirectDependenciesSourceFiles.getInstalledPackages
private function getInstalledPackages(string $vendorDir): array { try { $installedData = (new JsonLoader($vendorDir . '/composer/installed.json'))->getData(); } catch (NotReadableException $e) { $message = 'The composer dependencies have not been installed, run composer install/update first'; throw new DependenciesNotInstalledException($message); } $installedPackages = []; $packages = $installedData['packages'] ?? $installedData; foreach ($packages as $vendorJson) { $vendorName = $vendorJson['name']; $installedPackages[$vendorName] = $vendorJson; } return $installedPackages; }
php
private function getInstalledPackages(string $vendorDir): array { try { $installedData = (new JsonLoader($vendorDir . '/composer/installed.json'))->getData(); } catch (NotReadableException $e) { $message = 'The composer dependencies have not been installed, run composer install/update first'; throw new DependenciesNotInstalledException($message); } $installedPackages = []; $packages = $installedData['packages'] ?? $installedData; foreach ($packages as $vendorJson) { $vendorName = $vendorJson['name']; $installedPackages[$vendorName] = $vendorJson; } return $installedPackages; }
[ "private", "function", "getInstalledPackages", "(", "string", "$", "vendorDir", ")", ":", "array", "{", "try", "{", "$", "installedData", "=", "(", "new", "JsonLoader", "(", "$", "vendorDir", ".", "'/composer/installed.json'", ")", ")", "->", "getData", "(", ...
Lookup each vendor package's composer.json info from installed.json @param string $vendorDir @return array Keys are the package name and value is the composer.json as an array @throws DependenciesNotInstalledException When composer install/update has not been run
[ "Lookup", "each", "vendor", "package", "s", "composer", ".", "json", "info", "from", "installed", ".", "json" ]
1554ea89dae55e8fac7365120b58571d38ca6cf3
https://github.com/maglnet/ComposerRequireChecker/blob/1554ea89dae55e8fac7365120b58571d38ca6cf3/src/ComposerRequireChecker/FileLocator/LocateComposerPackageDirectDependenciesSourceFiles.php#L46-L64
train
nystudio107/craft-typogrify
src/variables/TypogrifyVariable.php
TypogrifyVariable.normalizeText
private function normalizeText($text): string { /* @TODO: try to resolve at a later date; Twig's `| raw` just returns a string, not `Markup` so we can't use that as a check if ($text instanceof Markup) { // Either came from a Redactor field (or the like) or they manually added a |raw tag. We can trust it $text = (string)$text; } else { // We don't trust it, so escape any HTML $twig = Craft::$app->view->twig; try { $text = twig_escape_filter($twig, $text); } catch (\Twig_Error_Runtime $e) { $error = $e->getMessage(); Craft::error($error, __METHOD__); // We don't want unescaped text slipping through, so set the text to the error message $text = $error; } } */ // If it's null or otherwise empty, just return an empty string if (empty($text)) { $text = ''; } $text = (string)$text; $settings = Typogrify::$plugin->getSettings(); if ($settings['default_escape'] === true) { $twig = Craft::$app->view->twig; $text = twig_escape_filter($twig, $text); } return $text; }
php
private function normalizeText($text): string { /* @TODO: try to resolve at a later date; Twig's `| raw` just returns a string, not `Markup` so we can't use that as a check if ($text instanceof Markup) { // Either came from a Redactor field (or the like) or they manually added a |raw tag. We can trust it $text = (string)$text; } else { // We don't trust it, so escape any HTML $twig = Craft::$app->view->twig; try { $text = twig_escape_filter($twig, $text); } catch (\Twig_Error_Runtime $e) { $error = $e->getMessage(); Craft::error($error, __METHOD__); // We don't want unescaped text slipping through, so set the text to the error message $text = $error; } } */ // If it's null or otherwise empty, just return an empty string if (empty($text)) { $text = ''; } $text = (string)$text; $settings = Typogrify::$plugin->getSettings(); if ($settings['default_escape'] === true) { $twig = Craft::$app->view->twig; $text = twig_escape_filter($twig, $text); } return $text; }
[ "private", "function", "normalizeText", "(", "$", "text", ")", ":", "string", "{", "/* @TODO: try to resolve at a later date; Twig's `| raw` just returns a string, not `Markup` so we can't use that as a check\n if ($text instanceof Markup) {\n // Either came from a Redactor fie...
Normalize the passed in text to ensure that untrusted strings are escaped @param $text @return string
[ "Normalize", "the", "passed", "in", "text", "to", "ensure", "that", "untrusted", "strings", "are", "escaped" ]
ca3df19a42d74fd6e3e523edf330b98eb032ae60
https://github.com/nystudio107/craft-typogrify/blob/ca3df19a42d74fd6e3e523edf330b98eb032ae60/src/variables/TypogrifyVariable.php#L283-L316
train
nystudio107/craft-twigpack
src/services/Manifest.php
Manifest.getCssModuleTags
public function getCssModuleTags(string $moduleName, bool $async = false, $config = null): string { $settings = Twigpack::$plugin->getSettings(); $config = $config ?? $settings->getAttributes(); return ManifestHelper::getCssModuleTags($config, $moduleName, $async); }
php
public function getCssModuleTags(string $moduleName, bool $async = false, $config = null): string { $settings = Twigpack::$plugin->getSettings(); $config = $config ?? $settings->getAttributes(); return ManifestHelper::getCssModuleTags($config, $moduleName, $async); }
[ "public", "function", "getCssModuleTags", "(", "string", "$", "moduleName", ",", "bool", "$", "async", "=", "false", ",", "$", "config", "=", "null", ")", ":", "string", "{", "$", "settings", "=", "Twigpack", "::", "$", "plugin", "->", "getSettings", "("...
Return the HTML tags to include the CSS @param string $moduleName @param bool $async @param null|array $config @return string @throws \yii\web\NotFoundHttpException
[ "Return", "the", "HTML", "tags", "to", "include", "the", "CSS" ]
1bf0aa6b6c0787347259be0b96b1553ac5d5375e
https://github.com/nystudio107/craft-twigpack/blob/1bf0aa6b6c0787347259be0b96b1553ac5d5375e/src/services/Manifest.php#L41-L47
train
nystudio107/craft-twigpack
src/Twigpack.php
Twigpack.installEventListeners
protected function installEventListeners() { // Remember the name of the currently rendering template // Handler: View::EVENT_BEFORE_RENDER_PAGE_TEMPLATE Event::on( View::class, View::EVENT_BEFORE_RENDER_PAGE_TEMPLATE, function (TemplateEvent $event) { self::$templateName = $event->template; } ); // Handler: CraftVariable::EVENT_INIT Event::on( CraftVariable::class, CraftVariable::EVENT_INIT, function (Event $event) { /** @var CraftVariable $variable */ $variable = $event->sender; $variable->set('twigpack', ManifestVariable::class); } ); // Handler: TemplateCaches::EVENT_AFTER_DELETE_CACHES Event::on( TemplateCaches::class, TemplateCaches::EVENT_AFTER_DELETE_CACHES, function (DeleteTemplateCachesEvent $event) { // Invalidate the caches when template caches are deleted $this->clearAllCaches(); } ); // Handler: Plugins::EVENT_AFTER_INSTALL_PLUGIN Event::on( Plugins::class, Plugins::EVENT_AFTER_INSTALL_PLUGIN, function (PluginEvent $event) { if ($event->plugin === $this) { // Invalidate our caches after we've been installed $this->clearAllCaches(); } } ); // Handler: ClearCaches::EVENT_REGISTER_CACHE_OPTIONS Event::on( ClearCaches::class, ClearCaches::EVENT_REGISTER_CACHE_OPTIONS, function (RegisterCacheOptionsEvent $event) { Craft::debug( 'ClearCaches::EVENT_REGISTER_CACHE_OPTIONS', __METHOD__ ); // Register our caches for the Clear Cache Utility $event->options = array_merge( $event->options, $this->customAdminCpCacheOptions() ); } ); // delay attaching event handler to the view component after it is fully configured $app = Craft::$app; if ($app->getConfig()->getGeneral()->devMode) { $app->on(Application::EVENT_BEFORE_REQUEST, function () use ($app) { $app->getView()->on(View::EVENT_END_BODY, [$this, 'injectErrorEntry']); }); } }
php
protected function installEventListeners() { // Remember the name of the currently rendering template // Handler: View::EVENT_BEFORE_RENDER_PAGE_TEMPLATE Event::on( View::class, View::EVENT_BEFORE_RENDER_PAGE_TEMPLATE, function (TemplateEvent $event) { self::$templateName = $event->template; } ); // Handler: CraftVariable::EVENT_INIT Event::on( CraftVariable::class, CraftVariable::EVENT_INIT, function (Event $event) { /** @var CraftVariable $variable */ $variable = $event->sender; $variable->set('twigpack', ManifestVariable::class); } ); // Handler: TemplateCaches::EVENT_AFTER_DELETE_CACHES Event::on( TemplateCaches::class, TemplateCaches::EVENT_AFTER_DELETE_CACHES, function (DeleteTemplateCachesEvent $event) { // Invalidate the caches when template caches are deleted $this->clearAllCaches(); } ); // Handler: Plugins::EVENT_AFTER_INSTALL_PLUGIN Event::on( Plugins::class, Plugins::EVENT_AFTER_INSTALL_PLUGIN, function (PluginEvent $event) { if ($event->plugin === $this) { // Invalidate our caches after we've been installed $this->clearAllCaches(); } } ); // Handler: ClearCaches::EVENT_REGISTER_CACHE_OPTIONS Event::on( ClearCaches::class, ClearCaches::EVENT_REGISTER_CACHE_OPTIONS, function (RegisterCacheOptionsEvent $event) { Craft::debug( 'ClearCaches::EVENT_REGISTER_CACHE_OPTIONS', __METHOD__ ); // Register our caches for the Clear Cache Utility $event->options = array_merge( $event->options, $this->customAdminCpCacheOptions() ); } ); // delay attaching event handler to the view component after it is fully configured $app = Craft::$app; if ($app->getConfig()->getGeneral()->devMode) { $app->on(Application::EVENT_BEFORE_REQUEST, function () use ($app) { $app->getView()->on(View::EVENT_END_BODY, [$this, 'injectErrorEntry']); }); } }
[ "protected", "function", "installEventListeners", "(", ")", "{", "// Remember the name of the currently rendering template", "// Handler: View::EVENT_BEFORE_RENDER_PAGE_TEMPLATE", "Event", "::", "on", "(", "View", "::", "class", ",", "View", "::", "EVENT_BEFORE_RENDER_PAGE_TEMPLA...
Install our event listeners.
[ "Install", "our", "event", "listeners", "." ]
1bf0aa6b6c0787347259be0b96b1553ac5d5375e
https://github.com/nystudio107/craft-twigpack/blob/1bf0aa6b6c0787347259be0b96b1553ac5d5375e/src/Twigpack.php#L103-L167
train
nystudio107/craft-twigpack
src/Twigpack.php
Twigpack.injectErrorEntry
public function injectErrorEntry() { if (Craft::$app->getResponse()->isServerError || Craft::$app->getResponse()->isClientError) { $settings = self::$plugin->getSettings(); if (!empty($settings->errorEntry) && $settings->useDevServer) { try { $tags = self::$plugin->manifest->getJsModuleTags($settings->errorEntry, false); if ($tags !== null) { echo $tags; } } catch (NotFoundHttpException $e) { // That's okay, Twigpack will have already logged the error } } } }
php
public function injectErrorEntry() { if (Craft::$app->getResponse()->isServerError || Craft::$app->getResponse()->isClientError) { $settings = self::$plugin->getSettings(); if (!empty($settings->errorEntry) && $settings->useDevServer) { try { $tags = self::$plugin->manifest->getJsModuleTags($settings->errorEntry, false); if ($tags !== null) { echo $tags; } } catch (NotFoundHttpException $e) { // That's okay, Twigpack will have already logged the error } } } }
[ "public", "function", "injectErrorEntry", "(", ")", "{", "if", "(", "Craft", "::", "$", "app", "->", "getResponse", "(", ")", "->", "isServerError", "||", "Craft", "::", "$", "app", "->", "getResponse", "(", ")", "->", "isClientError", ")", "{", "$", "...
Inject the error entry point JavaScript for auto-reloading of Twig error pages
[ "Inject", "the", "error", "entry", "point", "JavaScript", "for", "auto", "-", "reloading", "of", "Twig", "error", "pages" ]
1bf0aa6b6c0787347259be0b96b1553ac5d5375e
https://github.com/nystudio107/craft-twigpack/blob/1bf0aa6b6c0787347259be0b96b1553ac5d5375e/src/Twigpack.php#L172-L187
train
nystudio107/craft-twigpack
src/helpers/Manifest.php
Manifest.getModuleEntry
public static function getModuleEntry(array $config, string $moduleName, string $type = 'modern', bool $soft = false) { $module = null; // Get the manifest file $manifest = self::getManifestFile($config, $type); if ($manifest !== null) { // Make sure it exists in the manifest if (empty($manifest[$moduleName])) { self::reportError(Craft::t( 'twigpack', 'Module does not exist in the manifest: {moduleName}', ['moduleName' => $moduleName] ), $soft); return null; } $module = $manifest[$moduleName]; } return $module; }
php
public static function getModuleEntry(array $config, string $moduleName, string $type = 'modern', bool $soft = false) { $module = null; // Get the manifest file $manifest = self::getManifestFile($config, $type); if ($manifest !== null) { // Make sure it exists in the manifest if (empty($manifest[$moduleName])) { self::reportError(Craft::t( 'twigpack', 'Module does not exist in the manifest: {moduleName}', ['moduleName' => $moduleName] ), $soft); return null; } $module = $manifest[$moduleName]; } return $module; }
[ "public", "static", "function", "getModuleEntry", "(", "array", "$", "config", ",", "string", "$", "moduleName", ",", "string", "$", "type", "=", "'modern'", ",", "bool", "$", "soft", "=", "false", ")", "{", "$", "module", "=", "null", ";", "// Get the m...
Return a module's raw entry from the manifest @param array $config @param string $moduleName @param string $type @param bool $soft @return null|string @throws NotFoundHttpException
[ "Return", "a", "module", "s", "raw", "entry", "from", "the", "manifest" ]
1bf0aa6b6c0787347259be0b96b1553ac5d5375e
https://github.com/nystudio107/craft-twigpack/blob/1bf0aa6b6c0787347259be0b96b1553ac5d5375e/src/helpers/Manifest.php#L256-L276
train
nystudio107/craft-twigpack
src/helpers/Manifest.php
Manifest.getManifestFile
public static function getManifestFile(array $config, string $type = 'modern') { $manifest = null; // Determine whether we should use the devServer for HMR or not $devMode = Craft::$app->getConfig()->getGeneral()->devMode; self::$isHot = ($devMode && $config['useDevServer']); // Try to get the manifest while ($manifest === null) { $manifestPath = self::$isHot ? $config['devServer']['manifestPath'] : $config['server']['manifestPath']; // Normalize the path $path = self::combinePaths($manifestPath, $config['manifest'][$type]); $manifest = self::getJsonFile($path); // If the manifest isn't found, and it was hot, fall back on non-hot if ($manifest === null) { // We couldn't find a manifest; throw an error self::reportError(Craft::t( 'twigpack', 'Manifest file not found at: {manifestPath}', ['manifestPath' => $manifestPath] ), true); if (self::$isHot) { // Try again, but not with home module replacement self::$isHot = false; } else { // Give up and return null return null; } } } return $manifest; }
php
public static function getManifestFile(array $config, string $type = 'modern') { $manifest = null; // Determine whether we should use the devServer for HMR or not $devMode = Craft::$app->getConfig()->getGeneral()->devMode; self::$isHot = ($devMode && $config['useDevServer']); // Try to get the manifest while ($manifest === null) { $manifestPath = self::$isHot ? $config['devServer']['manifestPath'] : $config['server']['manifestPath']; // Normalize the path $path = self::combinePaths($manifestPath, $config['manifest'][$type]); $manifest = self::getJsonFile($path); // If the manifest isn't found, and it was hot, fall back on non-hot if ($manifest === null) { // We couldn't find a manifest; throw an error self::reportError(Craft::t( 'twigpack', 'Manifest file not found at: {manifestPath}', ['manifestPath' => $manifestPath] ), true); if (self::$isHot) { // Try again, but not with home module replacement self::$isHot = false; } else { // Give up and return null return null; } } } return $manifest; }
[ "public", "static", "function", "getManifestFile", "(", "array", "$", "config", ",", "string", "$", "type", "=", "'modern'", ")", "{", "$", "manifest", "=", "null", ";", "// Determine whether we should use the devServer for HMR or not", "$", "devMode", "=", "Craft",...
Return a JSON-decoded manifest file @param array $config @param string $type @return null|array @throws NotFoundHttpException
[ "Return", "a", "JSON", "-", "decoded", "manifest", "file" ]
1bf0aa6b6c0787347259be0b96b1553ac5d5375e
https://github.com/nystudio107/craft-twigpack/blob/1bf0aa6b6c0787347259be0b96b1553ac5d5375e/src/helpers/Manifest.php#L287-L320
train
nystudio107/craft-twigpack
src/helpers/Manifest.php
Manifest.invalidateCaches
public static function invalidateCaches() { $cache = Craft::$app->getCache(); TagDependency::invalidate($cache, self::CACHE_TAG); Craft::info('All manifest caches cleared', __METHOD__); }
php
public static function invalidateCaches() { $cache = Craft::$app->getCache(); TagDependency::invalidate($cache, self::CACHE_TAG); Craft::info('All manifest caches cleared', __METHOD__); }
[ "public", "static", "function", "invalidateCaches", "(", ")", "{", "$", "cache", "=", "Craft", "::", "$", "app", "->", "getCache", "(", ")", ";", "TagDependency", "::", "invalidate", "(", "$", "cache", ",", "self", "::", "CACHE_TAG", ")", ";", "Craft", ...
Invalidate all of the manifest caches
[ "Invalidate", "all", "of", "the", "manifest", "caches" ]
1bf0aa6b6c0787347259be0b96b1553ac5d5375e
https://github.com/nystudio107/craft-twigpack/blob/1bf0aa6b6c0787347259be0b96b1553ac5d5375e/src/helpers/Manifest.php#L363-L368
train
nystudio107/craft-twigpack
src/helpers/Manifest.php
Manifest.getFileFromUri
protected static function getFileFromUri(string $path, callable $callback = null, bool $pathOnly = false) { // Resolve any aliases $alias = Craft::getAlias($path, false); if ($alias) { $path = $alias; } // If we only want the file via path, make sure it exists if ($pathOnly && !is_file($path)) { Craft::warning(Craft::t( 'twigpack', 'File does not exist: {path}', ['path' => $path] ), __METHOD__); return ''; } // Make sure it's a full URL if (!UrlHelper::isAbsoluteUrl($path) && !is_file($path)) { try { $path = UrlHelper::siteUrl($path); } catch (Exception $e) { Craft::error($e->getMessage(), __METHOD__); } } return self::getFileContents($path, $callback); }
php
protected static function getFileFromUri(string $path, callable $callback = null, bool $pathOnly = false) { // Resolve any aliases $alias = Craft::getAlias($path, false); if ($alias) { $path = $alias; } // If we only want the file via path, make sure it exists if ($pathOnly && !is_file($path)) { Craft::warning(Craft::t( 'twigpack', 'File does not exist: {path}', ['path' => $path] ), __METHOD__); return ''; } // Make sure it's a full URL if (!UrlHelper::isAbsoluteUrl($path) && !is_file($path)) { try { $path = UrlHelper::siteUrl($path); } catch (Exception $e) { Craft::error($e->getMessage(), __METHOD__); } } return self::getFileContents($path, $callback); }
[ "protected", "static", "function", "getFileFromUri", "(", "string", "$", "path", ",", "callable", "$", "callback", "=", "null", ",", "bool", "$", "pathOnly", "=", "false", ")", "{", "// Resolve any aliases", "$", "alias", "=", "Craft", "::", "getAlias", "(",...
Return the contents of a file from a URI path @param string $path @param callable|null $callback @param bool $pathOnly @return null|mixed
[ "Return", "the", "contents", "of", "a", "file", "from", "a", "URI", "path" ]
1bf0aa6b6c0787347259be0b96b1553ac5d5375e
https://github.com/nystudio107/craft-twigpack/blob/1bf0aa6b6c0787347259be0b96b1553ac5d5375e/src/helpers/Manifest.php#L394-L421
train
nystudio107/craft-twigpack
src/helpers/Manifest.php
Manifest.getFileContents
protected static function getFileContents(string $path, callable $callback = null) { // Return the memoized manifest if it exists if (!empty(self::$files[$path])) { return self::$files[$path]; } // Create the dependency tags $dependency = new TagDependency([ 'tags' => [ self::CACHE_TAG, self::CACHE_TAG.$path, ], ]); // Set the cache duration based on devMode $cacheDuration = Craft::$app->getConfig()->getGeneral()->devMode ? self::DEVMODE_CACHE_DURATION : null; // Get the result from the cache, or parse the file $cache = Craft::$app->getCache(); $file = $cache->getOrSet( self::CACHE_KEY.$path, function () use ($path, $callback) { $result = null; if (UrlHelper::isAbsoluteUrl($path)) { /** * Silly work-around for what appears to be a file_get_contents bug with https * http://stackoverflow.com/questions/10524748/why-im-getting-500-error-when-using-file-get-contents-but-works-in-a-browser */ $opts = [ 'ssl' => [ 'verify_peer' => false, 'verify_peer_name' => false, ], 'http' => [ 'ignore_errors' => true, 'header' => "User-Agent:Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13\r\n", ], ]; $context = stream_context_create($opts); $contents = @file_get_contents($path, false, $context); } else { $contents = @file_get_contents($path); } if ($contents) { $result = $contents; if ($callback) { $result = $callback($result); } } return $result; }, $cacheDuration, $dependency ); self::$files[$path] = $file; return $file; }
php
protected static function getFileContents(string $path, callable $callback = null) { // Return the memoized manifest if it exists if (!empty(self::$files[$path])) { return self::$files[$path]; } // Create the dependency tags $dependency = new TagDependency([ 'tags' => [ self::CACHE_TAG, self::CACHE_TAG.$path, ], ]); // Set the cache duration based on devMode $cacheDuration = Craft::$app->getConfig()->getGeneral()->devMode ? self::DEVMODE_CACHE_DURATION : null; // Get the result from the cache, or parse the file $cache = Craft::$app->getCache(); $file = $cache->getOrSet( self::CACHE_KEY.$path, function () use ($path, $callback) { $result = null; if (UrlHelper::isAbsoluteUrl($path)) { /** * Silly work-around for what appears to be a file_get_contents bug with https * http://stackoverflow.com/questions/10524748/why-im-getting-500-error-when-using-file-get-contents-but-works-in-a-browser */ $opts = [ 'ssl' => [ 'verify_peer' => false, 'verify_peer_name' => false, ], 'http' => [ 'ignore_errors' => true, 'header' => "User-Agent:Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13\r\n", ], ]; $context = stream_context_create($opts); $contents = @file_get_contents($path, false, $context); } else { $contents = @file_get_contents($path); } if ($contents) { $result = $contents; if ($callback) { $result = $callback($result); } } return $result; }, $cacheDuration, $dependency ); self::$files[$path] = $file; return $file; }
[ "protected", "static", "function", "getFileContents", "(", "string", "$", "path", ",", "callable", "$", "callback", "=", "null", ")", "{", "// Return the memoized manifest if it exists", "if", "(", "!", "empty", "(", "self", "::", "$", "files", "[", "$", "path...
Return the contents of a file from the passed in path @param string $path @param callable $callback @return null|mixed
[ "Return", "the", "contents", "of", "a", "file", "from", "the", "passed", "in", "path" ]
1bf0aa6b6c0787347259be0b96b1553ac5d5375e
https://github.com/nystudio107/craft-twigpack/blob/1bf0aa6b6c0787347259be0b96b1553ac5d5375e/src/helpers/Manifest.php#L431-L489
train
nystudio107/craft-twigpack
src/helpers/Manifest.php
Manifest.combinePaths
protected static function combinePaths(string ...$paths): string { $last_key = \count($paths) - 1; array_walk($paths, function (&$val, $key) use ($last_key) { switch ($key) { case 0: $val = rtrim($val, '/ '); break; case $last_key: $val = ltrim($val, '/ '); break; default: $val = trim($val, '/ '); break; } }); $first = array_shift($paths); $last = array_pop($paths); $paths = array_filter($paths); array_unshift($paths, $first); $paths[] = $last; return implode('/', $paths); }
php
protected static function combinePaths(string ...$paths): string { $last_key = \count($paths) - 1; array_walk($paths, function (&$val, $key) use ($last_key) { switch ($key) { case 0: $val = rtrim($val, '/ '); break; case $last_key: $val = ltrim($val, '/ '); break; default: $val = trim($val, '/ '); break; } }); $first = array_shift($paths); $last = array_pop($paths); $paths = array_filter($paths); array_unshift($paths, $first); $paths[] = $last; return implode('/', $paths); }
[ "protected", "static", "function", "combinePaths", "(", "string", "...", "$", "paths", ")", ":", "string", "{", "$", "last_key", "=", "\\", "count", "(", "$", "paths", ")", "-", "1", ";", "array_walk", "(", "$", "paths", ",", "function", "(", "&", "$...
Combined the passed in paths, whether file system or URL @param string ...$paths @return string
[ "Combined", "the", "passed", "in", "paths", "whether", "file", "system", "or", "URL" ]
1bf0aa6b6c0787347259be0b96b1553ac5d5375e
https://github.com/nystudio107/craft-twigpack/blob/1bf0aa6b6c0787347259be0b96b1553ac5d5375e/src/helpers/Manifest.php#L498-L522
train
nystudio107/craft-twigpack
src/variables/ManifestVariable.php
ManifestVariable.includeFile
public function includeFile(string $path): \Twig\Markup { return Template::raw( Twigpack::$plugin->manifest->getFile($path) ); }
php
public function includeFile(string $path): \Twig\Markup { return Template::raw( Twigpack::$plugin->manifest->getFile($path) ); }
[ "public", "function", "includeFile", "(", "string", "$", "path", ")", ":", "\\", "Twig", "\\", "Markup", "{", "return", "Template", "::", "raw", "(", "Twigpack", "::", "$", "plugin", "->", "manifest", "->", "getFile", "(", "$", "path", ")", ")", ";", ...
Returns the contents of a file from a URI path @param string $path @return \Twig\Markup
[ "Returns", "the", "contents", "of", "a", "file", "from", "a", "URI", "path" ]
1bf0aa6b6c0787347259be0b96b1553ac5d5375e
https://github.com/nystudio107/craft-twigpack/blob/1bf0aa6b6c0787347259be0b96b1553ac5d5375e/src/variables/ManifestVariable.php#L136-L141
train
cebe/php-openapi
src/Writer.php
Writer.writeToYaml
public static function writeToYaml(SpecObjectInterface $object): string { return Yaml::dump($object->getSerializableData(), 256, 2, Yaml::DUMP_OBJECT_AS_MAP); }
php
public static function writeToYaml(SpecObjectInterface $object): string { return Yaml::dump($object->getSerializableData(), 256, 2, Yaml::DUMP_OBJECT_AS_MAP); }
[ "public", "static", "function", "writeToYaml", "(", "SpecObjectInterface", "$", "object", ")", ":", "string", "{", "return", "Yaml", "::", "dump", "(", "$", "object", "->", "getSerializableData", "(", ")", ",", "256", ",", "2", ",", "Yaml", "::", "DUMP_OBJ...
Convert OpenAPI spec object to YAML data. @param SpecObjectInterface|OpenApi the OpenApi object instance. @return string YAML string.
[ "Convert", "OpenAPI", "spec", "object", "to", "YAML", "data", "." ]
0f70820c2bf1e9e16cd8d091004fe372f11e032b
https://github.com/cebe/php-openapi/blob/0f70820c2bf1e9e16cd8d091004fe372f11e032b/src/Writer.php#L34-L37
train
cebe/php-openapi
src/Writer.php
Writer.writeToJsonFile
public static function writeToJsonFile(SpecObjectInterface $object, string $fileName): void { file_put_contents($fileName, static::writeToJson($object)); }
php
public static function writeToJsonFile(SpecObjectInterface $object, string $fileName): void { file_put_contents($fileName, static::writeToJson($object)); }
[ "public", "static", "function", "writeToJsonFile", "(", "SpecObjectInterface", "$", "object", ",", "string", "$", "fileName", ")", ":", "void", "{", "file_put_contents", "(", "$", "fileName", ",", "static", "::", "writeToJson", "(", "$", "object", ")", ")", ...
Write OpenAPI spec object to JSON file. @param SpecObjectInterface|OpenApi the OpenApi object instance. @param string $fileName file name to write to.
[ "Write", "OpenAPI", "spec", "object", "to", "JSON", "file", "." ]
0f70820c2bf1e9e16cd8d091004fe372f11e032b
https://github.com/cebe/php-openapi/blob/0f70820c2bf1e9e16cd8d091004fe372f11e032b/src/Writer.php#L44-L47
train
cebe/php-openapi
src/Writer.php
Writer.writeToYamlFile
public static function writeToYamlFile(SpecObjectInterface $object, string $fileName): void { file_put_contents($fileName, static::writeToYaml($object)); }
php
public static function writeToYamlFile(SpecObjectInterface $object, string $fileName): void { file_put_contents($fileName, static::writeToYaml($object)); }
[ "public", "static", "function", "writeToYamlFile", "(", "SpecObjectInterface", "$", "object", ",", "string", "$", "fileName", ")", ":", "void", "{", "file_put_contents", "(", "$", "fileName", ",", "static", "::", "writeToYaml", "(", "$", "object", ")", ")", ...
Write OpenAPI spec object to YAML file. @param SpecObjectInterface|OpenApi the OpenApi object instance. @param string $fileName file name to write to.
[ "Write", "OpenAPI", "spec", "object", "to", "YAML", "file", "." ]
0f70820c2bf1e9e16cd8d091004fe372f11e032b
https://github.com/cebe/php-openapi/blob/0f70820c2bf1e9e16cd8d091004fe372f11e032b/src/Writer.php#L54-L57
train
cebe/php-openapi
src/ReferenceContext.php
ReferenceContext.resolveRelativeUri
public function resolveRelativeUri(string $uri): string { $parts = parse_url($uri); if (isset($parts['scheme'])) { // absolute URL return $uri; } $baseUri = $this->getUri(); if (strncmp($baseUri, 'file://', 7) === 0) { if (isset($parts['path'][0]) && $parts['path'][0] === '/') { // absolute path return 'file://' . $parts['path']; } if (isset($parts['path'])) { // relative path return dirname($baseUri) . '/' . $parts['path']; } throw new UnresolvableReferenceException("Invalid URI: '$uri'"); } $baseParts = parse_url($baseUri); $absoluteUri = implode('', [ $baseParts['scheme'], '://', isset($baseParts['username']) ? $baseParts['username'] . ( isset($baseParts['password']) ? ':' . $baseParts['password'] : '' ) . '@' : '', $baseParts['host'] ?? '', isset($baseParts['port']) ? ':' . $baseParts['port'] : '', ]); if (isset($parts['path'][0]) && $parts['path'][0] === '/') { $absoluteUri .= $parts['path']; } elseif (isset($parts['path'])) { $absoluteUri .= rtrim(dirname($baseParts['path'] ?? ''), '/') . '/' . $parts['path']; } return $absoluteUri . (isset($parts['query']) ? '?' . $parts['query'] : '') . (isset($parts['fragment']) ? '#' . $parts['fragment'] : ''); }
php
public function resolveRelativeUri(string $uri): string { $parts = parse_url($uri); if (isset($parts['scheme'])) { // absolute URL return $uri; } $baseUri = $this->getUri(); if (strncmp($baseUri, 'file://', 7) === 0) { if (isset($parts['path'][0]) && $parts['path'][0] === '/') { // absolute path return 'file://' . $parts['path']; } if (isset($parts['path'])) { // relative path return dirname($baseUri) . '/' . $parts['path']; } throw new UnresolvableReferenceException("Invalid URI: '$uri'"); } $baseParts = parse_url($baseUri); $absoluteUri = implode('', [ $baseParts['scheme'], '://', isset($baseParts['username']) ? $baseParts['username'] . ( isset($baseParts['password']) ? ':' . $baseParts['password'] : '' ) . '@' : '', $baseParts['host'] ?? '', isset($baseParts['port']) ? ':' . $baseParts['port'] : '', ]); if (isset($parts['path'][0]) && $parts['path'][0] === '/') { $absoluteUri .= $parts['path']; } elseif (isset($parts['path'])) { $absoluteUri .= rtrim(dirname($baseParts['path'] ?? ''), '/') . '/' . $parts['path']; } return $absoluteUri . (isset($parts['query']) ? '?' . $parts['query'] : '') . (isset($parts['fragment']) ? '#' . $parts['fragment'] : ''); }
[ "public", "function", "resolveRelativeUri", "(", "string", "$", "uri", ")", ":", "string", "{", "$", "parts", "=", "parse_url", "(", "$", "uri", ")", ";", "if", "(", "isset", "(", "$", "parts", "[", "'scheme'", "]", ")", ")", "{", "// absolute URL", ...
Resolve a relative URI to an absolute URI in the current context. @param string $uri @throws UnresolvableReferenceException @return string
[ "Resolve", "a", "relative", "URI", "to", "an", "absolute", "URI", "in", "the", "current", "context", "." ]
0f70820c2bf1e9e16cd8d091004fe372f11e032b
https://github.com/cebe/php-openapi/blob/0f70820c2bf1e9e16cd8d091004fe372f11e032b/src/ReferenceContext.php#L74-L114
train
cebe/php-openapi
src/spec/PathItem.php
PathItem.getOperations
public function getOperations() { $operations = []; foreach (static::attributes() as $attribute => $type) { if ($type === Operation::class && isset($this->$attribute)) { $operations[$attribute] = $this->$attribute; } } return $operations; }
php
public function getOperations() { $operations = []; foreach (static::attributes() as $attribute => $type) { if ($type === Operation::class && isset($this->$attribute)) { $operations[$attribute] = $this->$attribute; } } return $operations; }
[ "public", "function", "getOperations", "(", ")", "{", "$", "operations", "=", "[", "]", ";", "foreach", "(", "static", "::", "attributes", "(", ")", "as", "$", "attribute", "=>", "$", "type", ")", "{", "if", "(", "$", "type", "===", "Operation", "::"...
Return all operations of this Path. @return Operation[]
[ "Return", "all", "operations", "of", "this", "Path", "." ]
0f70820c2bf1e9e16cd8d091004fe372f11e032b
https://github.com/cebe/php-openapi/blob/0f70820c2bf1e9e16cd8d091004fe372f11e032b/src/spec/PathItem.php#L69-L78
train
cebe/php-openapi
src/spec/Reference.php
Reference.resolve
public function resolve(ReferenceContext $context = null) { if ($context === null) { $context = $this->getContext(); if ($context === null) { throw new UnresolvableReferenceException('No context given for resolving reference.'); } } if (($pos = strpos($this->_ref, '#')) === 0) { // resolve in current document $jsonPointer = substr($this->_ref, 1); // TODO type error if resolved object does not match $this->_to ? return $this->resolveJsonPointer($jsonPointer, $context->getBaseSpec()); } $file = ($pos === false) ? $this->_ref : substr($this->_ref, 0, $pos); $file = $context->resolveRelativeUri($file); $jsonPointer = ($pos === false) ? '' : substr($this->_ref, $pos + 1); // TODO could be a good idea to cache loaded files in current context to avoid loading the same files over and over again $fileContent = $this->fetchReferencedFile($file); $referencedData = $this->resolveJsonPointer($jsonPointer, $fileContent); /** @var $referencedObject SpecObjectInterface */ $referencedObject = new $this->_to($referencedData); if ($jsonPointer === '') { $referencedObject->setReferenceContext(new ReferenceContext($referencedObject, $file)); } else { // TODO resolving references recursively does not work as we do not know the base type of the file at this point // $referencedObject->resolveReferences(new ReferenceContext($referencedObject, $file)); } return $referencedObject; }
php
public function resolve(ReferenceContext $context = null) { if ($context === null) { $context = $this->getContext(); if ($context === null) { throw new UnresolvableReferenceException('No context given for resolving reference.'); } } if (($pos = strpos($this->_ref, '#')) === 0) { // resolve in current document $jsonPointer = substr($this->_ref, 1); // TODO type error if resolved object does not match $this->_to ? return $this->resolveJsonPointer($jsonPointer, $context->getBaseSpec()); } $file = ($pos === false) ? $this->_ref : substr($this->_ref, 0, $pos); $file = $context->resolveRelativeUri($file); $jsonPointer = ($pos === false) ? '' : substr($this->_ref, $pos + 1); // TODO could be a good idea to cache loaded files in current context to avoid loading the same files over and over again $fileContent = $this->fetchReferencedFile($file); $referencedData = $this->resolveJsonPointer($jsonPointer, $fileContent); /** @var $referencedObject SpecObjectInterface */ $referencedObject = new $this->_to($referencedData); if ($jsonPointer === '') { $referencedObject->setReferenceContext(new ReferenceContext($referencedObject, $file)); } else { // TODO resolving references recursively does not work as we do not know the base type of the file at this point // $referencedObject->resolveReferences(new ReferenceContext($referencedObject, $file)); } return $referencedObject; }
[ "public", "function", "resolve", "(", "ReferenceContext", "$", "context", "=", "null", ")", "{", "if", "(", "$", "context", "===", "null", ")", "{", "$", "context", "=", "$", "this", "->", "getContext", "(", ")", ";", "if", "(", "$", "context", "==="...
Resolve this reference. @param ReferenceContext $context the reference context to use for resolution. If not specified, `getContext()` will be called to determine the context, if that does not return a context, the UnresolvableReferenceException will be thrown. @return SpecObjectInterface the resolved spec type. @throws UnresolvableReferenceException in case of errors.
[ "Resolve", "this", "reference", "." ]
0f70820c2bf1e9e16cd8d091004fe372f11e032b
https://github.com/cebe/php-openapi/blob/0f70820c2bf1e9e16cd8d091004fe372f11e032b/src/spec/Reference.php#L123-L156
train
cebe/php-openapi
src/Reader.php
Reader.readFromJson
public static function readFromJson(string $json, string $baseType = OpenApi::class): SpecObjectInterface { return new $baseType(json_decode($json, true)); }
php
public static function readFromJson(string $json, string $baseType = OpenApi::class): SpecObjectInterface { return new $baseType(json_decode($json, true)); }
[ "public", "static", "function", "readFromJson", "(", "string", "$", "json", ",", "string", "$", "baseType", "=", "OpenApi", "::", "class", ")", ":", "SpecObjectInterface", "{", "return", "new", "$", "baseType", "(", "json_decode", "(", "$", "json", ",", "t...
Populate OpenAPI spec object from JSON data. @param string $json the JSON string to decode. @param string $baseType the base Type to instantiate. This must be an instance of [[SpecObjectInterface]]. The default is [[OpenApi]] which is the base type of a OpenAPI specification file. You may choose a different type if you instantiate objects from sub sections of a specification. @return SpecObjectInterface|OpenApi the OpenApi object instance. @throws TypeErrorException in case invalid spec data is supplied.
[ "Populate", "OpenAPI", "spec", "object", "from", "JSON", "data", "." ]
0f70820c2bf1e9e16cd8d091004fe372f11e032b
https://github.com/cebe/php-openapi/blob/0f70820c2bf1e9e16cd8d091004fe372f11e032b/src/Reader.php#L30-L33
train
cebe/php-openapi
src/Reader.php
Reader.readFromYaml
public static function readFromYaml(string $yaml, string $baseType = OpenApi::class): SpecObjectInterface { return new $baseType(Yaml::parse($yaml)); }
php
public static function readFromYaml(string $yaml, string $baseType = OpenApi::class): SpecObjectInterface { return new $baseType(Yaml::parse($yaml)); }
[ "public", "static", "function", "readFromYaml", "(", "string", "$", "yaml", ",", "string", "$", "baseType", "=", "OpenApi", "::", "class", ")", ":", "SpecObjectInterface", "{", "return", "new", "$", "baseType", "(", "Yaml", "::", "parse", "(", "$", "yaml",...
Populate OpenAPI spec object from YAML data. @param string $yaml the YAML string to decode. @param string $baseType the base Type to instantiate. This must be an instance of [[SpecObjectInterface]]. The default is [[OpenApi]] which is the base type of a OpenAPI specification file. You may choose a different type if you instantiate objects from sub sections of a specification. @return SpecObjectInterface|OpenApi the OpenApi object instance. @throws TypeErrorException in case invalid spec data is supplied.
[ "Populate", "OpenAPI", "spec", "object", "from", "YAML", "data", "." ]
0f70820c2bf1e9e16cd8d091004fe372f11e032b
https://github.com/cebe/php-openapi/blob/0f70820c2bf1e9e16cd8d091004fe372f11e032b/src/Reader.php#L44-L47
train
cebe/php-openapi
src/Reader.php
Reader.readFromJsonFile
public static function readFromJsonFile(string $fileName, string $baseType = OpenApi::class, $resolveReferences = true): SpecObjectInterface { $spec = static::readFromJson(file_get_contents($fileName), $baseType); $spec->setReferenceContext(new ReferenceContext($spec, $fileName)); if ($resolveReferences) { $spec->resolveReferences(); } return $spec; }
php
public static function readFromJsonFile(string $fileName, string $baseType = OpenApi::class, $resolveReferences = true): SpecObjectInterface { $spec = static::readFromJson(file_get_contents($fileName), $baseType); $spec->setReferenceContext(new ReferenceContext($spec, $fileName)); if ($resolveReferences) { $spec->resolveReferences(); } return $spec; }
[ "public", "static", "function", "readFromJsonFile", "(", "string", "$", "fileName", ",", "string", "$", "baseType", "=", "OpenApi", "::", "class", ",", "$", "resolveReferences", "=", "true", ")", ":", "SpecObjectInterface", "{", "$", "spec", "=", "static", "...
Populate OpenAPI spec object from a JSON file. @param string $fileName the file name of the file to be read. If `$resolveReferences` is true (the default), this should be an absolute URL, a `file://` URI or an absolute path to allow resolving relative path references. @param string $baseType the base Type to instantiate. This must be an instance of [[SpecObjectInterface]]. The default is [[OpenApi]] which is the base type of a OpenAPI specification file. You may choose a different type if you instantiate objects from sub sections of a specification. @param bool $resolveReferences whether to automatically resolve references in the specification. If `true`, all [[Reference]] objects will be replaced with their referenced spec objects by calling [[SpecObjectInterface::resolveReferences()]]. @return SpecObjectInterface|OpenApi the OpenApi object instance. @throws TypeErrorException in case invalid spec data is supplied. @throws UnresolvableReferenceException in case references could not be resolved.
[ "Populate", "OpenAPI", "spec", "object", "from", "a", "JSON", "file", "." ]
0f70820c2bf1e9e16cd8d091004fe372f11e032b
https://github.com/cebe/php-openapi/blob/0f70820c2bf1e9e16cd8d091004fe372f11e032b/src/Reader.php#L64-L72
train
cebe/php-openapi
src/Reader.php
Reader.readFromYamlFile
public static function readFromYamlFile(string $fileName, string $baseType = OpenApi::class, $resolveReferences = true): SpecObjectInterface { $spec = static::readFromYaml(file_get_contents($fileName), $baseType); $spec->setReferenceContext(new ReferenceContext($spec, $fileName)); if ($resolveReferences) { $spec->resolveReferences(); } return $spec; }
php
public static function readFromYamlFile(string $fileName, string $baseType = OpenApi::class, $resolveReferences = true): SpecObjectInterface { $spec = static::readFromYaml(file_get_contents($fileName), $baseType); $spec->setReferenceContext(new ReferenceContext($spec, $fileName)); if ($resolveReferences) { $spec->resolveReferences(); } return $spec; }
[ "public", "static", "function", "readFromYamlFile", "(", "string", "$", "fileName", ",", "string", "$", "baseType", "=", "OpenApi", "::", "class", ",", "$", "resolveReferences", "=", "true", ")", ":", "SpecObjectInterface", "{", "$", "spec", "=", "static", "...
Populate OpenAPI spec object from YAML file. @param string $fileName the file name of the file to be read. If `$resolveReferences` is true (the default), this should be an absolute URL, a `file://` URI or an absolute path to allow resolving relative path references. @param string $baseType the base Type to instantiate. This must be an instance of [[SpecObjectInterface]]. The default is [[OpenApi]] which is the base type of a OpenAPI specification file. You may choose a different type if you instantiate objects from sub sections of a specification. @param bool $resolveReferences whether to automatically resolve references in the specification. If `true`, all [[Reference]] objects will be replaced with their referenced spec objects by calling [[SpecObjectInterface::resolveReferences()]]. @return SpecObjectInterface|OpenApi the OpenApi object instance. @throws TypeErrorException in case invalid spec data is supplied. @throws UnresolvableReferenceException in case references could not be resolved.
[ "Populate", "OpenAPI", "spec", "object", "from", "YAML", "file", "." ]
0f70820c2bf1e9e16cd8d091004fe372f11e032b
https://github.com/cebe/php-openapi/blob/0f70820c2bf1e9e16cd8d091004fe372f11e032b/src/Reader.php#L89-L97
train
RobDWaller/ReallySimpleJWT
src/Build.php
Build.setHeaderClaim
public function setHeaderClaim(string $key, $value): self { $this->header[$key] = $value; return $this; }
php
public function setHeaderClaim(string $key, $value): self { $this->header[$key] = $value; return $this; }
[ "public", "function", "setHeaderClaim", "(", "string", "$", "key", ",", "$", "value", ")", ":", "self", "{", "$", "this", "->", "header", "[", "$", "key", "]", "=", "$", "value", ";", "return", "$", "this", ";", "}" ]
Add custom claims to the JWT header @param string $key @param mixed $value @return Build
[ "Add", "custom", "claims", "to", "the", "JWT", "header" ]
1df7d62951c93babdf2962493588561382dbca38
https://github.com/RobDWaller/ReallySimpleJWT/blob/1df7d62951c93babdf2962493588561382dbca38/src/Build.php#L111-L116
train
RobDWaller/ReallySimpleJWT
src/Build.php
Build.setSecret
public function setSecret(string $secret): self { if (!$this->validate->secret($secret)) { throw new ValidateException('Invalid secret.', 9); } $this->secret = $secret; return $this; }
php
public function setSecret(string $secret): self { if (!$this->validate->secret($secret)) { throw new ValidateException('Invalid secret.', 9); } $this->secret = $secret; return $this; }
[ "public", "function", "setSecret", "(", "string", "$", "secret", ")", ":", "self", "{", "if", "(", "!", "$", "this", "->", "validate", "->", "secret", "(", "$", "secret", ")", ")", "{", "throw", "new", "ValidateException", "(", "'Invalid secret.'", ",", ...
Set the JWT secret for encrypting the JWT signature. The secret must comply with the validation rules defined in the ReallySimpleJWT\Validate class. @param string $secret @return Build @throws Exception\ValidateException
[ "Set", "the", "JWT", "secret", "for", "encrypting", "the", "JWT", "signature", ".", "The", "secret", "must", "comply", "with", "the", "validation", "rules", "defined", "in", "the", "ReallySimpleJWT", "\\", "Validate", "class", "." ]
1df7d62951c93babdf2962493588561382dbca38
https://github.com/RobDWaller/ReallySimpleJWT/blob/1df7d62951c93babdf2962493588561382dbca38/src/Build.php#L142-L151
train
RobDWaller/ReallySimpleJWT
src/Build.php
Build.setAudience
public function setAudience($audience): self { if (is_string($audience) || is_array($audience)) { $this->payload['aud'] = $audience; return $this; } throw new ValidateException('Invalid Audience claim.', 10); }
php
public function setAudience($audience): self { if (is_string($audience) || is_array($audience)) { $this->payload['aud'] = $audience; return $this; } throw new ValidateException('Invalid Audience claim.', 10); }
[ "public", "function", "setAudience", "(", "$", "audience", ")", ":", "self", "{", "if", "(", "is_string", "(", "$", "audience", ")", "||", "is_array", "(", "$", "audience", ")", ")", "{", "$", "this", "->", "payload", "[", "'aud'", "]", "=", "$", "...
Set the audience JWT payload claim. This defines a list of 'principals' who will process the JWT. Eg a website or websites who will validate users who use this token. This claim can either be a single string or an array of strings. @param mixed $audience @return Build @throws Exception\ValidateException
[ "Set", "the", "audience", "JWT", "payload", "claim", ".", "This", "defines", "a", "list", "of", "principals", "who", "will", "process", "the", "JWT", ".", "Eg", "a", "website", "or", "websites", "who", "will", "validate", "users", "who", "use", "this", "...
1df7d62951c93babdf2962493588561382dbca38
https://github.com/RobDWaller/ReallySimpleJWT/blob/1df7d62951c93babdf2962493588561382dbca38/src/Build.php#L191-L200
train
RobDWaller/ReallySimpleJWT
src/Build.php
Build.setExpiration
public function setExpiration(int $timestamp): self { if (!$this->validate->expiration($timestamp)) { throw new ValidateException('Expiration claim has expired.', 4); } $this->payload['exp'] = $timestamp; return $this; }
php
public function setExpiration(int $timestamp): self { if (!$this->validate->expiration($timestamp)) { throw new ValidateException('Expiration claim has expired.', 4); } $this->payload['exp'] = $timestamp; return $this; }
[ "public", "function", "setExpiration", "(", "int", "$", "timestamp", ")", ":", "self", "{", "if", "(", "!", "$", "this", "->", "validate", "->", "expiration", "(", "$", "timestamp", ")", ")", "{", "throw", "new", "ValidateException", "(", "'Expiration clai...
Set the expiration JWT payload claim. This sets the time at which the JWT should expire and no longer be accepted. @param int $timestamp @return Build @throws Exception\ValidateException
[ "Set", "the", "expiration", "JWT", "payload", "claim", ".", "This", "sets", "the", "time", "at", "which", "the", "JWT", "should", "expire", "and", "no", "longer", "be", "accepted", "." ]
1df7d62951c93babdf2962493588561382dbca38
https://github.com/RobDWaller/ReallySimpleJWT/blob/1df7d62951c93babdf2962493588561382dbca38/src/Build.php#L210-L219
train
RobDWaller/ReallySimpleJWT
src/Build.php
Build.setPayloadClaim
public function setPayloadClaim(string $key, $value): self { $this->payload[$key] = $value; return $this; }
php
public function setPayloadClaim(string $key, $value): self { $this->payload[$key] = $value; return $this; }
[ "public", "function", "setPayloadClaim", "(", "string", "$", "key", ",", "$", "value", ")", ":", "self", "{", "$", "this", "->", "payload", "[", "$", "key", "]", "=", "$", "value", ";", "return", "$", "this", ";", "}" ]
Set a custom payload claim on the JWT. The RFC calls these private claims. Eg you may wish to set a user_id or a username in the JWT payload. @param string $key @param mixed $value @return Build
[ "Set", "a", "custom", "payload", "claim", "on", "the", "JWT", ".", "The", "RFC", "calls", "these", "private", "claims", ".", "Eg", "you", "may", "wish", "to", "set", "a", "user_id", "or", "a", "username", "in", "the", "JWT", "payload", "." ]
1df7d62951c93babdf2962493588561382dbca38
https://github.com/RobDWaller/ReallySimpleJWT/blob/1df7d62951c93babdf2962493588561382dbca38/src/Build.php#L272-L277
train
RobDWaller/ReallySimpleJWT
src/Build.php
Build.build
public function build(): Jwt { return new Jwt( $this->encode->encode($this->jsonEncode($this->getHeader())) . "." . $this->encode->encode($this->jsonEncode($this->getPayload())) . "." . $this->getSignature(), $this->secret ); }
php
public function build(): Jwt { return new Jwt( $this->encode->encode($this->jsonEncode($this->getHeader())) . "." . $this->encode->encode($this->jsonEncode($this->getPayload())) . "." . $this->getSignature(), $this->secret ); }
[ "public", "function", "build", "(", ")", ":", "Jwt", "{", "return", "new", "Jwt", "(", "$", "this", "->", "encode", "->", "encode", "(", "$", "this", "->", "jsonEncode", "(", "$", "this", "->", "getHeader", "(", ")", ")", ")", ".", "\".\"", ".", ...
Build the token, this is the last method which should be called after all the header and payload claims have been set. It will encode the header and payload, and generate the JWT signature. It will then concatenate each part with dots into a single string. This JWT string along with the secret are then used to generate a new instance of the JWT class which is returned. @return Jwt
[ "Build", "the", "token", "this", "is", "the", "last", "method", "which", "should", "be", "called", "after", "all", "the", "header", "and", "payload", "claims", "have", "been", "set", ".", "It", "will", "encode", "the", "header", "and", "payload", "and", ...
1df7d62951c93babdf2962493588561382dbca38
https://github.com/RobDWaller/ReallySimpleJWT/blob/1df7d62951c93babdf2962493588561382dbca38/src/Build.php#L301-L309
train
RobDWaller/ReallySimpleJWT
src/Build.php
Build.getSignature
private function getSignature(): string { if (!empty($this->secret)) { return $this->encode->signature( $this->jsonEncode($this->getHeader()), $this->jsonEncode($this->getPayload()), $this->secret ); } throw new ValidateException('Invalid secret.', 9); }
php
private function getSignature(): string { if (!empty($this->secret)) { return $this->encode->signature( $this->jsonEncode($this->getHeader()), $this->jsonEncode($this->getPayload()), $this->secret ); } throw new ValidateException('Invalid secret.', 9); }
[ "private", "function", "getSignature", "(", ")", ":", "string", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "secret", ")", ")", "{", "return", "$", "this", "->", "encode", "->", "signature", "(", "$", "this", "->", "jsonEncode", "(", "$", ...
Generate and return the JWT signature this is made up of the header, payload and secret. @return string @throws Exception\ValidateException
[ "Generate", "and", "return", "the", "JWT", "signature", "this", "is", "made", "up", "of", "the", "header", "payload", "and", "secret", "." ]
1df7d62951c93babdf2962493588561382dbca38
https://github.com/RobDWaller/ReallySimpleJWT/blob/1df7d62951c93babdf2962493588561382dbca38/src/Build.php#L334-L345
train
RobDWaller/ReallySimpleJWT
src/Encode.php
Encode.decode
public function decode(string $toDecode): string { return (string) base64_decode( $this->addPadding($this->toBase64($toDecode)), true ); }
php
public function decode(string $toDecode): string { return (string) base64_decode( $this->addPadding($this->toBase64($toDecode)), true ); }
[ "public", "function", "decode", "(", "string", "$", "toDecode", ")", ":", "string", "{", "return", "(", "string", ")", "base64_decode", "(", "$", "this", "->", "addPadding", "(", "$", "this", "->", "toBase64", "(", "$", "toDecode", ")", ")", ",", "true...
Decode a Base64 Url string to a json string @param string $toDecode @return string
[ "Decode", "a", "Base64", "Url", "string", "to", "a", "json", "string" ]
1df7d62951c93babdf2962493588561382dbca38
https://github.com/RobDWaller/ReallySimpleJWT/blob/1df7d62951c93babdf2962493588561382dbca38/src/Encode.php#L72-L78
train
RobDWaller/ReallySimpleJWT
src/Encode.php
Encode.signature
public function signature(string $header, string $payload, string $secret): string { return $this->encode( $this->hash( $this->getHashAlgorithm(), $this->encode($header) . "." . $this->encode($payload), $secret ) ); }
php
public function signature(string $header, string $payload, string $secret): string { return $this->encode( $this->hash( $this->getHashAlgorithm(), $this->encode($header) . "." . $this->encode($payload), $secret ) ); }
[ "public", "function", "signature", "(", "string", "$", "header", ",", "string", "$", "payload", ",", "string", "$", "secret", ")", ":", "string", "{", "return", "$", "this", "->", "encode", "(", "$", "this", "->", "hash", "(", "$", "this", "->", "get...
Generate the JWT signature. The header and payload are encoded, concatenated with a dot, hashed via sha256 with a secret, and then encoded and returned. @param string $header @param string $payload @param string $secret @return string
[ "Generate", "the", "JWT", "signature", ".", "The", "header", "and", "payload", "are", "encoded", "concatenated", "with", "a", "dot", "hashed", "via", "sha256", "with", "a", "secret", "and", "then", "encoded", "and", "returned", "." ]
1df7d62951c93babdf2962493588561382dbca38
https://github.com/RobDWaller/ReallySimpleJWT/blob/1df7d62951c93babdf2962493588561382dbca38/src/Encode.php#L90-L99
train
RobDWaller/ReallySimpleJWT
src/Encode.php
Encode.hash
private function hash(string $algorithm, string $toHash, string $secret): string { return hash_hmac($algorithm, $toHash, $secret, true); }
php
private function hash(string $algorithm, string $toHash, string $secret): string { return hash_hmac($algorithm, $toHash, $secret, true); }
[ "private", "function", "hash", "(", "string", "$", "algorithm", ",", "string", "$", "toHash", ",", "string", "$", "secret", ")", ":", "string", "{", "return", "hash_hmac", "(", "$", "algorithm", ",", "$", "toHash", ",", "$", "secret", ",", "true", ")",...
Hash the JWT signature string using sha256. @param string $algorithm @param string $toHash @param string $secret @return string
[ "Hash", "the", "JWT", "signature", "string", "using", "sha256", "." ]
1df7d62951c93babdf2962493588561382dbca38
https://github.com/RobDWaller/ReallySimpleJWT/blob/1df7d62951c93babdf2962493588561382dbca38/src/Encode.php#L109-L112
train
RobDWaller/ReallySimpleJWT
src/Encode.php
Encode.addPadding
private function addPadding(string $base64String): string { if (strlen($base64String) % 4 !== 0) { return $this->addPadding($base64String . '='); } return $base64String; }
php
private function addPadding(string $base64String): string { if (strlen($base64String) % 4 !== 0) { return $this->addPadding($base64String . '='); } return $base64String; }
[ "private", "function", "addPadding", "(", "string", "$", "base64String", ")", ":", "string", "{", "if", "(", "strlen", "(", "$", "base64String", ")", "%", "4", "!==", "0", ")", "{", "return", "$", "this", "->", "addPadding", "(", "$", "base64String", "...
Add padding to base64 strings which require it. Some base64 URL strings which are decoded will have missing padding which is represented by the equals sign. @param string $base64String @return string
[ "Add", "padding", "to", "base64", "strings", "which", "require", "it", ".", "Some", "base64", "URL", "strings", "which", "are", "decoded", "will", "have", "missing", "padding", "which", "is", "represented", "by", "the", "equals", "sign", "." ]
1df7d62951c93babdf2962493588561382dbca38
https://github.com/RobDWaller/ReallySimpleJWT/blob/1df7d62951c93babdf2962493588561382dbca38/src/Encode.php#L144-L151
train
RobDWaller/ReallySimpleJWT
src/Parse.php
Parse.validate
public function validate(): self { if (!$this->validate->structure($this->jwt->getToken())) { throw new ValidateException('Token is invalid.', 1); } $this->validateSignature(); return $this; }
php
public function validate(): self { if (!$this->validate->structure($this->jwt->getToken())) { throw new ValidateException('Token is invalid.', 1); } $this->validateSignature(); return $this; }
[ "public", "function", "validate", "(", ")", ":", "self", "{", "if", "(", "!", "$", "this", "->", "validate", "->", "structure", "(", "$", "this", "->", "jwt", "->", "getToken", "(", ")", ")", ")", "{", "throw", "new", "ValidateException", "(", "'Toke...
Validate the JWT has the right string structure and the signature is valid and has not been tampered with. @return Parse
[ "Validate", "the", "JWT", "has", "the", "right", "string", "structure", "and", "the", "signature", "is", "valid", "and", "has", "not", "been", "tampered", "with", "." ]
1df7d62951c93babdf2962493588561382dbca38
https://github.com/RobDWaller/ReallySimpleJWT/blob/1df7d62951c93babdf2962493588561382dbca38/src/Parse.php#L72-L81
train
RobDWaller/ReallySimpleJWT
src/Parse.php
Parse.parse
public function parse(): Parsed { return new Parsed( $this->jwt, $this->decodeHeader(), $this->decodePayload(), $this->getSignature() ); }
php
public function parse(): Parsed { return new Parsed( $this->jwt, $this->decodeHeader(), $this->decodePayload(), $this->getSignature() ); }
[ "public", "function", "parse", "(", ")", ":", "Parsed", "{", "return", "new", "Parsed", "(", "$", "this", "->", "jwt", ",", "$", "this", "->", "decodeHeader", "(", ")", ",", "$", "this", "->", "decodePayload", "(", ")", ",", "$", "this", "->", "get...
Generate the Parsed Value Object. This method should be called last after the relevant validate methods have been called. @return Parsed
[ "Generate", "the", "Parsed", "Value", "Object", ".", "This", "method", "should", "be", "called", "last", "after", "the", "relevant", "validate", "methods", "have", "been", "called", "." ]
1df7d62951c93babdf2962493588561382dbca38
https://github.com/RobDWaller/ReallySimpleJWT/blob/1df7d62951c93babdf2962493588561382dbca38/src/Parse.php#L119-L127
train
RobDWaller/ReallySimpleJWT
src/Parse.php
Parse.validateSignature
private function validateSignature(): void { $signature = ''; try { $signature = $this->encode->signature( $this->encode->decode($this->getHeader()), $this->encode->decode($this->getPayload()), $this->jwt->getSecret() ); } catch (\Throwable $e) { throw new ValidateException('Token could not be parsed.', 2); } if (!$this->validate->signature($signature, $this->getSignature())) { throw new ValidateException('Signature is invalid.', 3); } }
php
private function validateSignature(): void { $signature = ''; try { $signature = $this->encode->signature( $this->encode->decode($this->getHeader()), $this->encode->decode($this->getPayload()), $this->jwt->getSecret() ); } catch (\Throwable $e) { throw new ValidateException('Token could not be parsed.', 2); } if (!$this->validate->signature($signature, $this->getSignature())) { throw new ValidateException('Signature is invalid.', 3); } }
[ "private", "function", "validateSignature", "(", ")", ":", "void", "{", "$", "signature", "=", "''", ";", "try", "{", "$", "signature", "=", "$", "this", "->", "encode", "->", "signature", "(", "$", "this", "->", "encode", "->", "decode", "(", "$", "...
Validate the JWT's signature. The provided signature taken from the JWT should match one newly generated from the JWT header and payload. @throws Exception\ValidateException
[ "Validate", "the", "JWT", "s", "signature", ".", "The", "provided", "signature", "taken", "from", "the", "JWT", "should", "match", "one", "newly", "generated", "from", "the", "JWT", "header", "and", "payload", "." ]
1df7d62951c93babdf2962493588561382dbca38
https://github.com/RobDWaller/ReallySimpleJWT/blob/1df7d62951c93babdf2962493588561382dbca38/src/Parse.php#L135-L152
train
RobDWaller/ReallySimpleJWT
src/Token.php
Token.create
public static function create($userId, string $secret, int $expiration, string $issuer): string { $builder = self::builder(); return $builder->setPayloadClaim('user_id', $userId) ->setSecret($secret) ->setExpiration($expiration) ->setIssuer($issuer) ->setIssuedAt(time()) ->build() ->getToken(); }
php
public static function create($userId, string $secret, int $expiration, string $issuer): string { $builder = self::builder(); return $builder->setPayloadClaim('user_id', $userId) ->setSecret($secret) ->setExpiration($expiration) ->setIssuer($issuer) ->setIssuedAt(time()) ->build() ->getToken(); }
[ "public", "static", "function", "create", "(", "$", "userId", ",", "string", "$", "secret", ",", "int", "$", "expiration", ",", "string", "$", "issuer", ")", ":", "string", "{", "$", "builder", "=", "self", "::", "builder", "(", ")", ";", "return", "...
Create a JSON Web Token that contains a user identifier and a basic payload including issued at, expiration and issuer. @param mixed $userId @param string $secret @param int $expiration @param string $issuer @return string
[ "Create", "a", "JSON", "Web", "Token", "that", "contains", "a", "user", "identifier", "and", "a", "basic", "payload", "including", "issued", "at", "expiration", "and", "issuer", "." ]
1df7d62951c93babdf2962493588561382dbca38
https://github.com/RobDWaller/ReallySimpleJWT/blob/1df7d62951c93babdf2962493588561382dbca38/src/Token.php#L38-L49
train
RobDWaller/ReallySimpleJWT
src/Token.php
Token.customPayload
public static function customPayload(array $payload, string $secret): string { $builder = self::builder(); foreach ($payload as $key => $value) { if (is_int($key)) { throw new ValidateException('Invalid payload claim.', 8); } $builder->setPayloadClaim($key, $value); } return $builder->setSecret($secret) ->build() ->getToken(); }
php
public static function customPayload(array $payload, string $secret): string { $builder = self::builder(); foreach ($payload as $key => $value) { if (is_int($key)) { throw new ValidateException('Invalid payload claim.', 8); } $builder->setPayloadClaim($key, $value); } return $builder->setSecret($secret) ->build() ->getToken(); }
[ "public", "static", "function", "customPayload", "(", "array", "$", "payload", ",", "string", "$", "secret", ")", ":", "string", "{", "$", "builder", "=", "self", "::", "builder", "(", ")", ";", "foreach", "(", "$", "payload", "as", "$", "key", "=>", ...
Create a JSON Web Token with a custom payload built from a key value array. @param array $payload @return string
[ "Create", "a", "JSON", "Web", "Token", "with", "a", "custom", "payload", "built", "from", "a", "key", "value", "array", "." ]
1df7d62951c93babdf2962493588561382dbca38
https://github.com/RobDWaller/ReallySimpleJWT/blob/1df7d62951c93babdf2962493588561382dbca38/src/Token.php#L59-L74
train
RobDWaller/ReallySimpleJWT
src/Token.php
Token.validate
public static function validate(string $token, string $secret): bool { $parse = self::parser($token, $secret); if (!self::validateWithExpiration($parse)) { return false; } if (!self::validateNotBefore($parse)) { return false; } return true; }
php
public static function validate(string $token, string $secret): bool { $parse = self::parser($token, $secret); if (!self::validateWithExpiration($parse)) { return false; } if (!self::validateNotBefore($parse)) { return false; } return true; }
[ "public", "static", "function", "validate", "(", "string", "$", "token", ",", "string", "$", "secret", ")", ":", "bool", "{", "$", "parse", "=", "self", "::", "parser", "(", "$", "token", ",", "$", "secret", ")", ";", "if", "(", "!", "self", "::", ...
Validate the Json web token, check it's structure and signature. Also check its expiration claim and not before claim if they are set. @param string $token @param string $secret @return bool
[ "Validate", "the", "Json", "web", "token", "check", "it", "s", "structure", "and", "signature", ".", "Also", "check", "its", "expiration", "claim", "and", "not", "before", "claim", "if", "they", "are", "set", "." ]
1df7d62951c93babdf2962493588561382dbca38
https://github.com/RobDWaller/ReallySimpleJWT/blob/1df7d62951c93babdf2962493588561382dbca38/src/Token.php#L85-L98
train
RobDWaller/ReallySimpleJWT
src/Token.php
Token.getHeader
public static function getHeader(string $token, string $secret): array { $parser = self::parser($token, $secret); return $parser->validate()->parse()->getHeader(); }
php
public static function getHeader(string $token, string $secret): array { $parser = self::parser($token, $secret); return $parser->validate()->parse()->getHeader(); }
[ "public", "static", "function", "getHeader", "(", "string", "$", "token", ",", "string", "$", "secret", ")", ":", "array", "{", "$", "parser", "=", "self", "::", "parser", "(", "$", "token", ",", "$", "secret", ")", ";", "return", "$", "parser", "->"...
Return the header of the token as an associative array. You should run the validate method on your token before retrieving the header. @param string $token @return array
[ "Return", "the", "header", "of", "the", "token", "as", "an", "associative", "array", ".", "You", "should", "run", "the", "validate", "method", "on", "your", "token", "before", "retrieving", "the", "header", "." ]
1df7d62951c93babdf2962493588561382dbca38
https://github.com/RobDWaller/ReallySimpleJWT/blob/1df7d62951c93babdf2962493588561382dbca38/src/Token.php#L108-L113
train
RobDWaller/ReallySimpleJWT
src/Token.php
Token.getPayload
public static function getPayload(string $token, string $secret): array { $parser = self::parser($token, $secret); return $parser->validate()->parse()->getPayload(); }
php
public static function getPayload(string $token, string $secret): array { $parser = self::parser($token, $secret); return $parser->validate()->parse()->getPayload(); }
[ "public", "static", "function", "getPayload", "(", "string", "$", "token", ",", "string", "$", "secret", ")", ":", "array", "{", "$", "parser", "=", "self", "::", "parser", "(", "$", "token", ",", "$", "secret", ")", ";", "return", "$", "parser", "->...
Return the payload of the token as an associative array. You should run the validate method on your token before retrieving the payload. @param string $token @return array
[ "Return", "the", "payload", "of", "the", "token", "as", "an", "associative", "array", ".", "You", "should", "run", "the", "validate", "method", "on", "your", "token", "before", "retrieving", "the", "payload", "." ]
1df7d62951c93babdf2962493588561382dbca38
https://github.com/RobDWaller/ReallySimpleJWT/blob/1df7d62951c93babdf2962493588561382dbca38/src/Token.php#L123-L128
train
RobDWaller/ReallySimpleJWT
src/Token.php
Token.parser
public static function parser(string $token, string $secret): Parse { $jwt = new Jwt($token, $secret); return new Parse($jwt, new Validate(), new Encode()); }
php
public static function parser(string $token, string $secret): Parse { $jwt = new Jwt($token, $secret); return new Parse($jwt, new Validate(), new Encode()); }
[ "public", "static", "function", "parser", "(", "string", "$", "token", ",", "string", "$", "secret", ")", ":", "Parse", "{", "$", "jwt", "=", "new", "Jwt", "(", "$", "token", ",", "$", "secret", ")", ";", "return", "new", "Parse", "(", "$", "jwt", ...
Factory method to return instance of the ReallySimpleJWT\Parse class. @return Parse
[ "Factory", "method", "to", "return", "instance", "of", "the", "ReallySimpleJWT", "\\", "Parse", "class", "." ]
1df7d62951c93babdf2962493588561382dbca38
https://github.com/RobDWaller/ReallySimpleJWT/blob/1df7d62951c93babdf2962493588561382dbca38/src/Token.php#L145-L150
train
RobDWaller/ReallySimpleJWT
src/Token.php
Token.validateWithExpiration
private static function validateWithExpiration(Parse $parse): bool { try { $parse->validate() ->validateExpiration(); } catch (ValidateException $e) { if (in_array($e->getCode(), [1, 2, 3, 4], true)) { return false; } } return true; }
php
private static function validateWithExpiration(Parse $parse): bool { try { $parse->validate() ->validateExpiration(); } catch (ValidateException $e) { if (in_array($e->getCode(), [1, 2, 3, 4], true)) { return false; } } return true; }
[ "private", "static", "function", "validateWithExpiration", "(", "Parse", "$", "parse", ")", ":", "bool", "{", "try", "{", "$", "parse", "->", "validate", "(", ")", "->", "validateExpiration", "(", ")", ";", "}", "catch", "(", "ValidateException", "$", "e",...
Run standard validation and expiration validation against the token. Will not return false if the expiration claim is not set. @param Parse $parse @return bool
[ "Run", "standard", "validation", "and", "expiration", "validation", "against", "the", "token", ".", "Will", "not", "return", "false", "if", "the", "expiration", "claim", "is", "not", "set", "." ]
1df7d62951c93babdf2962493588561382dbca38
https://github.com/RobDWaller/ReallySimpleJWT/blob/1df7d62951c93babdf2962493588561382dbca38/src/Token.php#L159-L171
train
RobDWaller/ReallySimpleJWT
src/Token.php
Token.validateNotBefore
private static function validateNotBefore(Parse $parse): bool { try { $parse->validateNotBefore(); } catch (ValidateException $e) { if ($e->getCode() === 5) { return false; } } return true; }
php
private static function validateNotBefore(Parse $parse): bool { try { $parse->validateNotBefore(); } catch (ValidateException $e) { if ($e->getCode() === 5) { return false; } } return true; }
[ "private", "static", "function", "validateNotBefore", "(", "Parse", "$", "parse", ")", ":", "bool", "{", "try", "{", "$", "parse", "->", "validateNotBefore", "(", ")", ";", "}", "catch", "(", "ValidateException", "$", "e", ")", "{", "if", "(", "$", "e"...
Run not before validation against token. Will not return false if the not before claim is not set. @param Parse $parse @return bool
[ "Run", "not", "before", "validation", "against", "token", ".", "Will", "not", "return", "false", "if", "the", "not", "before", "claim", "is", "not", "set", "." ]
1df7d62951c93babdf2962493588561382dbca38
https://github.com/RobDWaller/ReallySimpleJWT/blob/1df7d62951c93babdf2962493588561382dbca38/src/Token.php#L180-L191
train
GrahamCampbell/Laravel-Throttle
src/Throttlers/CacheThrottler.php
CacheThrottler.hit
public function hit() { if ($this->store instanceof RedisStore) { return $this->hitRedis(); } if ($this->count()) { $this->store->increment($this->key); $this->number++; } else { $this->store->put($this->key, 1, $this->time); $this->number = 1; } return $this; }
php
public function hit() { if ($this->store instanceof RedisStore) { return $this->hitRedis(); } if ($this->count()) { $this->store->increment($this->key); $this->number++; } else { $this->store->put($this->key, 1, $this->time); $this->number = 1; } return $this; }
[ "public", "function", "hit", "(", ")", "{", "if", "(", "$", "this", "->", "store", "instanceof", "RedisStore", ")", "{", "return", "$", "this", "->", "hitRedis", "(", ")", ";", "}", "if", "(", "$", "this", "->", "count", "(", ")", ")", "{", "$", ...
Hit the throttle. @return $this
[ "Hit", "the", "throttle", "." ]
ab15752f6cfee2f9901a9af3524f53dfa95326cd
https://github.com/GrahamCampbell/Laravel-Throttle/blob/ab15752f6cfee2f9901a9af3524f53dfa95326cd/src/Throttlers/CacheThrottler.php#L99-L114
train
GrahamCampbell/Laravel-Throttle
src/Throttlers/CacheThrottler.php
CacheThrottler.clear
public function clear() { $this->number = 0; $this->store->put($this->key, $this->number, $this->time); return $this; }
php
public function clear() { $this->number = 0; $this->store->put($this->key, $this->number, $this->time); return $this; }
[ "public", "function", "clear", "(", ")", "{", "$", "this", "->", "number", "=", "0", ";", "$", "this", "->", "store", "->", "put", "(", "$", "this", "->", "key", ",", "$", "this", "->", "number", ",", "$", "this", "->", "time", ")", ";", "retur...
Clear the throttle. @return $this
[ "Clear", "the", "throttle", "." ]
ab15752f6cfee2f9901a9af3524f53dfa95326cd
https://github.com/GrahamCampbell/Laravel-Throttle/blob/ab15752f6cfee2f9901a9af3524f53dfa95326cd/src/Throttlers/CacheThrottler.php#L121-L128
train
GrahamCampbell/Laravel-Throttle
src/Throttlers/CacheThrottler.php
CacheThrottler.count
public function count() { if ($this->number !== null) { return $this->number; } $this->number = (int) $this->store->get($this->key); if (!$this->number) { $this->number = 0; } return $this->number; }
php
public function count() { if ($this->number !== null) { return $this->number; } $this->number = (int) $this->store->get($this->key); if (!$this->number) { $this->number = 0; } return $this->number; }
[ "public", "function", "count", "(", ")", "{", "if", "(", "$", "this", "->", "number", "!==", "null", ")", "{", "return", "$", "this", "->", "number", ";", "}", "$", "this", "->", "number", "=", "(", "int", ")", "$", "this", "->", "store", "->", ...
Get the throttle hit count. @return int
[ "Get", "the", "throttle", "hit", "count", "." ]
ab15752f6cfee2f9901a9af3524f53dfa95326cd
https://github.com/GrahamCampbell/Laravel-Throttle/blob/ab15752f6cfee2f9901a9af3524f53dfa95326cd/src/Throttlers/CacheThrottler.php#L135-L148
train
GrahamCampbell/Laravel-Throttle
src/Throttlers/CacheThrottler.php
CacheThrottler.hitRedis
protected function hitRedis() { $lua = 'local v = redis.call(\'incr\', KEYS[1]) '. 'if v>1 then return v '. 'else redis.call(\'setex\', KEYS[1], ARGV[1], 1) return 1 end'; $this->number = $this->store->connection()->eval($lua, 1, $this->computeRedisKey(), $this->time * 60); return $this; }
php
protected function hitRedis() { $lua = 'local v = redis.call(\'incr\', KEYS[1]) '. 'if v>1 then return v '. 'else redis.call(\'setex\', KEYS[1], ARGV[1], 1) return 1 end'; $this->number = $this->store->connection()->eval($lua, 1, $this->computeRedisKey(), $this->time * 60); return $this; }
[ "protected", "function", "hitRedis", "(", ")", "{", "$", "lua", "=", "'local v = redis.call(\\'incr\\', KEYS[1]) '", ".", "'if v>1 then return v '", ".", "'else redis.call(\\'setex\\', KEYS[1], ARGV[1], 1) return 1 end'", ";", "$", "this", "->", "number", "=", "$", "this", ...
An atomic hit implementation for redis. @return $this
[ "An", "atomic", "hit", "implementation", "for", "redis", "." ]
ab15752f6cfee2f9901a9af3524f53dfa95326cd
https://github.com/GrahamCampbell/Laravel-Throttle/blob/ab15752f6cfee2f9901a9af3524f53dfa95326cd/src/Throttlers/CacheThrottler.php#L175-L184
train