repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6 values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1 value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
neos/flow-development-collection | Neos.Flow/Classes/Cli/ConsoleOutput.php | ConsoleOutput.getProgressBar | protected function getProgressBar(): ProgressBar
{
if ($this->progressBar === null) {
$this->progressBar = new ProgressBar($this->output);
}
return $this->progressBar;
} | php | protected function getProgressBar(): ProgressBar
{
if ($this->progressBar === null) {
$this->progressBar = new ProgressBar($this->output);
}
return $this->progressBar;
} | [
"protected",
"function",
"getProgressBar",
"(",
")",
":",
"ProgressBar",
"{",
"if",
"(",
"$",
"this",
"->",
"progressBar",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"progressBar",
"=",
"new",
"ProgressBar",
"(",
"$",
"this",
"->",
"output",
")",
";",
... | Returns or initializes the symfony/console ProgressHelper
@return ProgressBar | [
"Returns",
"or",
"initializes",
"the",
"symfony",
"/",
"console",
"ProgressHelper"
] | train | https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Cli/ConsoleOutput.php#L388-L394 |
neos/flow-development-collection | Neos.Flow/Classes/Cli/ConsoleOutput.php | ConsoleOutput.getTable | protected function getTable(): Table
{
if ($this->table === null) {
$this->table = new Table($this->output);
}
return $this->table;
} | php | protected function getTable(): Table
{
if ($this->table === null) {
$this->table = new Table($this->output);
}
return $this->table;
} | [
"protected",
"function",
"getTable",
"(",
")",
":",
"Table",
"{",
"if",
"(",
"$",
"this",
"->",
"table",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"table",
"=",
"new",
"Table",
"(",
"$",
"this",
"->",
"output",
")",
";",
"}",
"return",
"$",
"th... | Returns or initializes the symfony/console Table
@return Table | [
"Returns",
"or",
"initializes",
"the",
"symfony",
"/",
"console",
"Table"
] | train | https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Cli/ConsoleOutput.php#L401-L407 |
neos/flow-development-collection | Neos.Flow/Classes/Monitor/FileMonitor.php | FileMonitor.createFileMonitorAtBoot | public static function createFileMonitorAtBoot($identifier, Bootstrap $bootstrap)
{
$fileMonitorCache = $bootstrap->getEarlyInstance(CacheManager::class)->getCache('Flow_Monitor');
// The change detector needs to be instantiated and registered manually because
// it has a complex dependency (cache) but still needs to be a singleton.
$fileChangeDetector = new ChangeDetectionStrategy\ModificationTimeStrategy();
$fileChangeDetector->injectCache($fileMonitorCache);
$bootstrap->getObjectManager()->registerShutdownObject($fileChangeDetector, 'shutdownObject');
$fileMonitor = new FileMonitor($identifier);
$fileMonitor->injectCache($fileMonitorCache);
$fileMonitor->injectChangeDetectionStrategy($fileChangeDetector);
$fileMonitor->injectSignalDispatcher($bootstrap->getEarlyInstance(Dispatcher::class));
$fileMonitor->injectLogger($bootstrap->getEarlyInstance(PsrLoggerFactoryInterface::class)->get('systemLogger'));
return $fileMonitor;
} | php | public static function createFileMonitorAtBoot($identifier, Bootstrap $bootstrap)
{
$fileMonitorCache = $bootstrap->getEarlyInstance(CacheManager::class)->getCache('Flow_Monitor');
// The change detector needs to be instantiated and registered manually because
// it has a complex dependency (cache) but still needs to be a singleton.
$fileChangeDetector = new ChangeDetectionStrategy\ModificationTimeStrategy();
$fileChangeDetector->injectCache($fileMonitorCache);
$bootstrap->getObjectManager()->registerShutdownObject($fileChangeDetector, 'shutdownObject');
$fileMonitor = new FileMonitor($identifier);
$fileMonitor->injectCache($fileMonitorCache);
$fileMonitor->injectChangeDetectionStrategy($fileChangeDetector);
$fileMonitor->injectSignalDispatcher($bootstrap->getEarlyInstance(Dispatcher::class));
$fileMonitor->injectLogger($bootstrap->getEarlyInstance(PsrLoggerFactoryInterface::class)->get('systemLogger'));
return $fileMonitor;
} | [
"public",
"static",
"function",
"createFileMonitorAtBoot",
"(",
"$",
"identifier",
",",
"Bootstrap",
"$",
"bootstrap",
")",
"{",
"$",
"fileMonitorCache",
"=",
"$",
"bootstrap",
"->",
"getEarlyInstance",
"(",
"CacheManager",
"::",
"class",
")",
"->",
"getCache",
... | Helper method to create a FileMonitor instance during boot sequence as injections have to be done manually.
@param string $identifier
@param Bootstrap $bootstrap
@return FileMonitor | [
"Helper",
"method",
"to",
"create",
"a",
"FileMonitor",
"instance",
"during",
"boot",
"sequence",
"as",
"injections",
"have",
"to",
"be",
"done",
"manually",
"."
] | train | https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Monitor/FileMonitor.php#L106-L123 |
neos/flow-development-collection | Neos.Flow/Classes/Monitor/FileMonitor.php | FileMonitor.injectChangeDetectionStrategy | public function injectChangeDetectionStrategy(ChangeDetectionStrategyInterface $changeDetectionStrategy)
{
$this->changeDetectionStrategy = $changeDetectionStrategy;
$this->changeDetectionStrategy->setFileMonitor($this);
} | php | public function injectChangeDetectionStrategy(ChangeDetectionStrategyInterface $changeDetectionStrategy)
{
$this->changeDetectionStrategy = $changeDetectionStrategy;
$this->changeDetectionStrategy->setFileMonitor($this);
} | [
"public",
"function",
"injectChangeDetectionStrategy",
"(",
"ChangeDetectionStrategyInterface",
"$",
"changeDetectionStrategy",
")",
"{",
"$",
"this",
"->",
"changeDetectionStrategy",
"=",
"$",
"changeDetectionStrategy",
";",
"$",
"this",
"->",
"changeDetectionStrategy",
"-... | Injects the Change Detection Strategy
@param ChangeDetectionStrategyInterface $changeDetectionStrategy The strategy to use for detecting changes
@return void | [
"Injects",
"the",
"Change",
"Detection",
"Strategy"
] | train | https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Monitor/FileMonitor.php#L131-L135 |
neos/flow-development-collection | Neos.Flow/Classes/Monitor/FileMonitor.php | FileMonitor.monitorFile | public function monitorFile($pathAndFilename)
{
if (!is_string($pathAndFilename)) {
throw new \InvalidArgumentException('String expected, ' . gettype($pathAndFilename), ' given.', 1231171809);
}
$pathAndFilename = Files::getUnixStylePath($pathAndFilename);
if (array_search($pathAndFilename, $this->monitoredFiles) === false) {
$this->monitoredFiles[] = $pathAndFilename;
}
} | php | public function monitorFile($pathAndFilename)
{
if (!is_string($pathAndFilename)) {
throw new \InvalidArgumentException('String expected, ' . gettype($pathAndFilename), ' given.', 1231171809);
}
$pathAndFilename = Files::getUnixStylePath($pathAndFilename);
if (array_search($pathAndFilename, $this->monitoredFiles) === false) {
$this->monitoredFiles[] = $pathAndFilename;
}
} | [
"public",
"function",
"monitorFile",
"(",
"$",
"pathAndFilename",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"pathAndFilename",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'String expected, '",
".",
"gettype",
"(",
"$",
"pathAn... | Adds the specified file to the list of files to be monitored.
The file in question does not necessarily have to exist.
@param string $pathAndFilename Absolute path and filename of the file to monitor
@return void
@throws \InvalidArgumentException
@api | [
"Adds",
"the",
"specified",
"file",
"to",
"the",
"list",
"of",
"files",
"to",
"be",
"monitored",
".",
"The",
"file",
"in",
"question",
"does",
"not",
"necessarily",
"have",
"to",
"exist",
"."
] | train | https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Monitor/FileMonitor.php#L190-L199 |
neos/flow-development-collection | Neos.Flow/Classes/Monitor/FileMonitor.php | FileMonitor.monitorDirectory | public function monitorDirectory($path, $filenamePattern = null)
{
if (!is_string($path)) {
throw new \InvalidArgumentException('String expected, ' . gettype($path), ' given.', 1231171810);
}
$path = Files::getNormalizedPath(Files::getUnixStylePath($path));
if (!array_key_exists($path, $this->monitoredDirectories)) {
$this->monitoredDirectories[$path] = $filenamePattern;
}
} | php | public function monitorDirectory($path, $filenamePattern = null)
{
if (!is_string($path)) {
throw new \InvalidArgumentException('String expected, ' . gettype($path), ' given.', 1231171810);
}
$path = Files::getNormalizedPath(Files::getUnixStylePath($path));
if (!array_key_exists($path, $this->monitoredDirectories)) {
$this->monitoredDirectories[$path] = $filenamePattern;
}
} | [
"public",
"function",
"monitorDirectory",
"(",
"$",
"path",
",",
"$",
"filenamePattern",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"path",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'String expected, '",
".",
... | Adds the specified directory to the list of directories to be monitored.
All files in these directories will be monitored too.
@param string $path Absolute path of the directory to monitor
@param string $filenamePattern A pattern for filenames to consider for file monitoring (regular expression)
@return void
@throws \InvalidArgumentException
@api | [
"Adds",
"the",
"specified",
"directory",
"to",
"the",
"list",
"of",
"directories",
"to",
"be",
"monitored",
".",
"All",
"files",
"in",
"these",
"directories",
"will",
"be",
"monitored",
"too",
"."
] | train | https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Monitor/FileMonitor.php#L211-L220 |
neos/flow-development-collection | Neos.Flow/Classes/Monitor/FileMonitor.php | FileMonitor.detectChanges | public function detectChanges()
{
if ($this->changedFiles === null || $this->changedPaths === null) {
$this->loadDetectedDirectoriesAndFiles();
$changesDetected = false;
$this->changedPaths = $this->changedFiles = [];
$this->changedFiles = $this->detectChangedFiles($this->monitoredFiles);
foreach ($this->monitoredDirectories as $path => $filenamePattern) {
$changesDetected = $this->detectChangesOnPath($path, $filenamePattern) ? true : $changesDetected;
}
if ($changesDetected) {
$this->saveDetectedDirectoriesAndFiles();
}
$this->directoriesAndFiles = null;
}
$changedFileCount = count($this->changedFiles);
$changedPathCount = count($this->changedPaths);
if ($changedFileCount > 0) {
$this->emitFilesHaveChanged($this->identifier, $this->changedFiles);
}
if ($changedPathCount > 0) {
$this->emitDirectoriesHaveChanged($this->identifier, $this->changedPaths);
}
if ($changedFileCount > 0 || $changedPathCount) {
$this->logger->info(sprintf('File Monitor "%s" detected %s changed files and %s changed directories.', $this->identifier, $changedFileCount, $changedPathCount), LogEnvironment::fromMethodName(__METHOD__));
}
} | php | public function detectChanges()
{
if ($this->changedFiles === null || $this->changedPaths === null) {
$this->loadDetectedDirectoriesAndFiles();
$changesDetected = false;
$this->changedPaths = $this->changedFiles = [];
$this->changedFiles = $this->detectChangedFiles($this->monitoredFiles);
foreach ($this->monitoredDirectories as $path => $filenamePattern) {
$changesDetected = $this->detectChangesOnPath($path, $filenamePattern) ? true : $changesDetected;
}
if ($changesDetected) {
$this->saveDetectedDirectoriesAndFiles();
}
$this->directoriesAndFiles = null;
}
$changedFileCount = count($this->changedFiles);
$changedPathCount = count($this->changedPaths);
if ($changedFileCount > 0) {
$this->emitFilesHaveChanged($this->identifier, $this->changedFiles);
}
if ($changedPathCount > 0) {
$this->emitDirectoriesHaveChanged($this->identifier, $this->changedPaths);
}
if ($changedFileCount > 0 || $changedPathCount) {
$this->logger->info(sprintf('File Monitor "%s" detected %s changed files and %s changed directories.', $this->identifier, $changedFileCount, $changedPathCount), LogEnvironment::fromMethodName(__METHOD__));
}
} | [
"public",
"function",
"detectChanges",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"changedFiles",
"===",
"null",
"||",
"$",
"this",
"->",
"changedPaths",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"loadDetectedDirectoriesAndFiles",
"(",
")",
";",
"$",
... | Detects changes of the files and directories to be monitored and emits signals
accordingly.
@return void
@api | [
"Detects",
"changes",
"of",
"the",
"files",
"and",
"directories",
"to",
"be",
"monitored",
"and",
"emits",
"signals",
"accordingly",
"."
] | train | https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Monitor/FileMonitor.php#L251-L281 |
neos/flow-development-collection | Neos.Flow/Classes/Monitor/FileMonitor.php | FileMonitor.detectChangesOnPath | protected function detectChangesOnPath($path, $filenamePattern)
{
$currentDirectoryChanged = false;
try {
$currentSubDirectoriesAndFiles = $this->readMonitoredDirectoryRecursively($path, $filenamePattern);
} catch (\Exception $exception) {
$currentSubDirectoriesAndFiles = [];
$this->changedPaths[$path] = ChangeDetectionStrategyInterface::STATUS_DELETED;
}
$nowDetectedFilesAndDirectories = [];
if (!isset($this->directoriesAndFiles[$path])) {
$this->directoriesAndFiles[$path] = [];
$this->changedPaths[$path] = ChangeDetectionStrategyInterface::STATUS_CREATED;
}
foreach ($currentSubDirectoriesAndFiles as $pathAndFilename) {
$status = $this->changeDetectionStrategy->getFileStatus($pathAndFilename);
if ($status !== ChangeDetectionStrategyInterface::STATUS_UNCHANGED) {
$this->changedFiles[$pathAndFilename] = $status;
$currentDirectoryChanged = true;
}
if (isset($this->directoriesAndFiles[$path][$pathAndFilename])) {
unset($this->directoriesAndFiles[$path][$pathAndFilename]);
}
$nowDetectedFilesAndDirectories[$pathAndFilename] = 1;
}
if ($this->directoriesAndFiles[$path] !== []) {
foreach (array_keys($this->directoriesAndFiles[$path]) as $pathAndFilename) {
$this->changedFiles[$pathAndFilename] = ChangeDetectionStrategyInterface::STATUS_DELETED;
if ($this->changeDetectionStrategy instanceof StrategyWithMarkDeletedInterface) {
$this->changeDetectionStrategy->setFileDeleted($pathAndFilename);
} else {
// This call is needed to mark the file deleted in any possibly existing caches of the strategy.
// The return value is not important as we know this file doesn't exist so we set the status to DELETED anyway.
$this->changeDetectionStrategy->getFileStatus($pathAndFilename);
}
}
$currentDirectoryChanged = true;
}
if ($currentDirectoryChanged) {
$this->setDetectedFilesForPath($path, $nowDetectedFilesAndDirectories);
}
return $currentDirectoryChanged;
} | php | protected function detectChangesOnPath($path, $filenamePattern)
{
$currentDirectoryChanged = false;
try {
$currentSubDirectoriesAndFiles = $this->readMonitoredDirectoryRecursively($path, $filenamePattern);
} catch (\Exception $exception) {
$currentSubDirectoriesAndFiles = [];
$this->changedPaths[$path] = ChangeDetectionStrategyInterface::STATUS_DELETED;
}
$nowDetectedFilesAndDirectories = [];
if (!isset($this->directoriesAndFiles[$path])) {
$this->directoriesAndFiles[$path] = [];
$this->changedPaths[$path] = ChangeDetectionStrategyInterface::STATUS_CREATED;
}
foreach ($currentSubDirectoriesAndFiles as $pathAndFilename) {
$status = $this->changeDetectionStrategy->getFileStatus($pathAndFilename);
if ($status !== ChangeDetectionStrategyInterface::STATUS_UNCHANGED) {
$this->changedFiles[$pathAndFilename] = $status;
$currentDirectoryChanged = true;
}
if (isset($this->directoriesAndFiles[$path][$pathAndFilename])) {
unset($this->directoriesAndFiles[$path][$pathAndFilename]);
}
$nowDetectedFilesAndDirectories[$pathAndFilename] = 1;
}
if ($this->directoriesAndFiles[$path] !== []) {
foreach (array_keys($this->directoriesAndFiles[$path]) as $pathAndFilename) {
$this->changedFiles[$pathAndFilename] = ChangeDetectionStrategyInterface::STATUS_DELETED;
if ($this->changeDetectionStrategy instanceof StrategyWithMarkDeletedInterface) {
$this->changeDetectionStrategy->setFileDeleted($pathAndFilename);
} else {
// This call is needed to mark the file deleted in any possibly existing caches of the strategy.
// The return value is not important as we know this file doesn't exist so we set the status to DELETED anyway.
$this->changeDetectionStrategy->getFileStatus($pathAndFilename);
}
}
$currentDirectoryChanged = true;
}
if ($currentDirectoryChanged) {
$this->setDetectedFilesForPath($path, $nowDetectedFilesAndDirectories);
}
return $currentDirectoryChanged;
} | [
"protected",
"function",
"detectChangesOnPath",
"(",
"$",
"path",
",",
"$",
"filenamePattern",
")",
"{",
"$",
"currentDirectoryChanged",
"=",
"false",
";",
"try",
"{",
"$",
"currentSubDirectoriesAndFiles",
"=",
"$",
"this",
"->",
"readMonitoredDirectoryRecursively",
... | Detect changes for one of the monitored paths.
@param string $path
@param string $filenamePattern
@return boolean true if any changes were detected in this path | [
"Detect",
"changes",
"for",
"one",
"of",
"the",
"monitored",
"paths",
"."
] | train | https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Monitor/FileMonitor.php#L290-L338 |
neos/flow-development-collection | Neos.Flow/Classes/Monitor/FileMonitor.php | FileMonitor.readMonitoredDirectoryRecursively | protected function readMonitoredDirectoryRecursively($path, $filenamePattern)
{
$directories = [Files::getNormalizedPath($path)];
while ($directories !== []) {
$currentDirectory = array_pop($directories);
if (is_file($currentDirectory . '.flowFileMonitorIgnore')) {
continue;
}
if ($handle = opendir($currentDirectory)) {
while (false !== ($filename = readdir($handle))) {
if ($filename[0] === '.') {
continue;
}
$pathAndFilename = $currentDirectory . $filename;
if (is_dir($pathAndFilename)) {
array_push($directories, $pathAndFilename . DIRECTORY_SEPARATOR);
} elseif ($filenamePattern === null || preg_match('|' . $filenamePattern . '|', $filename) === 1) {
yield $pathAndFilename;
}
}
closedir($handle);
}
}
} | php | protected function readMonitoredDirectoryRecursively($path, $filenamePattern)
{
$directories = [Files::getNormalizedPath($path)];
while ($directories !== []) {
$currentDirectory = array_pop($directories);
if (is_file($currentDirectory . '.flowFileMonitorIgnore')) {
continue;
}
if ($handle = opendir($currentDirectory)) {
while (false !== ($filename = readdir($handle))) {
if ($filename[0] === '.') {
continue;
}
$pathAndFilename = $currentDirectory . $filename;
if (is_dir($pathAndFilename)) {
array_push($directories, $pathAndFilename . DIRECTORY_SEPARATOR);
} elseif ($filenamePattern === null || preg_match('|' . $filenamePattern . '|', $filename) === 1) {
yield $pathAndFilename;
}
}
closedir($handle);
}
}
} | [
"protected",
"function",
"readMonitoredDirectoryRecursively",
"(",
"$",
"path",
",",
"$",
"filenamePattern",
")",
"{",
"$",
"directories",
"=",
"[",
"Files",
"::",
"getNormalizedPath",
"(",
"$",
"path",
")",
"]",
";",
"while",
"(",
"$",
"directories",
"!==",
... | Read a monitored directory recursively, taking into account filename patterns
@param string $path The path of a monitored directory
@param string $filenamePattern
@return \Generator<string> A generator returning filenames with full path | [
"Read",
"a",
"monitored",
"directory",
"recursively",
"taking",
"into",
"account",
"filename",
"patterns"
] | train | https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Monitor/FileMonitor.php#L347-L370 |
neos/flow-development-collection | Neos.Flow/Classes/Monitor/FileMonitor.php | FileMonitor.loadDetectedDirectoriesAndFiles | protected function loadDetectedDirectoriesAndFiles()
{
if ($this->directoriesAndFiles === null) {
$this->directoriesAndFiles = json_decode($this->cache->get($this->identifier . '_directoriesAndFiles'), true);
if (!is_array($this->directoriesAndFiles)) {
$this->directoriesAndFiles = [];
}
}
} | php | protected function loadDetectedDirectoriesAndFiles()
{
if ($this->directoriesAndFiles === null) {
$this->directoriesAndFiles = json_decode($this->cache->get($this->identifier . '_directoriesAndFiles'), true);
if (!is_array($this->directoriesAndFiles)) {
$this->directoriesAndFiles = [];
}
}
} | [
"protected",
"function",
"loadDetectedDirectoriesAndFiles",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"directoriesAndFiles",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"directoriesAndFiles",
"=",
"json_decode",
"(",
"$",
"this",
"->",
"cache",
"->",
"get",... | Loads the last detected files for this monitor.
@return void | [
"Loads",
"the",
"last",
"detected",
"files",
"for",
"this",
"monitor",
"."
] | train | https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Monitor/FileMonitor.php#L377-L385 |
neos/flow-development-collection | Neos.Flow/Classes/Monitor/FileMonitor.php | FileMonitor.detectChangedFiles | protected function detectChangedFiles(array $pathAndFilenames)
{
$changedFiles = [];
foreach ($pathAndFilenames as $pathAndFilename) {
$status = $this->changeDetectionStrategy->getFileStatus($pathAndFilename);
if ($status !== ChangeDetectionStrategyInterface::STATUS_UNCHANGED) {
$changedFiles[$pathAndFilename] = $status;
}
}
return $changedFiles;
} | php | protected function detectChangedFiles(array $pathAndFilenames)
{
$changedFiles = [];
foreach ($pathAndFilenames as $pathAndFilename) {
$status = $this->changeDetectionStrategy->getFileStatus($pathAndFilename);
if ($status !== ChangeDetectionStrategyInterface::STATUS_UNCHANGED) {
$changedFiles[$pathAndFilename] = $status;
}
}
return $changedFiles;
} | [
"protected",
"function",
"detectChangedFiles",
"(",
"array",
"$",
"pathAndFilenames",
")",
"{",
"$",
"changedFiles",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"pathAndFilenames",
"as",
"$",
"pathAndFilename",
")",
"{",
"$",
"status",
"=",
"$",
"this",
"->",
... | Detects changes in the given list of files and emits signals if necessary.
@param array $pathAndFilenames A list of full path and filenames of files to check
@return array An array of changed files (key = path and filenmae) and their status (value) | [
"Detects",
"changes",
"in",
"the",
"given",
"list",
"of",
"files",
"and",
"emits",
"signals",
"if",
"necessary",
"."
] | train | https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Monitor/FileMonitor.php#L413-L423 |
bramus/monolog-colored-line-formatter | src/Formatter/ColorSchemes/ColorSchemeTrait.php | ColorSchemeTrait.setColorizeArray | public function setColorizeArray(array $colorScheme)
{
// Only store entries that exist as Monolog\Logger levels
$allowedLogLevels = array_values(\Monolog\Logger::getLevels());
$colorScheme = array_intersect_key($colorScheme, array_flip($allowedLogLevels));
// Store the filtered colorScheme
$this->colorScheme = $colorScheme;
} | php | public function setColorizeArray(array $colorScheme)
{
// Only store entries that exist as Monolog\Logger levels
$allowedLogLevels = array_values(\Monolog\Logger::getLevels());
$colorScheme = array_intersect_key($colorScheme, array_flip($allowedLogLevels));
// Store the filtered colorScheme
$this->colorScheme = $colorScheme;
} | [
"public",
"function",
"setColorizeArray",
"(",
"array",
"$",
"colorScheme",
")",
"{",
"// Only store entries that exist as Monolog\\Logger levels",
"$",
"allowedLogLevels",
"=",
"array_values",
"(",
"\\",
"Monolog",
"\\",
"Logger",
"::",
"getLevels",
"(",
")",
")",
";... | Set the Color Scheme Array
@param array $colorScheme The Color Scheme Array | [
"Set",
"the",
"Color",
"Scheme",
"Array"
] | train | https://github.com/bramus/monolog-colored-line-formatter/blob/38475caf0f207fdb6d84ee0a08492dc3f49ef8e6/src/Formatter/ColorSchemes/ColorSchemeTrait.php#L35-L43 |
bramus/monolog-colored-line-formatter | src/Formatter/ColoredLineFormatter.php | ColoredLineFormatter.format | public function format(array $record) : string
{
// Get the Color Scheme
$colorScheme = $this->getColorScheme();
// Let the parent class to the formatting, yet wrap it in the color linked to the level
return $colorScheme->getColorizeString($record['level']).trim(parent::format($record)).$colorScheme->getResetString()."\n";
} | php | public function format(array $record) : string
{
// Get the Color Scheme
$colorScheme = $this->getColorScheme();
// Let the parent class to the formatting, yet wrap it in the color linked to the level
return $colorScheme->getColorizeString($record['level']).trim(parent::format($record)).$colorScheme->getResetString()."\n";
} | [
"public",
"function",
"format",
"(",
"array",
"$",
"record",
")",
":",
"string",
"{",
"// Get the Color Scheme",
"$",
"colorScheme",
"=",
"$",
"this",
"->",
"getColorScheme",
"(",
")",
";",
"// Let the parent class to the formatting, yet wrap it in the color linked to the... | {@inheritdoc} | [
"{"
] | train | https://github.com/bramus/monolog-colored-line-formatter/blob/38475caf0f207fdb6d84ee0a08492dc3f49ef8e6/src/Formatter/ColoredLineFormatter.php#L58-L65 |
alexdebril/rss-atom-bundle | Provider/MockProvider.php | MockProvider.getFeedContent | public function getFeedContent(array $options) : FeedInterface
{
$feed = new Feed();
$id = array_key_exists('id', $options) ? $options['id'] : null;
if ($id === 'not-found') {
throw new FeedNotFoundException();
}
$feed->setPublicId($id);
$feed->setTitle('thank you for using RssAtomBundle');
$feed->setDescription('this is the mock FeedContent');
$feed->setLink('https://raw.github.com/alexdebril/rss-atom-bundle/');
$feed->setLastModified(new \DateTime());
return $this->addItem($feed);
} | php | public function getFeedContent(array $options) : FeedInterface
{
$feed = new Feed();
$id = array_key_exists('id', $options) ? $options['id'] : null;
if ($id === 'not-found') {
throw new FeedNotFoundException();
}
$feed->setPublicId($id);
$feed->setTitle('thank you for using RssAtomBundle');
$feed->setDescription('this is the mock FeedContent');
$feed->setLink('https://raw.github.com/alexdebril/rss-atom-bundle/');
$feed->setLastModified(new \DateTime());
return $this->addItem($feed);
} | [
"public",
"function",
"getFeedContent",
"(",
"array",
"$",
"options",
")",
":",
"FeedInterface",
"{",
"$",
"feed",
"=",
"new",
"Feed",
"(",
")",
";",
"$",
"id",
"=",
"array_key_exists",
"(",
"'id'",
",",
"$",
"options",
")",
"?",
"$",
"options",
"[",
... | @param array $options
@return FeedInterface
@throws FeedNotFoundException | [
"@param",
"array",
"$options"
] | train | https://github.com/alexdebril/rss-atom-bundle/blob/87b93273eb7e995547060ac17d9a1b21061013e3/Provider/MockProvider.php#L31-L49 |
alexdebril/rss-atom-bundle | DependencyInjection/Configuration.php | Configuration.getConfigTreeBuilder | public function getConfigTreeBuilder() : TreeBuilder
{
$treeBuilder = new TreeBuilder();
$treeBuilder->root('debril_rss_atom')
->children()
->booleanNode('private')
->info('Change cache headers so the RSS feed is not cached by public caches (like reverse-proxies...).')
->defaultValue(false)
->end()
->booleanNode('force_refresh')
->info('Do not send 304 status if the feed has not been modified since last hit')
->defaultValue(false)
->end()
->scalarNode('content_type_json')
->info('Content-Type header value to use for json feed generation.')
->defaultValue('application/json')
->end()
->scalarNode('content_type_xml')
->info('Content-Type header value to use for xml feed generation (atom and rss).')
->defaultValue('application/xhtml+xml')
->end()
->arrayNode('date_formats')
->prototype('scalar')->end()
->end()
->end()
;
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
} | php | public function getConfigTreeBuilder() : TreeBuilder
{
$treeBuilder = new TreeBuilder();
$treeBuilder->root('debril_rss_atom')
->children()
->booleanNode('private')
->info('Change cache headers so the RSS feed is not cached by public caches (like reverse-proxies...).')
->defaultValue(false)
->end()
->booleanNode('force_refresh')
->info('Do not send 304 status if the feed has not been modified since last hit')
->defaultValue(false)
->end()
->scalarNode('content_type_json')
->info('Content-Type header value to use for json feed generation.')
->defaultValue('application/json')
->end()
->scalarNode('content_type_xml')
->info('Content-Type header value to use for xml feed generation (atom and rss).')
->defaultValue('application/xhtml+xml')
->end()
->arrayNode('date_formats')
->prototype('scalar')->end()
->end()
->end()
;
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
} | [
"public",
"function",
"getConfigTreeBuilder",
"(",
")",
":",
"TreeBuilder",
"{",
"$",
"treeBuilder",
"=",
"new",
"TreeBuilder",
"(",
")",
";",
"$",
"treeBuilder",
"->",
"root",
"(",
"'debril_rss_atom'",
")",
"->",
"children",
"(",
")",
"->",
"booleanNode",
"... | {@inheritDoc} | [
"{"
] | train | https://github.com/alexdebril/rss-atom-bundle/blob/87b93273eb7e995547060ac17d9a1b21061013e3/DependencyInjection/Configuration.php#L18-L50 |
alexdebril/rss-atom-bundle | Provider/DoctrineFeedContentProvider.php | DoctrineFeedContentProvider.getFeedContent | public function getFeedContent(array $options) : FeedInterface
{
// fetch feed from data repository
$feed = $this->getDoctrine()
->getManager()
->getRepository($this->getRepositoryName())
->findOneById($this->getIdFromOptions($options));
// if the feed is an actual FeedInterface instance, then return it
if ($feed instanceof FeedInterface) {
return $feed;
}
// $feed is null, which means no Feed was found with this id.
throw new FeedNotFoundException();
} | php | public function getFeedContent(array $options) : FeedInterface
{
// fetch feed from data repository
$feed = $this->getDoctrine()
->getManager()
->getRepository($this->getRepositoryName())
->findOneById($this->getIdFromOptions($options));
// if the feed is an actual FeedInterface instance, then return it
if ($feed instanceof FeedInterface) {
return $feed;
}
// $feed is null, which means no Feed was found with this id.
throw new FeedNotFoundException();
} | [
"public",
"function",
"getFeedContent",
"(",
"array",
"$",
"options",
")",
":",
"FeedInterface",
"{",
"// fetch feed from data repository",
"$",
"feed",
"=",
"$",
"this",
"->",
"getDoctrine",
"(",
")",
"->",
"getManager",
"(",
")",
"->",
"getRepository",
"(",
... | @param array $options
@return FeedInterface
@throws FeedNotFoundException | [
"@param",
"array",
"$options"
] | train | https://github.com/alexdebril/rss-atom-bundle/blob/87b93273eb7e995547060ac17d9a1b21061013e3/Provider/DoctrineFeedContentProvider.php#L71-L86 |
alexdebril/rss-atom-bundle | Provider/DoctrineFeedContentProvider.php | DoctrineFeedContentProvider.getIdFromOptions | public function getIdFromOptions(array $options) : string
{
$optionsResolver = new OptionsResolver();
$optionsResolver->setRequired('id');
$options = $optionsResolver->resolve($options);
return $options['id'];
} | php | public function getIdFromOptions(array $options) : string
{
$optionsResolver = new OptionsResolver();
$optionsResolver->setRequired('id');
$options = $optionsResolver->resolve($options);
return $options['id'];
} | [
"public",
"function",
"getIdFromOptions",
"(",
"array",
"$",
"options",
")",
":",
"string",
"{",
"$",
"optionsResolver",
"=",
"new",
"OptionsResolver",
"(",
")",
";",
"$",
"optionsResolver",
"->",
"setRequired",
"(",
"'id'",
")",
";",
"$",
"options",
"=",
... | @param array $options
@return string | [
"@param",
"array",
"$options"
] | train | https://github.com/alexdebril/rss-atom-bundle/blob/87b93273eb7e995547060ac17d9a1b21061013e3/Provider/DoctrineFeedContentProvider.php#L101-L109 |
alexdebril/rss-atom-bundle | Controller/StreamController.php | StreamController.getModifiedSince | protected function getModifiedSince() : \DateTime
{
if (is_null($this->since)) {
$this->since = new \DateTime('@0');
}
return $this->since;
} | php | protected function getModifiedSince() : \DateTime
{
if (is_null($this->since)) {
$this->since = new \DateTime('@0');
}
return $this->since;
} | [
"protected",
"function",
"getModifiedSince",
"(",
")",
":",
"\\",
"DateTime",
"{",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"since",
")",
")",
"{",
"$",
"this",
"->",
"since",
"=",
"new",
"\\",
"DateTime",
"(",
"'@0'",
")",
";",
"}",
"return",
... | Extract the 'If-Modified-Since' value from the headers.
@return \DateTime | [
"Extract",
"the",
"If",
"-",
"Modified",
"-",
"Since",
"value",
"from",
"the",
"headers",
"."
] | train | https://github.com/alexdebril/rss-atom-bundle/blob/87b93273eb7e995547060ac17d9a1b21061013e3/Controller/StreamController.php#L50-L57 |
alexdebril/rss-atom-bundle | Controller/StreamController.php | StreamController.setModifiedSince | protected function setModifiedSince(Request $request) : self
{
$this->since = new \DateTime();
if ($request->headers->has('If-Modified-Since')) {
$string = $request->headers->get('If-Modified-Since');
$this->since = \DateTime::createFromFormat(\DateTime::RSS, $string);
} else {
$this->since->setTimestamp(1);
}
return $this;
} | php | protected function setModifiedSince(Request $request) : self
{
$this->since = new \DateTime();
if ($request->headers->has('If-Modified-Since')) {
$string = $request->headers->get('If-Modified-Since');
$this->since = \DateTime::createFromFormat(\DateTime::RSS, $string);
} else {
$this->since->setTimestamp(1);
}
return $this;
} | [
"protected",
"function",
"setModifiedSince",
"(",
"Request",
"$",
"request",
")",
":",
"self",
"{",
"$",
"this",
"->",
"since",
"=",
"new",
"\\",
"DateTime",
"(",
")",
";",
"if",
"(",
"$",
"request",
"->",
"headers",
"->",
"has",
"(",
"'If-Modified-Since... | @param Request $request
@return $this | [
"@param",
"Request",
"$request"
] | train | https://github.com/alexdebril/rss-atom-bundle/blob/87b93273eb7e995547060ac17d9a1b21061013e3/Controller/StreamController.php#L64-L75 |
alexdebril/rss-atom-bundle | Controller/StreamController.php | StreamController.createStreamResponse | protected function createStreamResponse(array $options, string $format, FeedContentProviderInterface $provider, FeedIo $feedIo) : Response
{
$content = $this->getContent($options, $provider);
if ($this->mustForceRefresh() || $content->getLastModified() > $this->getModifiedSince()) {
$response = new Response($feedIo->format($content, $format));
$this->setFeedHeaders($response, $content, $format);
} else {
$response = new Response();
$response->setNotModified();
}
return $response;
} | php | protected function createStreamResponse(array $options, string $format, FeedContentProviderInterface $provider, FeedIo $feedIo) : Response
{
$content = $this->getContent($options, $provider);
if ($this->mustForceRefresh() || $content->getLastModified() > $this->getModifiedSince()) {
$response = new Response($feedIo->format($content, $format));
$this->setFeedHeaders($response, $content, $format);
} else {
$response = new Response();
$response->setNotModified();
}
return $response;
} | [
"protected",
"function",
"createStreamResponse",
"(",
"array",
"$",
"options",
",",
"string",
"$",
"format",
",",
"FeedContentProviderInterface",
"$",
"provider",
",",
"FeedIo",
"$",
"feedIo",
")",
":",
"Response",
"{",
"$",
"content",
"=",
"$",
"this",
"->",
... | Generate the HTTP response
200 : a full body containing the stream
304 : Not modified.
@param array $options
@param $format
@param FeedContentProviderInterface $provider
@param FeedIo $feedIo
@return Response
@throws \Exception | [
"Generate",
"the",
"HTTP",
"response",
"200",
":",
"a",
"full",
"body",
"containing",
"the",
"stream",
"304",
":",
"Not",
"modified",
"."
] | train | https://github.com/alexdebril/rss-atom-bundle/blob/87b93273eb7e995547060ac17d9a1b21061013e3/Controller/StreamController.php#L91-L105 |
alexdebril/rss-atom-bundle | Controller/StreamController.php | StreamController.getContent | protected function getContent(array $options, FeedContentProviderInterface $provider) : FeedInterface
{
try {
return $provider->getFeedContent($options);
} catch (FeedNotFoundException $e) {
throw $this->createNotFoundException('feed not found');
}
} | php | protected function getContent(array $options, FeedContentProviderInterface $provider) : FeedInterface
{
try {
return $provider->getFeedContent($options);
} catch (FeedNotFoundException $e) {
throw $this->createNotFoundException('feed not found');
}
} | [
"protected",
"function",
"getContent",
"(",
"array",
"$",
"options",
",",
"FeedContentProviderInterface",
"$",
"provider",
")",
":",
"FeedInterface",
"{",
"try",
"{",
"return",
"$",
"provider",
"->",
"getFeedContent",
"(",
"$",
"options",
")",
";",
"}",
"catch... | Get the Stream's content using a FeedContentProviderInterface
The FeedContentProviderInterface instance is provided as a service
default : debril.provider.service.
@param array $options
@param FeedContentProviderInterface $provider
@return FeedInterface
@throws \Exception | [
"Get",
"the",
"Stream",
"s",
"content",
"using",
"a",
"FeedContentProviderInterface",
"The",
"FeedContentProviderInterface",
"instance",
"is",
"provided",
"as",
"a",
"service",
"default",
":",
"debril",
".",
"provider",
".",
"service",
"."
] | train | https://github.com/alexdebril/rss-atom-bundle/blob/87b93273eb7e995547060ac17d9a1b21061013e3/Controller/StreamController.php#L143-L150 |
wp-cli/db-command | src/DB_Command.php | DB_Command.create | public function create( $_, $assoc_args ) {
self::run_query( self::get_create_query(), self::get_dbuser_dbpass_args( $assoc_args ) );
WP_CLI::success( 'Database created.' );
} | php | public function create( $_, $assoc_args ) {
self::run_query( self::get_create_query(), self::get_dbuser_dbpass_args( $assoc_args ) );
WP_CLI::success( 'Database created.' );
} | [
"public",
"function",
"create",
"(",
"$",
"_",
",",
"$",
"assoc_args",
")",
"{",
"self",
"::",
"run_query",
"(",
"self",
"::",
"get_create_query",
"(",
")",
",",
"self",
"::",
"get_dbuser_dbpass_args",
"(",
"$",
"assoc_args",
")",
")",
";",
"WP_CLI",
"::... | Creates a new database.
Runs `CREATE_DATABASE` SQL statement using `DB_HOST`, `DB_NAME`,
`DB_USER` and `DB_PASSWORD` database credentials specified in
wp-config.php.
## OPTIONS
[--dbuser=<value>]
: Username to pass to mysql. Defaults to DB_USER.
[--dbpass=<value>]
: Password to pass to mysql. Defaults to DB_PASSWORD.
## EXAMPLES
$ wp db create
Success: Database created. | [
"Creates",
"a",
"new",
"database",
"."
] | train | https://github.com/wp-cli/db-command/blob/dc0f8e4d5783d8a4ee01da1119b8fe8038fe1aa0/src/DB_Command.php#L50-L55 |
wp-cli/db-command | src/DB_Command.php | DB_Command.drop | public function drop( $_, $assoc_args ) {
WP_CLI::confirm( "Are you sure you want to drop the '" . DB_NAME . "' database?", $assoc_args );
self::run_query( sprintf( 'DROP DATABASE `%s`', DB_NAME ), self::get_dbuser_dbpass_args( $assoc_args ) );
WP_CLI::success( 'Database dropped.' );
} | php | public function drop( $_, $assoc_args ) {
WP_CLI::confirm( "Are you sure you want to drop the '" . DB_NAME . "' database?", $assoc_args );
self::run_query( sprintf( 'DROP DATABASE `%s`', DB_NAME ), self::get_dbuser_dbpass_args( $assoc_args ) );
WP_CLI::success( 'Database dropped.' );
} | [
"public",
"function",
"drop",
"(",
"$",
"_",
",",
"$",
"assoc_args",
")",
"{",
"WP_CLI",
"::",
"confirm",
"(",
"\"Are you sure you want to drop the '\"",
".",
"DB_NAME",
".",
"\"' database?\"",
",",
"$",
"assoc_args",
")",
";",
"self",
"::",
"run_query",
"(",
... | Deletes the existing database.
Runs `DROP_DATABASE` SQL statement using `DB_HOST`, `DB_NAME`,
`DB_USER` and `DB_PASSWORD` database credentials specified in
wp-config.php.
## OPTIONS
[--dbuser=<value>]
: Username to pass to mysql. Defaults to DB_USER.
[--dbpass=<value>]
: Password to pass to mysql. Defaults to DB_PASSWORD.
[--yes]
: Answer yes to the confirmation message.
## EXAMPLES
$ wp db drop --yes
Success: Database dropped. | [
"Deletes",
"the",
"existing",
"database",
"."
] | train | https://github.com/wp-cli/db-command/blob/dc0f8e4d5783d8a4ee01da1119b8fe8038fe1aa0/src/DB_Command.php#L80-L86 |
wp-cli/db-command | src/DB_Command.php | DB_Command.reset | public function reset( $_, $assoc_args ) {
WP_CLI::confirm( "Are you sure you want to reset the '" . DB_NAME . "' database?", $assoc_args );
$mysql_args = self::get_dbuser_dbpass_args( $assoc_args );
self::run_query( sprintf( 'DROP DATABASE IF EXISTS `%s`', DB_NAME ), $mysql_args );
self::run_query( self::get_create_query(), $mysql_args );
WP_CLI::success( 'Database reset.' );
} | php | public function reset( $_, $assoc_args ) {
WP_CLI::confirm( "Are you sure you want to reset the '" . DB_NAME . "' database?", $assoc_args );
$mysql_args = self::get_dbuser_dbpass_args( $assoc_args );
self::run_query( sprintf( 'DROP DATABASE IF EXISTS `%s`', DB_NAME ), $mysql_args );
self::run_query( self::get_create_query(), $mysql_args );
WP_CLI::success( 'Database reset.' );
} | [
"public",
"function",
"reset",
"(",
"$",
"_",
",",
"$",
"assoc_args",
")",
"{",
"WP_CLI",
"::",
"confirm",
"(",
"\"Are you sure you want to reset the '\"",
".",
"DB_NAME",
".",
"\"' database?\"",
",",
"$",
"assoc_args",
")",
";",
"$",
"mysql_args",
"=",
"self"... | Removes all tables from the database.
Runs `DROP_DATABASE` and `CREATE_DATABASE` SQL statements using
`DB_HOST`, `DB_NAME`, `DB_USER` and `DB_PASSWORD` database credentials
specified in wp-config.php.
## OPTIONS
[--dbuser=<value>]
: Username to pass to mysql. Defaults to DB_USER.
[--dbpass=<value>]
: Password to pass to mysql. Defaults to DB_PASSWORD.
[--yes]
: Answer yes to the confirmation message.
## EXAMPLES
$ wp db reset --yes
Success: Database reset. | [
"Removes",
"all",
"tables",
"from",
"the",
"database",
"."
] | train | https://github.com/wp-cli/db-command/blob/dc0f8e4d5783d8a4ee01da1119b8fe8038fe1aa0/src/DB_Command.php#L111-L120 |
wp-cli/db-command | src/DB_Command.php | DB_Command.clean | public function clean( $_, $assoc_args ) {
global $wpdb;
WP_CLI::confirm(
sprintf(
"Are you sure you want to drop all the tables on '%s' that use the current site's database prefix ('%s')?",
DB_NAME,
$wpdb->get_blog_prefix()
),
$assoc_args
);
$mysql_args = self::get_dbuser_dbpass_args( $assoc_args );
$tables = Utils\wp_get_table_names(
array(),
array( 'all-tables-with-prefix' )
);
foreach ( $tables as $table ) {
self::run_query(
sprintf(
'DROP TABLE IF EXISTS `%s`.`%s`',
DB_NAME,
$table
),
$mysql_args
);
}
WP_CLI::success( 'Tables dropped.' );
} | php | public function clean( $_, $assoc_args ) {
global $wpdb;
WP_CLI::confirm(
sprintf(
"Are you sure you want to drop all the tables on '%s' that use the current site's database prefix ('%s')?",
DB_NAME,
$wpdb->get_blog_prefix()
),
$assoc_args
);
$mysql_args = self::get_dbuser_dbpass_args( $assoc_args );
$tables = Utils\wp_get_table_names(
array(),
array( 'all-tables-with-prefix' )
);
foreach ( $tables as $table ) {
self::run_query(
sprintf(
'DROP TABLE IF EXISTS `%s`.`%s`',
DB_NAME,
$table
),
$mysql_args
);
}
WP_CLI::success( 'Tables dropped.' );
} | [
"public",
"function",
"clean",
"(",
"$",
"_",
",",
"$",
"assoc_args",
")",
"{",
"global",
"$",
"wpdb",
";",
"WP_CLI",
"::",
"confirm",
"(",
"sprintf",
"(",
"\"Are you sure you want to drop all the tables on '%s' that use the current site's database prefix ('%s')?\"",
",",... | Removes all tables with `$table_prefix` from the database.
Runs `DROP_TABLE` for each table that has a `$table_prefix` as specified
in wp-config.php.
## OPTIONS
[--dbuser=<value>]
: Username to pass to mysql. Defaults to DB_USER.
[--dbpass=<value>]
: Password to pass to mysql. Defaults to DB_PASSWORD.
[--yes]
: Answer yes to the confirmation message.
## EXAMPLES
# Delete all tables that match the current site prefix.
$ wp db clean --yes
Success: Tables dropped.
@when after_wp_load | [
"Removes",
"all",
"tables",
"with",
"$table_prefix",
"from",
"the",
"database",
"."
] | train | https://github.com/wp-cli/db-command/blob/dc0f8e4d5783d8a4ee01da1119b8fe8038fe1aa0/src/DB_Command.php#L147-L178 |
wp-cli/db-command | src/DB_Command.php | DB_Command.check | public function check( $_, $assoc_args ) {
$assoc_args['check'] = true;
self::run(
Utils\esc_cmd( '/usr/bin/env mysqlcheck --no-defaults %s', DB_NAME ),
$assoc_args
);
WP_CLI::success( 'Database checked.' );
} | php | public function check( $_, $assoc_args ) {
$assoc_args['check'] = true;
self::run(
Utils\esc_cmd( '/usr/bin/env mysqlcheck --no-defaults %s', DB_NAME ),
$assoc_args
);
WP_CLI::success( 'Database checked.' );
} | [
"public",
"function",
"check",
"(",
"$",
"_",
",",
"$",
"assoc_args",
")",
"{",
"$",
"assoc_args",
"[",
"'check'",
"]",
"=",
"true",
";",
"self",
"::",
"run",
"(",
"Utils",
"\\",
"esc_cmd",
"(",
"'/usr/bin/env mysqlcheck --no-defaults %s'",
",",
"DB_NAME",
... | Checks the current status of the database.
Runs `mysqlcheck` utility with `--check` using `DB_HOST`,
`DB_NAME`, `DB_USER` and `DB_PASSWORD` database credentials
specified in wp-config.php.
[See docs](http://dev.mysql.com/doc/refman/5.7/en/check-table.html)
for more details on the `CHECK TABLE` statement.
## OPTIONS
[--dbuser=<value>]
: Username to pass to mysqlcheck. Defaults to DB_USER.
[--dbpass=<value>]
: Password to pass to mysqlcheck. Defaults to DB_PASSWORD.
[--<field>=<value>]
: Extra arguments to pass to mysqlcheck. [Refer to mysqlcheck docs](https://dev.mysql.com/doc/en/mysqlcheck.html).
## EXAMPLES
$ wp db check
Success: Database checked. | [
"Checks",
"the",
"current",
"status",
"of",
"the",
"database",
"."
] | train | https://github.com/wp-cli/db-command/blob/dc0f8e4d5783d8a4ee01da1119b8fe8038fe1aa0/src/DB_Command.php#L206-L214 |
wp-cli/db-command | src/DB_Command.php | DB_Command.cli | public function cli( $args, $assoc_args ) {
if ( ! isset( $assoc_args['database'] ) ) {
$assoc_args['database'] = DB_NAME;
}
self::run( '/usr/bin/env mysql --no-defaults --no-auto-rehash', $assoc_args );
} | php | public function cli( $args, $assoc_args ) {
if ( ! isset( $assoc_args['database'] ) ) {
$assoc_args['database'] = DB_NAME;
}
self::run( '/usr/bin/env mysql --no-defaults --no-auto-rehash', $assoc_args );
} | [
"public",
"function",
"cli",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"assoc_args",
"[",
"'database'",
"]",
")",
")",
"{",
"$",
"assoc_args",
"[",
"'database'",
"]",
"=",
"DB_NAME",
";",
"}",
"self",
":... | Opens a MySQL console using credentials from wp-config.php
## OPTIONS
[--database=<database>]
: Use a specific database. Defaults to DB_NAME.
[--default-character-set=<character-set>]
: Use a specific character set. Defaults to DB_CHARSET when defined.
[--dbuser=<value>]
: Username to pass to mysql. Defaults to DB_USER.
[--dbpass=<value>]
: Password to pass to mysql. Defaults to DB_PASSWORD.
[--<field>=<value>]
: Extra arguments to pass to mysql. [Refer to mysql docs](https://dev.mysql.com/doc/en/mysql-command-options.html).
## EXAMPLES
# Open MySQL console
$ wp db cli
mysql>
@alias connect | [
"Opens",
"a",
"MySQL",
"console",
"using",
"credentials",
"from",
"wp",
"-",
"config",
".",
"php"
] | train | https://github.com/wp-cli/db-command/blob/dc0f8e4d5783d8a4ee01da1119b8fe8038fe1aa0/src/DB_Command.php#L316-L322 |
wp-cli/db-command | src/DB_Command.php | DB_Command.query | public function query( $args, $assoc_args ) {
$assoc_args['database'] = DB_NAME;
// The query might come from STDIN.
if ( ! empty( $args ) ) {
$assoc_args['execute'] = $args[0];
}
self::run( '/usr/bin/env mysql --no-defaults --no-auto-rehash', $assoc_args );
} | php | public function query( $args, $assoc_args ) {
$assoc_args['database'] = DB_NAME;
// The query might come from STDIN.
if ( ! empty( $args ) ) {
$assoc_args['execute'] = $args[0];
}
self::run( '/usr/bin/env mysql --no-defaults --no-auto-rehash', $assoc_args );
} | [
"public",
"function",
"query",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"$",
"assoc_args",
"[",
"'database'",
"]",
"=",
"DB_NAME",
";",
"// The query might come from STDIN.",
"if",
"(",
"!",
"empty",
"(",
"$",
"args",
")",
")",
"{",
"$",
"asso... | Executes a SQL query against the database.
Executes an arbitrary SQL query using `DB_HOST`, `DB_NAME`, `DB_USER`
and `DB_PASSWORD` database credentials specified in wp-config.php.
## OPTIONS
[<sql>]
: A SQL query. If not passed, will try to read from STDIN.
[--dbuser=<value>]
: Username to pass to mysql. Defaults to DB_USER.
[--dbpass=<value>]
: Password to pass to mysql. Defaults to DB_PASSWORD.
[--<field>=<value>]
: Extra arguments to pass to mysql. [Refer to mysql docs](https://dev.mysql.com/doc/en/mysql-command-options.html).
## EXAMPLES
# Execute a query stored in a file
$ wp db query < debug.sql
# Check all tables in the database
$ wp db query "CHECK TABLE $(wp db tables | paste -s -d, -);"
+---------------------------------------+-------+----------+----------+
| Table | Op | Msg_type | Msg_text |
+---------------------------------------+-------+----------+----------+
| wordpress_dbase.wp_users | check | status | OK |
| wordpress_dbase.wp_usermeta | check | status | OK |
| wordpress_dbase.wp_posts | check | status | OK |
| wordpress_dbase.wp_comments | check | status | OK |
| wordpress_dbase.wp_links | check | status | OK |
| wordpress_dbase.wp_options | check | status | OK |
| wordpress_dbase.wp_postmeta | check | status | OK |
| wordpress_dbase.wp_terms | check | status | OK |
| wordpress_dbase.wp_term_taxonomy | check | status | OK |
| wordpress_dbase.wp_term_relationships | check | status | OK |
| wordpress_dbase.wp_termmeta | check | status | OK |
| wordpress_dbase.wp_commentmeta | check | status | OK |
+---------------------------------------+-------+----------+----------+
# Pass extra arguments through to MySQL
$ wp db query 'SELECT * FROM wp_options WHERE option_name="home"' --skip-column-names
+---+------+------------------------------+-----+
| 2 | home | http://wordpress-develop.dev | yes |
+---+------+------------------------------+-----+ | [
"Executes",
"a",
"SQL",
"query",
"against",
"the",
"database",
"."
] | train | https://github.com/wp-cli/db-command/blob/dc0f8e4d5783d8a4ee01da1119b8fe8038fe1aa0/src/DB_Command.php#L374-L383 |
wp-cli/db-command | src/DB_Command.php | DB_Command.export | public function export( $args, $assoc_args ) {
if ( ! empty( $args[0] ) ) {
$result_file = $args[0];
} else {
// phpcs:ignore WordPress.WP.AlternativeFunctions.rand_mt_rand -- WordPress is not loaded.
$hash = substr( md5( mt_rand() ), 0, 7 );
$result_file = sprintf( '%s-%s-%s.sql', DB_NAME, date( 'Y-m-d' ), $hash );
}
$stdout = ( '-' === $result_file );
$porcelain = Utils\get_flag_value( $assoc_args, 'porcelain' );
// Bail if both porcelain and STDOUT are set.
if ( $stdout && $porcelain ) {
WP_CLI::error( 'Porcelain is not allowed when output mode is STDOUT.' );
}
if ( ! $stdout ) {
$assoc_args['result-file'] = $result_file;
}
$support_column_statistics = exec( 'mysqldump --help | grep "column-statistics"' );
if ( $support_column_statistics ) {
$command = '/usr/bin/env mysqldump --no-defaults --skip-column-statistics %s';
} else {
$command = '/usr/bin/env mysqldump --no-defaults %s';
}
$command_esc_args = array( DB_NAME );
if ( isset( $assoc_args['tables'] ) ) {
$tables = explode( ',', trim( $assoc_args['tables'], ',' ) );
unset( $assoc_args['tables'] );
$command .= ' --tables';
foreach ( $tables as $table ) {
$command .= ' %s';
$command_esc_args[] = trim( $table );
}
}
$exclude_tables = Utils\get_flag_value( $assoc_args, 'exclude_tables' );
if ( isset( $exclude_tables ) ) {
$tables = explode( ',', trim( $assoc_args['exclude_tables'], ',' ) );
unset( $assoc_args['exclude_tables'] );
foreach ( $tables as $table ) {
$command .= ' --ignore-table';
$command .= ' %s';
$command_esc_args[] = trim( DB_NAME . '.' . $table );
}
}
$escaped_command = call_user_func_array( '\WP_CLI\Utils\esc_cmd', array_merge( array( $command ), $command_esc_args ) );
// Remove parameters not needed for SQL run.
unset( $assoc_args['porcelain'] );
self::run( $escaped_command, $assoc_args );
if ( $porcelain ) {
WP_CLI::line( $result_file );
} elseif ( ! $stdout ) {
WP_CLI::success( sprintf( "Exported to '%s'.", $result_file ) );
}
} | php | public function export( $args, $assoc_args ) {
if ( ! empty( $args[0] ) ) {
$result_file = $args[0];
} else {
// phpcs:ignore WordPress.WP.AlternativeFunctions.rand_mt_rand -- WordPress is not loaded.
$hash = substr( md5( mt_rand() ), 0, 7 );
$result_file = sprintf( '%s-%s-%s.sql', DB_NAME, date( 'Y-m-d' ), $hash );
}
$stdout = ( '-' === $result_file );
$porcelain = Utils\get_flag_value( $assoc_args, 'porcelain' );
// Bail if both porcelain and STDOUT are set.
if ( $stdout && $porcelain ) {
WP_CLI::error( 'Porcelain is not allowed when output mode is STDOUT.' );
}
if ( ! $stdout ) {
$assoc_args['result-file'] = $result_file;
}
$support_column_statistics = exec( 'mysqldump --help | grep "column-statistics"' );
if ( $support_column_statistics ) {
$command = '/usr/bin/env mysqldump --no-defaults --skip-column-statistics %s';
} else {
$command = '/usr/bin/env mysqldump --no-defaults %s';
}
$command_esc_args = array( DB_NAME );
if ( isset( $assoc_args['tables'] ) ) {
$tables = explode( ',', trim( $assoc_args['tables'], ',' ) );
unset( $assoc_args['tables'] );
$command .= ' --tables';
foreach ( $tables as $table ) {
$command .= ' %s';
$command_esc_args[] = trim( $table );
}
}
$exclude_tables = Utils\get_flag_value( $assoc_args, 'exclude_tables' );
if ( isset( $exclude_tables ) ) {
$tables = explode( ',', trim( $assoc_args['exclude_tables'], ',' ) );
unset( $assoc_args['exclude_tables'] );
foreach ( $tables as $table ) {
$command .= ' --ignore-table';
$command .= ' %s';
$command_esc_args[] = trim( DB_NAME . '.' . $table );
}
}
$escaped_command = call_user_func_array( '\WP_CLI\Utils\esc_cmd', array_merge( array( $command ), $command_esc_args ) );
// Remove parameters not needed for SQL run.
unset( $assoc_args['porcelain'] );
self::run( $escaped_command, $assoc_args );
if ( $porcelain ) {
WP_CLI::line( $result_file );
} elseif ( ! $stdout ) {
WP_CLI::success( sprintf( "Exported to '%s'.", $result_file ) );
}
} | [
"public",
"function",
"export",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"args",
"[",
"0",
"]",
")",
")",
"{",
"$",
"result_file",
"=",
"$",
"args",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"// phpcs:i... | Exports the database to a file or to STDOUT.
Runs `mysqldump` utility using `DB_HOST`, `DB_NAME`, `DB_USER` and
`DB_PASSWORD` database credentials specified in wp-config.php.
## OPTIONS
[<file>]
: The name of the SQL file to export. If '-', then outputs to STDOUT. If
omitted, it will be '{dbname}-{Y-m-d}-{random-hash}.sql'.
[--dbuser=<value>]
: Username to pass to mysqldump. Defaults to DB_USER.
[--dbpass=<value>]
: Password to pass to mysqldump. Defaults to DB_PASSWORD.
[--<field>=<value>]
: Extra arguments to pass to mysqldump. [Refer to mysqldump docs](https://dev.mysql.com/doc/en/mysqldump.html#mysqldump-option-summary).
[--tables=<tables>]
: The comma separated list of specific tables to export. Excluding this parameter will export all tables in the database.
[--exclude_tables=<tables>]
: The comma separated list of specific tables that should be skipped from exporting. Excluding this parameter will export all tables in the database.
[--porcelain]
: Output filename for the exported database.
## EXAMPLES
# Export database with drop query included
$ wp db export --add-drop-table
Success: Exported to 'wordpress_dbase-db72bb5.sql'.
# Export certain tables
$ wp db export --tables=wp_options,wp_users
Success: Exported to 'wordpress_dbase-db72bb5.sql'.
# Export all tables matching a wildcard
$ wp db export --tables=$(wp db tables 'wp_user*' --format=csv)
Success: Exported to 'wordpress_dbase-db72bb5.sql'.
# Export all tables matching prefix
$ wp db export --tables=$(wp db tables --all-tables-with-prefix --format=csv)
Success: Exported to 'wordpress_dbase-db72bb5.sql'.
# Export certain posts without create table statements
$ wp db export --no-create-info=true --tables=wp_posts --where="ID in (100,101,102)"
Success: Exported to 'wordpress_dbase-db72bb5.sql'.
# Export relating meta for certain posts without create table statements
$ wp db export --no-create-info=true --tables=wp_postmeta --where="post_id in (100,101,102)"
Success: Exported to 'wordpress_dbase-db72bb5.sql'.
# Skip certain tables from the exported database
$ wp db export --exclude_tables=wp_options,wp_users
Success: Exported to 'wordpress_dbase-db72bb5.sql'.
# Skip all tables matching a wildcard from the exported database
$ wp db export --exclude_tables=$(wp db tables 'wp_user*' --format=csv)
Success: Exported to 'wordpress_dbase-db72bb5.sql'.
# Skip all tables matching prefix from the exported database
$ wp db export --exclude_tables=$(wp db tables --all-tables-with-prefix --format=csv)
Success: Exported to 'wordpress_dbase-db72bb5.sql'.
# Export database to STDOUT.
$ wp db export -
-- MySQL dump 10.13 Distrib 5.7.19, for osx10.12 (x86_64)
--
-- Host: localhost Database: wpdev
-- ------------------------------------------------------
-- Server version 5.7.19
...
@alias dump | [
"Exports",
"the",
"database",
"to",
"a",
"file",
"or",
"to",
"STDOUT",
"."
] | train | https://github.com/wp-cli/db-command/blob/dc0f8e4d5783d8a4ee01da1119b8fe8038fe1aa0/src/DB_Command.php#L464-L528 |
wp-cli/db-command | src/DB_Command.php | DB_Command.import | public function import( $args, $assoc_args ) {
if ( ! empty( $args[0] ) ) {
$result_file = $args[0];
} else {
$result_file = sprintf( '%s.sql', DB_NAME );
}
$mysql_args = array(
'database' => DB_NAME,
);
$mysql_args = array_merge( self::get_dbuser_dbpass_args( $assoc_args ), $mysql_args );
if ( '-' !== $result_file ) {
if ( ! is_readable( $result_file ) ) {
WP_CLI::error( sprintf( 'Import file missing or not readable: %s', $result_file ) );
}
$query = Utils\get_flag_value( $assoc_args, 'skip-optimization' )
? 'SOURCE %s;'
: 'SET autocommit = 0; SET unique_checks = 0; SET foreign_key_checks = 0; SOURCE %s; COMMIT;';
$mysql_args['execute'] = sprintf( $query, $result_file );
}
// Check if any mysql option pass.
$mysql_args = array_merge( $mysql_args, self::get_mysql_args( $assoc_args ) );
self::run( '/usr/bin/env mysql --no-defaults --no-auto-rehash', $mysql_args );
WP_CLI::success( sprintf( "Imported from '%s'.", $result_file ) );
} | php | public function import( $args, $assoc_args ) {
if ( ! empty( $args[0] ) ) {
$result_file = $args[0];
} else {
$result_file = sprintf( '%s.sql', DB_NAME );
}
$mysql_args = array(
'database' => DB_NAME,
);
$mysql_args = array_merge( self::get_dbuser_dbpass_args( $assoc_args ), $mysql_args );
if ( '-' !== $result_file ) {
if ( ! is_readable( $result_file ) ) {
WP_CLI::error( sprintf( 'Import file missing or not readable: %s', $result_file ) );
}
$query = Utils\get_flag_value( $assoc_args, 'skip-optimization' )
? 'SOURCE %s;'
: 'SET autocommit = 0; SET unique_checks = 0; SET foreign_key_checks = 0; SOURCE %s; COMMIT;';
$mysql_args['execute'] = sprintf( $query, $result_file );
}
// Check if any mysql option pass.
$mysql_args = array_merge( $mysql_args, self::get_mysql_args( $assoc_args ) );
self::run( '/usr/bin/env mysql --no-defaults --no-auto-rehash', $mysql_args );
WP_CLI::success( sprintf( "Imported from '%s'.", $result_file ) );
} | [
"public",
"function",
"import",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"args",
"[",
"0",
"]",
")",
")",
"{",
"$",
"result_file",
"=",
"$",
"args",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"$",
"res... | Imports a database from a file or from STDIN.
Runs SQL queries using `DB_HOST`, `DB_NAME`, `DB_USER` and
`DB_PASSWORD` database credentials specified in wp-config.php. This
does not create database by itself and only performs whatever tasks are
defined in the SQL.
## OPTIONS
[<file>]
: The name of the SQL file to import. If '-', then reads from STDIN. If omitted, it will look for '{dbname}.sql'.
[--dbuser=<value>]
: Username to pass to mysql. Defaults to DB_USER.
[--dbpass=<value>]
: Password to pass to mysql. Defaults to DB_PASSWORD.
[--<field>=<value>]
: Extra arguments to pass to mysql. [Refer to mysql binary docs](https://dev.mysql.com/doc/refman/8.0/en/mysql-command-options.html).
[--skip-optimization]
: When using an SQL file, do not include speed optimization such as disabling auto-commit and key checks.
## EXAMPLES
# Import MySQL from a file.
$ wp db import wordpress_dbase.sql
Success: Imported from 'wordpress_dbase.sql'. | [
"Imports",
"a",
"database",
"from",
"a",
"file",
"or",
"from",
"STDIN",
"."
] | train | https://github.com/wp-cli/db-command/blob/dc0f8e4d5783d8a4ee01da1119b8fe8038fe1aa0/src/DB_Command.php#L561-L590 |
wp-cli/db-command | src/DB_Command.php | DB_Command.tables | public function tables( $args, $assoc_args ) {
$format = Utils\get_flag_value( $assoc_args, 'format' );
unset( $assoc_args['format'] );
if ( empty( $args ) && empty( $assoc_args ) ) {
$assoc_args['scope'] = 'all';
}
$tables = Utils\wp_get_table_names( $args, $assoc_args );
if ( 'csv' === $format ) {
WP_CLI::line( implode( ',', $tables ) );
} else {
foreach ( $tables as $table ) {
WP_CLI::line( $table );
}
}
} | php | public function tables( $args, $assoc_args ) {
$format = Utils\get_flag_value( $assoc_args, 'format' );
unset( $assoc_args['format'] );
if ( empty( $args ) && empty( $assoc_args ) ) {
$assoc_args['scope'] = 'all';
}
$tables = Utils\wp_get_table_names( $args, $assoc_args );
if ( 'csv' === $format ) {
WP_CLI::line( implode( ',', $tables ) );
} else {
foreach ( $tables as $table ) {
WP_CLI::line( $table );
}
}
} | [
"public",
"function",
"tables",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"$",
"format",
"=",
"Utils",
"\\",
"get_flag_value",
"(",
"$",
"assoc_args",
",",
"'format'",
")",
";",
"unset",
"(",
"$",
"assoc_args",
"[",
"'format'",
"]",
")",
";",... | Lists the database tables.
Defaults to all tables registered to the $wpdb database handler.
## OPTIONS
[<table>...]
: List tables based on wildcard search, e.g. 'wp_*_options' or 'wp_post?'.
[--scope=<scope>]
: Can be all, global, ms_global, blog, or old tables. Defaults to all.
[--network]
: List all the tables in a multisite install.
[--all-tables-with-prefix]
: List all tables that match the table prefix even if not registered on $wpdb. Overrides --network.
[--all-tables]
: List all tables in the database, regardless of the prefix, and even if not registered on $wpdb. Overrides --all-tables-with-prefix.
[--format=<format>]
: Render output in a particular format.
---
default: list
options:
- list
- csv
---
## EXAMPLES
# List tables for a single site, without shared tables like 'wp_users'
$ wp db tables --scope=blog --url=sub.example.com
wp_3_posts
wp_3_comments
wp_3_options
wp_3_postmeta
wp_3_terms
wp_3_term_taxonomy
wp_3_term_relationships
wp_3_termmeta
wp_3_commentmeta
# Export only tables for a single site
$ wp db export --tables=$(wp db tables --url=sub.example.com --format=csv)
Success: Exported to wordpress_dbase.sql
@when after_wp_load | [
"Lists",
"the",
"database",
"tables",
"."
] | train | https://github.com/wp-cli/db-command/blob/dc0f8e4d5783d8a4ee01da1119b8fe8038fe1aa0/src/DB_Command.php#L643-L661 |
wp-cli/db-command | src/DB_Command.php | DB_Command.size | public function size( $args, $assoc_args ) {
global $wpdb;
$format = Utils\get_flag_value( $assoc_args, 'format' );
$size_format = Utils\get_flag_value( $assoc_args, 'size_format' );
$human_readable = Utils\get_flag_value( $assoc_args, 'human-readable', false );
$tables = Utils\get_flag_value( $assoc_args, 'tables' );
$tables = ! empty( $tables );
$all_tables = Utils\get_flag_value( $assoc_args, 'all-tables' );
$all_tables_with_prefix = Utils\get_flag_value( $assoc_args, 'all-tables-with-prefix' );
if ( ! is_null( $size_format ) && $human_readable ) {
WP_CLI::error( 'Cannot use --size_format and --human-readable arguments at the same time.' );
}
unset( $assoc_args['format'] );
unset( $assoc_args['size_format'] );
unset( $assoc_args['human-readable'] );
unset( $assoc_args['tables'] );
if ( empty( $args ) && empty( $assoc_args ) ) {
$assoc_args['scope'] = 'all';
}
// Build rows for the formatter.
$rows = array();
$fields = array( 'Name', 'Size' );
$default_unit = ( empty( $size_format ) && ! $human_readable ) ? ' B' : '';
if ( $tables || $all_tables || $all_tables_with_prefix ) {
// Add all of the table sizes
foreach ( Utils\wp_get_table_names( $args, $assoc_args ) as $table_name ) {
// Get the table size.
$table_bytes = $wpdb->get_var(
$wpdb->prepare(
'SELECT SUM(data_length + index_length) FROM information_schema.TABLES where table_schema = %s and Table_Name = %s GROUP BY Table_Name LIMIT 1',
DB_NAME,
$table_name
)
);
// Add the table size to the list.
$rows[] = array(
'Name' => $table_name,
'Size' => strtoupper( $table_bytes ) . $default_unit,
);
}
} else {
// Get the database size.
$db_bytes = $wpdb->get_var(
$wpdb->prepare(
'SELECT SUM(data_length + index_length) FROM information_schema.TABLES where table_schema = %s GROUP BY table_schema;',
DB_NAME
)
);
// Add the database size to the list.
$rows[] = array(
'Name' => DB_NAME,
'Size' => strtoupper( $db_bytes ) . $default_unit,
);
}
if ( ! empty( $size_format ) || $human_readable ) {
foreach ( $rows as $index => $row ) {
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound -- Backfilling WP native constants.
if ( ! defined( 'KB_IN_BYTES' ) ) {
define( 'KB_IN_BYTES', 1024 );
}
if ( ! defined( 'MB_IN_BYTES' ) ) {
define( 'MB_IN_BYTES', 1024 * KB_IN_BYTES );
}
if ( ! defined( 'GB_IN_BYTES' ) ) {
define( 'GB_IN_BYTES', 1024 * MB_IN_BYTES );
}
if ( ! defined( 'TB_IN_BYTES' ) ) {
define( 'TB_IN_BYTES', 1024 * GB_IN_BYTES );
}
// phpcs:enable
if ( $human_readable ) {
$size_key = floor( log( $row['Size'] ) / log( 1000 ) );
$sizes = array( 'B', 'KB', 'MB', 'GB', 'TB' );
$size_format = isset( $sizes[ $size_key ] ) ? $sizes[ $size_key ] : $sizes[0];
}
// Display the database size as a number.
switch ( $size_format ) {
case 'TB':
$divisor = pow( 1000, 4 );
break;
case 'GB':
$divisor = pow( 1000, 3 );
break;
case 'MB':
$divisor = pow( 1000, 2 );
break;
case 'KB':
$divisor = 1000;
break;
case 'tb':
case 'TiB':
$divisor = TB_IN_BYTES;
break;
case 'gb':
case 'GiB':
$divisor = GB_IN_BYTES;
break;
case 'mb':
case 'MiB':
$divisor = MB_IN_BYTES;
break;
case 'kb':
case 'KiB':
$divisor = KB_IN_BYTES;
break;
case 'b':
case 'B':
default:
$divisor = 1;
break;
}
$size_format_display = preg_replace( '/IB$/u', 'iB', strtoupper( $size_format ) );
$rows[ $index ]['Size'] = ceil( $row['Size'] / $divisor ) . ' ' . $size_format_display;
}
}
if ( ! empty( $size_format ) && ! $tables && ! $format && ! $human_readable && true !== $all_tables && true !== $all_tables_with_prefix ) {
WP_CLI::Line( filter_var( $rows[0]['Size'], FILTER_SANITIZE_NUMBER_INT ) );
} else {
// Display the rows.
$args = array(
'format' => $format,
);
$formatter = new Formatter( $args, $fields );
$formatter->display_items( $rows );
}
} | php | public function size( $args, $assoc_args ) {
global $wpdb;
$format = Utils\get_flag_value( $assoc_args, 'format' );
$size_format = Utils\get_flag_value( $assoc_args, 'size_format' );
$human_readable = Utils\get_flag_value( $assoc_args, 'human-readable', false );
$tables = Utils\get_flag_value( $assoc_args, 'tables' );
$tables = ! empty( $tables );
$all_tables = Utils\get_flag_value( $assoc_args, 'all-tables' );
$all_tables_with_prefix = Utils\get_flag_value( $assoc_args, 'all-tables-with-prefix' );
if ( ! is_null( $size_format ) && $human_readable ) {
WP_CLI::error( 'Cannot use --size_format and --human-readable arguments at the same time.' );
}
unset( $assoc_args['format'] );
unset( $assoc_args['size_format'] );
unset( $assoc_args['human-readable'] );
unset( $assoc_args['tables'] );
if ( empty( $args ) && empty( $assoc_args ) ) {
$assoc_args['scope'] = 'all';
}
// Build rows for the formatter.
$rows = array();
$fields = array( 'Name', 'Size' );
$default_unit = ( empty( $size_format ) && ! $human_readable ) ? ' B' : '';
if ( $tables || $all_tables || $all_tables_with_prefix ) {
// Add all of the table sizes
foreach ( Utils\wp_get_table_names( $args, $assoc_args ) as $table_name ) {
// Get the table size.
$table_bytes = $wpdb->get_var(
$wpdb->prepare(
'SELECT SUM(data_length + index_length) FROM information_schema.TABLES where table_schema = %s and Table_Name = %s GROUP BY Table_Name LIMIT 1',
DB_NAME,
$table_name
)
);
// Add the table size to the list.
$rows[] = array(
'Name' => $table_name,
'Size' => strtoupper( $table_bytes ) . $default_unit,
);
}
} else {
// Get the database size.
$db_bytes = $wpdb->get_var(
$wpdb->prepare(
'SELECT SUM(data_length + index_length) FROM information_schema.TABLES where table_schema = %s GROUP BY table_schema;',
DB_NAME
)
);
// Add the database size to the list.
$rows[] = array(
'Name' => DB_NAME,
'Size' => strtoupper( $db_bytes ) . $default_unit,
);
}
if ( ! empty( $size_format ) || $human_readable ) {
foreach ( $rows as $index => $row ) {
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound -- Backfilling WP native constants.
if ( ! defined( 'KB_IN_BYTES' ) ) {
define( 'KB_IN_BYTES', 1024 );
}
if ( ! defined( 'MB_IN_BYTES' ) ) {
define( 'MB_IN_BYTES', 1024 * KB_IN_BYTES );
}
if ( ! defined( 'GB_IN_BYTES' ) ) {
define( 'GB_IN_BYTES', 1024 * MB_IN_BYTES );
}
if ( ! defined( 'TB_IN_BYTES' ) ) {
define( 'TB_IN_BYTES', 1024 * GB_IN_BYTES );
}
// phpcs:enable
if ( $human_readable ) {
$size_key = floor( log( $row['Size'] ) / log( 1000 ) );
$sizes = array( 'B', 'KB', 'MB', 'GB', 'TB' );
$size_format = isset( $sizes[ $size_key ] ) ? $sizes[ $size_key ] : $sizes[0];
}
// Display the database size as a number.
switch ( $size_format ) {
case 'TB':
$divisor = pow( 1000, 4 );
break;
case 'GB':
$divisor = pow( 1000, 3 );
break;
case 'MB':
$divisor = pow( 1000, 2 );
break;
case 'KB':
$divisor = 1000;
break;
case 'tb':
case 'TiB':
$divisor = TB_IN_BYTES;
break;
case 'gb':
case 'GiB':
$divisor = GB_IN_BYTES;
break;
case 'mb':
case 'MiB':
$divisor = MB_IN_BYTES;
break;
case 'kb':
case 'KiB':
$divisor = KB_IN_BYTES;
break;
case 'b':
case 'B':
default:
$divisor = 1;
break;
}
$size_format_display = preg_replace( '/IB$/u', 'iB', strtoupper( $size_format ) );
$rows[ $index ]['Size'] = ceil( $row['Size'] / $divisor ) . ' ' . $size_format_display;
}
}
if ( ! empty( $size_format ) && ! $tables && ! $format && ! $human_readable && true !== $all_tables && true !== $all_tables_with_prefix ) {
WP_CLI::Line( filter_var( $rows[0]['Size'], FILTER_SANITIZE_NUMBER_INT ) );
} else {
// Display the rows.
$args = array(
'format' => $format,
);
$formatter = new Formatter( $args, $fields );
$formatter->display_items( $rows );
}
} | [
"public",
"function",
"size",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"global",
"$",
"wpdb",
";",
"$",
"format",
"=",
"Utils",
"\\",
"get_flag_value",
"(",
"$",
"assoc_args",
",",
"'format'",
")",
";",
"$",
"size_format",
"=",
"Utils",
"\\"... | Displays the database name and size.
Display the database name and size for `DB_NAME` specified in wp-config.php.
The size defaults to a human-readable number.
Available size formats include:
* b (bytes)
* kb (kilobytes)
* mb (megabytes)
* gb (gigabytes)
* tb (terabytes)
* B (ISO Byte setting, with no conversion)
* KB (ISO Kilobyte setting, with 1 KB = 1,000 B)
* KiB (ISO Kibibyte setting, with 1 KiB = 1,024 B)
* MB (ISO Megabyte setting, with 1 MB = 1,000 KB)
* MiB (ISO Mebibyte setting, with 1 MiB = 1,024 KiB)
* GB (ISO Gigabyte setting, with 1 GB = 1,000 MB)
* GiB (ISO Gibibyte setting, with 1 GiB = 1,024 MiB)
* TB (ISO Terabyte setting, with 1 TB = 1,000 GB)
* TiB (ISO Tebibyte setting, with 1 TiB = 1,024 GiB)
## OPTIONS
[--size_format=<format>]
: Display the database size only, as a bare number.
---
options:
- b
- kb
- mb
- gb
- tb
- B
- KB
- KiB
- MB
- MiB
- GB
- GiB
- TB
- TiB
---
[--tables]
: Display each table name and size instead of the database size.
[--human-readable]
: Display database sizes in human readable formats.
[--format=<format>]
: Render output in a particular format.
---
options:
- table
- csv
- json
- yaml
---
[--scope=<scope>]
: Can be all, global, ms_global, blog, or old tables. Defaults to all.
[--network]
: List all the tables in a multisite install.
[--all-tables-with-prefix]
: List all tables that match the table prefix even if not registered on $wpdb. Overrides --network.
[--all-tables]
: List all tables in the database, regardless of the prefix, and even if not registered on $wpdb. Overrides --all-tables-with-prefix.
## EXAMPLES
$ wp db size
+-------------------+------+
| Name | Size |
+-------------------+------+
| wordpress_default | 6 MB |
+-------------------+------+
$ wp db size --tables
+-----------------------+-------+
| Name | Size |
+-----------------------+-------+
| wp_users | 64 KB |
| wp_usermeta | 48 KB |
| wp_posts | 80 KB |
| wp_comments | 96 KB |
| wp_links | 32 KB |
| wp_options | 32 KB |
| wp_postmeta | 48 KB |
| wp_terms | 48 KB |
| wp_term_taxonomy | 48 KB |
| wp_term_relationships | 32 KB |
| wp_termmeta | 48 KB |
| wp_commentmeta | 48 KB |
+-----------------------+-------+
$ wp db size --size_format=b
5865472
$ wp db size --size_format=kb
5728
$ wp db size --size_format=mb
6
@when after_wp_load | [
"Displays",
"the",
"database",
"name",
"and",
"size",
"."
] | train | https://github.com/wp-cli/db-command/blob/dc0f8e4d5783d8a4ee01da1119b8fe8038fe1aa0/src/DB_Command.php#L773-L926 |
wp-cli/db-command | src/DB_Command.php | DB_Command.search | public function search( $args, $assoc_args ) {
global $wpdb;
$start_run_time = microtime( true );
$search = array_shift( $args );
$before_context = Utils\get_flag_value( $assoc_args, 'before_context', 40 );
$before_context = '' === $before_context ? $before_context : (int) $before_context;
$after_context = Utils\get_flag_value( $assoc_args, 'after_context', 40 );
$after_context = '' === $after_context ? $after_context : (int) $after_context;
$regex = Utils\get_flag_value( $assoc_args, 'regex', false );
if ( false !== $regex ) {
$regex_flags = Utils\get_flag_value( $assoc_args, 'regex-flags', false );
$default_regex_delimiter = false;
$regex_delimiter = Utils\get_flag_value( $assoc_args, 'regex-delimiter', '' );
if ( '' === $regex_delimiter ) {
$regex_delimiter = chr( 1 );
$default_regex_delimiter = true;
}
}
$colors = self::get_colors(
$assoc_args,
array(
'table_column' => '%G',
'id' => '%Y',
'match' => $before_context || $after_context ? '%3%k' : '',
)
);
$table_column_once = Utils\get_flag_value( $assoc_args, 'table_column_once', false );
$one_line = Utils\get_flag_value( $assoc_args, 'one_line', false );
$matches_only = Utils\get_flag_value( $assoc_args, 'matches_only', false );
$stats = Utils\get_flag_value( $assoc_args, 'stats', false );
$column_count = 0;
$row_count = 0;
$match_count = 0;
$skipped = array();
if ( $regex ) {
// Note the user must escape the delimiter in the search.
$search_regex = $regex_delimiter . $search . $regex_delimiter;
if ( $regex_flags ) {
$search_regex .= $regex_flags;
}
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- Unsure why this is needed, leaving in for now.
if ( false === @preg_match( $search_regex, '' ) ) {
if ( $default_regex_delimiter ) {
$flags_msg = $regex_flags ? "flags '$regex_flags'" : 'no flags';
$msg = "The regex pattern '$search' with default delimiter 'chr(1)' and {$flags_msg} fails.";
} else {
$msg = "The regex '$search_regex' fails.";
}
WP_CLI::error( $msg );
}
} else {
$search_regex = '#' . preg_quote( $search, '#' ) . '#i';
$esc_like_search = '%' . Utils\esc_like( $search ) . '%';
}
$encoding = null;
if ( 0 === strpos( $wpdb->charset, 'utf8' ) ) {
$encoding = 'UTF-8';
}
$tables = Utils\wp_get_table_names( $args, $assoc_args );
$start_search_time = microtime( true );
foreach ( $tables as $table ) {
list( $primary_keys, $text_columns, $all_columns ) = self::get_columns( $table );
if ( ! $all_columns ) {
WP_CLI::error( "No such table '$table'." );
}
if ( ! $text_columns ) {
if ( $stats ) {
$skipped[] = $table;
} else {
// Don't bother warning for term relationships (which is just 3 int columns).
if ( ! preg_match( '/_term_relationships$/', $table ) ) {
WP_CLI::warning( $primary_keys ? "No text columns for table '$table' - skipped." : "No primary key or text columns for table '$table' - skipped." );
}
}
continue;
}
$table_sql = self::esc_sql_ident( $table );
$column_count += count( $text_columns );
if ( ! $primary_keys ) {
WP_CLI::warning( "No primary key for table '$table'. No row ids will be outputted." );
$primary_key = '';
$primary_key_sql = '';
} else {
$primary_key = array_shift( $primary_keys );
$primary_key_sql = self::esc_sql_ident( $primary_key ) . ', ';
}
foreach ( $text_columns as $column ) {
$column_sql = self::esc_sql_ident( $column );
if ( $regex ) {
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Escaped through esc_sql_ident/esc_like.
$results = $wpdb->get_results( "SELECT {$primary_key_sql}{$column_sql} FROM {$table_sql}" );
} else {
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Escaped through esc_sql_ident/esc_like.
$results = $wpdb->get_results( $wpdb->prepare( "SELECT {$primary_key_sql}{$column_sql} FROM {$table_sql} WHERE {$column_sql} LIKE %s;", $esc_like_search ) );
}
if ( $results ) {
$row_count += count( $results );
$table_column_val = $colors['table_column'][0] . "{$table}:{$column}" . $colors['table_column'][1];
$outputted_table_column_once = false;
foreach ( $results as $result ) {
$col_val = $result->$column;
if ( preg_match_all( $search_regex, $col_val, $matches, PREG_OFFSET_CAPTURE ) ) {
if ( ! $matches_only && ( ! $table_column_once || ! $outputted_table_column_once ) && ! $one_line ) {
WP_CLI::log( $table_column_val );
$outputted_table_column_once = true;
}
$pk_val = $primary_key ? ( $colors['id'][0] . $result->$primary_key . $colors['id'][1] . ':' ) : '';
$bits = array();
$col_encoding = $encoding;
if ( ! $col_encoding && ( $before_context || $after_context ) && function_exists( 'mb_detect_encoding' ) ) {
$col_encoding = mb_detect_encoding( $col_val, null, true /*strict*/ );
}
$append_next = false;
$last_offset = 0;
$match_cnt = count( $matches[0] );
for ( $i = 0; $i < $match_cnt; $i++ ) {
$match = $matches[0][ $i ][0];
$offset = $matches[0][ $i ][1];
$log = $colors['match'][0] . $match . $colors['match'][1];
$before = '';
$after = '';
$after_shortened = false;
// Offsets are in bytes, so need to use `strlen()` and `substr()` before using `safe_substr()`.
if ( $before_context && $offset && ! $append_next ) {
$before = \cli\safe_substr( substr( $col_val, $last_offset, $offset - $last_offset ), -$before_context, null /*length*/, false /*is_width*/, $col_encoding );
}
if ( $after_context ) {
$end_offset = $offset + strlen( $match );
$after = \cli\safe_substr( substr( $col_val, $end_offset ), 0, $after_context, false /*is_width*/, $col_encoding );
// To lessen context duplication in output, shorten the after context if it overlaps with the next match.
if ( $i + 1 < $match_cnt && $end_offset + strlen( $after ) > $matches[0][ $i + 1 ][1] ) {
$after = substr( $after, 0, $matches[0][ $i + 1 ][1] - $end_offset );
$after_shortened = true;
// On the next iteration, will append with no before context.
}
}
if ( $append_next ) {
$cnt = count( $bits );
$bits[ $cnt - 1 ] .= $log . $after;
} else {
$bits[] = $before . $log . $after;
}
$append_next = $after_shortened;
$last_offset = $offset;
}
$match_count += $match_cnt;
$col_val = implode( ' [...] ', $bits );
WP_CLI::log( $matches_only ? $col_val : ( $one_line ? "{$table_column_val}:{$pk_val}{$col_val}" : "{$pk_val}{$col_val}" ) );
}
}
}
}
}
if ( $stats ) {
$table_count = count( $tables );
$skipped_count = count( $skipped );
$match_str = 1 === $match_count ? 'match' : 'matches';
$table_str = 1 === $table_count ? 'table' : 'tables';
$column_str = 1 === $column_count ? 'column' : 'columns';
$row_str = 1 === $row_count ? 'row' : 'rows';
$skipped_str = 1 === $skipped_count ? 'table skipped' : 'tables skipped';
if ( 0 !== $skipped_count ) {
$skipped_str .= ': ' . implode( ', ', $skipped );
}
$end_time = microtime( true );
$run_time = $end_time - $start_run_time;
$search_time = $end_time - $start_search_time;
$stats_msg = sprintf(
'Found %d %s in %.3fs (%.3fs searching). Searched %d %s, %d %s, %d %s. %d %s.',
$match_count,
$match_str,
$run_time,
$search_time,
$table_count,
$table_str,
$column_count,
$column_str,
$row_count,
$row_str,
$skipped_count,
$skipped_str
);
WP_CLI::success( $stats_msg );
}
} | php | public function search( $args, $assoc_args ) {
global $wpdb;
$start_run_time = microtime( true );
$search = array_shift( $args );
$before_context = Utils\get_flag_value( $assoc_args, 'before_context', 40 );
$before_context = '' === $before_context ? $before_context : (int) $before_context;
$after_context = Utils\get_flag_value( $assoc_args, 'after_context', 40 );
$after_context = '' === $after_context ? $after_context : (int) $after_context;
$regex = Utils\get_flag_value( $assoc_args, 'regex', false );
if ( false !== $regex ) {
$regex_flags = Utils\get_flag_value( $assoc_args, 'regex-flags', false );
$default_regex_delimiter = false;
$regex_delimiter = Utils\get_flag_value( $assoc_args, 'regex-delimiter', '' );
if ( '' === $regex_delimiter ) {
$regex_delimiter = chr( 1 );
$default_regex_delimiter = true;
}
}
$colors = self::get_colors(
$assoc_args,
array(
'table_column' => '%G',
'id' => '%Y',
'match' => $before_context || $after_context ? '%3%k' : '',
)
);
$table_column_once = Utils\get_flag_value( $assoc_args, 'table_column_once', false );
$one_line = Utils\get_flag_value( $assoc_args, 'one_line', false );
$matches_only = Utils\get_flag_value( $assoc_args, 'matches_only', false );
$stats = Utils\get_flag_value( $assoc_args, 'stats', false );
$column_count = 0;
$row_count = 0;
$match_count = 0;
$skipped = array();
if ( $regex ) {
// Note the user must escape the delimiter in the search.
$search_regex = $regex_delimiter . $search . $regex_delimiter;
if ( $regex_flags ) {
$search_regex .= $regex_flags;
}
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- Unsure why this is needed, leaving in for now.
if ( false === @preg_match( $search_regex, '' ) ) {
if ( $default_regex_delimiter ) {
$flags_msg = $regex_flags ? "flags '$regex_flags'" : 'no flags';
$msg = "The regex pattern '$search' with default delimiter 'chr(1)' and {$flags_msg} fails.";
} else {
$msg = "The regex '$search_regex' fails.";
}
WP_CLI::error( $msg );
}
} else {
$search_regex = '#' . preg_quote( $search, '#' ) . '#i';
$esc_like_search = '%' . Utils\esc_like( $search ) . '%';
}
$encoding = null;
if ( 0 === strpos( $wpdb->charset, 'utf8' ) ) {
$encoding = 'UTF-8';
}
$tables = Utils\wp_get_table_names( $args, $assoc_args );
$start_search_time = microtime( true );
foreach ( $tables as $table ) {
list( $primary_keys, $text_columns, $all_columns ) = self::get_columns( $table );
if ( ! $all_columns ) {
WP_CLI::error( "No such table '$table'." );
}
if ( ! $text_columns ) {
if ( $stats ) {
$skipped[] = $table;
} else {
// Don't bother warning for term relationships (which is just 3 int columns).
if ( ! preg_match( '/_term_relationships$/', $table ) ) {
WP_CLI::warning( $primary_keys ? "No text columns for table '$table' - skipped." : "No primary key or text columns for table '$table' - skipped." );
}
}
continue;
}
$table_sql = self::esc_sql_ident( $table );
$column_count += count( $text_columns );
if ( ! $primary_keys ) {
WP_CLI::warning( "No primary key for table '$table'. No row ids will be outputted." );
$primary_key = '';
$primary_key_sql = '';
} else {
$primary_key = array_shift( $primary_keys );
$primary_key_sql = self::esc_sql_ident( $primary_key ) . ', ';
}
foreach ( $text_columns as $column ) {
$column_sql = self::esc_sql_ident( $column );
if ( $regex ) {
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Escaped through esc_sql_ident/esc_like.
$results = $wpdb->get_results( "SELECT {$primary_key_sql}{$column_sql} FROM {$table_sql}" );
} else {
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Escaped through esc_sql_ident/esc_like.
$results = $wpdb->get_results( $wpdb->prepare( "SELECT {$primary_key_sql}{$column_sql} FROM {$table_sql} WHERE {$column_sql} LIKE %s;", $esc_like_search ) );
}
if ( $results ) {
$row_count += count( $results );
$table_column_val = $colors['table_column'][0] . "{$table}:{$column}" . $colors['table_column'][1];
$outputted_table_column_once = false;
foreach ( $results as $result ) {
$col_val = $result->$column;
if ( preg_match_all( $search_regex, $col_val, $matches, PREG_OFFSET_CAPTURE ) ) {
if ( ! $matches_only && ( ! $table_column_once || ! $outputted_table_column_once ) && ! $one_line ) {
WP_CLI::log( $table_column_val );
$outputted_table_column_once = true;
}
$pk_val = $primary_key ? ( $colors['id'][0] . $result->$primary_key . $colors['id'][1] . ':' ) : '';
$bits = array();
$col_encoding = $encoding;
if ( ! $col_encoding && ( $before_context || $after_context ) && function_exists( 'mb_detect_encoding' ) ) {
$col_encoding = mb_detect_encoding( $col_val, null, true /*strict*/ );
}
$append_next = false;
$last_offset = 0;
$match_cnt = count( $matches[0] );
for ( $i = 0; $i < $match_cnt; $i++ ) {
$match = $matches[0][ $i ][0];
$offset = $matches[0][ $i ][1];
$log = $colors['match'][0] . $match . $colors['match'][1];
$before = '';
$after = '';
$after_shortened = false;
// Offsets are in bytes, so need to use `strlen()` and `substr()` before using `safe_substr()`.
if ( $before_context && $offset && ! $append_next ) {
$before = \cli\safe_substr( substr( $col_val, $last_offset, $offset - $last_offset ), -$before_context, null /*length*/, false /*is_width*/, $col_encoding );
}
if ( $after_context ) {
$end_offset = $offset + strlen( $match );
$after = \cli\safe_substr( substr( $col_val, $end_offset ), 0, $after_context, false /*is_width*/, $col_encoding );
// To lessen context duplication in output, shorten the after context if it overlaps with the next match.
if ( $i + 1 < $match_cnt && $end_offset + strlen( $after ) > $matches[0][ $i + 1 ][1] ) {
$after = substr( $after, 0, $matches[0][ $i + 1 ][1] - $end_offset );
$after_shortened = true;
// On the next iteration, will append with no before context.
}
}
if ( $append_next ) {
$cnt = count( $bits );
$bits[ $cnt - 1 ] .= $log . $after;
} else {
$bits[] = $before . $log . $after;
}
$append_next = $after_shortened;
$last_offset = $offset;
}
$match_count += $match_cnt;
$col_val = implode( ' [...] ', $bits );
WP_CLI::log( $matches_only ? $col_val : ( $one_line ? "{$table_column_val}:{$pk_val}{$col_val}" : "{$pk_val}{$col_val}" ) );
}
}
}
}
}
if ( $stats ) {
$table_count = count( $tables );
$skipped_count = count( $skipped );
$match_str = 1 === $match_count ? 'match' : 'matches';
$table_str = 1 === $table_count ? 'table' : 'tables';
$column_str = 1 === $column_count ? 'column' : 'columns';
$row_str = 1 === $row_count ? 'row' : 'rows';
$skipped_str = 1 === $skipped_count ? 'table skipped' : 'tables skipped';
if ( 0 !== $skipped_count ) {
$skipped_str .= ': ' . implode( ', ', $skipped );
}
$end_time = microtime( true );
$run_time = $end_time - $start_run_time;
$search_time = $end_time - $start_search_time;
$stats_msg = sprintf(
'Found %d %s in %.3fs (%.3fs searching). Searched %d %s, %d %s, %d %s. %d %s.',
$match_count,
$match_str,
$run_time,
$search_time,
$table_count,
$table_str,
$column_count,
$column_str,
$row_count,
$row_str,
$skipped_count,
$skipped_str
);
WP_CLI::success( $stats_msg );
}
} | [
"public",
"function",
"search",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"global",
"$",
"wpdb",
";",
"$",
"start_run_time",
"=",
"microtime",
"(",
"true",
")",
";",
"$",
"search",
"=",
"array_shift",
"(",
"$",
"args",
")",
";",
"$",
"befor... | Finds a string in the database.
Searches through all or a selection of database tables for a given string, Outputs colorized references to the string.
Defaults to searching through all tables registered to $wpdb. On multisite, this default is limited to the tables for the current site.
## OPTIONS
<search>
: String to search for. The search is case-insensitive by default.
[<tables>...]
: One or more tables to search through for the string.
[--network]
: Search through all the tables registered to $wpdb in a multisite install.
[--all-tables-with-prefix]
: Search through all tables that match the registered table prefix, even if not registered on $wpdb. On one hand, sometimes plugins use tables without registering them to $wpdb. On another hand, this could return tables you don't expect. Overrides --network.
[--all-tables]
: Search through ALL tables in the database, regardless of the prefix, and even if not registered on $wpdb. Overrides --network and --all-tables-with-prefix.
[--before_context=<num>]
: Number of characters to display before the match.
---
default: 40
---
[--after_context=<num>]
: Number of characters to display after the match.
---
default: 40
---
[--regex]
: Runs the search as a regular expression (without delimiters). The search becomes case-sensitive (i.e. no PCRE flags are added). Delimiters must be escaped if they occur in the expression.
[--regex-flags=<regex-flags>]
: Pass PCRE modifiers to the regex search (e.g. 'i' for case-insensitivity).
[--regex-delimiter=<regex-delimiter>]
: The delimiter to use for the regex. It must be escaped if it appears in the search string. The default value is the result of `chr(1)`.
[--table_column_once]
: Output the 'table:column' line once before all matching row lines in the table column rather than before each matching row.
[--one_line]
: Place the 'table:column' output on the same line as the row id and match ('table:column:id:match'). Overrides --table_column_once.
[--matches_only]
: Only output the string matches (including context). No 'table:column's or row ids are outputted.
[--stats]
: Output stats on the number of matches found, time taken, tables/columns/rows searched, tables skipped.
[--table_column_color=<color_code>]
: Percent color code to use for the 'table:column' output. For a list of available percent color codes, see below. Default '%G' (bright green).
[--id_color=<color_code>]
: Percent color code to use for the row id output. For a list of available percent color codes, see below. Default '%Y' (bright yellow).
[--match_color=<color_code>]
: Percent color code to use for the match (unless both before and after context are 0, when no color code is used). For a list of available percent color codes, see below. Default '%3%k' (black on a mustard background).
The percent color codes available are:
| Code | Color
| ---- | -----
| %y | Yellow (dark) (mustard)
| %g | Green (dark)
| %b | Blue (dark)
| %r | Red (dark)
| %m | Magenta (dark)
| %c | Cyan (dark)
| %w | White (dark) (light gray)
| %k | Black
| %Y | Yellow (bright)
| %G | Green (bright)
| %B | Blue (bright)
| %R | Red (bright)
| %M | Magenta (bright)
| %C | Cyan (bright)
| %W | White
| %K | Black (bright) (dark gray)
| %3 | Yellow background (dark) (mustard)
| %2 | Green background (dark)
| %4 | Blue background (dark)
| %1 | Red background (dark)
| %5 | Magenta background (dark)
| %6 | Cyan background (dark)
| %7 | White background (dark) (light gray)
| %0 | Black background
| %8 | Reverse
| %U | Underline
| %F | Blink (unlikely to work)
They can be concatenated. For instance, the default match color of black on a mustard (dark yellow) background `%3%k` can be made black on a bright yellow background with `%Y%0%8`.
## EXAMPLES
# Search through the database for the 'wordpress-develop' string
$ wp db search wordpress-develop
wp_options:option_value
1:http://wordpress-develop.dev
wp_options:option_value
1:http://example.com/foo
...
# Search through a multisite database on the subsite 'foo' for the 'example.com' string
$ wp db search example.com --url=example.com/foo
wp_2_comments:comment_author_url
1:http://example.com/
wp_2_options:option_value
...
# Search through the database for the 'https?://' regular expression, printing stats.
$ wp db search 'https?://' --regex --stats
wp_comments:comment_author_url
1:https://wordpress.org/
...
Success: Found 99146 matches in 10.752s (10.559s searching). Searched 12 tables, 53 columns, 1358907 rows. 1 table skipped: wp_term_relationships.
# SQL search database table 'wp_options' where 'option_name' match 'foo'
wp db query 'SELECT * FROM wp_options WHERE option_name like "%foo%"' --skip-column-names
+----+--------------+--------------------------------+-----+
| 98 | foo_options | a:1:{s:12:"_multiwidget";i:1;} | yes |
| 99 | foo_settings | a:0:{} | yes |
+----+--------------+--------------------------------+-----+
# SQL search and delete records from database table 'wp_options' where 'option_name' match 'foo'
wp db query "DELETE from wp_options where option_id in ($(wp db query "SELECT GROUP_CONCAT(option_id SEPARATOR ',') from wp_options where option_name like '%foo%';" --silent --skip-column-names))"
@when after_wp_load | [
"Finds",
"a",
"string",
"in",
"the",
"database",
"."
] | train | https://github.com/wp-cli/db-command/blob/dc0f8e4d5783d8a4ee01da1119b8fe8038fe1aa0/src/DB_Command.php#L1082-L1284 |
wp-cli/db-command | src/DB_Command.php | DB_Command.columns | public function columns( $args, $assoc_args ) {
global $wpdb;
$format = Utils\get_flag_value( $assoc_args, 'format' );
Utils\wp_get_table_names( array( $args[0] ), array() );
$columns = $wpdb->get_results(
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Asserted to be a valid table name through wp_get_table_names.
'SHOW COLUMNS FROM ' . $args[0]
);
$formatter_fields = array( 'Field', 'Type', 'Null', 'Key', 'Default', 'Extra' );
$formatter_args = array(
'format' => $format,
);
$formatter = new Formatter( $formatter_args, $formatter_fields );
$formatter->display_items( $columns );
} | php | public function columns( $args, $assoc_args ) {
global $wpdb;
$format = Utils\get_flag_value( $assoc_args, 'format' );
Utils\wp_get_table_names( array( $args[0] ), array() );
$columns = $wpdb->get_results(
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Asserted to be a valid table name through wp_get_table_names.
'SHOW COLUMNS FROM ' . $args[0]
);
$formatter_fields = array( 'Field', 'Type', 'Null', 'Key', 'Default', 'Extra' );
$formatter_args = array(
'format' => $format,
);
$formatter = new Formatter( $formatter_args, $formatter_fields );
$formatter->display_items( $columns );
} | [
"public",
"function",
"columns",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"global",
"$",
"wpdb",
";",
"$",
"format",
"=",
"Utils",
"\\",
"get_flag_value",
"(",
"$",
"assoc_args",
",",
"'format'",
")",
";",
"Utils",
"\\",
"wp_get_table_names",
... | Displays information about a given table.
## OPTIONS
[<table>]
: Name of the database table.
[--format]
: Render output in a particular format.
---
default: table
options:
- table
- csv
- json
- yaml
---
## EXAMPLES
$ wp db columns wp_posts
+-----------------------+---------------------+------+-----+---------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------------+---------------------+------+-----+---------------------+----------------+
| ID | bigint(20) unsigned | NO | PRI | | auto_increment |
| post_author | bigint(20) unsigned | NO | MUL | 0 | |
| post_date | datetime | NO | | 0000-00-00 00:00:00 | |
| post_date_gmt | datetime | NO | | 0000-00-00 00:00:00 | |
| post_content | longtext | NO | | | |
| post_title | text | NO | | | |
| post_excerpt | text | NO | | | |
| post_status | varchar(20) | NO | | publish | |
| comment_status | varchar(20) | NO | | open | |
| ping_status | varchar(20) | NO | | open | |
| post_password | varchar(255) | NO | | | |
| post_name | varchar(200) | NO | MUL | | |
| to_ping | text | NO | | | |
| pinged | text | NO | | | |
| post_modified | datetime | NO | | 0000-00-00 00:00:00 | |
| post_modified_gmt | datetime | NO | | 0000-00-00 00:00:00 | |
| post_content_filtered | longtext | NO | | | |
| post_parent | bigint(20) unsigned | NO | MUL | 0 | |
| guid | varchar(255) | NO | | | |
| menu_order | int(11) | NO | | 0 | |
| post_type | varchar(20) | NO | MUL | post | |
| post_mime_type | varchar(100) | NO | | | |
| comment_count | bigint(20) | NO | | 0 | |
+-----------------------+---------------------+------+-----+---------------------+----------------+
@when after_wp_load | [
"Displays",
"information",
"about",
"a",
"given",
"table",
"."
] | train | https://github.com/wp-cli/db-command/blob/dc0f8e4d5783d8a4ee01da1119b8fe8038fe1aa0/src/DB_Command.php#L1338-L1357 |
wp-cli/db-command | src/DB_Command.php | DB_Command.get_dbuser_dbpass_args | private static function get_dbuser_dbpass_args( $assoc_args ) {
$mysql_args = array();
$dbuser = Utils\get_flag_value( $assoc_args, 'dbuser' );
if ( null !== $dbuser ) {
$mysql_args['dbuser'] = $dbuser;
}
$dbpass = Utils\get_flag_value( $assoc_args, 'dbpass' );
if ( null !== $dbpass ) {
$mysql_args['dbpass'] = $dbpass;
}
return $mysql_args;
} | php | private static function get_dbuser_dbpass_args( $assoc_args ) {
$mysql_args = array();
$dbuser = Utils\get_flag_value( $assoc_args, 'dbuser' );
if ( null !== $dbuser ) {
$mysql_args['dbuser'] = $dbuser;
}
$dbpass = Utils\get_flag_value( $assoc_args, 'dbpass' );
if ( null !== $dbpass ) {
$mysql_args['dbpass'] = $dbpass;
}
return $mysql_args;
} | [
"private",
"static",
"function",
"get_dbuser_dbpass_args",
"(",
"$",
"assoc_args",
")",
"{",
"$",
"mysql_args",
"=",
"array",
"(",
")",
";",
"$",
"dbuser",
"=",
"Utils",
"\\",
"get_flag_value",
"(",
"$",
"assoc_args",
",",
"'dbuser'",
")",
";",
"if",
"(",
... | Helper to pluck 'dbuser' and 'dbpass' from associative args array.
@param array $assoc_args Associative args array.
@return array Array with `dbuser' and 'dbpass' set if in passed-in associative args array. | [
"Helper",
"to",
"pluck",
"dbuser",
"and",
"dbpass",
"from",
"associative",
"args",
"array",
"."
] | train | https://github.com/wp-cli/db-command/blob/dc0f8e4d5783d8a4ee01da1119b8fe8038fe1aa0/src/DB_Command.php#L1407-L1418 |
wp-cli/db-command | src/DB_Command.php | DB_Command.get_columns | private static function get_columns( $table ) {
global $wpdb;
$table_sql = self::esc_sql_ident( $table );
$primary_keys = array();
$text_columns = array();
$all_columns = array();
$suppress_errors = $wpdb->suppress_errors();
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Escaped through esc_sql_ident/esc_like.
$results = $wpdb->get_results( "DESCRIBE $table_sql" );
if ( $results ) {
foreach ( $results as $col ) {
// phpcs:disable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Property names come from database.
if ( 'PRI' === $col->Key ) {
$primary_keys[] = $col->Field;
}
if ( self::is_text_col( $col->Type ) ) {
$text_columns[] = $col->Field;
}
$all_columns[] = $col->Field;
// phpcs:enable
}
}
$wpdb->suppress_errors( $suppress_errors );
return array( $primary_keys, $text_columns, $all_columns );
} | php | private static function get_columns( $table ) {
global $wpdb;
$table_sql = self::esc_sql_ident( $table );
$primary_keys = array();
$text_columns = array();
$all_columns = array();
$suppress_errors = $wpdb->suppress_errors();
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Escaped through esc_sql_ident/esc_like.
$results = $wpdb->get_results( "DESCRIBE $table_sql" );
if ( $results ) {
foreach ( $results as $col ) {
// phpcs:disable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Property names come from database.
if ( 'PRI' === $col->Key ) {
$primary_keys[] = $col->Field;
}
if ( self::is_text_col( $col->Type ) ) {
$text_columns[] = $col->Field;
}
$all_columns[] = $col->Field;
// phpcs:enable
}
}
$wpdb->suppress_errors( $suppress_errors );
return array( $primary_keys, $text_columns, $all_columns );
} | [
"private",
"static",
"function",
"get_columns",
"(",
"$",
"table",
")",
"{",
"global",
"$",
"wpdb",
";",
"$",
"table_sql",
"=",
"self",
"::",
"esc_sql_ident",
"(",
"$",
"table",
")",
";",
"$",
"primary_keys",
"=",
"array",
"(",
")",
";",
"$",
"text_col... | Gets the column names of a db table differentiated into key columns and text columns and all columns.
@param string $table The table name.
@return array A 3 element array consisting of an array of primary key column names, an array of text column names, and an array containing all column names. | [
"Gets",
"the",
"column",
"names",
"of",
"a",
"db",
"table",
"differentiated",
"into",
"key",
"columns",
"and",
"text",
"columns",
"and",
"all",
"columns",
"."
] | train | https://github.com/wp-cli/db-command/blob/dc0f8e4d5783d8a4ee01da1119b8fe8038fe1aa0/src/DB_Command.php#L1426-L1452 |
wp-cli/db-command | src/DB_Command.php | DB_Command.get_mysql_args | private static function get_mysql_args( $assoc_args ) {
$allowed_mysql_options = [
'auto-rehash',
'auto-vertical-output',
'batch',
'binary-as-hex',
'binary-mode',
'bind-address',
'character-sets-dir',
'column-names',
'column-type-info',
'comments',
'compress',
'connect-expired-password',
'connect_timeout',
'database',
'debug',
'debug-check',
'debug-info',
'default-auth',
'default-character-set',
'defaults-extra-file',
'defaults-file',
'defaults-group-suffix',
'delimiter',
'enable-cleartext-plugin',
'execute',
'force',
'get-server-public-key',
'help',
'histignore',
'host',
'html',
'ignore-spaces',
'init-command',
'line-numbers',
'local-infile',
'login-path',
'max_allowed_packet',
'max_join_size',
'named-commands',
'net_buffer_length',
'no-beep',
'one-database',
'pager',
'pipe',
'plugin-dir',
'port',
'print-defaults',
'protocol',
'quick',
'raw',
'reconnect',
'i-am-a-dummy',
'safe-updates',
'secure-auth',
'select_limit',
'server-public-key-path',
'shared-memory-base-name',
'show-warnings',
'sigint-ignore',
'silent',
'skip-auto-rehash',
'skip-column-names',
'skip-line-numbers',
'skip-named-commands',
'skip-pager',
'skip-reconnect',
'socket',
'ssl-ca',
'ssl-capath',
'ssl-cert',
'ssl-cipher',
'ssl-crl',
'ssl-crlpath',
'ssl-fips-mode',
'ssl-key',
'ssl-mode',
'syslog',
'table',
'tee',
'tls-version',
'unbuffered',
'verbose',
'version',
'vertical',
'wait',
'xml',
];
$mysql_args = array();
foreach ( $assoc_args as $mysql_option_key => $mysql_option_value ) {
// Check flags to make sure they only contain valid options.
if ( in_array( $mysql_option_key, $allowed_mysql_options, true ) && ! empty( $mysql_option_value ) ) {
$mysql_args[ $mysql_option_key ] = $mysql_option_value;
}
}
return $mysql_args;
} | php | private static function get_mysql_args( $assoc_args ) {
$allowed_mysql_options = [
'auto-rehash',
'auto-vertical-output',
'batch',
'binary-as-hex',
'binary-mode',
'bind-address',
'character-sets-dir',
'column-names',
'column-type-info',
'comments',
'compress',
'connect-expired-password',
'connect_timeout',
'database',
'debug',
'debug-check',
'debug-info',
'default-auth',
'default-character-set',
'defaults-extra-file',
'defaults-file',
'defaults-group-suffix',
'delimiter',
'enable-cleartext-plugin',
'execute',
'force',
'get-server-public-key',
'help',
'histignore',
'host',
'html',
'ignore-spaces',
'init-command',
'line-numbers',
'local-infile',
'login-path',
'max_allowed_packet',
'max_join_size',
'named-commands',
'net_buffer_length',
'no-beep',
'one-database',
'pager',
'pipe',
'plugin-dir',
'port',
'print-defaults',
'protocol',
'quick',
'raw',
'reconnect',
'i-am-a-dummy',
'safe-updates',
'secure-auth',
'select_limit',
'server-public-key-path',
'shared-memory-base-name',
'show-warnings',
'sigint-ignore',
'silent',
'skip-auto-rehash',
'skip-column-names',
'skip-line-numbers',
'skip-named-commands',
'skip-pager',
'skip-reconnect',
'socket',
'ssl-ca',
'ssl-capath',
'ssl-cert',
'ssl-cipher',
'ssl-crl',
'ssl-crlpath',
'ssl-fips-mode',
'ssl-key',
'ssl-mode',
'syslog',
'table',
'tee',
'tls-version',
'unbuffered',
'verbose',
'version',
'vertical',
'wait',
'xml',
];
$mysql_args = array();
foreach ( $assoc_args as $mysql_option_key => $mysql_option_value ) {
// Check flags to make sure they only contain valid options.
if ( in_array( $mysql_option_key, $allowed_mysql_options, true ) && ! empty( $mysql_option_value ) ) {
$mysql_args[ $mysql_option_key ] = $mysql_option_value;
}
}
return $mysql_args;
} | [
"private",
"static",
"function",
"get_mysql_args",
"(",
"$",
"assoc_args",
")",
"{",
"$",
"allowed_mysql_options",
"=",
"[",
"'auto-rehash'",
",",
"'auto-vertical-output'",
",",
"'batch'",
",",
"'binary-as-hex'",
",",
"'binary-mode'",
",",
"'bind-address'",
",",
"'c... | Helper to pluck `mysql` options from associative args array.
@param array $assoc_args Associative args array.
@return array Array with `mysql` options set if in passed-in associative args array. | [
"Helper",
"to",
"pluck",
"mysql",
"options",
"from",
"associative",
"args",
"array",
"."
] | train | https://github.com/wp-cli/db-command/blob/dc0f8e4d5783d8a4ee01da1119b8fe8038fe1aa0/src/DB_Command.php#L1531-L1632 |
itbdw/ip-database | src/IpLocation.php | IpLocation.getAddr | private function getAddr($ip)
{
$result = [];
$is_china = false;
$seperator_sheng = '省';
$seperator_shi = '市';
$seperator_xian = '县';
$seperator_qu = '区';
if (!$this->isValidIpV4($ip)) {
$result['error'] = 'ip invalid';
return $result;
} else {
$location = $this->getlocationfromip($ip); // $location[country] [area]
if (!$location) {
$result['error'] = 'file open failed';
return $result;
}
$location['org_country'] = $location['country']; //北京市朝阳区
$location['org_area'] = $location['area']; // 金桥国际小区
$location['province'] = $location['city'] = $location['county'] = '';
$_tmp_province = explode($seperator_sheng, $location['country']);
//存在 省 标志 xxx省yyyy 中的yyyy
if (isset($_tmp_province[1])) {
$is_china = true;
//省
$location['province'] = $_tmp_province[0]; //河北
if (strpos($_tmp_province[1], $seperator_shi) !== false) {
$_tmp_city = explode($seperator_shi, $_tmp_province[1]);
//市
$location['city'] = $_tmp_city[0] . $seperator_shi;
//县
if (isset($_tmp_city[1])) {
if (strpos($_tmp_city[1], $seperator_xian) !== false) {
$_tmp_county = explode($seperator_xian, $_tmp_city[1]);
$location['county'] = $_tmp_county[0] . $seperator_xian;
}
//区
if (!$location['county'] && strpos($_tmp_city[1], $seperator_qu) !== false) {
$_tmp_qu = explode($seperator_qu, $_tmp_city[1]);
$location['county'] = $_tmp_qu[0] . $seperator_qu;
}
}
}
} else {
//处理内蒙古不带省份类型的和直辖市
foreach ($this->dict_province as $key => $value) {
if (false !== strpos($location['country'], $value)) {
$is_china = true;
//直辖市
if (in_array($value, $this->dict_city_directly)) {
$_tmp_province = explode($seperator_shi, $location['country']);
//直辖市
$location['province'] = $_tmp_province[0];
//市辖区
if (isset($_tmp_province[1])) {
if (strpos($_tmp_province[1], $seperator_qu) !== false) {
$_tmp_qu = explode($seperator_qu, $_tmp_province[1]);
$location['city'] = $_tmp_qu[0] . $seperator_qu;
}
}
} else {
//省
$location['province'] = $value;
//没有省份标志 只能替换
$_tmp_city = str_replace($location['province'], '', $location['country']);
//防止直辖市捣乱 上海市xxx区 =》 市xx区
$_tmp_shi_pos = mb_stripos($_tmp_city, $seperator_shi);
if ($_tmp_shi_pos === 0) {
$_tmp_city = mb_substr($_tmp_city, 1);
}
//内蒙古 类型的 获取市县信息
if (strpos($_tmp_city, $seperator_shi) !== false) {
//市
$_tmp_city = explode($seperator_shi, $_tmp_city);
$location['city'] = $_tmp_city[0] . $seperator_shi;
//县
if (isset($_tmp_city[1])) {
if (strpos($_tmp_city[1], $seperator_xian) !== false) {
$_tmp_county = explode($seperator_xian, $_tmp_city[1]);
$location['county'] = $_tmp_county[0] . $seperator_xian;
}
//区
if (!$location['county'] && strpos($_tmp_city[1], $seperator_qu) !== false) {
$_tmp_qu = explode($seperator_qu, $_tmp_city[1]);
$location['county'] = $_tmp_qu[0] . $seperator_qu;
}
}
}
}
break;
}
}
}
if ($is_china) {
$location['country'] = '中国';
}
$location['isp'] = $this->getIsp($location['area']);
$result['ip'] = $location['ip'];
// $result['beginip'] = $location['beginip'];
// $result['endip'] = $location['endip'];
// $result['org_country'] = $location['org_country']; //纯真数据库返回的列1
// $result['org_area'] = $location['org_area'];
$result['country'] = $location['country'];
$result['province'] = $location['province'];
$result['city'] = $location['city'];
$result['county'] = $location['county'];
$result['isp'] = $location['isp'];
$result['area'] = $location['country'] . $location['province'] . $location['city'] . $location['county'] . $location['org_area'];
}
return $result; //array
} | php | private function getAddr($ip)
{
$result = [];
$is_china = false;
$seperator_sheng = '省';
$seperator_shi = '市';
$seperator_xian = '县';
$seperator_qu = '区';
if (!$this->isValidIpV4($ip)) {
$result['error'] = 'ip invalid';
return $result;
} else {
$location = $this->getlocationfromip($ip); // $location[country] [area]
if (!$location) {
$result['error'] = 'file open failed';
return $result;
}
$location['org_country'] = $location['country']; //北京市朝阳区
$location['org_area'] = $location['area']; // 金桥国际小区
$location['province'] = $location['city'] = $location['county'] = '';
$_tmp_province = explode($seperator_sheng, $location['country']);
//存在 省 标志 xxx省yyyy 中的yyyy
if (isset($_tmp_province[1])) {
$is_china = true;
//省
$location['province'] = $_tmp_province[0]; //河北
if (strpos($_tmp_province[1], $seperator_shi) !== false) {
$_tmp_city = explode($seperator_shi, $_tmp_province[1]);
//市
$location['city'] = $_tmp_city[0] . $seperator_shi;
//县
if (isset($_tmp_city[1])) {
if (strpos($_tmp_city[1], $seperator_xian) !== false) {
$_tmp_county = explode($seperator_xian, $_tmp_city[1]);
$location['county'] = $_tmp_county[0] . $seperator_xian;
}
//区
if (!$location['county'] && strpos($_tmp_city[1], $seperator_qu) !== false) {
$_tmp_qu = explode($seperator_qu, $_tmp_city[1]);
$location['county'] = $_tmp_qu[0] . $seperator_qu;
}
}
}
} else {
//处理内蒙古不带省份类型的和直辖市
foreach ($this->dict_province as $key => $value) {
if (false !== strpos($location['country'], $value)) {
$is_china = true;
//直辖市
if (in_array($value, $this->dict_city_directly)) {
$_tmp_province = explode($seperator_shi, $location['country']);
//直辖市
$location['province'] = $_tmp_province[0];
//市辖区
if (isset($_tmp_province[1])) {
if (strpos($_tmp_province[1], $seperator_qu) !== false) {
$_tmp_qu = explode($seperator_qu, $_tmp_province[1]);
$location['city'] = $_tmp_qu[0] . $seperator_qu;
}
}
} else {
//省
$location['province'] = $value;
//没有省份标志 只能替换
$_tmp_city = str_replace($location['province'], '', $location['country']);
//防止直辖市捣乱 上海市xxx区 =》 市xx区
$_tmp_shi_pos = mb_stripos($_tmp_city, $seperator_shi);
if ($_tmp_shi_pos === 0) {
$_tmp_city = mb_substr($_tmp_city, 1);
}
//内蒙古 类型的 获取市县信息
if (strpos($_tmp_city, $seperator_shi) !== false) {
//市
$_tmp_city = explode($seperator_shi, $_tmp_city);
$location['city'] = $_tmp_city[0] . $seperator_shi;
//县
if (isset($_tmp_city[1])) {
if (strpos($_tmp_city[1], $seperator_xian) !== false) {
$_tmp_county = explode($seperator_xian, $_tmp_city[1]);
$location['county'] = $_tmp_county[0] . $seperator_xian;
}
//区
if (!$location['county'] && strpos($_tmp_city[1], $seperator_qu) !== false) {
$_tmp_qu = explode($seperator_qu, $_tmp_city[1]);
$location['county'] = $_tmp_qu[0] . $seperator_qu;
}
}
}
}
break;
}
}
}
if ($is_china) {
$location['country'] = '中国';
}
$location['isp'] = $this->getIsp($location['area']);
$result['ip'] = $location['ip'];
// $result['beginip'] = $location['beginip'];
// $result['endip'] = $location['endip'];
// $result['org_country'] = $location['org_country']; //纯真数据库返回的列1
// $result['org_area'] = $location['org_area'];
$result['country'] = $location['country'];
$result['province'] = $location['province'];
$result['city'] = $location['city'];
$result['county'] = $location['county'];
$result['isp'] = $location['isp'];
$result['area'] = $location['country'] . $location['province'] . $location['city'] . $location['county'] . $location['org_area'];
}
return $result; //array
} | [
"private",
"function",
"getAddr",
"(",
"$",
"ip",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"$",
"is_china",
"=",
"false",
";",
"$",
"seperator_sheng",
"=",
"'省';",
"",
"$",
"seperator_shi",
"=",
"'市';",
"",
"$",
"seperator_xian",
"=",
"'县';",
"",... | 如果ip错误,返回 $result['error'] 信息
province city county isp 对中国以外的ip无法识别
<code>
$result 是返回的数组
$result['ip'] 输入的ip
$result['country'] 国家 如 中国
$result['province'] 省份信息 如 河北省
$result['city'] 市区 如 邢台市
$result['county'] 郡县 如 威县
$result['isp'] 运营商 如 联通
$result['area'] 最完整的信息 如 中国河北省邢台市威县新科网吧(北外街)
</code>
@param $ip
@return array | [
"如果ip错误,返回",
"$result",
"[",
"error",
"]",
"信息",
"province",
"city",
"county",
"isp",
"对中国以外的ip无法识别",
"<code",
">",
"$result",
"是返回的数组",
"$result",
"[",
"ip",
"]",
"输入的ip",
"$result",
"[",
"country",
"]",
"国家",
"如",
"中国",
"$result",
"[",
"province",
"]",
... | train | https://github.com/itbdw/ip-database/blob/24c203c50080d4ef2f1744930253095c76a58c3d/src/IpLocation.php#L193-L330 |
itbdw/ip-database | src/IpLocation.php | IpLocation.getlocationfromip | private function getlocationfromip($ip)
{
if (!$this->fp) {
return null;
} // 如果数据文件没有被正确打开,则直接返回空
$location['ip'] = $ip;
$ip = $this->packip($location['ip']); // 将输入的IP地址转化为可比较的IP地址
// 不合法的IP地址会被转化为255.255.255.255
// 对分搜索
$l = 0; // 搜索的下边界
$u = $this->totalip; // 搜索的上边界
$findip = $this->lastip; // 如果没有找到就返回最后一条IP记录(qqwry.dat的版本信息)
while ($l <= $u) { // 当上边界小于下边界时,查找失败
$i = floor(($l + $u) / 2); // 计算近似中间记录
fseek($this->fp, $this->firstip + $i * 7);
$beginip = strrev(fread($this->fp, 4)); // 获取中间记录的开始IP地址
// strrev函数在这里的作用是将little-endian的压缩IP地址转化为big-endian的格式
// 以便用于比较,后面相同。
if ($ip < $beginip) { // 用户的IP小于中间记录的开始IP地址时
$u = $i - 1; // 将搜索的上边界修改为中间记录减一
} else {
fseek($this->fp, $this->getlong3());
$endip = strrev(fread($this->fp, 4)); // 获取中间记录的结束IP地址
if ($ip > $endip) { // 用户的IP大于中间记录的结束IP地址时
$l = $i + 1; // 将搜索的下边界修改为中间记录加一
} else { // 用户的IP在中间记录的IP范围内时
$findip = $this->firstip + $i * 7;
break; // 则表示找到结果,退出循环
}
}
}
//获取查找到的IP地理位置信息
fseek($this->fp, $findip);
$location['beginip'] = long2ip($this->getlong()); // 用户IP所在范围的开始地址
$offset = $this->getlong3();
fseek($this->fp, $offset);
$location['endip'] = long2ip($this->getlong()); // 用户IP所在范围的结束地址
$byte = fread($this->fp, 1); // 标志字节
switch (ord($byte)) {
case 1: // 标志字节为1,表示国家和区域信息都被同时重定向
$countryOffset = $this->getlong3(); // 重定向地址
fseek($this->fp, $countryOffset);
$byte = fread($this->fp, 1); // 标志字节
switch (ord($byte)) {
case 2: // 标志字节为2,表示国家信息被重定向
fseek($this->fp, $this->getlong3());
$location['country'] = $this->getstring();
fseek($this->fp, $countryOffset + 4);
$location['area'] = $this->getarea();
break;
default: // 否则,表示国家信息没有被重定向
$location['country'] = $this->getstring($byte);
$location['area'] = $this->getarea();
break;
}
break;
case 2: // 标志字节为2,表示国家信息被重定向
fseek($this->fp, $this->getlong3());
$location['country'] = $this->getstring();
fseek($this->fp, $offset + 8);
$location['area'] = $this->getarea();
break;
default: // 否则,表示国家信息没有被重定向
$location['country'] = $this->getstring($byte);
$location['area'] = $this->getarea();
break;
}
$location['country'] = iconv("GBK", "UTF-8", $location['country']);
$location['area'] = iconv("GBK", "UTF-8", $location['area']);
if ($location['country'] == " CZ88.NET" || $location['country'] == "纯真网络") { // CZ88.NET表示没有有效信息
$location['country'] = "无数据";
}
if ($location['area'] == " CZ88.NET") {
$location['area'] = "";
}
return $location;
} | php | private function getlocationfromip($ip)
{
if (!$this->fp) {
return null;
} // 如果数据文件没有被正确打开,则直接返回空
$location['ip'] = $ip;
$ip = $this->packip($location['ip']); // 将输入的IP地址转化为可比较的IP地址
// 不合法的IP地址会被转化为255.255.255.255
// 对分搜索
$l = 0; // 搜索的下边界
$u = $this->totalip; // 搜索的上边界
$findip = $this->lastip; // 如果没有找到就返回最后一条IP记录(qqwry.dat的版本信息)
while ($l <= $u) { // 当上边界小于下边界时,查找失败
$i = floor(($l + $u) / 2); // 计算近似中间记录
fseek($this->fp, $this->firstip + $i * 7);
$beginip = strrev(fread($this->fp, 4)); // 获取中间记录的开始IP地址
// strrev函数在这里的作用是将little-endian的压缩IP地址转化为big-endian的格式
// 以便用于比较,后面相同。
if ($ip < $beginip) { // 用户的IP小于中间记录的开始IP地址时
$u = $i - 1; // 将搜索的上边界修改为中间记录减一
} else {
fseek($this->fp, $this->getlong3());
$endip = strrev(fread($this->fp, 4)); // 获取中间记录的结束IP地址
if ($ip > $endip) { // 用户的IP大于中间记录的结束IP地址时
$l = $i + 1; // 将搜索的下边界修改为中间记录加一
} else { // 用户的IP在中间记录的IP范围内时
$findip = $this->firstip + $i * 7;
break; // 则表示找到结果,退出循环
}
}
}
//获取查找到的IP地理位置信息
fseek($this->fp, $findip);
$location['beginip'] = long2ip($this->getlong()); // 用户IP所在范围的开始地址
$offset = $this->getlong3();
fseek($this->fp, $offset);
$location['endip'] = long2ip($this->getlong()); // 用户IP所在范围的结束地址
$byte = fread($this->fp, 1); // 标志字节
switch (ord($byte)) {
case 1: // 标志字节为1,表示国家和区域信息都被同时重定向
$countryOffset = $this->getlong3(); // 重定向地址
fseek($this->fp, $countryOffset);
$byte = fread($this->fp, 1); // 标志字节
switch (ord($byte)) {
case 2: // 标志字节为2,表示国家信息被重定向
fseek($this->fp, $this->getlong3());
$location['country'] = $this->getstring();
fseek($this->fp, $countryOffset + 4);
$location['area'] = $this->getarea();
break;
default: // 否则,表示国家信息没有被重定向
$location['country'] = $this->getstring($byte);
$location['area'] = $this->getarea();
break;
}
break;
case 2: // 标志字节为2,表示国家信息被重定向
fseek($this->fp, $this->getlong3());
$location['country'] = $this->getstring();
fseek($this->fp, $offset + 8);
$location['area'] = $this->getarea();
break;
default: // 否则,表示国家信息没有被重定向
$location['country'] = $this->getstring($byte);
$location['area'] = $this->getarea();
break;
}
$location['country'] = iconv("GBK", "UTF-8", $location['country']);
$location['area'] = iconv("GBK", "UTF-8", $location['area']);
if ($location['country'] == " CZ88.NET" || $location['country'] == "纯真网络") { // CZ88.NET表示没有有效信息
$location['country'] = "无数据";
}
if ($location['area'] == " CZ88.NET") {
$location['area'] = "";
}
return $location;
} | [
"private",
"function",
"getlocationfromip",
"(",
"$",
"ip",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"fp",
")",
"{",
"return",
"null",
";",
"}",
"// 如果数据文件没有被正确打开,则直接返回空",
"$",
"location",
"[",
"'ip'",
"]",
"=",
"$",
"ip",
";",
"$",
"ip",
"=",
... | 根据所给 IP 地址或域名返回所在地区信息
@access public
@param string $ip
@return array | [
"根据所给",
"IP",
"地址或域名返回所在地区信息"
] | train | https://github.com/itbdw/ip-database/blob/24c203c50080d4ef2f1744930253095c76a58c3d/src/IpLocation.php#L350-L432 |
itbdw/ip-database | src/IpLocation.php | IpLocation.ip2long | private function ip2long($ip)
{
$ip_arr = explode('.', $ip);
$iplong = (16777216 * intval($ip_arr[0])) + (65536 * intval($ip_arr[1])) + (256 * intval($ip_arr[2])) + intval($ip_arr[3]);
return $iplong;
} | php | private function ip2long($ip)
{
$ip_arr = explode('.', $ip);
$iplong = (16777216 * intval($ip_arr[0])) + (65536 * intval($ip_arr[1])) + (256 * intval($ip_arr[2])) + intval($ip_arr[3]);
return $iplong;
} | [
"private",
"function",
"ip2long",
"(",
"$",
"ip",
")",
"{",
"$",
"ip_arr",
"=",
"explode",
"(",
"'.'",
",",
"$",
"ip",
")",
";",
"$",
"iplong",
"=",
"(",
"16777216",
"*",
"intval",
"(",
"$",
"ip_arr",
"[",
"0",
"]",
")",
")",
"+",
"(",
"65536",... | Ip 地址转为数字地址
php 的 ip2long 这个函数有问题
133.205.0.0 ==>> 2244804608
@param string $ip 要转换的 ip 地址
@return int 转换完成的数字 | [
"Ip",
"地址转为数字地址",
"php",
"的",
"ip2long",
"这个函数有问题",
"133",
".",
"205",
".",
"0",
".",
"0",
"==",
">>",
"2244804608"
] | train | https://github.com/itbdw/ip-database/blob/24c203c50080d4ef2f1744930253095c76a58c3d/src/IpLocation.php#L456-L462 |
spatie/dropbox-api | src/Client.php | Client.copy | public function copy(string $fromPath, string $toPath): array
{
$parameters = [
'from_path' => $this->normalizePath($fromPath),
'to_path' => $this->normalizePath($toPath),
];
return $this->rpcEndpointRequest('files/copy_v2', $parameters);
} | php | public function copy(string $fromPath, string $toPath): array
{
$parameters = [
'from_path' => $this->normalizePath($fromPath),
'to_path' => $this->normalizePath($toPath),
];
return $this->rpcEndpointRequest('files/copy_v2', $parameters);
} | [
"public",
"function",
"copy",
"(",
"string",
"$",
"fromPath",
",",
"string",
"$",
"toPath",
")",
":",
"array",
"{",
"$",
"parameters",
"=",
"[",
"'from_path'",
"=>",
"$",
"this",
"->",
"normalizePath",
"(",
"$",
"fromPath",
")",
",",
"'to_path'",
"=>",
... | Copy a file or folder to a different location in the user's Dropbox.
If the source path is a folder all its contents will be copied.
@link https://www.dropbox.com/developers/documentation/http/documentation#files-copy_v2 | [
"Copy",
"a",
"file",
"or",
"folder",
"to",
"a",
"different",
"location",
"in",
"the",
"user",
"s",
"Dropbox",
"."
] | train | https://github.com/spatie/dropbox-api/blob/dc930cde4fdb802d20d0aeef5a98c3805fdcf9c2/src/Client.php#L67-L75 |
spatie/dropbox-api | src/Client.php | Client.createFolder | public function createFolder(string $path): array
{
$parameters = [
'path' => $this->normalizePath($path),
];
$object = $this->rpcEndpointRequest('files/create_folder', $parameters);
$object['.tag'] = 'folder';
return $object;
} | php | public function createFolder(string $path): array
{
$parameters = [
'path' => $this->normalizePath($path),
];
$object = $this->rpcEndpointRequest('files/create_folder', $parameters);
$object['.tag'] = 'folder';
return $object;
} | [
"public",
"function",
"createFolder",
"(",
"string",
"$",
"path",
")",
":",
"array",
"{",
"$",
"parameters",
"=",
"[",
"'path'",
"=>",
"$",
"this",
"->",
"normalizePath",
"(",
"$",
"path",
")",
",",
"]",
";",
"$",
"object",
"=",
"$",
"this",
"->",
... | Create a folder at a given path.
@link https://www.dropbox.com/developers/documentation/http/documentation#files-create_folder | [
"Create",
"a",
"folder",
"at",
"a",
"given",
"path",
"."
] | train | https://github.com/spatie/dropbox-api/blob/dc930cde4fdb802d20d0aeef5a98c3805fdcf9c2/src/Client.php#L82-L93 |
spatie/dropbox-api | src/Client.php | Client.createSharedLinkWithSettings | public function createSharedLinkWithSettings(string $path, array $settings = [])
{
$parameters = [
'path' => $this->normalizePath($path),
];
if (count($settings)) {
$parameters = array_merge(compact('settings'), $parameters);
}
return $this->rpcEndpointRequest('sharing/create_shared_link_with_settings', $parameters);
} | php | public function createSharedLinkWithSettings(string $path, array $settings = [])
{
$parameters = [
'path' => $this->normalizePath($path),
];
if (count($settings)) {
$parameters = array_merge(compact('settings'), $parameters);
}
return $this->rpcEndpointRequest('sharing/create_shared_link_with_settings', $parameters);
} | [
"public",
"function",
"createSharedLinkWithSettings",
"(",
"string",
"$",
"path",
",",
"array",
"$",
"settings",
"=",
"[",
"]",
")",
"{",
"$",
"parameters",
"=",
"[",
"'path'",
"=>",
"$",
"this",
"->",
"normalizePath",
"(",
"$",
"path",
")",
",",
"]",
... | Create a shared link with custom settings.
If no settings are given then the default visibility is RequestedVisibility.public.
The resolved visibility, though, may depend on other aspects such as team and
shared folder settings). Only for paid users.
@link https://www.dropbox.com/developers/documentation/http/documentation#sharing-create_shared_link_with_settings | [
"Create",
"a",
"shared",
"link",
"with",
"custom",
"settings",
"."
] | train | https://github.com/spatie/dropbox-api/blob/dc930cde4fdb802d20d0aeef5a98c3805fdcf9c2/src/Client.php#L104-L115 |
spatie/dropbox-api | src/Client.php | Client.listSharedLinks | public function listSharedLinks(string $path = null, bool $direct_only = false, string $cursor = null): array
{
$parameters = [
'path' => $path ? $this->normalizePath($path) : null,
'cursor' => $cursor,
'direct_only' => $direct_only,
];
$body = $this->rpcEndpointRequest('sharing/list_shared_links', $parameters);
return $body['links'];
} | php | public function listSharedLinks(string $path = null, bool $direct_only = false, string $cursor = null): array
{
$parameters = [
'path' => $path ? $this->normalizePath($path) : null,
'cursor' => $cursor,
'direct_only' => $direct_only,
];
$body = $this->rpcEndpointRequest('sharing/list_shared_links', $parameters);
return $body['links'];
} | [
"public",
"function",
"listSharedLinks",
"(",
"string",
"$",
"path",
"=",
"null",
",",
"bool",
"$",
"direct_only",
"=",
"false",
",",
"string",
"$",
"cursor",
"=",
"null",
")",
":",
"array",
"{",
"$",
"parameters",
"=",
"[",
"'path'",
"=>",
"$",
"path"... | List shared links.
For empty path returns a list of all shared links. For non-empty path
returns a list of all shared links with access to the given path.
If direct_only is set true, only direct links to the path will be returned, otherwise
it may return link to the path itself and parent folders as described on docs.
@link https://www.dropbox.com/developers/documentation/http/documentation#sharing-list_shared_links | [
"List",
"shared",
"links",
"."
] | train | https://github.com/spatie/dropbox-api/blob/dc930cde4fdb802d20d0aeef5a98c3805fdcf9c2/src/Client.php#L128-L139 |
spatie/dropbox-api | src/Client.php | Client.delete | public function delete(string $path): array
{
$parameters = [
'path' => $this->normalizePath($path),
];
return $this->rpcEndpointRequest('files/delete', $parameters);
} | php | public function delete(string $path): array
{
$parameters = [
'path' => $this->normalizePath($path),
];
return $this->rpcEndpointRequest('files/delete', $parameters);
} | [
"public",
"function",
"delete",
"(",
"string",
"$",
"path",
")",
":",
"array",
"{",
"$",
"parameters",
"=",
"[",
"'path'",
"=>",
"$",
"this",
"->",
"normalizePath",
"(",
"$",
"path",
")",
",",
"]",
";",
"return",
"$",
"this",
"->",
"rpcEndpointRequest"... | Delete the file or folder at a given path.
If the path is a folder, all its contents will be deleted too.
A successful response indicates that the file or folder was deleted.
@link https://www.dropbox.com/developers/documentation/http/documentation#files-delete | [
"Delete",
"the",
"file",
"or",
"folder",
"at",
"a",
"given",
"path",
"."
] | train | https://github.com/spatie/dropbox-api/blob/dc930cde4fdb802d20d0aeef5a98c3805fdcf9c2/src/Client.php#L149-L156 |
spatie/dropbox-api | src/Client.php | Client.download | public function download(string $path)
{
$arguments = [
'path' => $this->normalizePath($path),
];
$response = $this->contentEndpointRequest('files/download', $arguments);
return StreamWrapper::getResource($response->getBody());
} | php | public function download(string $path)
{
$arguments = [
'path' => $this->normalizePath($path),
];
$response = $this->contentEndpointRequest('files/download', $arguments);
return StreamWrapper::getResource($response->getBody());
} | [
"public",
"function",
"download",
"(",
"string",
"$",
"path",
")",
"{",
"$",
"arguments",
"=",
"[",
"'path'",
"=>",
"$",
"this",
"->",
"normalizePath",
"(",
"$",
"path",
")",
",",
"]",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"contentEndpointReque... | Download a file from a user's Dropbox.
@param string $path
@return resource
@link https://www.dropbox.com/developers/documentation/http/documentation#files-download | [
"Download",
"a",
"file",
"from",
"a",
"user",
"s",
"Dropbox",
"."
] | train | https://github.com/spatie/dropbox-api/blob/dc930cde4fdb802d20d0aeef5a98c3805fdcf9c2/src/Client.php#L167-L176 |
spatie/dropbox-api | src/Client.php | Client.getMetadata | public function getMetadata(string $path): array
{
$parameters = [
'path' => $this->normalizePath($path),
];
return $this->rpcEndpointRequest('files/get_metadata', $parameters);
} | php | public function getMetadata(string $path): array
{
$parameters = [
'path' => $this->normalizePath($path),
];
return $this->rpcEndpointRequest('files/get_metadata', $parameters);
} | [
"public",
"function",
"getMetadata",
"(",
"string",
"$",
"path",
")",
":",
"array",
"{",
"$",
"parameters",
"=",
"[",
"'path'",
"=>",
"$",
"this",
"->",
"normalizePath",
"(",
"$",
"path",
")",
",",
"]",
";",
"return",
"$",
"this",
"->",
"rpcEndpointReq... | Returns the metadata for a file or folder.
Note: Metadata for the root folder is unsupported.
@link https://www.dropbox.com/developers/documentation/http/documentation#files-get_metadata | [
"Returns",
"the",
"metadata",
"for",
"a",
"file",
"or",
"folder",
"."
] | train | https://github.com/spatie/dropbox-api/blob/dc930cde4fdb802d20d0aeef5a98c3805fdcf9c2/src/Client.php#L185-L192 |
spatie/dropbox-api | src/Client.php | Client.getTemporaryLink | public function getTemporaryLink(string $path): string
{
$parameters = [
'path' => $this->normalizePath($path),
];
$body = $this->rpcEndpointRequest('files/get_temporary_link', $parameters);
return $body['link'];
} | php | public function getTemporaryLink(string $path): string
{
$parameters = [
'path' => $this->normalizePath($path),
];
$body = $this->rpcEndpointRequest('files/get_temporary_link', $parameters);
return $body['link'];
} | [
"public",
"function",
"getTemporaryLink",
"(",
"string",
"$",
"path",
")",
":",
"string",
"{",
"$",
"parameters",
"=",
"[",
"'path'",
"=>",
"$",
"this",
"->",
"normalizePath",
"(",
"$",
"path",
")",
",",
"]",
";",
"$",
"body",
"=",
"$",
"this",
"->",... | Get a temporary link to stream content of a file.
This link will expire in four hours and afterwards you will get 410 Gone.
Content-Type of the link is determined automatically by the file's mime type.
@link https://www.dropbox.com/developers/documentation/http/documentation#files-get_temporary_link | [
"Get",
"a",
"temporary",
"link",
"to",
"stream",
"content",
"of",
"a",
"file",
"."
] | train | https://github.com/spatie/dropbox-api/blob/dc930cde4fdb802d20d0aeef5a98c3805fdcf9c2/src/Client.php#L202-L211 |
spatie/dropbox-api | src/Client.php | Client.getThumbnail | public function getThumbnail(string $path, string $format = 'jpeg', string $size = 'w64h64'): string
{
$arguments = [
'path' => $this->normalizePath($path),
'format' => $format,
'size' => $size,
];
$response = $this->contentEndpointRequest('files/get_thumbnail', $arguments);
return (string) $response->getBody();
} | php | public function getThumbnail(string $path, string $format = 'jpeg', string $size = 'w64h64'): string
{
$arguments = [
'path' => $this->normalizePath($path),
'format' => $format,
'size' => $size,
];
$response = $this->contentEndpointRequest('files/get_thumbnail', $arguments);
return (string) $response->getBody();
} | [
"public",
"function",
"getThumbnail",
"(",
"string",
"$",
"path",
",",
"string",
"$",
"format",
"=",
"'jpeg'",
",",
"string",
"$",
"size",
"=",
"'w64h64'",
")",
":",
"string",
"{",
"$",
"arguments",
"=",
"[",
"'path'",
"=>",
"$",
"this",
"->",
"normali... | Get a thumbnail for an image.
This method currently supports files with the following file extensions:
jpg, jpeg, png, tiff, tif, gif and bmp.
Photos that are larger than 20MB in size won't be converted to a thumbnail.
@link https://www.dropbox.com/developers/documentation/http/documentation#files-get_thumbnail | [
"Get",
"a",
"thumbnail",
"for",
"an",
"image",
"."
] | train | https://github.com/spatie/dropbox-api/blob/dc930cde4fdb802d20d0aeef5a98c3805fdcf9c2/src/Client.php#L223-L234 |
spatie/dropbox-api | src/Client.php | Client.listFolder | public function listFolder(string $path = '', bool $recursive = false): array
{
$parameters = [
'path' => $this->normalizePath($path),
'recursive' => $recursive,
];
return $this->rpcEndpointRequest('files/list_folder', $parameters);
} | php | public function listFolder(string $path = '', bool $recursive = false): array
{
$parameters = [
'path' => $this->normalizePath($path),
'recursive' => $recursive,
];
return $this->rpcEndpointRequest('files/list_folder', $parameters);
} | [
"public",
"function",
"listFolder",
"(",
"string",
"$",
"path",
"=",
"''",
",",
"bool",
"$",
"recursive",
"=",
"false",
")",
":",
"array",
"{",
"$",
"parameters",
"=",
"[",
"'path'",
"=>",
"$",
"this",
"->",
"normalizePath",
"(",
"$",
"path",
")",
",... | Starts returning the contents of a folder.
If the result's ListFolderResult.has_more field is true, call
list_folder/continue with the returned ListFolderResult.cursor to retrieve more entries.
Note: auth.RateLimitError may be returned if multiple list_folder or list_folder/continue calls
with same parameters are made simultaneously by same API app for same user. If your app implements
retry logic, please hold off the retry until the previous request finishes.
@link https://www.dropbox.com/developers/documentation/http/documentation#files-list_folder | [
"Starts",
"returning",
"the",
"contents",
"of",
"a",
"folder",
"."
] | train | https://github.com/spatie/dropbox-api/blob/dc930cde4fdb802d20d0aeef5a98c3805fdcf9c2/src/Client.php#L248-L256 |
spatie/dropbox-api | src/Client.php | Client.move | public function move(string $fromPath, string $toPath): array
{
$parameters = [
'from_path' => $this->normalizePath($fromPath),
'to_path' => $this->normalizePath($toPath),
];
return $this->rpcEndpointRequest('files/move_v2', $parameters);
} | php | public function move(string $fromPath, string $toPath): array
{
$parameters = [
'from_path' => $this->normalizePath($fromPath),
'to_path' => $this->normalizePath($toPath),
];
return $this->rpcEndpointRequest('files/move_v2', $parameters);
} | [
"public",
"function",
"move",
"(",
"string",
"$",
"fromPath",
",",
"string",
"$",
"toPath",
")",
":",
"array",
"{",
"$",
"parameters",
"=",
"[",
"'from_path'",
"=>",
"$",
"this",
"->",
"normalizePath",
"(",
"$",
"fromPath",
")",
",",
"'to_path'",
"=>",
... | Move a file or folder to a different location in the user's Dropbox.
If the source path is a folder all its contents will be moved.
@link https://www.dropbox.com/developers/documentation/http/documentation#files-move_v2 | [
"Move",
"a",
"file",
"or",
"folder",
"to",
"a",
"different",
"location",
"in",
"the",
"user",
"s",
"Dropbox",
"."
] | train | https://github.com/spatie/dropbox-api/blob/dc930cde4fdb802d20d0aeef5a98c3805fdcf9c2/src/Client.php#L276-L284 |
spatie/dropbox-api | src/Client.php | Client.shouldUploadChunked | protected function shouldUploadChunked($contents): bool
{
$size = is_string($contents) ? strlen($contents) : fstat($contents)['size'];
if ($this->isPipe($contents)) {
return true;
}
if ($size === null) {
return true;
}
return $size > $this->maxChunkSize;
} | php | protected function shouldUploadChunked($contents): bool
{
$size = is_string($contents) ? strlen($contents) : fstat($contents)['size'];
if ($this->isPipe($contents)) {
return true;
}
if ($size === null) {
return true;
}
return $size > $this->maxChunkSize;
} | [
"protected",
"function",
"shouldUploadChunked",
"(",
"$",
"contents",
")",
":",
"bool",
"{",
"$",
"size",
"=",
"is_string",
"(",
"$",
"contents",
")",
"?",
"strlen",
"(",
"$",
"contents",
")",
":",
"fstat",
"(",
"$",
"contents",
")",
"[",
"'size'",
"]"... | The file should be uploaded in chunks if it size exceeds the 150 MB threshold
or if the resource size could not be determined (eg. a popen() stream).
@param string|resource $contents
@return bool | [
"The",
"file",
"should",
"be",
"uploaded",
"in",
"chunks",
"if",
"it",
"size",
"exceeds",
"the",
"150",
"MB",
"threshold",
"or",
"if",
"the",
"resource",
"size",
"could",
"not",
"be",
"determined",
"(",
"eg",
".",
"a",
"popen",
"()",
"stream",
")",
"."... | train | https://github.com/spatie/dropbox-api/blob/dc930cde4fdb802d20d0aeef5a98c3805fdcf9c2/src/Client.php#L294-L307 |
spatie/dropbox-api | src/Client.php | Client.upload | public function upload(string $path, $contents, $mode = 'add'): array
{
if ($this->shouldUploadChunked($contents)) {
return $this->uploadChunked($path, $contents, $mode);
}
$arguments = [
'path' => $this->normalizePath($path),
'mode' => $mode,
];
$response = $this->contentEndpointRequest('files/upload', $arguments, $contents);
$metadata = json_decode($response->getBody(), true);
$metadata['.tag'] = 'file';
return $metadata;
} | php | public function upload(string $path, $contents, $mode = 'add'): array
{
if ($this->shouldUploadChunked($contents)) {
return $this->uploadChunked($path, $contents, $mode);
}
$arguments = [
'path' => $this->normalizePath($path),
'mode' => $mode,
];
$response = $this->contentEndpointRequest('files/upload', $arguments, $contents);
$metadata = json_decode($response->getBody(), true);
$metadata['.tag'] = 'file';
return $metadata;
} | [
"public",
"function",
"upload",
"(",
"string",
"$",
"path",
",",
"$",
"contents",
",",
"$",
"mode",
"=",
"'add'",
")",
":",
"array",
"{",
"if",
"(",
"$",
"this",
"->",
"shouldUploadChunked",
"(",
"$",
"contents",
")",
")",
"{",
"return",
"$",
"this",... | Create a new file with the contents provided in the request.
Do not use this to upload a file larger than 150 MB. Instead, create an upload session with upload_session/start.
@link https://www.dropbox.com/developers/documentation/http/documentation#files-upload
@param string $path
@param string|resource $contents
@param string $mode
@return array | [
"Create",
"a",
"new",
"file",
"with",
"the",
"contents",
"provided",
"in",
"the",
"request",
"."
] | train | https://github.com/spatie/dropbox-api/blob/dc930cde4fdb802d20d0aeef5a98c3805fdcf9c2/src/Client.php#L334-L352 |
spatie/dropbox-api | src/Client.php | Client.uploadChunked | public function uploadChunked(string $path, $contents, $mode = 'add', $chunkSize = null): array
{
if ($chunkSize === null || $chunkSize > $this->maxChunkSize) {
$chunkSize = $this->maxChunkSize;
}
$stream = $this->getStream($contents);
$cursor = $this->uploadChunk(self::UPLOAD_SESSION_START, $stream, $chunkSize, null);
while (! $stream->eof()) {
$cursor = $this->uploadChunk(self::UPLOAD_SESSION_APPEND, $stream, $chunkSize, $cursor);
}
return $this->uploadSessionFinish('', $cursor, $path, $mode);
} | php | public function uploadChunked(string $path, $contents, $mode = 'add', $chunkSize = null): array
{
if ($chunkSize === null || $chunkSize > $this->maxChunkSize) {
$chunkSize = $this->maxChunkSize;
}
$stream = $this->getStream($contents);
$cursor = $this->uploadChunk(self::UPLOAD_SESSION_START, $stream, $chunkSize, null);
while (! $stream->eof()) {
$cursor = $this->uploadChunk(self::UPLOAD_SESSION_APPEND, $stream, $chunkSize, $cursor);
}
return $this->uploadSessionFinish('', $cursor, $path, $mode);
} | [
"public",
"function",
"uploadChunked",
"(",
"string",
"$",
"path",
",",
"$",
"contents",
",",
"$",
"mode",
"=",
"'add'",
",",
"$",
"chunkSize",
"=",
"null",
")",
":",
"array",
"{",
"if",
"(",
"$",
"chunkSize",
"===",
"null",
"||",
"$",
"chunkSize",
"... | Upload file split in chunks. This allows uploading large files, since
Dropbox API v2 limits the content size to 150MB.
The chunk size will affect directly the memory usage, so be careful.
Large chunks tends to speed up the upload, while smaller optimizes memory usage.
@param string $path
@param string|resource $contents
@param string $mode
@param int $chunkSize
@return array | [
"Upload",
"file",
"split",
"in",
"chunks",
".",
"This",
"allows",
"uploading",
"large",
"files",
"since",
"Dropbox",
"API",
"v2",
"limits",
"the",
"content",
"size",
"to",
"150MB",
"."
] | train | https://github.com/spatie/dropbox-api/blob/dc930cde4fdb802d20d0aeef5a98c3805fdcf9c2/src/Client.php#L368-L383 |
spatie/dropbox-api | src/Client.php | Client.uploadSessionStart | public function uploadSessionStart($contents, bool $close = false): UploadSessionCursor
{
$arguments = compact('close');
$response = json_decode(
$this->contentEndpointRequest('files/upload_session/start', $arguments, $contents)->getBody(),
true
);
return new UploadSessionCursor($response['session_id'], ($contents instanceof StreamInterface ? $contents->tell() : strlen($contents)));
} | php | public function uploadSessionStart($contents, bool $close = false): UploadSessionCursor
{
$arguments = compact('close');
$response = json_decode(
$this->contentEndpointRequest('files/upload_session/start', $arguments, $contents)->getBody(),
true
);
return new UploadSessionCursor($response['session_id'], ($contents instanceof StreamInterface ? $contents->tell() : strlen($contents)));
} | [
"public",
"function",
"uploadSessionStart",
"(",
"$",
"contents",
",",
"bool",
"$",
"close",
"=",
"false",
")",
":",
"UploadSessionCursor",
"{",
"$",
"arguments",
"=",
"compact",
"(",
"'close'",
")",
";",
"$",
"response",
"=",
"json_decode",
"(",
"$",
"thi... | Upload sessions allow you to upload a single file in one or more requests,
for example where the size of the file is greater than 150 MB.
This call starts a new upload session with the given data.
@link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-start
@param string|StreamInterface $contents
@param bool $close
@return UploadSessionCursor | [
"Upload",
"sessions",
"allow",
"you",
"to",
"upload",
"a",
"single",
"file",
"in",
"one",
"or",
"more",
"requests",
"for",
"example",
"where",
"the",
"size",
"of",
"the",
"file",
"is",
"greater",
"than",
"150",
"MB",
".",
"This",
"call",
"starts",
"a",
... | train | https://github.com/spatie/dropbox-api/blob/dc930cde4fdb802d20d0aeef5a98c3805fdcf9c2/src/Client.php#L437-L447 |
spatie/dropbox-api | src/Client.php | Client.uploadSessionAppend | public function uploadSessionAppend($contents, UploadSessionCursor $cursor, bool $close = false): UploadSessionCursor
{
$arguments = compact('cursor', 'close');
$pos = $contents instanceof StreamInterface ? $contents->tell() : 0;
$this->contentEndpointRequest('files/upload_session/append_v2', $arguments, $contents);
$cursor->offset += $contents instanceof StreamInterface ? ($contents->tell() - $pos) : strlen($contents);
return $cursor;
} | php | public function uploadSessionAppend($contents, UploadSessionCursor $cursor, bool $close = false): UploadSessionCursor
{
$arguments = compact('cursor', 'close');
$pos = $contents instanceof StreamInterface ? $contents->tell() : 0;
$this->contentEndpointRequest('files/upload_session/append_v2', $arguments, $contents);
$cursor->offset += $contents instanceof StreamInterface ? ($contents->tell() - $pos) : strlen($contents);
return $cursor;
} | [
"public",
"function",
"uploadSessionAppend",
"(",
"$",
"contents",
",",
"UploadSessionCursor",
"$",
"cursor",
",",
"bool",
"$",
"close",
"=",
"false",
")",
":",
"UploadSessionCursor",
"{",
"$",
"arguments",
"=",
"compact",
"(",
"'cursor'",
",",
"'close'",
")",... | Append more data to an upload session.
When the parameter close is set, this call will close the session.
A single request should not upload more than 150 MB.
@link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-append_v2
@param string|StreamInterface $contents
@param UploadSessionCursor $cursor
@param bool $close
@return \Spatie\Dropbox\UploadSessionCursor | [
"Append",
"more",
"data",
"to",
"an",
"upload",
"session",
".",
"When",
"the",
"parameter",
"close",
"is",
"set",
"this",
"call",
"will",
"close",
"the",
"session",
".",
"A",
"single",
"request",
"should",
"not",
"upload",
"more",
"than",
"150",
"MB",
".... | train | https://github.com/spatie/dropbox-api/blob/dc930cde4fdb802d20d0aeef5a98c3805fdcf9c2/src/Client.php#L462-L472 |
spatie/dropbox-api | src/Client.php | Client.uploadSessionFinish | public function uploadSessionFinish($contents, UploadSessionCursor $cursor, string $path, $mode = 'add', $autorename = false, $mute = false): array
{
$arguments = compact('cursor');
$arguments['commit'] = compact('path', 'mode', 'autorename', 'mute');
$response = $this->contentEndpointRequest(
'files/upload_session/finish',
$arguments,
($contents == '') ? null : $contents
);
$metadata = json_decode($response->getBody(), true);
$metadata['.tag'] = 'file';
return $metadata;
} | php | public function uploadSessionFinish($contents, UploadSessionCursor $cursor, string $path, $mode = 'add', $autorename = false, $mute = false): array
{
$arguments = compact('cursor');
$arguments['commit'] = compact('path', 'mode', 'autorename', 'mute');
$response = $this->contentEndpointRequest(
'files/upload_session/finish',
$arguments,
($contents == '') ? null : $contents
);
$metadata = json_decode($response->getBody(), true);
$metadata['.tag'] = 'file';
return $metadata;
} | [
"public",
"function",
"uploadSessionFinish",
"(",
"$",
"contents",
",",
"UploadSessionCursor",
"$",
"cursor",
",",
"string",
"$",
"path",
",",
"$",
"mode",
"=",
"'add'",
",",
"$",
"autorename",
"=",
"false",
",",
"$",
"mute",
"=",
"false",
")",
":",
"arr... | Finish an upload session and save the uploaded data to the given file path.
A single request should not upload more than 150 MB.
@link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-finish
@param string|StreamInterface $contents
@param \Spatie\Dropbox\UploadSessionCursor $cursor
@param string $path
@param string|array $mode
@param bool $autorename
@param bool $mute
@return array | [
"Finish",
"an",
"upload",
"session",
"and",
"save",
"the",
"uploaded",
"data",
"to",
"the",
"given",
"file",
"path",
".",
"A",
"single",
"request",
"should",
"not",
"upload",
"more",
"than",
"150",
"MB",
"."
] | train | https://github.com/spatie/dropbox-api/blob/dc930cde4fdb802d20d0aeef5a98c3805fdcf9c2/src/Client.php#L489-L505 |
spatie/dropbox-api | src/Client.php | Client.contentEndpointRequest | public function contentEndpointRequest(string $endpoint, array $arguments, $body = ''): ResponseInterface
{
$headers = ['Dropbox-API-Arg' => json_encode($arguments)];
if ($body !== '') {
$headers['Content-Type'] = 'application/octet-stream';
}
try {
$response = $this->client->post($this->getEndpointUrl('content', $endpoint), [
'headers' => $this->getHeaders($headers),
'body' => $body,
]);
} catch (ClientException $exception) {
throw $this->determineException($exception);
}
return $response;
} | php | public function contentEndpointRequest(string $endpoint, array $arguments, $body = ''): ResponseInterface
{
$headers = ['Dropbox-API-Arg' => json_encode($arguments)];
if ($body !== '') {
$headers['Content-Type'] = 'application/octet-stream';
}
try {
$response = $this->client->post($this->getEndpointUrl('content', $endpoint), [
'headers' => $this->getHeaders($headers),
'body' => $body,
]);
} catch (ClientException $exception) {
throw $this->determineException($exception);
}
return $response;
} | [
"public",
"function",
"contentEndpointRequest",
"(",
"string",
"$",
"endpoint",
",",
"array",
"$",
"arguments",
",",
"$",
"body",
"=",
"''",
")",
":",
"ResponseInterface",
"{",
"$",
"headers",
"=",
"[",
"'Dropbox-API-Arg'",
"=>",
"json_encode",
"(",
"$",
"ar... | @param string $endpoint
@param array $arguments
@param string|resource|StreamInterface $body
@return \Psr\Http\Message\ResponseInterface
@throws \Exception | [
"@param",
"string",
"$endpoint",
"@param",
"array",
"$arguments",
"@param",
"string|resource|StreamInterface",
"$body"
] | train | https://github.com/spatie/dropbox-api/blob/dc930cde4fdb802d20d0aeef5a98c3805fdcf9c2/src/Client.php#L558-L576 |
spatie/dropbox-api | src/Client.php | Client.getStream | protected function getStream($contents)
{
if ($this->isPipe($contents)) {
/* @var resource $contents */
return new PumpStream(function ($length) use ($contents) {
$data = fread($contents, $length);
if (strlen($data) === 0) {
return false;
}
return $data;
});
}
return Psr7\stream_for($contents);
} | php | protected function getStream($contents)
{
if ($this->isPipe($contents)) {
/* @var resource $contents */
return new PumpStream(function ($length) use ($contents) {
$data = fread($contents, $length);
if (strlen($data) === 0) {
return false;
}
return $data;
});
}
return Psr7\stream_for($contents);
} | [
"protected",
"function",
"getStream",
"(",
"$",
"contents",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isPipe",
"(",
"$",
"contents",
")",
")",
"{",
"/* @var resource $contents */",
"return",
"new",
"PumpStream",
"(",
"function",
"(",
"$",
"length",
")",
"us... | @param $contents
@return \GuzzleHttp\Psr7\PumpStream|\GuzzleHttp\Psr7\Stream | [
"@param",
"$contents"
] | train | https://github.com/spatie/dropbox-api/blob/dc930cde4fdb802d20d0aeef5a98c3805fdcf9c2/src/Client.php#L611-L626 |
wp-cli/media-command | src/Media_Command.php | Media_Command.regenerate | public function regenerate( $args, $assoc_args = array() ) {
$assoc_args = wp_parse_args(
$assoc_args,
[ 'image_size' => '' ]
);
$image_size = $assoc_args['image_size'];
if ( $image_size && ! in_array( $image_size, get_intermediate_image_sizes(), true ) ) {
WP_CLI::error( sprintf( 'Unknown image size "%s".', $image_size ) );
}
if ( empty( $args ) ) {
if ( $image_size ) {
WP_CLI::confirm( sprintf( 'Do you really want to regenerate the "%s" image size for all images?', $image_size ), $assoc_args );
} else {
WP_CLI::confirm( 'Do you really want to regenerate all images?', $assoc_args );
}
}
$skip_delete = Utils\get_flag_value( $assoc_args, 'skip-delete' );
$only_missing = Utils\get_flag_value( $assoc_args, 'only-missing' );
if ( $only_missing ) {
$skip_delete = true;
}
$additional_mime_types = array();
if ( Utils\wp_version_compare( '4.7', '>=' ) ) {
$additional_mime_types[] = 'application/pdf';
}
$images = $this->get_images( $args, $additional_mime_types );
$count = $images->post_count;
if ( ! $count ) {
WP_CLI::warning( 'No images found.' );
return;
}
WP_CLI::log(
sprintf(
'Found %1$d %2$s to regenerate.',
$count,
_n( 'image', 'images', $count )
)
);
if ( $image_size ) {
$image_size_filters = $this->add_image_size_filters( $image_size );
}
$number = 0;
$successes = 0;
$errors = 0;
$skips = 0;
foreach ( $images->posts as $post ) {
$number++;
if ( 0 === $number % self::WP_CLEAR_OBJECT_CACHE_INTERVAL ) {
Utils\wp_clear_object_cache();
}
$this->process_regeneration( $post->ID, $skip_delete, $only_missing, $image_size, $number . '/' . $count, $successes, $errors, $skips );
}
if ( $image_size ) {
$this->remove_image_size_filters( $image_size_filters );
}
Utils\report_batch_operation_results( 'image', 'regenerate', $count, $successes, $errors, $skips );
} | php | public function regenerate( $args, $assoc_args = array() ) {
$assoc_args = wp_parse_args(
$assoc_args,
[ 'image_size' => '' ]
);
$image_size = $assoc_args['image_size'];
if ( $image_size && ! in_array( $image_size, get_intermediate_image_sizes(), true ) ) {
WP_CLI::error( sprintf( 'Unknown image size "%s".', $image_size ) );
}
if ( empty( $args ) ) {
if ( $image_size ) {
WP_CLI::confirm( sprintf( 'Do you really want to regenerate the "%s" image size for all images?', $image_size ), $assoc_args );
} else {
WP_CLI::confirm( 'Do you really want to regenerate all images?', $assoc_args );
}
}
$skip_delete = Utils\get_flag_value( $assoc_args, 'skip-delete' );
$only_missing = Utils\get_flag_value( $assoc_args, 'only-missing' );
if ( $only_missing ) {
$skip_delete = true;
}
$additional_mime_types = array();
if ( Utils\wp_version_compare( '4.7', '>=' ) ) {
$additional_mime_types[] = 'application/pdf';
}
$images = $this->get_images( $args, $additional_mime_types );
$count = $images->post_count;
if ( ! $count ) {
WP_CLI::warning( 'No images found.' );
return;
}
WP_CLI::log(
sprintf(
'Found %1$d %2$s to regenerate.',
$count,
_n( 'image', 'images', $count )
)
);
if ( $image_size ) {
$image_size_filters = $this->add_image_size_filters( $image_size );
}
$number = 0;
$successes = 0;
$errors = 0;
$skips = 0;
foreach ( $images->posts as $post ) {
$number++;
if ( 0 === $number % self::WP_CLEAR_OBJECT_CACHE_INTERVAL ) {
Utils\wp_clear_object_cache();
}
$this->process_regeneration( $post->ID, $skip_delete, $only_missing, $image_size, $number . '/' . $count, $successes, $errors, $skips );
}
if ( $image_size ) {
$this->remove_image_size_filters( $image_size_filters );
}
Utils\report_batch_operation_results( 'image', 'regenerate', $count, $successes, $errors, $skips );
} | [
"public",
"function",
"regenerate",
"(",
"$",
"args",
",",
"$",
"assoc_args",
"=",
"array",
"(",
")",
")",
"{",
"$",
"assoc_args",
"=",
"wp_parse_args",
"(",
"$",
"assoc_args",
",",
"[",
"'image_size'",
"=>",
"''",
"]",
")",
";",
"$",
"image_size",
"="... | Regenerates thumbnails for one or more attachments.
## OPTIONS
[<attachment-id>...]
: One or more IDs of the attachments to regenerate.
[--image_size=<image_size>]
: Name of the image size to regenerate. Only thumbnails of this image size will be regenerated, thumbnails of other image sizes will not.
[--skip-delete]
: Skip deletion of the original thumbnails. If your thumbnails are linked from sources outside your control, it's likely best to leave them around. Defaults to false.
[--only-missing]
: Only generate thumbnails for images missing image sizes.
[--yes]
: Answer yes to the confirmation message. Confirmation only shows when no IDs passed as arguments.
## EXAMPLES
# Regenerate thumbnails for given attachment IDs.
$ wp media regenerate 123 124 125
Found 3 images to regenerate.
1/3 Regenerated thumbnails for "Vertical Image" (ID 123).
2/3 Regenerated thumbnails for "Horizontal Image" (ID 124).
3/3 Regenerated thumbnails for "Beautiful Picture" (ID 125).
Success: Regenerated 3 of 3 images.
# Regenerate all thumbnails, without confirmation.
$ wp media regenerate --yes
Found 3 images to regenerate.
1/3 Regenerated thumbnails for "Sydney Harbor Bridge" (ID 760).
2/3 Regenerated thumbnails for "Boardwalk" (ID 757).
3/3 Regenerated thumbnails for "Sunburst Over River" (ID 756).
Success: Regenerated 3 of 3 images.
# Re-generate all thumbnails that have IDs between 1000 and 2000.
$ seq 1000 2000 | xargs wp media regenerate
Found 4 images to regenerate.
1/4 Regenerated thumbnails for "Vertical Featured Image" (ID 1027).
2/4 Regenerated thumbnails for "Horizontal Featured Image" (ID 1022).
3/4 Regenerated thumbnails for "Unicorn Wallpaper" (ID 1045).
4/4 Regenerated thumbnails for "I Am Worth Loving Wallpaper" (ID 1023).
Success: Regenerated 4 of 4 images.
# Re-generate only the thumbnails of "large" image size for all images.
$ wp media regenerate --image_size=large
Do you really want to regenerate the "large" image size for all images? [y/n] y
Found 3 images to regenerate.
1/3 Regenerated "large" thumbnail for "Sydney Harbor Bridge" (ID 760).
2/3 No "large" thumbnail regeneration needed for "Boardwalk" (ID 757).
3/3 Regenerated "large" thumbnail for "Sunburst Over River" (ID 756).
Success: Regenerated 3 of 3 images. | [
"Regenerates",
"thumbnails",
"for",
"one",
"or",
"more",
"attachments",
"."
] | train | https://github.com/wp-cli/media-command/blob/68e2402dcef11ae10e8902cf93a1d370db07ed78/src/Media_Command.php#L102-L170 |
wp-cli/media-command | src/Media_Command.php | Media_Command.import | public function import( $args, $assoc_args = array() ) {
$assoc_args = wp_parse_args(
$assoc_args,
array(
'title' => '',
'caption' => '',
'alt' => '',
'desc' => '',
)
);
// Assume the most generic term
$noun = 'item';
// Current site's timezone offset.
$gmt_offset = get_option( 'gmt_offset' );
// Use the noun `image` when sure the media file is an image
if ( Utils\get_flag_value( $assoc_args, 'featured_image' ) || $assoc_args['alt'] ) {
$noun = 'image';
}
if ( isset( $assoc_args['post_id'] ) ) {
if ( ! get_post( $assoc_args['post_id'] ) ) {
WP_CLI::warning( 'Invalid --post_id' );
$assoc_args['post_id'] = false;
}
} else {
$assoc_args['post_id'] = false;
}
$number = 0;
$successes = 0;
$errors = 0;
foreach ( $args as $file ) {
$number++;
if ( 0 === $number % self::WP_CLEAR_OBJECT_CACHE_INTERVAL ) {
Utils\wp_clear_object_cache();
}
// phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url -- parse_url will only be used in absence of wp_parse_url.
$is_file_remote = function_exists( 'wp_parse_url' ) ? wp_parse_url( $file, PHP_URL_HOST ) : parse_url( $file, PHP_URL_HOST );
$orig_filename = $file;
$file_time = '';
if ( empty( $is_file_remote ) ) {
if ( ! file_exists( $file ) ) {
WP_CLI::warning( "Unable to import file '$file'. Reason: File doesn't exist." );
$errors++;
continue;
}
if ( Utils\get_flag_value( $assoc_args, 'skip-copy' ) ) {
$tempfile = $file;
} else {
$tempfile = $this->make_copy( $file );
}
$name = Utils\basename( $file );
if ( Utils\get_flag_value( $assoc_args, 'preserve-filetime' ) ) {
$file_time = @filemtime( $file );
}
} else {
$tempfile = download_url( $file );
if ( is_wp_error( $tempfile ) ) {
WP_CLI::warning(
sprintf(
"Unable to import file '%s'. Reason: %s",
$file,
implode( ', ', $tempfile->get_error_messages() )
)
);
$errors++;
continue;
}
$name = strtok( Utils\basename( $file ), '?' );
}
$file_array = array(
'tmp_name' => $tempfile,
'name' => $name,
);
$post_array = array(
'post_title' => $assoc_args['title'],
'post_excerpt' => $assoc_args['caption'],
'post_content' => $assoc_args['desc'],
);
if ( ! empty( $file_time ) ) {
$post_array['post_date'] = gmdate( 'Y-m-d H:i:s', $file_time + ( $gmt_offset * HOUR_IN_SECONDS ) );
$post_array['post_date_gmt'] = gmdate( 'Y-m-d H:i:s', $file_time );
$post_array['post_modified'] = gmdate( 'Y-m-d H:i:s', $file_time + ( $gmt_offset * HOUR_IN_SECONDS ) );
$post_array['post_modified_gmt'] = gmdate( 'Y-m-d H:i:s', $file_time );
}
$post_array = wp_slash( $post_array );
// use image exif/iptc data for title and caption defaults if possible
if ( empty( $post_array['post_title'] ) || empty( $post_array['post_excerpt'] ) ) {
// @codingStandardsIgnoreStart
$image_meta = @wp_read_image_metadata( $tempfile );
// @codingStandardsIgnoreEnd
if ( ! empty( $image_meta ) ) {
if ( empty( $post_array['post_title'] ) && trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
$post_array['post_title'] = $image_meta['title'];
}
if ( empty( $post_array['post_excerpt'] ) && trim( $image_meta['caption'] ) ) {
$post_array['post_excerpt'] = $image_meta['caption'];
}
}
}
if ( empty( $post_array['post_title'] ) ) {
$post_array['post_title'] = preg_replace( '/\.[^.]+$/', '', Utils\basename( $file ) );
}
if ( Utils\get_flag_value( $assoc_args, 'skip-copy' ) ) {
$wp_filetype = wp_check_filetype( $file, null );
$post_array['post_mime_type'] = $wp_filetype['type'];
$post_array['post_status'] = 'inherit';
$success = wp_insert_attachment( $post_array, $file, $assoc_args['post_id'] );
if ( is_wp_error( $success ) ) {
WP_CLI::warning(
sprintf(
"Unable to insert file '%s'. Reason: %s",
$orig_filename,
implode( ', ', $success->get_error_messages() )
)
);
$errors++;
continue;
}
wp_update_attachment_metadata( $success, wp_generate_attachment_metadata( $success, $file ) );
} else {
// Deletes the temporary file.
$success = media_handle_sideload( $file_array, $assoc_args['post_id'], $assoc_args['title'], $post_array );
if ( is_wp_error( $success ) ) {
WP_CLI::warning(
sprintf(
"Unable to import file '%s'. Reason: %s",
$orig_filename,
implode( ', ', $success->get_error_messages() )
)
);
$errors++;
continue;
}
}
// Set alt text
if ( $assoc_args['alt'] ) {
update_post_meta( $success, '_wp_attachment_image_alt', wp_slash( $assoc_args['alt'] ) );
}
// Set as featured image, if --post_id and --featured_image are set
if ( $assoc_args['post_id'] && Utils\get_flag_value( $assoc_args, 'featured_image' ) ) {
update_post_meta( $assoc_args['post_id'], '_thumbnail_id', $success );
}
$attachment_success_text = '';
if ( $assoc_args['post_id'] ) {
$attachment_success_text = " and attached to post {$assoc_args['post_id']}";
if ( Utils\get_flag_value( $assoc_args, 'featured_image' ) ) {
$attachment_success_text .= ' as featured image';
}
}
if ( Utils\get_flag_value( $assoc_args, 'porcelain' ) ) {
WP_CLI::line( $success );
} else {
WP_CLI::log(
sprintf(
"Imported file '%s' as attachment ID %d%s.",
$orig_filename,
$success,
$attachment_success_text
)
);
}
$successes++;
}
// Report the result of the operation
if ( ! Utils\get_flag_value( $assoc_args, 'porcelain' ) ) {
Utils\report_batch_operation_results( $noun, 'import', count( $args ), $successes, $errors );
} elseif ( $errors ) {
WP_CLI::halt( 1 );
}
} | php | public function import( $args, $assoc_args = array() ) {
$assoc_args = wp_parse_args(
$assoc_args,
array(
'title' => '',
'caption' => '',
'alt' => '',
'desc' => '',
)
);
// Assume the most generic term
$noun = 'item';
// Current site's timezone offset.
$gmt_offset = get_option( 'gmt_offset' );
// Use the noun `image` when sure the media file is an image
if ( Utils\get_flag_value( $assoc_args, 'featured_image' ) || $assoc_args['alt'] ) {
$noun = 'image';
}
if ( isset( $assoc_args['post_id'] ) ) {
if ( ! get_post( $assoc_args['post_id'] ) ) {
WP_CLI::warning( 'Invalid --post_id' );
$assoc_args['post_id'] = false;
}
} else {
$assoc_args['post_id'] = false;
}
$number = 0;
$successes = 0;
$errors = 0;
foreach ( $args as $file ) {
$number++;
if ( 0 === $number % self::WP_CLEAR_OBJECT_CACHE_INTERVAL ) {
Utils\wp_clear_object_cache();
}
// phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url -- parse_url will only be used in absence of wp_parse_url.
$is_file_remote = function_exists( 'wp_parse_url' ) ? wp_parse_url( $file, PHP_URL_HOST ) : parse_url( $file, PHP_URL_HOST );
$orig_filename = $file;
$file_time = '';
if ( empty( $is_file_remote ) ) {
if ( ! file_exists( $file ) ) {
WP_CLI::warning( "Unable to import file '$file'. Reason: File doesn't exist." );
$errors++;
continue;
}
if ( Utils\get_flag_value( $assoc_args, 'skip-copy' ) ) {
$tempfile = $file;
} else {
$tempfile = $this->make_copy( $file );
}
$name = Utils\basename( $file );
if ( Utils\get_flag_value( $assoc_args, 'preserve-filetime' ) ) {
$file_time = @filemtime( $file );
}
} else {
$tempfile = download_url( $file );
if ( is_wp_error( $tempfile ) ) {
WP_CLI::warning(
sprintf(
"Unable to import file '%s'. Reason: %s",
$file,
implode( ', ', $tempfile->get_error_messages() )
)
);
$errors++;
continue;
}
$name = strtok( Utils\basename( $file ), '?' );
}
$file_array = array(
'tmp_name' => $tempfile,
'name' => $name,
);
$post_array = array(
'post_title' => $assoc_args['title'],
'post_excerpt' => $assoc_args['caption'],
'post_content' => $assoc_args['desc'],
);
if ( ! empty( $file_time ) ) {
$post_array['post_date'] = gmdate( 'Y-m-d H:i:s', $file_time + ( $gmt_offset * HOUR_IN_SECONDS ) );
$post_array['post_date_gmt'] = gmdate( 'Y-m-d H:i:s', $file_time );
$post_array['post_modified'] = gmdate( 'Y-m-d H:i:s', $file_time + ( $gmt_offset * HOUR_IN_SECONDS ) );
$post_array['post_modified_gmt'] = gmdate( 'Y-m-d H:i:s', $file_time );
}
$post_array = wp_slash( $post_array );
// use image exif/iptc data for title and caption defaults if possible
if ( empty( $post_array['post_title'] ) || empty( $post_array['post_excerpt'] ) ) {
// @codingStandardsIgnoreStart
$image_meta = @wp_read_image_metadata( $tempfile );
// @codingStandardsIgnoreEnd
if ( ! empty( $image_meta ) ) {
if ( empty( $post_array['post_title'] ) && trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
$post_array['post_title'] = $image_meta['title'];
}
if ( empty( $post_array['post_excerpt'] ) && trim( $image_meta['caption'] ) ) {
$post_array['post_excerpt'] = $image_meta['caption'];
}
}
}
if ( empty( $post_array['post_title'] ) ) {
$post_array['post_title'] = preg_replace( '/\.[^.]+$/', '', Utils\basename( $file ) );
}
if ( Utils\get_flag_value( $assoc_args, 'skip-copy' ) ) {
$wp_filetype = wp_check_filetype( $file, null );
$post_array['post_mime_type'] = $wp_filetype['type'];
$post_array['post_status'] = 'inherit';
$success = wp_insert_attachment( $post_array, $file, $assoc_args['post_id'] );
if ( is_wp_error( $success ) ) {
WP_CLI::warning(
sprintf(
"Unable to insert file '%s'. Reason: %s",
$orig_filename,
implode( ', ', $success->get_error_messages() )
)
);
$errors++;
continue;
}
wp_update_attachment_metadata( $success, wp_generate_attachment_metadata( $success, $file ) );
} else {
// Deletes the temporary file.
$success = media_handle_sideload( $file_array, $assoc_args['post_id'], $assoc_args['title'], $post_array );
if ( is_wp_error( $success ) ) {
WP_CLI::warning(
sprintf(
"Unable to import file '%s'. Reason: %s",
$orig_filename,
implode( ', ', $success->get_error_messages() )
)
);
$errors++;
continue;
}
}
// Set alt text
if ( $assoc_args['alt'] ) {
update_post_meta( $success, '_wp_attachment_image_alt', wp_slash( $assoc_args['alt'] ) );
}
// Set as featured image, if --post_id and --featured_image are set
if ( $assoc_args['post_id'] && Utils\get_flag_value( $assoc_args, 'featured_image' ) ) {
update_post_meta( $assoc_args['post_id'], '_thumbnail_id', $success );
}
$attachment_success_text = '';
if ( $assoc_args['post_id'] ) {
$attachment_success_text = " and attached to post {$assoc_args['post_id']}";
if ( Utils\get_flag_value( $assoc_args, 'featured_image' ) ) {
$attachment_success_text .= ' as featured image';
}
}
if ( Utils\get_flag_value( $assoc_args, 'porcelain' ) ) {
WP_CLI::line( $success );
} else {
WP_CLI::log(
sprintf(
"Imported file '%s' as attachment ID %d%s.",
$orig_filename,
$success,
$attachment_success_text
)
);
}
$successes++;
}
// Report the result of the operation
if ( ! Utils\get_flag_value( $assoc_args, 'porcelain' ) ) {
Utils\report_batch_operation_results( $noun, 'import', count( $args ), $successes, $errors );
} elseif ( $errors ) {
WP_CLI::halt( 1 );
}
} | [
"public",
"function",
"import",
"(",
"$",
"args",
",",
"$",
"assoc_args",
"=",
"array",
"(",
")",
")",
"{",
"$",
"assoc_args",
"=",
"wp_parse_args",
"(",
"$",
"assoc_args",
",",
"array",
"(",
"'title'",
"=>",
"''",
",",
"'caption'",
"=>",
"''",
",",
... | Creates attachments from local files or URLs.
## OPTIONS
<file>...
: Path to file or files to be imported. Supports the glob(3) capabilities of the current shell.
If file is recognized as a URL (for example, with a scheme of http or ftp), the file will be
downloaded to a temp file before being sideloaded.
[--post_id=<post_id>]
: ID of the post to attach the imported files to.
[--title=<title>]
: Attachment title (post title field).
[--caption=<caption>]
: Caption for attachent (post excerpt field).
[--alt=<alt_text>]
: Alt text for image (saved as post meta).
[--desc=<description>]
: "Description" field (post content) of attachment post.
[--skip-copy]
: If set, media files (local only) are imported to the library but not moved on disk.
[--preserve-filetime]
: Use the file modified time as the post published & modified dates.
Remote files will always use the current time.
[--featured_image]
: If set, set the imported image as the Featured Image of the post its attached to.
[--porcelain]
: Output just the new attachment ID.
## EXAMPLES
# Import all jpgs in the current user's "Pictures" directory, not attached to any post.
$ wp media import ~/Pictures/**\/*.jpg
Imported file '/home/person/Pictures/landscape-photo.jpg' as attachment ID 1751.
Imported file '/home/person/Pictures/fashion-icon.jpg' as attachment ID 1752.
Success: Imported 2 of 2 items.
# Import a local image and set it to be the post thumbnail for a post.
$ wp media import ~/Downloads/image.png --post_id=123 --title="A downloaded picture" --featured_image
Imported file '/home/person/Downloads/image.png' as attachment ID 1753 and attached to post 123 as featured image.
Success: Imported 1 of 1 images.
# Import a local image, but set it as the featured image for all posts.
# 1. Import the image and get its attachment ID.
# 2. Assign the attachment ID as the featured image for all posts.
$ ATTACHMENT_ID="$(wp media import ~/Downloads/image.png --porcelain)"
$ wp post list --post_type=post --format=ids | xargs -d ' ' -I % wp post meta add % _thumbnail_id $ATTACHMENT_ID
Success: Added custom field.
Success: Added custom field.
# Import an image from the web.
$ wp media import http://s.wordpress.org/style/images/wp-header-logo.png --title='The WordPress logo' --alt="Semantic personal publishing"
Imported file 'http://s.wordpress.org/style/images/wp-header-logo.png' as attachment ID 1755.
Success: Imported 1 of 1 images.
# Get the URL for an attachment after import.
$ wp media import http://s.wordpress.org/style/images/wp-header-logo.png --porcelain | xargs -I {} wp post list --post__in={} --field=url --post_type=attachment
http://wordpress-develop.dev/wp-header-logo/ | [
"Creates",
"attachments",
"from",
"local",
"files",
"or",
"URLs",
"."
] | train | https://github.com/wp-cli/media-command/blob/68e2402dcef11ae10e8902cf93a1d370db07ed78/src/Media_Command.php#L240-L430 |
wp-cli/media-command | src/Media_Command.php | Media_Command.image_size | public function image_size( $args, $assoc_args ) {
$assoc_args = array_merge(
array(
'fields' => 'name,width,height,crop,ratio',
),
$assoc_args
);
$sizes = $this->get_registered_image_sizes();
usort(
$sizes,
function( $a, $b ) {
if ( $a['width'] === $b['width'] ) {
return 0;
}
return ( $a['width'] < $b['width'] ) ? 1 : -1;
}
);
array_unshift(
$sizes,
array(
'name' => 'full',
'width' => '',
'height' => '',
'crop' => 'N/A',
'ratio' => 'N/A',
)
);
WP_CLI\Utils\format_items( $assoc_args['format'], $sizes, explode( ',', $assoc_args['fields'] ) );
} | php | public function image_size( $args, $assoc_args ) {
$assoc_args = array_merge(
array(
'fields' => 'name,width,height,crop,ratio',
),
$assoc_args
);
$sizes = $this->get_registered_image_sizes();
usort(
$sizes,
function( $a, $b ) {
if ( $a['width'] === $b['width'] ) {
return 0;
}
return ( $a['width'] < $b['width'] ) ? 1 : -1;
}
);
array_unshift(
$sizes,
array(
'name' => 'full',
'width' => '',
'height' => '',
'crop' => 'N/A',
'ratio' => 'N/A',
)
);
WP_CLI\Utils\format_items( $assoc_args['format'], $sizes, explode( ',', $assoc_args['fields'] ) );
} | [
"public",
"function",
"image_size",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"$",
"assoc_args",
"=",
"array_merge",
"(",
"array",
"(",
"'fields'",
"=>",
"'name,width,height,crop,ratio'",
",",
")",
",",
"$",
"assoc_args",
")",
";",
"$",
"sizes",
... | Lists image sizes registered with WordPress.
## OPTIONS
[--fields=<fields>]
: Limit the output to specific fields. Defaults to all fields.
[--format=<format>]
: Render output in a specific format
---
default: table
options:
- table
- json
- csv
- yaml
- count
---
## AVAILABLE FIELDS
These fields will be displayed by default for each image size:
* name
* width
* height
* crop
* ratio
## EXAMPLES
# List all registered image sizes
$ wp media image-size
+---------------------------+-------+--------+-------+-------+
| name | width | height | crop | ratio |
+---------------------------+-------+--------+-------+-------+
| full | | | N/A | N/A |
| twentyfourteen-full-width | 1038 | 576 | hard | 173:96|
| large | 1024 | 1024 | soft | N/A |
| medium_large | 768 | 0 | soft | N/A |
| medium | 300 | 300 | soft | N/A |
| thumbnail | 150 | 150 | hard | 1:1 |
+---------------------------+-------+--------+-------+-------+
@subcommand image-size | [
"Lists",
"image",
"sizes",
"registered",
"with",
"WordPress",
"."
] | train | https://github.com/wp-cli/media-command/blob/68e2402dcef11ae10e8902cf93a1d370db07ed78/src/Media_Command.php#L478-L508 |
wp-cli/media-command | src/Media_Command.php | Media_Command.make_copy | private function make_copy( $path ) {
$dir = get_temp_dir();
$filename = Utils\basename( $path );
if ( empty( $filename ) ) {
$filename = time();
}
$filename = $dir . wp_unique_filename( $dir, $filename );
if ( ! copy( $path, $filename ) ) {
WP_CLI::error( "Could not create temporary file for $path." );
}
return $filename;
} | php | private function make_copy( $path ) {
$dir = get_temp_dir();
$filename = Utils\basename( $path );
if ( empty( $filename ) ) {
$filename = time();
}
$filename = $dir . wp_unique_filename( $dir, $filename );
if ( ! copy( $path, $filename ) ) {
WP_CLI::error( "Could not create temporary file for $path." );
}
return $filename;
} | [
"private",
"function",
"make_copy",
"(",
"$",
"path",
")",
"{",
"$",
"dir",
"=",
"get_temp_dir",
"(",
")",
";",
"$",
"filename",
"=",
"Utils",
"\\",
"basename",
"(",
"$",
"path",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"filename",
")",
")",
"{",
... | wp_tempnam() inexplicably forces a .tmp extension, which spoils MIME type detection | [
"wp_tempnam",
"()",
"inexplicably",
"forces",
"a",
".",
"tmp",
"extension",
"which",
"spoils",
"MIME",
"type",
"detection"
] | train | https://github.com/wp-cli/media-command/blob/68e2402dcef11ae10e8902cf93a1d370db07ed78/src/Media_Command.php#L536-L549 |
wp-cli/media-command | src/Media_Command.php | Media_Command.image_sizes_differ | private function image_sizes_differ( $image_sizes, $meta_sizes ) {
// Check if have new image size(s).
if ( array_diff( array_keys( $image_sizes ), array_keys( $meta_sizes ) ) ) {
return true;
}
// Check if image sizes have changed.
foreach ( $image_sizes as $name => $image_size ) {
if ( $image_size['width'] !== $meta_sizes[ $name ]['width'] || $image_size['height'] !== $meta_sizes[ $name ]['height'] ) {
return true;
}
}
return false;
} | php | private function image_sizes_differ( $image_sizes, $meta_sizes ) {
// Check if have new image size(s).
if ( array_diff( array_keys( $image_sizes ), array_keys( $meta_sizes ) ) ) {
return true;
}
// Check if image sizes have changed.
foreach ( $image_sizes as $name => $image_size ) {
if ( $image_size['width'] !== $meta_sizes[ $name ]['width'] || $image_size['height'] !== $meta_sizes[ $name ]['height'] ) {
return true;
}
}
return false;
} | [
"private",
"function",
"image_sizes_differ",
"(",
"$",
"image_sizes",
",",
"$",
"meta_sizes",
")",
"{",
"// Check if have new image size(s).",
"if",
"(",
"array_diff",
"(",
"array_keys",
"(",
"$",
"image_sizes",
")",
",",
"array_keys",
"(",
"$",
"meta_sizes",
")",... | Whether there's new image sizes or the width/height of existing image sizes have changed. | [
"Whether",
"there",
"s",
"new",
"image",
"sizes",
"or",
"the",
"width",
"/",
"height",
"of",
"existing",
"image",
"sizes",
"have",
"changed",
"."
] | train | https://github.com/wp-cli/media-command/blob/68e2402dcef11ae10e8902cf93a1d370db07ed78/src/Media_Command.php#L724-L736 |
wp-cli/media-command | src/Media_Command.php | Media_Command.get_intermediate_image_sizes_for_attachment | private function get_intermediate_image_sizes_for_attachment( $fullsizepath, $is_pdf, $metadata ) {
// Need to get width, height of attachment for image_resize_dimensions().
$editor = wp_get_image_editor( $fullsizepath );
if ( is_wp_error( $editor ) ) {
return $editor;
}
$result = $editor->load();
if ( is_wp_error( $result ) ) {
unset( $editor );
return $result;
}
list( $width, $height ) = array_values( $editor->get_size() );
unset( $editor );
$sizes = array();
foreach ( $this->get_intermediate_sizes( $is_pdf, $metadata ) as $name => $size ) {
// Need to check destination and original width or height differ before calling image_resize_dimensions(), otherwise it will return non-false.
$dims = image_resize_dimensions( $width, $height, $size['width'], $size['height'], $size['crop'] );
if ( ( $width !== $size['width'] || $height !== $size['height'] ) && $dims ) {
list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims;
$sizes[ $name ] = array(
'width' => $dst_w,
'height' => $dst_h,
);
}
}
return $sizes;
} | php | private function get_intermediate_image_sizes_for_attachment( $fullsizepath, $is_pdf, $metadata ) {
// Need to get width, height of attachment for image_resize_dimensions().
$editor = wp_get_image_editor( $fullsizepath );
if ( is_wp_error( $editor ) ) {
return $editor;
}
$result = $editor->load();
if ( is_wp_error( $result ) ) {
unset( $editor );
return $result;
}
list( $width, $height ) = array_values( $editor->get_size() );
unset( $editor );
$sizes = array();
foreach ( $this->get_intermediate_sizes( $is_pdf, $metadata ) as $name => $size ) {
// Need to check destination and original width or height differ before calling image_resize_dimensions(), otherwise it will return non-false.
$dims = image_resize_dimensions( $width, $height, $size['width'], $size['height'], $size['crop'] );
if ( ( $width !== $size['width'] || $height !== $size['height'] ) && $dims ) {
list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims;
$sizes[ $name ] = array(
'width' => $dst_w,
'height' => $dst_h,
);
}
}
return $sizes;
} | [
"private",
"function",
"get_intermediate_image_sizes_for_attachment",
"(",
"$",
"fullsizepath",
",",
"$",
"is_pdf",
",",
"$",
"metadata",
")",
"{",
"// Need to get width, height of attachment for image_resize_dimensions().",
"$",
"editor",
"=",
"wp_get_image_editor",
"(",
"$"... | and returns associative array with size name => width/height entries, resolved to crop values if applicable. | [
"and",
"returns",
"associative",
"array",
"with",
"size",
"name",
"=",
">",
"width",
"/",
"height",
"entries",
"resolved",
"to",
"crop",
"values",
"if",
"applicable",
"."
] | train | https://github.com/wp-cli/media-command/blob/68e2402dcef11ae10e8902cf93a1d370db07ed78/src/Media_Command.php#L740-L768 |
wp-cli/media-command | src/Media_Command.php | Media_Command.get_intermediate_sizes | private function get_intermediate_sizes( $is_pdf, $metadata ) {
if ( $is_pdf ) {
// Copied from wp_generate_attachment_metadata() in "wp-admin/includes/image.php".
$fallback_sizes = array(
'thumbnail',
'medium',
'large',
);
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Calling native WordPress hook.
$intermediate_image_sizes = apply_filters( 'fallback_intermediate_image_sizes', $fallback_sizes, $metadata );
} else {
$intermediate_image_sizes = get_intermediate_image_sizes();
}
// Adapted from wp_generate_attachment_metadata() in "wp-admin/includes/image.php".
if ( function_exists( 'wp_get_additional_image_sizes' ) ) {
$_wp_additional_image_sizes = wp_get_additional_image_sizes();
} else {
// For WP < 4.7.0.
global $_wp_additional_image_sizes;
if ( ! $_wp_additional_image_sizes ) {
// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Used as a fallback for WordPress version less than 4.7.0 as function wp_get_additional_image_sizes didn't exist then.
$_wp_additional_image_sizes = array();
}
}
$sizes = array();
foreach ( $intermediate_image_sizes as $s ) {
if ( isset( $_wp_additional_image_sizes[ $s ]['width'] ) ) {
$sizes[ $s ]['width'] = (int) $_wp_additional_image_sizes[ $s ]['width'];
} else {
$sizes[ $s ]['width'] = (int) get_option( "{$s}_size_w" );
}
if ( isset( $_wp_additional_image_sizes[ $s ]['height'] ) ) {
$sizes[ $s ]['height'] = (int) $_wp_additional_image_sizes[ $s ]['height'];
} else {
$sizes[ $s ]['height'] = (int) get_option( "{$s}_size_h" );
}
if ( isset( $_wp_additional_image_sizes[ $s ]['crop'] ) ) {
$sizes[ $s ]['crop'] = (bool) $_wp_additional_image_sizes[ $s ]['crop'];
} else {
// Force PDF thumbnails to be soft crops.
if ( $is_pdf && 'thumbnail' === $s ) {
$sizes[ $s ]['crop'] = false;
} else {
$sizes[ $s ]['crop'] = (bool) get_option( "{$s}_crop" );
}
}
}
// Check here that not PDF (as filter not applied in core if is) and `$metadata` is array (as may not be and filter only applied in core when is).
if ( ! $is_pdf && is_array( $metadata ) ) {
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Calling native WordPress hook.
$sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes, $metadata );
}
return $sizes;
} | php | private function get_intermediate_sizes( $is_pdf, $metadata ) {
if ( $is_pdf ) {
// Copied from wp_generate_attachment_metadata() in "wp-admin/includes/image.php".
$fallback_sizes = array(
'thumbnail',
'medium',
'large',
);
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Calling native WordPress hook.
$intermediate_image_sizes = apply_filters( 'fallback_intermediate_image_sizes', $fallback_sizes, $metadata );
} else {
$intermediate_image_sizes = get_intermediate_image_sizes();
}
// Adapted from wp_generate_attachment_metadata() in "wp-admin/includes/image.php".
if ( function_exists( 'wp_get_additional_image_sizes' ) ) {
$_wp_additional_image_sizes = wp_get_additional_image_sizes();
} else {
// For WP < 4.7.0.
global $_wp_additional_image_sizes;
if ( ! $_wp_additional_image_sizes ) {
// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Used as a fallback for WordPress version less than 4.7.0 as function wp_get_additional_image_sizes didn't exist then.
$_wp_additional_image_sizes = array();
}
}
$sizes = array();
foreach ( $intermediate_image_sizes as $s ) {
if ( isset( $_wp_additional_image_sizes[ $s ]['width'] ) ) {
$sizes[ $s ]['width'] = (int) $_wp_additional_image_sizes[ $s ]['width'];
} else {
$sizes[ $s ]['width'] = (int) get_option( "{$s}_size_w" );
}
if ( isset( $_wp_additional_image_sizes[ $s ]['height'] ) ) {
$sizes[ $s ]['height'] = (int) $_wp_additional_image_sizes[ $s ]['height'];
} else {
$sizes[ $s ]['height'] = (int) get_option( "{$s}_size_h" );
}
if ( isset( $_wp_additional_image_sizes[ $s ]['crop'] ) ) {
$sizes[ $s ]['crop'] = (bool) $_wp_additional_image_sizes[ $s ]['crop'];
} else {
// Force PDF thumbnails to be soft crops.
if ( $is_pdf && 'thumbnail' === $s ) {
$sizes[ $s ]['crop'] = false;
} else {
$sizes[ $s ]['crop'] = (bool) get_option( "{$s}_crop" );
}
}
}
// Check here that not PDF (as filter not applied in core if is) and `$metadata` is array (as may not be and filter only applied in core when is).
if ( ! $is_pdf && is_array( $metadata ) ) {
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Calling native WordPress hook.
$sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes, $metadata );
}
return $sizes;
} | [
"private",
"function",
"get_intermediate_sizes",
"(",
"$",
"is_pdf",
",",
"$",
"metadata",
")",
"{",
"if",
"(",
"$",
"is_pdf",
")",
"{",
"// Copied from wp_generate_attachment_metadata() in \"wp-admin/includes/image.php\".",
"$",
"fallback_sizes",
"=",
"array",
"(",
"'t... | Like WP's get_intermediate_image_sizes(), but returns associative array with name => size info entries (and caters for PDFs also). | [
"Like",
"WP",
"s",
"get_intermediate_image_sizes",
"()",
"but",
"returns",
"associative",
"array",
"with",
"name",
"=",
">",
"size",
"info",
"entries",
"(",
"and",
"caters",
"for",
"PDFs",
"also",
")",
"."
] | train | https://github.com/wp-cli/media-command/blob/68e2402dcef11ae10e8902cf93a1d370db07ed78/src/Media_Command.php#L771-L831 |
wp-cli/media-command | src/Media_Command.php | Media_Command.add_image_size_filters | private function add_image_size_filters( $image_size ) {
$image_size_filters = array();
// For images.
$image_size_filters['intermediate_image_sizes_advanced'] = function ( $sizes ) use ( $image_size ) {
// $sizes is associative array of name => size info entries.
if ( isset( $sizes[ $image_size ] ) ) {
return array( $image_size => $sizes[ $image_size ] );
}
return array();
};
// For PDF previews.
$image_size_filters['fallback_intermediate_image_sizes'] = function ( $fallback_sizes ) use ( $image_size ) {
// $fallback_sizes is indexed array of size names.
if ( in_array( $image_size, $fallback_sizes, true ) ) {
return array( $image_size );
}
return array();
};
foreach ( $image_size_filters as $name => $filter ) {
add_filter( $name, $filter, PHP_INT_MAX );
}
return $image_size_filters;
} | php | private function add_image_size_filters( $image_size ) {
$image_size_filters = array();
// For images.
$image_size_filters['intermediate_image_sizes_advanced'] = function ( $sizes ) use ( $image_size ) {
// $sizes is associative array of name => size info entries.
if ( isset( $sizes[ $image_size ] ) ) {
return array( $image_size => $sizes[ $image_size ] );
}
return array();
};
// For PDF previews.
$image_size_filters['fallback_intermediate_image_sizes'] = function ( $fallback_sizes ) use ( $image_size ) {
// $fallback_sizes is indexed array of size names.
if ( in_array( $image_size, $fallback_sizes, true ) ) {
return array( $image_size );
}
return array();
};
foreach ( $image_size_filters as $name => $filter ) {
add_filter( $name, $filter, PHP_INT_MAX );
}
return $image_size_filters;
} | [
"private",
"function",
"add_image_size_filters",
"(",
"$",
"image_size",
")",
"{",
"$",
"image_size_filters",
"=",
"array",
"(",
")",
";",
"// For images.",
"$",
"image_size_filters",
"[",
"'intermediate_image_sizes_advanced'",
"]",
"=",
"function",
"(",
"$",
"sizes... | Add filters to only process a particular intermediate image size in wp_generate_attachment_metadata(). | [
"Add",
"filters",
"to",
"only",
"process",
"a",
"particular",
"intermediate",
"image",
"size",
"in",
"wp_generate_attachment_metadata",
"()",
"."
] | train | https://github.com/wp-cli/media-command/blob/68e2402dcef11ae10e8902cf93a1d370db07ed78/src/Media_Command.php#L834-L860 |
wp-cli/media-command | src/Media_Command.php | Media_Command.remove_image_size_filters | private function remove_image_size_filters( $image_size_filters ) {
foreach ( $image_size_filters as $name => $filter ) {
remove_filter( $name, $filter, PHP_INT_MAX );
}
} | php | private function remove_image_size_filters( $image_size_filters ) {
foreach ( $image_size_filters as $name => $filter ) {
remove_filter( $name, $filter, PHP_INT_MAX );
}
} | [
"private",
"function",
"remove_image_size_filters",
"(",
"$",
"image_size_filters",
")",
"{",
"foreach",
"(",
"$",
"image_size_filters",
"as",
"$",
"name",
"=>",
"$",
"filter",
")",
"{",
"remove_filter",
"(",
"$",
"name",
",",
"$",
"filter",
",",
"PHP_INT_MAX"... | Remove above intermediate image size filters. | [
"Remove",
"above",
"intermediate",
"image",
"size",
"filters",
"."
] | train | https://github.com/wp-cli/media-command/blob/68e2402dcef11ae10e8902cf93a1d370db07ed78/src/Media_Command.php#L863-L867 |
wp-cli/media-command | src/Media_Command.php | Media_Command.update_attachment_metadata_for_image_size | private function update_attachment_metadata_for_image_size( $id, $new_metadata, $image_size ) {
$metadata = wp_get_attachment_metadata( $id );
if ( ! is_array( $metadata ) ) {
return false;
}
// If have metadata for image_size.
if ( ! empty( $new_metadata['sizes'][ $image_size ] ) ) {
$metadata['sizes'][ $image_size ] = $new_metadata['sizes'][ $image_size ];
wp_update_attachment_metadata( $id, $metadata );
return true;
}
// Else remove unused metadata if any.
if ( ! empty( $metadata['sizes'][ $image_size ] ) ) {
unset( $metadata['sizes'][ $image_size ] );
wp_update_attachment_metadata( $id, $metadata );
// Treat removing unused metadata as no change.
}
return false;
} | php | private function update_attachment_metadata_for_image_size( $id, $new_metadata, $image_size ) {
$metadata = wp_get_attachment_metadata( $id );
if ( ! is_array( $metadata ) ) {
return false;
}
// If have metadata for image_size.
if ( ! empty( $new_metadata['sizes'][ $image_size ] ) ) {
$metadata['sizes'][ $image_size ] = $new_metadata['sizes'][ $image_size ];
wp_update_attachment_metadata( $id, $metadata );
return true;
}
// Else remove unused metadata if any.
if ( ! empty( $metadata['sizes'][ $image_size ] ) ) {
unset( $metadata['sizes'][ $image_size ] );
wp_update_attachment_metadata( $id, $metadata );
// Treat removing unused metadata as no change.
}
return false;
} | [
"private",
"function",
"update_attachment_metadata_for_image_size",
"(",
"$",
"id",
",",
"$",
"new_metadata",
",",
"$",
"image_size",
")",
"{",
"$",
"metadata",
"=",
"wp_get_attachment_metadata",
"(",
"$",
"id",
")",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
... | Update attachment sizes metadata just for a particular intermediate image size. | [
"Update",
"attachment",
"sizes",
"metadata",
"just",
"for",
"a",
"particular",
"intermediate",
"image",
"size",
"."
] | train | https://github.com/wp-cli/media-command/blob/68e2402dcef11ae10e8902cf93a1d370db07ed78/src/Media_Command.php#L870-L891 |
wp-cli/media-command | src/Media_Command.php | Media_Command.get_images | private function get_images( $args = array(), $additional_mime_types = array() ) {
$mime_types = array_merge( array( 'image' ), $additional_mime_types );
$query_args = array(
'post_type' => 'attachment',
'post__in' => $args,
'post_mime_type' => $mime_types,
'post_status' => 'any',
'posts_per_page' => -1,
);
return new WP_Query( $query_args );
} | php | private function get_images( $args = array(), $additional_mime_types = array() ) {
$mime_types = array_merge( array( 'image' ), $additional_mime_types );
$query_args = array(
'post_type' => 'attachment',
'post__in' => $args,
'post_mime_type' => $mime_types,
'post_status' => 'any',
'posts_per_page' => -1,
);
return new WP_Query( $query_args );
} | [
"private",
"function",
"get_images",
"(",
"$",
"args",
"=",
"array",
"(",
")",
",",
"$",
"additional_mime_types",
"=",
"array",
"(",
")",
")",
"{",
"$",
"mime_types",
"=",
"array_merge",
"(",
"array",
"(",
"'image'",
")",
",",
"$",
"additional_mime_types",... | Get images from the installation.
@param array $args The query arguments to use. Optional.
@param array $additional_mime_types The additional mime types to search for. Optional.
@return WP_Query The query result. | [
"Get",
"images",
"from",
"the",
"installation",
"."
] | train | https://github.com/wp-cli/media-command/blob/68e2402dcef11ae10e8902cf93a1d370db07ed78/src/Media_Command.php#L901-L913 |
wp-cli/media-command | src/Media_Command.php | Media_Command.get_intermediate_size_metadata | private function get_intermediate_size_metadata( $size ) {
$width = intval( get_option( "{$size}_size_w" ) );
$height = intval( get_option( "{$size}_size_h" ) );
$crop = get_option( "{$size}_crop" );
return array(
'name' => $size,
'width' => $width,
'height' => $height,
'crop' => false !== $crop ? 'hard' : 'soft',
'ratio' => false !== $crop ? $this->get_ratio( $width, $height ) : 'N/A',
);
} | php | private function get_intermediate_size_metadata( $size ) {
$width = intval( get_option( "{$size}_size_w" ) );
$height = intval( get_option( "{$size}_size_h" ) );
$crop = get_option( "{$size}_crop" );
return array(
'name' => $size,
'width' => $width,
'height' => $height,
'crop' => false !== $crop ? 'hard' : 'soft',
'ratio' => false !== $crop ? $this->get_ratio( $width, $height ) : 'N/A',
);
} | [
"private",
"function",
"get_intermediate_size_metadata",
"(",
"$",
"size",
")",
"{",
"$",
"width",
"=",
"intval",
"(",
"get_option",
"(",
"\"{$size}_size_w\"",
")",
")",
";",
"$",
"height",
"=",
"intval",
"(",
"get_option",
"(",
"\"{$size}_size_h\"",
")",
")",... | Get the metadata for the passed intermediate image size.
@param string $size The image size to get the metadata for.
@return array The image size metadata. | [
"Get",
"the",
"metadata",
"for",
"the",
"passed",
"intermediate",
"image",
"size",
"."
] | train | https://github.com/wp-cli/media-command/blob/68e2402dcef11ae10e8902cf93a1d370db07ed78/src/Media_Command.php#L922-L934 |
wp-cli/media-command | src/Media_Command.php | Media_Command.get_registered_image_sizes | private function get_registered_image_sizes() {
global $_wp_additional_image_sizes;
$image_sizes = array();
$default_image_sizes = get_intermediate_image_sizes();
foreach ( $default_image_sizes as $size ) {
$image_sizes[] = $this->get_intermediate_size_metadata( $size );
}
if ( is_array( $_wp_additional_image_sizes ) ) {
foreach ( $_wp_additional_image_sizes as $size => $size_args ) {
$crop = filter_var( $size_args['crop'], FILTER_VALIDATE_BOOLEAN );
$image_sizes[] = array(
'name' => $size,
'width' => $size_args['width'],
'height' => $size_args['height'],
'crop' => empty( $crop ) || is_array( $size_args['crop'] ) ? 'soft' : 'hard',
'ratio' => empty( $crop ) || is_array( $size_args['crop'] ) ? 'N/A' : $this->get_ratio( $size_args['width'], $size_args['height'] ),
);
}
}
return $image_sizes;
} | php | private function get_registered_image_sizes() {
global $_wp_additional_image_sizes;
$image_sizes = array();
$default_image_sizes = get_intermediate_image_sizes();
foreach ( $default_image_sizes as $size ) {
$image_sizes[] = $this->get_intermediate_size_metadata( $size );
}
if ( is_array( $_wp_additional_image_sizes ) ) {
foreach ( $_wp_additional_image_sizes as $size => $size_args ) {
$crop = filter_var( $size_args['crop'], FILTER_VALIDATE_BOOLEAN );
$image_sizes[] = array(
'name' => $size,
'width' => $size_args['width'],
'height' => $size_args['height'],
'crop' => empty( $crop ) || is_array( $size_args['crop'] ) ? 'soft' : 'hard',
'ratio' => empty( $crop ) || is_array( $size_args['crop'] ) ? 'N/A' : $this->get_ratio( $size_args['width'], $size_args['height'] ),
);
}
}
return $image_sizes;
} | [
"private",
"function",
"get_registered_image_sizes",
"(",
")",
"{",
"global",
"$",
"_wp_additional_image_sizes",
";",
"$",
"image_sizes",
"=",
"array",
"(",
")",
";",
"$",
"default_image_sizes",
"=",
"get_intermediate_image_sizes",
"(",
")",
";",
"foreach",
"(",
"... | Get all the registered image sizes along with their dimensions.
@global array $_wp_additional_image_sizes The additional image sizes to parse.
@link https://wordpress.stackexchange.com/a/251602 Original solution.
@return array $image_sizes The image sizes | [
"Get",
"all",
"the",
"registered",
"image",
"sizes",
"along",
"with",
"their",
"dimensions",
"."
] | train | https://github.com/wp-cli/media-command/blob/68e2402dcef11ae10e8902cf93a1d370db07ed78/src/Media_Command.php#L945-L969 |
opensoft/rollout | src/Storage/PDOStorageAdapter.php | PDOStorageAdapter.get | public function get($key)
{
$statement = $this->pdoConnection->prepare($this->getSQLStatement(self::STMT_SELECT));
$statement->bindParam('key', $key);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$result = $statement->fetch();
if (false === $result) {
return null;
}
return $result['settings'];
} | php | public function get($key)
{
$statement = $this->pdoConnection->prepare($this->getSQLStatement(self::STMT_SELECT));
$statement->bindParam('key', $key);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$result = $statement->fetch();
if (false === $result) {
return null;
}
return $result['settings'];
} | [
"public",
"function",
"get",
"(",
"$",
"key",
")",
"{",
"$",
"statement",
"=",
"$",
"this",
"->",
"pdoConnection",
"->",
"prepare",
"(",
"$",
"this",
"->",
"getSQLStatement",
"(",
"self",
"::",
"STMT_SELECT",
")",
")",
";",
"$",
"statement",
"->",
"bin... | {@inheritdoc} | [
"{"
] | train | https://github.com/opensoft/rollout/blob/4df1b6888654c02506f5da813055934d414a8678/src/Storage/PDOStorageAdapter.php#L36-L52 |
opensoft/rollout | src/Storage/PDOStorageAdapter.php | PDOStorageAdapter.set | public function set($key, $value)
{
if (null === $this->get($key)) {
$sql = self::STMT_INSERT;
} else {
$sql = self::STMT_UPDATE;
}
$statement = $this->pdoConnection->prepare($this->getSQLStatement($sql));
$statement->bindParam('key', $key);
$statement->bindParam('value', $value);
$statement->execute();
} | php | public function set($key, $value)
{
if (null === $this->get($key)) {
$sql = self::STMT_INSERT;
} else {
$sql = self::STMT_UPDATE;
}
$statement = $this->pdoConnection->prepare($this->getSQLStatement($sql));
$statement->bindParam('key', $key);
$statement->bindParam('value', $value);
$statement->execute();
} | [
"public",
"function",
"set",
"(",
"$",
"key",
",",
"$",
"value",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"get",
"(",
"$",
"key",
")",
")",
"{",
"$",
"sql",
"=",
"self",
"::",
"STMT_INSERT",
";",
"}",
"else",
"{",
"$",
"sql",
"=... | {@inheritdoc} | [
"{"
] | train | https://github.com/opensoft/rollout/blob/4df1b6888654c02506f5da813055934d414a8678/src/Storage/PDOStorageAdapter.php#L57-L71 |
opensoft/rollout | src/Feature.php | Feature.clear | public function clear()
{
$this->groups = array();
$this->users = array();
$this->percentage = 0;
$this->requestParam = '';
$this->data = array();
} | php | public function clear()
{
$this->groups = array();
$this->users = array();
$this->percentage = 0;
$this->requestParam = '';
$this->data = array();
} | [
"public",
"function",
"clear",
"(",
")",
"{",
"$",
"this",
"->",
"groups",
"=",
"array",
"(",
")",
";",
"$",
"this",
"->",
"users",
"=",
"array",
"(",
")",
";",
"$",
"this",
"->",
"percentage",
"=",
"0",
";",
"$",
"this",
"->",
"requestParam",
"=... | Clear the feature of all configuration | [
"Clear",
"the",
"feature",
"of",
"all",
"configuration"
] | train | https://github.com/opensoft/rollout/blob/4df1b6888654c02506f5da813055934d414a8678/src/Feature.php#L202-L209 |
opensoft/rollout | src/Feature.php | Feature.isActive | public function isActive(Rollout $rollout, RolloutUserInterface $user = null, array $requestParameters = array())
{
if (null == $user) {
return $this->isParamInRequestParams($requestParameters)
|| $this->percentage == 100
|| $this->isInActiveGroup($rollout);
}
return $this->isParamInRequestParams($requestParameters) ||
$this->isUserInPercentage($user) ||
$this->isUserInActiveUsers($user) ||
$this->isInActiveGroup($rollout, $user);
} | php | public function isActive(Rollout $rollout, RolloutUserInterface $user = null, array $requestParameters = array())
{
if (null == $user) {
return $this->isParamInRequestParams($requestParameters)
|| $this->percentage == 100
|| $this->isInActiveGroup($rollout);
}
return $this->isParamInRequestParams($requestParameters) ||
$this->isUserInPercentage($user) ||
$this->isUserInActiveUsers($user) ||
$this->isInActiveGroup($rollout, $user);
} | [
"public",
"function",
"isActive",
"(",
"Rollout",
"$",
"rollout",
",",
"RolloutUserInterface",
"$",
"user",
"=",
"null",
",",
"array",
"$",
"requestParameters",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"null",
"==",
"$",
"user",
")",
"{",
"return",
... | Is the feature active?
@param Rollout $rollout
@param RolloutUserInterface|null $user
@param array $requestParameters
@return bool | [
"Is",
"the",
"feature",
"active?"
] | train | https://github.com/opensoft/rollout/blob/4df1b6888654c02506f5da813055934d414a8678/src/Feature.php#L219-L231 |
opensoft/rollout | src/Rollout.php | Rollout.remove | public function remove($feature)
{
$this->storage->remove($this->key($feature));
$features = $this->features();
if (in_array($feature, $features)) {
$features = array_diff($features, array($feature));
}
$this->storage->set($this->featuresKey(), implode(',', $features));
} | php | public function remove($feature)
{
$this->storage->remove($this->key($feature));
$features = $this->features();
if (in_array($feature, $features)) {
$features = array_diff($features, array($feature));
}
$this->storage->set($this->featuresKey(), implode(',', $features));
} | [
"public",
"function",
"remove",
"(",
"$",
"feature",
")",
"{",
"$",
"this",
"->",
"storage",
"->",
"remove",
"(",
"$",
"this",
"->",
"key",
"(",
"$",
"feature",
")",
")",
";",
"$",
"features",
"=",
"$",
"this",
"->",
"features",
"(",
")",
";",
"i... | Remove a feature definition from rollout
@param string $feature | [
"Remove",
"a",
"feature",
"definition",
"from",
"rollout"
] | train | https://github.com/opensoft/rollout/blob/4df1b6888654c02506f5da813055934d414a8678/src/Rollout.php#L224-L233 |
opensoft/rollout | src/Rollout.php | Rollout.setFeatureData | public function setFeatureData($feature, array $data)
{
$feature = $this->get($feature);
if ($feature) {
$feature->setData(array_merge($feature->getData(), $data));
$this->save($feature);
}
} | php | public function setFeatureData($feature, array $data)
{
$feature = $this->get($feature);
if ($feature) {
$feature->setData(array_merge($feature->getData(), $data));
$this->save($feature);
}
} | [
"public",
"function",
"setFeatureData",
"(",
"$",
"feature",
",",
"array",
"$",
"data",
")",
"{",
"$",
"feature",
"=",
"$",
"this",
"->",
"get",
"(",
"$",
"feature",
")",
";",
"if",
"(",
"$",
"feature",
")",
"{",
"$",
"feature",
"->",
"setData",
"(... | Update feature specific data
@example $rollout->setFeatureData('chat', array(
'description' => 'foo',
'release_date' => 'bar',
'whatever' => 'baz'
));
@param string $feature
@param array $data | [
"Update",
"feature",
"specific",
"data"
] | train | https://github.com/opensoft/rollout/blob/4df1b6888654c02506f5da813055934d414a8678/src/Rollout.php#L247-L254 |
opensoft/rollout | src/Rollout.php | Rollout.clearFeatureData | public function clearFeatureData($feature)
{
$feature = $this->get($feature);
if ($feature) {
$feature->setData(array());
$this->save($feature);
}
} | php | public function clearFeatureData($feature)
{
$feature = $this->get($feature);
if ($feature) {
$feature->setData(array());
$this->save($feature);
}
} | [
"public",
"function",
"clearFeatureData",
"(",
"$",
"feature",
")",
"{",
"$",
"feature",
"=",
"$",
"this",
"->",
"get",
"(",
"$",
"feature",
")",
";",
"if",
"(",
"$",
"feature",
")",
"{",
"$",
"feature",
"->",
"setData",
"(",
"array",
"(",
")",
")"... | Clear all feature data
@param string $feature | [
"Clear",
"all",
"feature",
"data"
] | train | https://github.com/opensoft/rollout/blob/4df1b6888654c02506f5da813055934d414a8678/src/Rollout.php#L261-L268 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.addClass | public function addClass($name)
{
foreach ($this as $node) {
if ($node instanceof \DOMElement) {
/** @var \DOMElement $node */
$classes = preg_split('/\s+/s', $node->getAttribute('class'));
$found = false;
$count = count($classes);
for ($i = 0; $i < $count; $i++) {
if ($classes[$i] == $name) {
$found = true;
}
}
if (!$found) {
$classes[] = $name;
$node->setAttribute('class', trim(join(' ', $classes)));
}
}
}
return $this;
} | php | public function addClass($name)
{
foreach ($this as $node) {
if ($node instanceof \DOMElement) {
/** @var \DOMElement $node */
$classes = preg_split('/\s+/s', $node->getAttribute('class'));
$found = false;
$count = count($classes);
for ($i = 0; $i < $count; $i++) {
if ($classes[$i] == $name) {
$found = true;
}
}
if (!$found) {
$classes[] = $name;
$node->setAttribute('class', trim(join(' ', $classes)));
}
}
}
return $this;
} | [
"public",
"function",
"addClass",
"(",
"$",
"name",
")",
"{",
"foreach",
"(",
"$",
"this",
"as",
"$",
"node",
")",
"{",
"if",
"(",
"$",
"node",
"instanceof",
"\\",
"DOMElement",
")",
"{",
"/** @var \\DOMElement $node */",
"$",
"classes",
"=",
"preg_split",... | Adds the specified class(es) to each element in the set of matched elements.
@param string $name One or more space-separated classes to be added to the class attribute of each matched element.
@return HtmlPageCrawler $this for chaining
@api | [
"Adds",
"the",
"specified",
"class",
"(",
"es",
")",
"to",
"each",
"element",
"in",
"the",
"set",
"of",
"matched",
"elements",
"."
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L47-L67 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.after | public function after($content)
{
$content = self::create($content);
$newnodes = array();
foreach ($this as $i => $node) {
/** @var \DOMNode $node */
$refnode = $node->nextSibling;
foreach ($content as $newnode) {
/** @var \DOMNode $newnode */
$newnode = static::importNewnode($newnode, $node, $i);
if ($refnode === null) {
$node->parentNode->appendChild($newnode);
} else {
$node->parentNode->insertBefore($newnode, $refnode);
}
$newnodes[] = $newnode;
}
}
$content->clear();
$content->add($newnodes);
return $this;
} | php | public function after($content)
{
$content = self::create($content);
$newnodes = array();
foreach ($this as $i => $node) {
/** @var \DOMNode $node */
$refnode = $node->nextSibling;
foreach ($content as $newnode) {
/** @var \DOMNode $newnode */
$newnode = static::importNewnode($newnode, $node, $i);
if ($refnode === null) {
$node->parentNode->appendChild($newnode);
} else {
$node->parentNode->insertBefore($newnode, $refnode);
}
$newnodes[] = $newnode;
}
}
$content->clear();
$content->add($newnodes);
return $this;
} | [
"public",
"function",
"after",
"(",
"$",
"content",
")",
"{",
"$",
"content",
"=",
"self",
"::",
"create",
"(",
"$",
"content",
")",
";",
"$",
"newnodes",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"as",
"$",
"i",
"=>",
"$",
"node"... | Insert content, specified by the parameter, after each element in the set of matched elements.
@param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $content
@return HtmlPageCrawler $this for chaining
@api | [
"Insert",
"content",
"specified",
"by",
"the",
"parameter",
"after",
"each",
"element",
"in",
"the",
"set",
"of",
"matched",
"elements",
"."
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L76-L97 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.append | public function append($content)
{
$content = self::create($content);
$newnodes = array();
foreach ($this as $i => $node) {
/** @var \DOMNode $node */
foreach ($content as $newnode) {
/** @var \DOMNode $newnode */
$newnode = static::importNewnode($newnode, $node, $i);
$node->appendChild($newnode);
$newnodes[] = $newnode;
}
}
$content->clear();
$content->add($newnodes);
return $this;
} | php | public function append($content)
{
$content = self::create($content);
$newnodes = array();
foreach ($this as $i => $node) {
/** @var \DOMNode $node */
foreach ($content as $newnode) {
/** @var \DOMNode $newnode */
$newnode = static::importNewnode($newnode, $node, $i);
$node->appendChild($newnode);
$newnodes[] = $newnode;
}
}
$content->clear();
$content->add($newnodes);
return $this;
} | [
"public",
"function",
"append",
"(",
"$",
"content",
")",
"{",
"$",
"content",
"=",
"self",
"::",
"create",
"(",
"$",
"content",
")",
";",
"$",
"newnodes",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"as",
"$",
"i",
"=>",
"$",
"node... | Insert HTML content as child nodes of each element after existing children
@param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $content HTML code fragment or DOMNode to append
@return HtmlPageCrawler $this for chaining
@api | [
"Insert",
"HTML",
"content",
"as",
"child",
"nodes",
"of",
"each",
"element",
"after",
"existing",
"children"
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L106-L122 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.appendTo | public function appendTo($element)
{
$e = self::create($element);
$newnodes = array();
foreach ($e as $i => $node) {
/** @var \DOMNode $node */
foreach ($this as $newnode) {
/** @var \DOMNode $newnode */
if ($node !== $newnode) {
$newnode = static::importNewnode($newnode, $node, $i);
$node->appendChild($newnode);
}
$newnodes[] = $newnode;
}
}
return self::create($newnodes);
} | php | public function appendTo($element)
{
$e = self::create($element);
$newnodes = array();
foreach ($e as $i => $node) {
/** @var \DOMNode $node */
foreach ($this as $newnode) {
/** @var \DOMNode $newnode */
if ($node !== $newnode) {
$newnode = static::importNewnode($newnode, $node, $i);
$node->appendChild($newnode);
}
$newnodes[] = $newnode;
}
}
return self::create($newnodes);
} | [
"public",
"function",
"appendTo",
"(",
"$",
"element",
")",
"{",
"$",
"e",
"=",
"self",
"::",
"create",
"(",
"$",
"element",
")",
";",
"$",
"newnodes",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"e",
"as",
"$",
"i",
"=>",
"$",
"node",
")... | Insert every element in the set of matched elements to the end of the target.
@param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $element
@return \Wa72\HtmlPageDom\HtmlPageCrawler A new Crawler object containing all elements appended to the target elements
@api | [
"Insert",
"every",
"element",
"in",
"the",
"set",
"of",
"matched",
"elements",
"to",
"the",
"end",
"of",
"the",
"target",
"."
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L131-L147 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.setAttribute | public function setAttribute($name, $value)
{
foreach ($this as $node) {
if ($node instanceof \DOMElement) {
/** @var \DOMElement $node */
$node->setAttribute($name, $value);
}
}
return $this;
} | php | public function setAttribute($name, $value)
{
foreach ($this as $node) {
if ($node instanceof \DOMElement) {
/** @var \DOMElement $node */
$node->setAttribute($name, $value);
}
}
return $this;
} | [
"public",
"function",
"setAttribute",
"(",
"$",
"name",
",",
"$",
"value",
")",
"{",
"foreach",
"(",
"$",
"this",
"as",
"$",
"node",
")",
"{",
"if",
"(",
"$",
"node",
"instanceof",
"\\",
"DOMElement",
")",
"{",
"/** @var \\DOMElement $node */",
"$",
"nod... | Sets an attribute on each element
@param string $name
@param string $value
@return HtmlPageCrawler $this for chaining | [
"Sets",
"an",
"attribute",
"on",
"each",
"element"
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L176-L185 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.getAttribute | public function getAttribute($name)
{
if (!count($this)) {
throw new \InvalidArgumentException('The current node list is empty.');
}
$node = $this->getNode(0);
return $node->hasAttribute($name) ? $node->getAttribute($name) : null;
} | php | public function getAttribute($name)
{
if (!count($this)) {
throw new \InvalidArgumentException('The current node list is empty.');
}
$node = $this->getNode(0);
return $node->hasAttribute($name) ? $node->getAttribute($name) : null;
} | [
"public",
"function",
"getAttribute",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"count",
"(",
"$",
"this",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'The current node list is empty.'",
")",
";",
"}",
"$",
"node",
"=",
"$",
... | Returns the attribute value of the first node of the list.
@param string $name The attribute name
@return string|null The attribute value or null if the attribute does not exist
@throws \InvalidArgumentException When current node is empty | [
"Returns",
"the",
"attribute",
"value",
"of",
"the",
"first",
"node",
"of",
"the",
"list",
"."
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L195-L202 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.before | public function before($content)
{
$content = self::create($content);
$newnodes = array();
foreach ($this as $i => $node) {
/** @var \DOMNode $node */
foreach ($content as $newnode) {
/** @var \DOMNode $newnode */
if ($node !== $newnode) {
$newnode = static::importNewnode($newnode, $node, $i);
$node->parentNode->insertBefore($newnode, $node);
$newnodes[] = $newnode;
}
}
}
$content->clear();
$content->add($newnodes);
return $this;
} | php | public function before($content)
{
$content = self::create($content);
$newnodes = array();
foreach ($this as $i => $node) {
/** @var \DOMNode $node */
foreach ($content as $newnode) {
/** @var \DOMNode $newnode */
if ($node !== $newnode) {
$newnode = static::importNewnode($newnode, $node, $i);
$node->parentNode->insertBefore($newnode, $node);
$newnodes[] = $newnode;
}
}
}
$content->clear();
$content->add($newnodes);
return $this;
} | [
"public",
"function",
"before",
"(",
"$",
"content",
")",
"{",
"$",
"content",
"=",
"self",
"::",
"create",
"(",
"$",
"content",
")",
";",
"$",
"newnodes",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"as",
"$",
"i",
"=>",
"$",
"node... | Insert content, specified by the parameter, before each element in the set of matched elements.
@param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $content
@return HtmlPageCrawler $this for chaining
@api | [
"Insert",
"content",
"specified",
"by",
"the",
"parameter",
"before",
"each",
"element",
"in",
"the",
"set",
"of",
"matched",
"elements",
"."
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L211-L229 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.css | public function css($key, $value = null)
{
if (null === $value) {
return $this->getStyle($key);
} else {
return $this->setStyle($key, $value);
}
} | php | public function css($key, $value = null)
{
if (null === $value) {
return $this->getStyle($key);
} else {
return $this->setStyle($key, $value);
}
} | [
"public",
"function",
"css",
"(",
"$",
"key",
",",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"value",
")",
"{",
"return",
"$",
"this",
"->",
"getStyle",
"(",
"$",
"key",
")",
";",
"}",
"else",
"{",
"return",
"$",
"this... | Get one CSS style property of the first element or set it for all elements in the list
Function is here for compatibility with jQuery; it is the same as getStyle() and setStyle()
@see HtmlPageCrawler::getStyle()
@see HtmlPageCrawler::setStyle()
@param string $key The name of the style property
@param null|string $value The CSS value to set, or NULL to get the current value
@return HtmlPageCrawler|string If no param is provided, returns the CSS styles of the first element
@api | [
"Get",
"one",
"CSS",
"style",
"property",
"of",
"the",
"first",
"element",
"or",
"set",
"it",
"for",
"all",
"elements",
"in",
"the",
"list"
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L268-L275 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.getStyle | public function getStyle($key)
{
$styles = Helpers::cssStringToArray($this->getAttribute('style'));
return (isset($styles[$key]) ? $styles[$key] : null);
} | php | public function getStyle($key)
{
$styles = Helpers::cssStringToArray($this->getAttribute('style'));
return (isset($styles[$key]) ? $styles[$key] : null);
} | [
"public",
"function",
"getStyle",
"(",
"$",
"key",
")",
"{",
"$",
"styles",
"=",
"Helpers",
"::",
"cssStringToArray",
"(",
"$",
"this",
"->",
"getAttribute",
"(",
"'style'",
")",
")",
";",
"return",
"(",
"isset",
"(",
"$",
"styles",
"[",
"$",
"key",
... | get one CSS style property of the first element
@param string $key name of the property
@return string|null value of the property | [
"get",
"one",
"CSS",
"style",
"property",
"of",
"the",
"first",
"element"
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L283-L287 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.setStyle | public function setStyle($key, $value)
{
foreach ($this as $node) {
if ($node instanceof \DOMElement) {
/** @var \DOMElement $node */
$styles = Helpers::cssStringToArray($node->getAttribute('style'));
if ($value != '') {
$styles[$key] = $value;
} elseif (isset($styles[$key])) {
unset($styles[$key]);
}
$node->setAttribute('style', Helpers::cssArrayToString($styles));
}
}
return $this;
} | php | public function setStyle($key, $value)
{
foreach ($this as $node) {
if ($node instanceof \DOMElement) {
/** @var \DOMElement $node */
$styles = Helpers::cssStringToArray($node->getAttribute('style'));
if ($value != '') {
$styles[$key] = $value;
} elseif (isset($styles[$key])) {
unset($styles[$key]);
}
$node->setAttribute('style', Helpers::cssArrayToString($styles));
}
}
return $this;
} | [
"public",
"function",
"setStyle",
"(",
"$",
"key",
",",
"$",
"value",
")",
"{",
"foreach",
"(",
"$",
"this",
"as",
"$",
"node",
")",
"{",
"if",
"(",
"$",
"node",
"instanceof",
"\\",
"DOMElement",
")",
"{",
"/** @var \\DOMElement $node */",
"$",
"styles",... | set one CSS style property for all elements in the list
@param string $key name of the property
@param string $value value of the property
@return HtmlPageCrawler $this for chaining | [
"set",
"one",
"CSS",
"style",
"property",
"for",
"all",
"elements",
"in",
"the",
"list"
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L296-L311 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.hasClass | public function hasClass($name)
{
foreach ($this as $node) {
if ($node instanceof \DOMElement && $class = $node->getAttribute('class')) {
$classes = preg_split('/\s+/s', $class);
if (in_array($name, $classes)) {
return true;
}
}
}
return false;
} | php | public function hasClass($name)
{
foreach ($this as $node) {
if ($node instanceof \DOMElement && $class = $node->getAttribute('class')) {
$classes = preg_split('/\s+/s', $class);
if (in_array($name, $classes)) {
return true;
}
}
}
return false;
} | [
"public",
"function",
"hasClass",
"(",
"$",
"name",
")",
"{",
"foreach",
"(",
"$",
"this",
"as",
"$",
"node",
")",
"{",
"if",
"(",
"$",
"node",
"instanceof",
"\\",
"DOMElement",
"&&",
"$",
"class",
"=",
"$",
"node",
"->",
"getAttribute",
"(",
"'class... | Determine whether any of the matched elements are assigned the given class.
@param string $name
@return bool
@api | [
"Determine",
"whether",
"any",
"of",
"the",
"matched",
"elements",
"are",
"assigned",
"the",
"given",
"class",
"."
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L335-L346 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.setInnerHtml | public function setInnerHtml($content)
{
$content = self::create($content);
foreach ($this as $node) {
$node->nodeValue = '';
foreach ($content as $newnode) {
/** @var \DOMNode $node */
/** @var \DOMNode $newnode */
$newnode = static::importNewnode($newnode, $node);
$node->appendChild($newnode);
}
}
return $this;
} | php | public function setInnerHtml($content)
{
$content = self::create($content);
foreach ($this as $node) {
$node->nodeValue = '';
foreach ($content as $newnode) {
/** @var \DOMNode $node */
/** @var \DOMNode $newnode */
$newnode = static::importNewnode($newnode, $node);
$node->appendChild($newnode);
}
}
return $this;
} | [
"public",
"function",
"setInnerHtml",
"(",
"$",
"content",
")",
"{",
"$",
"content",
"=",
"self",
"::",
"create",
"(",
"$",
"content",
")",
";",
"foreach",
"(",
"$",
"this",
"as",
"$",
"node",
")",
"{",
"$",
"node",
"->",
"nodeValue",
"=",
"''",
";... | Set the HTML contents of each element
@param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $content HTML code fragment
@return HtmlPageCrawler $this for chaining | [
"Set",
"the",
"HTML",
"contents",
"of",
"each",
"element"
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L354-L367 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.insertAfter | public function insertAfter($element)
{
$e = self::create($element);
$newnodes = array();
foreach ($e as $i => $node) {
/** @var \DOMNode $node */
$refnode = $node->nextSibling;
foreach ($this as $newnode) {
/** @var \DOMNode $newnode */
$newnode = static::importNewnode($newnode, $node, $i);
if ($refnode === null) {
$node->parentNode->appendChild($newnode);
} else {
$node->parentNode->insertBefore($newnode, $refnode);
}
$newnodes[] = $newnode;
}
}
return self::create($newnodes);
} | php | public function insertAfter($element)
{
$e = self::create($element);
$newnodes = array();
foreach ($e as $i => $node) {
/** @var \DOMNode $node */
$refnode = $node->nextSibling;
foreach ($this as $newnode) {
/** @var \DOMNode $newnode */
$newnode = static::importNewnode($newnode, $node, $i);
if ($refnode === null) {
$node->parentNode->appendChild($newnode);
} else {
$node->parentNode->insertBefore($newnode, $refnode);
}
$newnodes[] = $newnode;
}
}
return self::create($newnodes);
} | [
"public",
"function",
"insertAfter",
"(",
"$",
"element",
")",
"{",
"$",
"e",
"=",
"self",
"::",
"create",
"(",
"$",
"element",
")",
";",
"$",
"newnodes",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"e",
"as",
"$",
"i",
"=>",
"$",
"node",
... | Insert every element in the set of matched elements after the target.
@param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $element
@return \Wa72\HtmlPageDom\HtmlPageCrawler A new Crawler object containing all elements appended to the target elements
@api | [
"Insert",
"every",
"element",
"in",
"the",
"set",
"of",
"matched",
"elements",
"after",
"the",
"target",
"."
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L376-L395 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.insertBefore | public function insertBefore($element)
{
$e = self::create($element);
$newnodes = array();
foreach ($e as $i => $node) {
/** @var \DOMNode $node */
foreach ($this as $newnode) {
/** @var \DOMNode $newnode */
$newnode = static::importNewnode($newnode, $node, $i);
if ($newnode !== $node) {
$node->parentNode->insertBefore($newnode, $node);
}
$newnodes[] = $newnode;
}
}
return self::create($newnodes);
} | php | public function insertBefore($element)
{
$e = self::create($element);
$newnodes = array();
foreach ($e as $i => $node) {
/** @var \DOMNode $node */
foreach ($this as $newnode) {
/** @var \DOMNode $newnode */
$newnode = static::importNewnode($newnode, $node, $i);
if ($newnode !== $node) {
$node->parentNode->insertBefore($newnode, $node);
}
$newnodes[] = $newnode;
}
}
return self::create($newnodes);
} | [
"public",
"function",
"insertBefore",
"(",
"$",
"element",
")",
"{",
"$",
"e",
"=",
"self",
"::",
"create",
"(",
"$",
"element",
")",
";",
"$",
"newnodes",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"e",
"as",
"$",
"i",
"=>",
"$",
"node",
... | Insert every element in the set of matched elements before the target.
@param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $element
@return \Wa72\HtmlPageDom\HtmlPageCrawler A new Crawler object containing all elements appended to the target elements
@api | [
"Insert",
"every",
"element",
"in",
"the",
"set",
"of",
"matched",
"elements",
"before",
"the",
"target",
"."
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L404-L420 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.prepend | public function prepend($content)
{
$content = self::create($content);
$newnodes = array();
foreach ($this as $i => $node) {
$refnode = $node->firstChild;
/** @var \DOMNode $node */
foreach ($content as $newnode) {
/** @var \DOMNode $newnode */
$newnode = static::importNewnode($newnode, $node, $i);
if ($refnode === null) {
$node->appendChild($newnode);
} else if ($refnode !== $newnode) {
$node->insertBefore($newnode, $refnode);
}
$newnodes[] = $newnode;
}
}
$content->clear();
$content->add($newnodes);
return $this;
} | php | public function prepend($content)
{
$content = self::create($content);
$newnodes = array();
foreach ($this as $i => $node) {
$refnode = $node->firstChild;
/** @var \DOMNode $node */
foreach ($content as $newnode) {
/** @var \DOMNode $newnode */
$newnode = static::importNewnode($newnode, $node, $i);
if ($refnode === null) {
$node->appendChild($newnode);
} else if ($refnode !== $newnode) {
$node->insertBefore($newnode, $refnode);
}
$newnodes[] = $newnode;
}
}
$content->clear();
$content->add($newnodes);
return $this;
} | [
"public",
"function",
"prepend",
"(",
"$",
"content",
")",
"{",
"$",
"content",
"=",
"self",
"::",
"create",
"(",
"$",
"content",
")",
";",
"$",
"newnodes",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"as",
"$",
"i",
"=>",
"$",
"nod... | Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
@param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $content HTML code fragment
@return HtmlPageCrawler $this for chaining
@api | [
"Insert",
"content",
"specified",
"by",
"the",
"parameter",
"to",
"the",
"beginning",
"of",
"each",
"element",
"in",
"the",
"set",
"of",
"matched",
"elements",
"."
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L429-L450 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.prependTo | public function prependTo($element)
{
$e = self::create($element);
$newnodes = array();
foreach ($e as $i => $node) {
$refnode = $node->firstChild;
/** @var \DOMNode $node */
foreach ($this as $newnode) {
/** @var \DOMNode $newnode */
$newnode = static::importNewnode($newnode, $node, $i);
if ($newnode !== $node) {
if ($refnode === null) {
$node->appendChild($newnode);
} else {
$node->insertBefore($newnode, $refnode);
}
}
$newnodes[] = $newnode;
}
}
return self::create($newnodes);
} | php | public function prependTo($element)
{
$e = self::create($element);
$newnodes = array();
foreach ($e as $i => $node) {
$refnode = $node->firstChild;
/** @var \DOMNode $node */
foreach ($this as $newnode) {
/** @var \DOMNode $newnode */
$newnode = static::importNewnode($newnode, $node, $i);
if ($newnode !== $node) {
if ($refnode === null) {
$node->appendChild($newnode);
} else {
$node->insertBefore($newnode, $refnode);
}
}
$newnodes[] = $newnode;
}
}
return self::create($newnodes);
} | [
"public",
"function",
"prependTo",
"(",
"$",
"element",
")",
"{",
"$",
"e",
"=",
"self",
"::",
"create",
"(",
"$",
"element",
")",
";",
"$",
"newnodes",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"e",
"as",
"$",
"i",
"=>",
"$",
"node",
"... | Insert every element in the set of matched elements to the beginning of the target.
@param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $element
@return \Wa72\HtmlPageDom\HtmlPageCrawler A new Crawler object containing all elements prepended to the target elements
@api | [
"Insert",
"every",
"element",
"in",
"the",
"set",
"of",
"matched",
"elements",
"to",
"the",
"beginning",
"of",
"the",
"target",
"."
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L459-L480 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.remove | public function remove()
{
foreach ($this as $node) {
/**
* @var \DOMNode $node
*/
if ($node->parentNode instanceof \DOMElement) {
$node->parentNode->removeChild($node);
}
}
$this->clear();
} | php | public function remove()
{
foreach ($this as $node) {
/**
* @var \DOMNode $node
*/
if ($node->parentNode instanceof \DOMElement) {
$node->parentNode->removeChild($node);
}
}
$this->clear();
} | [
"public",
"function",
"remove",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"as",
"$",
"node",
")",
"{",
"/**\n * @var \\DOMNode $node\n */",
"if",
"(",
"$",
"node",
"->",
"parentNode",
"instanceof",
"\\",
"DOMElement",
")",
"{",
"$",
"... | Remove the set of matched elements from the DOM.
(as opposed to Crawler::clear() which detaches the nodes only from Crawler
but leaves them in the DOM)
@api | [
"Remove",
"the",
"set",
"of",
"matched",
"elements",
"from",
"the",
"DOM",
"."
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L490-L501 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.removeAttribute | public function removeAttribute($name)
{
foreach ($this as $node) {
if ($node instanceof \DOMElement) {
/** @var \DOMElement $node */
if ($node->hasAttribute($name)) {
$node->removeAttribute($name);
}
}
}
return $this;
} | php | public function removeAttribute($name)
{
foreach ($this as $node) {
if ($node instanceof \DOMElement) {
/** @var \DOMElement $node */
if ($node->hasAttribute($name)) {
$node->removeAttribute($name);
}
}
}
return $this;
} | [
"public",
"function",
"removeAttribute",
"(",
"$",
"name",
")",
"{",
"foreach",
"(",
"$",
"this",
"as",
"$",
"node",
")",
"{",
"if",
"(",
"$",
"node",
"instanceof",
"\\",
"DOMElement",
")",
"{",
"/** @var \\DOMElement $node */",
"if",
"(",
"$",
"node",
"... | Remove an attribute from each element in the set of matched elements.
@param string $name
@return HtmlPageCrawler | [
"Remove",
"an",
"attribute",
"from",
"each",
"element",
"in",
"the",
"set",
"of",
"matched",
"elements",
"."
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L523-L534 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.removeClass | public function removeClass($name)
{
foreach ($this as $node) {
if ($node instanceof \DOMElement) {
/** @var \DOMElement $node */
$classes = preg_split('/\s+/s', $node->getAttribute('class'));
$count = count($classes);
for ($i = 0; $i < $count; $i++) {
if ($classes[$i] == $name) {
unset($classes[$i]);
}
}
$node->setAttribute('class', trim(join(' ', $classes)));
}
}
return $this;
} | php | public function removeClass($name)
{
foreach ($this as $node) {
if ($node instanceof \DOMElement) {
/** @var \DOMElement $node */
$classes = preg_split('/\s+/s', $node->getAttribute('class'));
$count = count($classes);
for ($i = 0; $i < $count; $i++) {
if ($classes[$i] == $name) {
unset($classes[$i]);
}
}
$node->setAttribute('class', trim(join(' ', $classes)));
}
}
return $this;
} | [
"public",
"function",
"removeClass",
"(",
"$",
"name",
")",
"{",
"foreach",
"(",
"$",
"this",
"as",
"$",
"node",
")",
"{",
"if",
"(",
"$",
"node",
"instanceof",
"\\",
"DOMElement",
")",
"{",
"/** @var \\DOMElement $node */",
"$",
"classes",
"=",
"preg_spli... | Remove a class from each element in the list
@param string $name
@return HtmlPageCrawler $this for chaining
@api | [
"Remove",
"a",
"class",
"from",
"each",
"element",
"in",
"the",
"list"
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L543-L559 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.replaceAll | public function replaceAll($element)
{
$e = self::create($element);
$newnodes = array();
foreach ($e as $i => $node) {
/** @var \DOMNode $node */
$parent = $node->parentNode;
$refnode = $node->nextSibling;
foreach ($this as $j => $newnode) {
/** @var \DOMNode $newnode */
$newnode = static::importNewnode($newnode, $node, $i);
if ($j == 0) {
$parent->replaceChild($newnode, $node);
} else {
$parent->insertBefore($newnode, $refnode);
}
$newnodes[] = $newnode;
}
}
return self::create($newnodes);
} | php | public function replaceAll($element)
{
$e = self::create($element);
$newnodes = array();
foreach ($e as $i => $node) {
/** @var \DOMNode $node */
$parent = $node->parentNode;
$refnode = $node->nextSibling;
foreach ($this as $j => $newnode) {
/** @var \DOMNode $newnode */
$newnode = static::importNewnode($newnode, $node, $i);
if ($j == 0) {
$parent->replaceChild($newnode, $node);
} else {
$parent->insertBefore($newnode, $refnode);
}
$newnodes[] = $newnode;
}
}
return self::create($newnodes);
} | [
"public",
"function",
"replaceAll",
"(",
"$",
"element",
")",
"{",
"$",
"e",
"=",
"self",
"::",
"create",
"(",
"$",
"element",
")",
";",
"$",
"newnodes",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"e",
"as",
"$",
"i",
"=>",
"$",
"node",
... | Replace each target element with the set of matched elements.
@param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $element
@return \Wa72\HtmlPageDom\HtmlPageCrawler A new Crawler object containing all elements appended to the target elements
@api | [
"Replace",
"each",
"target",
"element",
"with",
"the",
"set",
"of",
"matched",
"elements",
"."
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L568-L588 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.replaceWith | public function replaceWith($content)
{
$content = self::create($content);
$newnodes = array();
foreach ($this as $i => $node) {
/** @var \DOMNode $node */
$parent = $node->parentNode;
$refnode = $node->nextSibling;
foreach ($content as $j => $newnode) {
/** @var \DOMNode $newnode */
$newnode = static::importNewnode($newnode, $node, $i);
if ($j == 0) {
$parent->replaceChild($newnode, $node);
} else {
$parent->insertBefore($newnode, $refnode);
}
$newnodes[] = $newnode;
}
}
$content->clear();
$content->add($newnodes);
return $this;
} | php | public function replaceWith($content)
{
$content = self::create($content);
$newnodes = array();
foreach ($this as $i => $node) {
/** @var \DOMNode $node */
$parent = $node->parentNode;
$refnode = $node->nextSibling;
foreach ($content as $j => $newnode) {
/** @var \DOMNode $newnode */
$newnode = static::importNewnode($newnode, $node, $i);
if ($j == 0) {
$parent->replaceChild($newnode, $node);
} else {
$parent->insertBefore($newnode, $refnode);
}
$newnodes[] = $newnode;
}
}
$content->clear();
$content->add($newnodes);
return $this;
} | [
"public",
"function",
"replaceWith",
"(",
"$",
"content",
")",
"{",
"$",
"content",
"=",
"self",
"::",
"create",
"(",
"$",
"content",
")",
";",
"$",
"newnodes",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"as",
"$",
"i",
"=>",
"$",
... | Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed.
@param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $content
@return \Wa72\HtmlPageDom\HtmlPageCrawler $this for chaining
@api | [
"Replace",
"each",
"element",
"in",
"the",
"set",
"of",
"matched",
"elements",
"with",
"the",
"provided",
"new",
"content",
"and",
"return",
"the",
"set",
"of",
"elements",
"that",
"was",
"removed",
"."
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L597-L619 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.