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 |
|---|---|---|---|---|---|---|---|---|---|---|
fxpio/composer-asset-plugin | Util/Perforce.php | Perforce.create | public static function create($repoConfig, $port, $path, ProcessExecutor $process, IOInterface $io)
{
$isWindows = \defined('PHP_WINDOWS_VERSION_BUILD');
return new self($repoConfig, $port, $path, $process, $isWindows, $io);
} | php | public static function create($repoConfig, $port, $path, ProcessExecutor $process, IOInterface $io)
{
$isWindows = \defined('PHP_WINDOWS_VERSION_BUILD');
return new self($repoConfig, $port, $path, $process, $isWindows, $io);
} | [
"public",
"static",
"function",
"create",
"(",
"$",
"repoConfig",
",",
"$",
"port",
",",
"$",
"path",
",",
"ProcessExecutor",
"$",
"process",
",",
"IOInterface",
"$",
"io",
")",
"{",
"$",
"isWindows",
"=",
"\\",
"defined",
"(",
"'PHP_WINDOWS_VERSION_BUILD'",... | Create perforce helper.
@param array $repoConfig
@param int|string $port
@param string $path
@param ProcessExecutor $process
@param IOInterface $io
@return Perforce | [
"Create",
"perforce",
"helper",
"."
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Util/Perforce.php#L65-L70 |
fxpio/composer-asset-plugin | Repository/AbstractAssetsRepository.php | AbstractAssetsRepository.search | public function search($query, $mode = 0, $type = null)
{
if (!$this->searchable) {
return array();
}
$url = str_replace('%query%', urlencode(Util::cleanPackageName($query)), $this->searchUrl);
$hostname = (string) parse_url($url, PHP_URL_HOST) ?: $url;
$json = (string) $this->rfs->getContents($hostname, $url, false);
$data = JsonFile::parseJson($json, $url);
$results = array();
/** @var array $item */
foreach ($data as $item) {
$results[] = $this->createSearchItem($item);
}
return $results;
} | php | public function search($query, $mode = 0, $type = null)
{
if (!$this->searchable) {
return array();
}
$url = str_replace('%query%', urlencode(Util::cleanPackageName($query)), $this->searchUrl);
$hostname = (string) parse_url($url, PHP_URL_HOST) ?: $url;
$json = (string) $this->rfs->getContents($hostname, $url, false);
$data = JsonFile::parseJson($json, $url);
$results = array();
/** @var array $item */
foreach ($data as $item) {
$results[] = $this->createSearchItem($item);
}
return $results;
} | [
"public",
"function",
"search",
"(",
"$",
"query",
",",
"$",
"mode",
"=",
"0",
",",
"$",
"type",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"searchable",
")",
"{",
"return",
"array",
"(",
")",
";",
"}",
"$",
"url",
"=",
"str_repl... | {@inheritdoc} | [
"{"
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Repository/AbstractAssetsRepository.php#L101-L119 |
fxpio/composer-asset-plugin | Repository/AbstractAssetsRepository.php | AbstractAssetsRepository.whatProvides | public function whatProvides(Pool $pool, $name, $bypassFilters = false)
{
if (null !== $provides = $this->findWhatProvides($name)) {
return $provides;
}
try {
$repoName = Util::convertAliasName($name);
$packageName = Util::cleanPackageName($repoName);
$packageUrl = $this->buildPackageUrl($packageName);
$cacheName = $packageName.'-'.sha1($packageName).'-package.json';
$data = $this->fetchFile($packageUrl, $cacheName);
$repo = $this->createVcsRepositoryConfig($data, Util::cleanPackageName($name));
$repo['asset-repository-manager'] = $this->assetRepositoryManager;
$repo['vcs-package-filter'] = $this->packageFilter;
$repo['vcs-driver-options'] = Util::getArrayValue($this->repoConfig, 'vcs-driver-options', array());
Util::addRepository($this->io, $this->repositoryManager, $this->repos, $name, $repo, $pool);
$this->providers[$name] = array();
} catch (\Exception $ex) {
$this->whatProvidesManageException($pool, $name, $ex);
}
return $this->providers[$name];
} | php | public function whatProvides(Pool $pool, $name, $bypassFilters = false)
{
if (null !== $provides = $this->findWhatProvides($name)) {
return $provides;
}
try {
$repoName = Util::convertAliasName($name);
$packageName = Util::cleanPackageName($repoName);
$packageUrl = $this->buildPackageUrl($packageName);
$cacheName = $packageName.'-'.sha1($packageName).'-package.json';
$data = $this->fetchFile($packageUrl, $cacheName);
$repo = $this->createVcsRepositoryConfig($data, Util::cleanPackageName($name));
$repo['asset-repository-manager'] = $this->assetRepositoryManager;
$repo['vcs-package-filter'] = $this->packageFilter;
$repo['vcs-driver-options'] = Util::getArrayValue($this->repoConfig, 'vcs-driver-options', array());
Util::addRepository($this->io, $this->repositoryManager, $this->repos, $name, $repo, $pool);
$this->providers[$name] = array();
} catch (\Exception $ex) {
$this->whatProvidesManageException($pool, $name, $ex);
}
return $this->providers[$name];
} | [
"public",
"function",
"whatProvides",
"(",
"Pool",
"$",
"pool",
",",
"$",
"name",
",",
"$",
"bypassFilters",
"=",
"false",
")",
"{",
"if",
"(",
"null",
"!==",
"$",
"provides",
"=",
"$",
"this",
"->",
"findWhatProvides",
"(",
"$",
"name",
")",
")",
"{... | {@inheritdoc} | [
"{"
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Repository/AbstractAssetsRepository.php#L124-L149 |
fxpio/composer-asset-plugin | Repository/AbstractAssetsRepository.php | AbstractAssetsRepository.findWhatProvides | protected function findWhatProvides($name)
{
$assetPrefix = $this->assetType->getComposerVendorName().'/';
if (false === strpos($name, $assetPrefix)) {
return array();
}
if (isset($this->providers[$name])) {
return $this->providers[$name];
}
$data = null;
if ($this->hasVcsRepository($name)) {
$this->providers[$name] = array();
$data = $this->providers[$name];
}
return $data;
} | php | protected function findWhatProvides($name)
{
$assetPrefix = $this->assetType->getComposerVendorName().'/';
if (false === strpos($name, $assetPrefix)) {
return array();
}
if (isset($this->providers[$name])) {
return $this->providers[$name];
}
$data = null;
if ($this->hasVcsRepository($name)) {
$this->providers[$name] = array();
$data = $this->providers[$name];
}
return $data;
} | [
"protected",
"function",
"findWhatProvides",
"(",
"$",
"name",
")",
"{",
"$",
"assetPrefix",
"=",
"$",
"this",
"->",
"assetType",
"->",
"getComposerVendorName",
"(",
")",
".",
"'/'",
";",
"if",
"(",
"false",
"===",
"strpos",
"(",
"$",
"name",
",",
"$",
... | Finds what provides in cache or return empty array if the
name is not a asset package.
@param string $name
@return null|array | [
"Finds",
"what",
"provides",
"in",
"cache",
"or",
"return",
"empty",
"array",
"if",
"the",
"name",
"is",
"not",
"a",
"asset",
"package",
"."
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Repository/AbstractAssetsRepository.php#L179-L198 |
fxpio/composer-asset-plugin | Repository/AbstractAssetsRepository.php | AbstractAssetsRepository.hasVcsRepository | protected function hasVcsRepository($name)
{
foreach ($this->repositoryManager->getRepositories() as $mRepo) {
if ($mRepo instanceof AssetVcsRepository
&& $name === $mRepo->getComposerPackageName()) {
return true;
}
}
return false;
} | php | protected function hasVcsRepository($name)
{
foreach ($this->repositoryManager->getRepositories() as $mRepo) {
if ($mRepo instanceof AssetVcsRepository
&& $name === $mRepo->getComposerPackageName()) {
return true;
}
}
return false;
} | [
"protected",
"function",
"hasVcsRepository",
"(",
"$",
"name",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"repositoryManager",
"->",
"getRepositories",
"(",
")",
"as",
"$",
"mRepo",
")",
"{",
"if",
"(",
"$",
"mRepo",
"instanceof",
"AssetVcsRepository",
"&&... | Checks if the package vcs repository is already include in repository manager.
@param string $name The package name of the vcs repository
@return bool | [
"Checks",
"if",
"the",
"package",
"vcs",
"repository",
"is",
"already",
"include",
"in",
"repository",
"manager",
"."
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Repository/AbstractAssetsRepository.php#L207-L217 |
fxpio/composer-asset-plugin | Repository/AbstractAssetsRepository.php | AbstractAssetsRepository.whatProvidesManageException | protected function whatProvidesManageException(Pool $pool, $name, \Exception $exception)
{
if ($exception instanceof TransportException) {
$this->fallbackWathProvides($pool, $name, $exception);
return;
}
throw $exception;
} | php | protected function whatProvidesManageException(Pool $pool, $name, \Exception $exception)
{
if ($exception instanceof TransportException) {
$this->fallbackWathProvides($pool, $name, $exception);
return;
}
throw $exception;
} | [
"protected",
"function",
"whatProvidesManageException",
"(",
"Pool",
"$",
"pool",
",",
"$",
"name",
",",
"\\",
"Exception",
"$",
"exception",
")",
"{",
"if",
"(",
"$",
"exception",
"instanceof",
"TransportException",
")",
"{",
"$",
"this",
"->",
"fallbackWathP... | Manage exception for "whatProvides" method.
@param Pool $pool
@param string $name
@param \Exception $exception
@throws \Exception When exception is not a TransportException instance | [
"Manage",
"exception",
"for",
"whatProvides",
"method",
"."
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Repository/AbstractAssetsRepository.php#L271-L280 |
fxpio/composer-asset-plugin | Repository/AbstractAssetsRepository.php | AbstractAssetsRepository.fallbackWathProvides | protected function fallbackWathProvides(Pool $pool, $name, TransportException $ex)
{
$providers = array();
if (404 === $ex->getCode() && !$this->fallbackProviders) {
$this->fallbackProviders = true;
$repoName = Util::convertAliasName($name);
$results = $this->search($repoName);
foreach ($results as $item) {
if ($name === strtolower($item['name'])) {
$providers = $this->whatProvides($pool, $item['name']);
break;
}
}
}
$this->fallbackProviders = false;
$this->providers[$name] = $providers;
} | php | protected function fallbackWathProvides(Pool $pool, $name, TransportException $ex)
{
$providers = array();
if (404 === $ex->getCode() && !$this->fallbackProviders) {
$this->fallbackProviders = true;
$repoName = Util::convertAliasName($name);
$results = $this->search($repoName);
foreach ($results as $item) {
if ($name === strtolower($item['name'])) {
$providers = $this->whatProvides($pool, $item['name']);
break;
}
}
}
$this->fallbackProviders = false;
$this->providers[$name] = $providers;
} | [
"protected",
"function",
"fallbackWathProvides",
"(",
"Pool",
"$",
"pool",
",",
"$",
"name",
",",
"TransportException",
"$",
"ex",
")",
"{",
"$",
"providers",
"=",
"array",
"(",
")",
";",
"if",
"(",
"404",
"===",
"$",
"ex",
"->",
"getCode",
"(",
")",
... | Searchs if the registry has a package with the same name exists with a
different camelcase.
@param Pool $pool
@param string $name
@param TransportException $ex | [
"Searchs",
"if",
"the",
"registry",
"has",
"a",
"package",
"with",
"the",
"same",
"name",
"exists",
"with",
"a",
"different",
"camelcase",
"."
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Repository/AbstractAssetsRepository.php#L290-L310 |
fxpio/composer-asset-plugin | Installer/IgnoreManager.php | IgnoreManager.addPattern | public function addPattern($pattern)
{
$this->doAddPattern($this->convertPattern($pattern));
$this->hasPattern = true;
} | php | public function addPattern($pattern)
{
$this->doAddPattern($this->convertPattern($pattern));
$this->hasPattern = true;
} | [
"public",
"function",
"addPattern",
"(",
"$",
"pattern",
")",
"{",
"$",
"this",
"->",
"doAddPattern",
"(",
"$",
"this",
"->",
"convertPattern",
"(",
"$",
"pattern",
")",
")",
";",
"$",
"this",
"->",
"hasPattern",
"=",
"true",
";",
"}"
] | Adds an ignore pattern.
@param string $pattern The pattern | [
"Adds",
"an",
"ignore",
"pattern",
"."
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Installer/IgnoreManager.php#L105-L109 |
fxpio/composer-asset-plugin | Installer/IgnoreManager.php | IgnoreManager.cleanup | public function cleanup()
{
if ($this->isEnabled() && $this->hasPattern() && realpath($this->installDir)) {
$paths = iterator_to_array($this->finder->in($this->installDir));
/** @var \SplFileInfo $path */
foreach ($paths as $path) {
$this->filesystem->remove($path);
}
}
} | php | public function cleanup()
{
if ($this->isEnabled() && $this->hasPattern() && realpath($this->installDir)) {
$paths = iterator_to_array($this->finder->in($this->installDir));
/** @var \SplFileInfo $path */
foreach ($paths as $path) {
$this->filesystem->remove($path);
}
}
} | [
"public",
"function",
"cleanup",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isEnabled",
"(",
")",
"&&",
"$",
"this",
"->",
"hasPattern",
"(",
")",
"&&",
"realpath",
"(",
"$",
"this",
"->",
"installDir",
")",
")",
"{",
"$",
"paths",
"=",
"iterato... | Deletes all files and directories that matches patterns. | [
"Deletes",
"all",
"files",
"and",
"directories",
"that",
"matches",
"patterns",
"."
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Installer/IgnoreManager.php#L114-L124 |
fxpio/composer-asset-plugin | Installer/IgnoreManager.php | IgnoreManager.doAddPattern | public function doAddPattern($pattern)
{
if (0 === strpos($pattern, '!')) {
$searchPattern = substr($pattern, 1);
$this->finder->notPath(Glob::toRegex($searchPattern, true, true));
$pathComponents = explode('/', $searchPattern);
if (1 < \count($pathComponents)) {
$parentDirectories = \array_slice($pathComponents, 0, -1);
$basePath = '';
foreach ($parentDirectories as $dir) {
$this->finder->notPath('/\b('.preg_quote($basePath.$dir, '/').')(?!\/)\b/');
$basePath .= $dir.'/';
}
}
} else {
$this->finder->path(Glob::toRegex($pattern, true, true));
}
} | php | public function doAddPattern($pattern)
{
if (0 === strpos($pattern, '!')) {
$searchPattern = substr($pattern, 1);
$this->finder->notPath(Glob::toRegex($searchPattern, true, true));
$pathComponents = explode('/', $searchPattern);
if (1 < \count($pathComponents)) {
$parentDirectories = \array_slice($pathComponents, 0, -1);
$basePath = '';
foreach ($parentDirectories as $dir) {
$this->finder->notPath('/\b('.preg_quote($basePath.$dir, '/').')(?!\/)\b/');
$basePath .= $dir.'/';
}
}
} else {
$this->finder->path(Glob::toRegex($pattern, true, true));
}
} | [
"public",
"function",
"doAddPattern",
"(",
"$",
"pattern",
")",
"{",
"if",
"(",
"0",
"===",
"strpos",
"(",
"$",
"pattern",
",",
"'!'",
")",
")",
"{",
"$",
"searchPattern",
"=",
"substr",
"(",
"$",
"pattern",
",",
"1",
")",
";",
"$",
"this",
"->",
... | Action for Add an ignore pattern.
@param string $pattern The pattern | [
"Action",
"for",
"Add",
"an",
"ignore",
"pattern",
"."
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Installer/IgnoreManager.php#L131-L151 |
fxpio/composer-asset-plugin | Installer/IgnoreManager.php | IgnoreManager.convertPattern | protected function convertPattern($pattern)
{
$prefix = 0 === strpos($pattern, '!') ? '!' : '';
$searchPattern = trim(ltrim($pattern, '!'), '/');
$pattern = $prefix.$searchPattern;
if (\in_array($searchPattern, array('*', '*.*'), true)) {
$this->doAddPattern($prefix.'.*');
} elseif (0 === strpos($searchPattern, '**/')) {
$this->doAddPattern($prefix.'**/'.$searchPattern);
$this->doAddPattern($prefix.substr($searchPattern, 3));
} else {
$this->convertPatternStep2($prefix, $searchPattern, $pattern);
}
return $pattern;
} | php | protected function convertPattern($pattern)
{
$prefix = 0 === strpos($pattern, '!') ? '!' : '';
$searchPattern = trim(ltrim($pattern, '!'), '/');
$pattern = $prefix.$searchPattern;
if (\in_array($searchPattern, array('*', '*.*'), true)) {
$this->doAddPattern($prefix.'.*');
} elseif (0 === strpos($searchPattern, '**/')) {
$this->doAddPattern($prefix.'**/'.$searchPattern);
$this->doAddPattern($prefix.substr($searchPattern, 3));
} else {
$this->convertPatternStep2($prefix, $searchPattern, $pattern);
}
return $pattern;
} | [
"protected",
"function",
"convertPattern",
"(",
"$",
"pattern",
")",
"{",
"$",
"prefix",
"=",
"0",
"===",
"strpos",
"(",
"$",
"pattern",
",",
"'!'",
")",
"?",
"'!'",
":",
"''",
";",
"$",
"searchPattern",
"=",
"trim",
"(",
"ltrim",
"(",
"$",
"pattern"... | Converter pattern to glob.
@param string $pattern The pattern
@return string The pattern converted | [
"Converter",
"pattern",
"to",
"glob",
"."
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Installer/IgnoreManager.php#L160-L176 |
fxpio/composer-asset-plugin | Installer/IgnoreManager.php | IgnoreManager.convertPatternStep2 | protected function convertPatternStep2($prefix, $searchPattern, $pattern)
{
if ('.*' === $searchPattern) {
$this->doAddPattern($prefix.'**/.*');
} elseif ('**' === $searchPattern) {
$this->finder->path('/.*/');
$this->finder->notPath('/^\..*(?!\/)/');
} elseif (preg_match('/\/\*$|\/\*\*$/', $pattern, $matches)) {
$this->doAddPattern(substr($pattern, 0, \strlen($pattern) - \strlen($matches[0])));
}
} | php | protected function convertPatternStep2($prefix, $searchPattern, $pattern)
{
if ('.*' === $searchPattern) {
$this->doAddPattern($prefix.'**/.*');
} elseif ('**' === $searchPattern) {
$this->finder->path('/.*/');
$this->finder->notPath('/^\..*(?!\/)/');
} elseif (preg_match('/\/\*$|\/\*\*$/', $pattern, $matches)) {
$this->doAddPattern(substr($pattern, 0, \strlen($pattern) - \strlen($matches[0])));
}
} | [
"protected",
"function",
"convertPatternStep2",
"(",
"$",
"prefix",
",",
"$",
"searchPattern",
",",
"$",
"pattern",
")",
"{",
"if",
"(",
"'.*'",
"===",
"$",
"searchPattern",
")",
"{",
"$",
"this",
"->",
"doAddPattern",
"(",
"$",
"prefix",
".",
"'**/.*'",
... | Step2: Converter pattern to glob.
@param string $prefix The prefix
@param string $searchPattern The search pattern
@param string $pattern The pattern | [
"Step2",
":",
"Converter",
"pattern",
"to",
"glob",
"."
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Installer/IgnoreManager.php#L185-L195 |
fxpio/composer-asset-plugin | Converter/AbstractPackageConverter.php | AbstractPackageConverter.convert | public function convert(array $data, array &$vcsRepos = array())
{
$keys = $this->getMapKeys();
$dependencies = $this->getMapDependencies();
$extras = $this->getMapExtras();
return $this->convertData($data, $keys, $dependencies, $extras, $vcsRepos);
} | php | public function convert(array $data, array &$vcsRepos = array())
{
$keys = $this->getMapKeys();
$dependencies = $this->getMapDependencies();
$extras = $this->getMapExtras();
return $this->convertData($data, $keys, $dependencies, $extras, $vcsRepos);
} | [
"public",
"function",
"convert",
"(",
"array",
"$",
"data",
",",
"array",
"&",
"$",
"vcsRepos",
"=",
"array",
"(",
")",
")",
"{",
"$",
"keys",
"=",
"$",
"this",
"->",
"getMapKeys",
"(",
")",
";",
"$",
"dependencies",
"=",
"$",
"this",
"->",
"getMap... | {@inheritdoc} | [
"{"
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Converter/AbstractPackageConverter.php#L42-L49 |
fxpio/composer-asset-plugin | Converter/AbstractPackageConverter.php | AbstractPackageConverter.convertData | protected function convertData(array $asset, array $keys, array $dependencies, array $extras, array &$vcsRepos = array())
{
$composer = array();
foreach ($keys as $assetKey => $composerKey) {
$this->convertKey($asset, $assetKey, $composer, $composerKey);
}
foreach ($dependencies as $assetKey => $composerKey) {
$this->convertDependencies($asset, $assetKey, $composer, $composerKey, $vcsRepos);
}
foreach ($extras as $assetKey => $composerKey) {
$this->convertExtraKey($asset, $assetKey, $composer, $composerKey);
}
return $composer;
} | php | protected function convertData(array $asset, array $keys, array $dependencies, array $extras, array &$vcsRepos = array())
{
$composer = array();
foreach ($keys as $assetKey => $composerKey) {
$this->convertKey($asset, $assetKey, $composer, $composerKey);
}
foreach ($dependencies as $assetKey => $composerKey) {
$this->convertDependencies($asset, $assetKey, $composer, $composerKey, $vcsRepos);
}
foreach ($extras as $assetKey => $composerKey) {
$this->convertExtraKey($asset, $assetKey, $composer, $composerKey);
}
return $composer;
} | [
"protected",
"function",
"convertData",
"(",
"array",
"$",
"asset",
",",
"array",
"$",
"keys",
",",
"array",
"$",
"dependencies",
",",
"array",
"$",
"extras",
",",
"array",
"&",
"$",
"vcsRepos",
"=",
"array",
"(",
")",
")",
"{",
"$",
"composer",
"=",
... | Converts the all keys (keys, dependencies and extra keys).
@param array $asset The asset data
@param array $keys The map of asset key and composer key
@param array $dependencies The map of asset dependency key and composer dependency key
@param array $extras The map of asset key and composer extra key
@param array $vcsRepos The list of new vcs configs
@return array The composer package converted | [
"Converts",
"the",
"all",
"keys",
"(",
"keys",
"dependencies",
"and",
"extra",
"keys",
")",
"."
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Converter/AbstractPackageConverter.php#L62-L79 |
fxpio/composer-asset-plugin | Converter/AbstractPackageConverter.php | AbstractPackageConverter.convertKey | protected function convertKey(array $asset, $assetKey, array &$composer, $composerKey)
{
if (\is_array($composerKey)) {
PackageUtil::convertArrayKey($asset, $assetKey, $composer, $composerKey);
} else {
PackageUtil::convertStringKey($asset, $assetKey, $composer, $composerKey);
}
} | php | protected function convertKey(array $asset, $assetKey, array &$composer, $composerKey)
{
if (\is_array($composerKey)) {
PackageUtil::convertArrayKey($asset, $assetKey, $composer, $composerKey);
} else {
PackageUtil::convertStringKey($asset, $assetKey, $composer, $composerKey);
}
} | [
"protected",
"function",
"convertKey",
"(",
"array",
"$",
"asset",
",",
"$",
"assetKey",
",",
"array",
"&",
"$",
"composer",
",",
"$",
"composerKey",
")",
"{",
"if",
"(",
"\\",
"is_array",
"(",
"$",
"composerKey",
")",
")",
"{",
"PackageUtil",
"::",
"c... | Converts the simple key of package.
@param array $asset The asset data
@param string $assetKey The asset key
@param array $composer The composer data
@param array|string $composerKey The composer key or array with composer key name and closure
@throws InvalidArgumentException When the 'composerKey' argument of asset packager converter is not an string or an array with the composer key and closure | [
"Converts",
"the",
"simple",
"key",
"of",
"package",
"."
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Converter/AbstractPackageConverter.php#L91-L98 |
fxpio/composer-asset-plugin | Converter/AbstractPackageConverter.php | AbstractPackageConverter.convertExtraKey | protected function convertExtraKey(array $asset, $assetKey, array &$composer, $composerKey, $extraKey = 'extra')
{
$extra = isset($composer[$extraKey]) ? $composer[$extraKey] : array();
$this->convertKey($asset, $assetKey, $extra, $composerKey);
if (\count($extra) > 0) {
$composer[$extraKey] = $extra;
}
} | php | protected function convertExtraKey(array $asset, $assetKey, array &$composer, $composerKey, $extraKey = 'extra')
{
$extra = isset($composer[$extraKey]) ? $composer[$extraKey] : array();
$this->convertKey($asset, $assetKey, $extra, $composerKey);
if (\count($extra) > 0) {
$composer[$extraKey] = $extra;
}
} | [
"protected",
"function",
"convertExtraKey",
"(",
"array",
"$",
"asset",
",",
"$",
"assetKey",
",",
"array",
"&",
"$",
"composer",
",",
"$",
"composerKey",
",",
"$",
"extraKey",
"=",
"'extra'",
")",
"{",
"$",
"extra",
"=",
"isset",
"(",
"$",
"composer",
... | Converts the extra key of package.
@param array $asset The asset data
@param string $assetKey The asset extra key
@param array $composer The composer data
@param array|string $composerKey The composer extra key or array with composer extra key name and closure
@param string $extraKey The extra key name | [
"Converts",
"the",
"extra",
"key",
"of",
"package",
"."
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Converter/AbstractPackageConverter.php#L109-L118 |
fxpio/composer-asset-plugin | Converter/AbstractPackageConverter.php | AbstractPackageConverter.convertDependencies | protected function convertDependencies(array $asset, $assetKey, array &$composer, $composerKey, array &$vcsRepos = array())
{
if (isset($asset[$assetKey]) && \is_array($asset[$assetKey])) {
$newDependencies = array();
foreach ($asset[$assetKey] as $dependency => $version) {
list($dependency, $version) = $this->convertDependency($dependency, $version, $vcsRepos, $composer);
$version = $this->assetType->getVersionConverter()->convertRange($version);
if (0 !== strpos($version, $dependency)) {
$newDependencies[$this->assetType->getComposerVendorName().'/'.$dependency] = $version;
}
}
$composer[$composerKey] = $newDependencies;
}
} | php | protected function convertDependencies(array $asset, $assetKey, array &$composer, $composerKey, array &$vcsRepos = array())
{
if (isset($asset[$assetKey]) && \is_array($asset[$assetKey])) {
$newDependencies = array();
foreach ($asset[$assetKey] as $dependency => $version) {
list($dependency, $version) = $this->convertDependency($dependency, $version, $vcsRepos, $composer);
$version = $this->assetType->getVersionConverter()->convertRange($version);
if (0 !== strpos($version, $dependency)) {
$newDependencies[$this->assetType->getComposerVendorName().'/'.$dependency] = $version;
}
}
$composer[$composerKey] = $newDependencies;
}
} | [
"protected",
"function",
"convertDependencies",
"(",
"array",
"$",
"asset",
",",
"$",
"assetKey",
",",
"array",
"&",
"$",
"composer",
",",
"$",
"composerKey",
",",
"array",
"&",
"$",
"vcsRepos",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"isset",
"("... | Converts simple key of package.
@param array $asset The asset data
@param string $assetKey The asset key of dependencies
@param array $composer The composer data
@param string $composerKey The composer key of dependencies
@param array $vcsRepos The list of new vcs configs | [
"Converts",
"simple",
"key",
"of",
"package",
"."
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Converter/AbstractPackageConverter.php#L129-L144 |
fxpio/composer-asset-plugin | Converter/AbstractPackageConverter.php | AbstractPackageConverter.convertDependency | protected function convertDependency($dependency, $version, array &$vcsRepos, array $composer)
{
list($dependency, $version) = PackageUtil::checkUrlVersion($this->assetType, $dependency, $version, $vcsRepos, $composer);
list($dependency, $version) = PackageUtil::checkAliasVersion($this->assetType, $dependency, $version);
list($dependency, $version) = PackageUtil::convertDependencyVersion($this->assetType, $dependency, $version);
return array($dependency, $version);
} | php | protected function convertDependency($dependency, $version, array &$vcsRepos, array $composer)
{
list($dependency, $version) = PackageUtil::checkUrlVersion($this->assetType, $dependency, $version, $vcsRepos, $composer);
list($dependency, $version) = PackageUtil::checkAliasVersion($this->assetType, $dependency, $version);
list($dependency, $version) = PackageUtil::convertDependencyVersion($this->assetType, $dependency, $version);
return array($dependency, $version);
} | [
"protected",
"function",
"convertDependency",
"(",
"$",
"dependency",
",",
"$",
"version",
",",
"array",
"&",
"$",
"vcsRepos",
",",
"array",
"$",
"composer",
")",
"{",
"list",
"(",
"$",
"dependency",
",",
"$",
"version",
")",
"=",
"PackageUtil",
"::",
"c... | Convert the .
@param string $dependency The dependency
@param string $version The version
@param array $vcsRepos The list of new vcs configs
@param array $composer The partial composer data
@return string[] The new dependency and the new version | [
"Convert",
"the",
"."
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Converter/AbstractPackageConverter.php#L156-L163 |
fxpio/composer-asset-plugin | Repository/Vcs/SvnDriver.php | SvnDriver.initialize | public function initialize()
{
$this->url = 0 === strpos($this->url, 'svn+http')
? substr($this->url, 4)
: $this->url;
parent::initialize();
} | php | public function initialize()
{
$this->url = 0 === strpos($this->url, 'svn+http')
? substr($this->url, 4)
: $this->url;
parent::initialize();
} | [
"public",
"function",
"initialize",
"(",
")",
"{",
"$",
"this",
"->",
"url",
"=",
"0",
"===",
"strpos",
"(",
"$",
"this",
"->",
"url",
",",
"'svn+http'",
")",
"?",
"substr",
"(",
"$",
"this",
"->",
"url",
",",
"4",
")",
":",
"$",
"this",
"->",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Repository/Vcs/SvnDriver.php#L30-L37 |
fxpio/composer-asset-plugin | Repository/Vcs/SvnDriver.php | SvnDriver.getComposerInformation | public function getComposerInformation($identifier)
{
$identifier = '/'.trim($identifier, '/').'/';
$this->infoCache[$identifier] = Util::readCache($this->infoCache, $this->cache, $this->repoConfig['asset-type'], trim($identifier, '/'), true);
if (!isset($this->infoCache[$identifier])) {
list($path, $rev) = $this->getPathRev($identifier);
$resource = $path.$this->repoConfig['filename'];
$output = $this->getComposerContent($resource, $rev);
$composer = $this->parseComposerContent($output, $resource, $path, $rev);
Util::writeCache($this->cache, $this->repoConfig['asset-type'], trim($identifier, '/'), $composer, true);
$this->infoCache[$identifier] = $composer;
}
return $this->infoCache[$identifier];
} | php | public function getComposerInformation($identifier)
{
$identifier = '/'.trim($identifier, '/').'/';
$this->infoCache[$identifier] = Util::readCache($this->infoCache, $this->cache, $this->repoConfig['asset-type'], trim($identifier, '/'), true);
if (!isset($this->infoCache[$identifier])) {
list($path, $rev) = $this->getPathRev($identifier);
$resource = $path.$this->repoConfig['filename'];
$output = $this->getComposerContent($resource, $rev);
$composer = $this->parseComposerContent($output, $resource, $path, $rev);
Util::writeCache($this->cache, $this->repoConfig['asset-type'], trim($identifier, '/'), $composer, true);
$this->infoCache[$identifier] = $composer;
}
return $this->infoCache[$identifier];
} | [
"public",
"function",
"getComposerInformation",
"(",
"$",
"identifier",
")",
"{",
"$",
"identifier",
"=",
"'/'",
".",
"trim",
"(",
"$",
"identifier",
",",
"'/'",
")",
".",
"'/'",
";",
"$",
"this",
"->",
"infoCache",
"[",
"$",
"identifier",
"]",
"=",
"U... | {@inheritdoc} | [
"{"
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Repository/Vcs/SvnDriver.php#L42-L58 |
fxpio/composer-asset-plugin | Repository/Vcs/SvnDriver.php | SvnDriver.supports | public static function supports(IOInterface $io, Config $config, $url, $deep = false)
{
if (0 === strpos($url, 'http') && preg_match('/\/svn|svn\//i', $url)) {
$url = 'svn'.substr($url, strpos($url, '://'));
}
return parent::supports($io, $config, $url, $deep);
} | php | public static function supports(IOInterface $io, Config $config, $url, $deep = false)
{
if (0 === strpos($url, 'http') && preg_match('/\/svn|svn\//i', $url)) {
$url = 'svn'.substr($url, strpos($url, '://'));
}
return parent::supports($io, $config, $url, $deep);
} | [
"public",
"static",
"function",
"supports",
"(",
"IOInterface",
"$",
"io",
",",
"Config",
"$",
"config",
",",
"$",
"url",
",",
"$",
"deep",
"=",
"false",
")",
"{",
"if",
"(",
"0",
"===",
"strpos",
"(",
"$",
"url",
",",
"'http'",
")",
"&&",
"preg_ma... | {@inheritdoc} | [
"{"
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Repository/Vcs/SvnDriver.php#L63-L70 |
fxpio/composer-asset-plugin | Repository/Vcs/SvnDriver.php | SvnDriver.getPathRev | protected function getPathRev($identifier)
{
$path = $identifier;
$rev = '';
preg_match('{^(.+?)(@\d+)?/$}', $identifier, $match);
if (!empty($match[2])) {
$path = $match[1];
$rev = $match[2];
}
return array($path, $rev);
} | php | protected function getPathRev($identifier)
{
$path = $identifier;
$rev = '';
preg_match('{^(.+?)(@\d+)?/$}', $identifier, $match);
if (!empty($match[2])) {
$path = $match[1];
$rev = $match[2];
}
return array($path, $rev);
} | [
"protected",
"function",
"getPathRev",
"(",
"$",
"identifier",
")",
"{",
"$",
"path",
"=",
"$",
"identifier",
";",
"$",
"rev",
"=",
"''",
";",
"preg_match",
"(",
"'{^(.+?)(@\\d+)?/$}'",
",",
"$",
"identifier",
",",
"$",
"match",
")",
";",
"if",
"(",
"!... | Get path and rev.
@param string $identifier The identifier
@return string[] | [
"Get",
"path",
"and",
"rev",
"."
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Repository/Vcs/SvnDriver.php#L79-L92 |
fxpio/composer-asset-plugin | Repository/Vcs/SvnDriver.php | SvnDriver.getComposerContent | protected function getComposerContent($resource, $rev)
{
$output = null;
try {
$output = $this->execute($this->getSvnCredetials('svn cat'), $this->baseUrl.$resource.$rev);
} catch (\RuntimeException $e) {
throw new TransportException($e->getMessage());
}
return $output;
} | php | protected function getComposerContent($resource, $rev)
{
$output = null;
try {
$output = $this->execute($this->getSvnCredetials('svn cat'), $this->baseUrl.$resource.$rev);
} catch (\RuntimeException $e) {
throw new TransportException($e->getMessage());
}
return $output;
} | [
"protected",
"function",
"getComposerContent",
"(",
"$",
"resource",
",",
"$",
"rev",
")",
"{",
"$",
"output",
"=",
"null",
";",
"try",
"{",
"$",
"output",
"=",
"$",
"this",
"->",
"execute",
"(",
"$",
"this",
"->",
"getSvnCredetials",
"(",
"'svn cat'",
... | Get the composer content.
@param string $resource The resource
@param string $rev The rev
@throws TransportException
@return null|string The composer content | [
"Get",
"the",
"composer",
"content",
"."
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Repository/Vcs/SvnDriver.php#L104-L115 |
fxpio/composer-asset-plugin | Repository/Vcs/SvnDriver.php | SvnDriver.parseComposerContent | protected function parseComposerContent($output, $resource, $path, $rev)
{
if (!trim($output)) {
return array('_nonexistent_package' => true);
}
$composer = (array) JsonFile::parseJson($output, $this->baseUrl.$resource.$rev);
return $this->addComposerTime($composer, $path, $rev);
} | php | protected function parseComposerContent($output, $resource, $path, $rev)
{
if (!trim($output)) {
return array('_nonexistent_package' => true);
}
$composer = (array) JsonFile::parseJson($output, $this->baseUrl.$resource.$rev);
return $this->addComposerTime($composer, $path, $rev);
} | [
"protected",
"function",
"parseComposerContent",
"(",
"$",
"output",
",",
"$",
"resource",
",",
"$",
"path",
",",
"$",
"rev",
")",
"{",
"if",
"(",
"!",
"trim",
"(",
"$",
"output",
")",
")",
"{",
"return",
"array",
"(",
"'_nonexistent_package'",
"=>",
"... | Parse the content of composer.
@param null|string $output The output of process executor
@param string $resource The resouce
@param string $path The path
@param string $rev The rev
@return array The composer | [
"Parse",
"the",
"content",
"of",
"composer",
"."
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Repository/Vcs/SvnDriver.php#L127-L136 |
fxpio/composer-asset-plugin | Repository/Vcs/SvnDriver.php | SvnDriver.addComposerTime | protected function addComposerTime(array $composer, $path, $rev)
{
if (!isset($composer['time'])) {
$output = $this->execute($this->getSvnCredetials('svn info'), $this->baseUrl.$path.$rev);
foreach ($this->process->splitLines($output) as $line) {
if ($line && preg_match('{^Last Changed Date: ([^(]+)}', $line, $match)) {
$date = new \DateTime($match[1], new \DateTimeZone('UTC'));
$composer['time'] = $date->format('Y-m-d H:i:s');
break;
}
}
}
return $composer;
} | php | protected function addComposerTime(array $composer, $path, $rev)
{
if (!isset($composer['time'])) {
$output = $this->execute($this->getSvnCredetials('svn info'), $this->baseUrl.$path.$rev);
foreach ($this->process->splitLines($output) as $line) {
if ($line && preg_match('{^Last Changed Date: ([^(]+)}', $line, $match)) {
$date = new \DateTime($match[1], new \DateTimeZone('UTC'));
$composer['time'] = $date->format('Y-m-d H:i:s');
break;
}
}
}
return $composer;
} | [
"protected",
"function",
"addComposerTime",
"(",
"array",
"$",
"composer",
",",
"$",
"path",
",",
"$",
"rev",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"composer",
"[",
"'time'",
"]",
")",
")",
"{",
"$",
"output",
"=",
"$",
"this",
"->",
"execut... | Add time in composer.
@param array $composer The composer
@param string $path The path
@param string $rev The rev
@return array The composer | [
"Add",
"time",
"in",
"composer",
"."
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Repository/Vcs/SvnDriver.php#L147-L163 |
fxpio/composer-asset-plugin | Repository/Vcs/SvnDriver.php | SvnDriver.getSvnCredetials | protected function getSvnCredetials($command)
{
$httpBasic = $this->config->get('http-basic');
$parsedUrl = parse_url($this->baseUrl);
$svnCommand = $command;
if ($parsedUrl && isset($httpBasic[$parsedUrl['host']])) {
if ($httpBasic[$parsedUrl['host']]['username'] && $httpBasic[$parsedUrl['host']]['password']) {
$uname = $httpBasic[$parsedUrl['host']]['username'];
$pw = $httpBasic[$parsedUrl['host']]['password'];
$svnCommand = $command.sprintf(' --username %s --password %s --no-auth-cache', $uname, $pw);
}
}
return $svnCommand;
} | php | protected function getSvnCredetials($command)
{
$httpBasic = $this->config->get('http-basic');
$parsedUrl = parse_url($this->baseUrl);
$svnCommand = $command;
if ($parsedUrl && isset($httpBasic[$parsedUrl['host']])) {
if ($httpBasic[$parsedUrl['host']]['username'] && $httpBasic[$parsedUrl['host']]['password']) {
$uname = $httpBasic[$parsedUrl['host']]['username'];
$pw = $httpBasic[$parsedUrl['host']]['password'];
$svnCommand = $command.sprintf(' --username %s --password %s --no-auth-cache', $uname, $pw);
}
}
return $svnCommand;
} | [
"protected",
"function",
"getSvnCredetials",
"(",
"$",
"command",
")",
"{",
"$",
"httpBasic",
"=",
"$",
"this",
"->",
"config",
"->",
"get",
"(",
"'http-basic'",
")",
";",
"$",
"parsedUrl",
"=",
"parse_url",
"(",
"$",
"this",
"->",
"baseUrl",
")",
";",
... | Get the credentials of SVN.
@param string $command The command
@return string | [
"Get",
"the",
"credentials",
"of",
"SVN",
"."
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Repository/Vcs/SvnDriver.php#L172-L188 |
fxpio/composer-asset-plugin | Repository/DefaultRegistryFactory.php | DefaultRegistryFactory.create | public static function create(AssetRepositoryManager $arm, VcsPackageFilter $filter, Config $config)
{
$rm = $arm->getRepositoryManager();
foreach (Assets::getDefaultRegistries() as $assetType => $registryClass) {
$repoConfig = AssetPlugin::createRepositoryConfig($arm, $filter, $config, $assetType);
$rm->setRepositoryClass($assetType, $registryClass);
$rm->addRepository($rm->createRepository($assetType, $repoConfig));
}
} | php | public static function create(AssetRepositoryManager $arm, VcsPackageFilter $filter, Config $config)
{
$rm = $arm->getRepositoryManager();
foreach (Assets::getDefaultRegistries() as $assetType => $registryClass) {
$repoConfig = AssetPlugin::createRepositoryConfig($arm, $filter, $config, $assetType);
$rm->setRepositoryClass($assetType, $registryClass);
$rm->addRepository($rm->createRepository($assetType, $repoConfig));
}
} | [
"public",
"static",
"function",
"create",
"(",
"AssetRepositoryManager",
"$",
"arm",
",",
"VcsPackageFilter",
"$",
"filter",
",",
"Config",
"$",
"config",
")",
"{",
"$",
"rm",
"=",
"$",
"arm",
"->",
"getRepositoryManager",
"(",
")",
";",
"foreach",
"(",
"A... | {@inheritdoc} | [
"{"
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Repository/DefaultRegistryFactory.php#L28-L38 |
fxpio/composer-asset-plugin | Repository/ResolutionManager.php | ResolutionManager.doSolveResolutions | protected function doSolveResolutions(array $data, $section)
{
if (\array_key_exists($section, $data) && \is_array($data[$section])) {
foreach ($data[$section] as $dependency => &$range) {
foreach ($this->resolutions as $resolutionDependency => $resolutionRange) {
if ($dependency === $resolutionDependency) {
$range = $resolutionRange;
}
}
}
}
return $data;
} | php | protected function doSolveResolutions(array $data, $section)
{
if (\array_key_exists($section, $data) && \is_array($data[$section])) {
foreach ($data[$section] as $dependency => &$range) {
foreach ($this->resolutions as $resolutionDependency => $resolutionRange) {
if ($dependency === $resolutionDependency) {
$range = $resolutionRange;
}
}
}
}
return $data;
} | [
"protected",
"function",
"doSolveResolutions",
"(",
"array",
"$",
"data",
",",
"$",
"section",
")",
"{",
"if",
"(",
"\\",
"array_key_exists",
"(",
"$",
"section",
",",
"$",
"data",
")",
"&&",
"\\",
"is_array",
"(",
"$",
"data",
"[",
"$",
"section",
"]"... | Solve the dependency resolutions.
@param array $data The data of asset composer package
@param string $section The dependency section in package
@return array | [
"Solve",
"the",
"dependency",
"resolutions",
"."
] | train | https://github.com/fxpio/composer-asset-plugin/blob/6d5cfd0a4f4c3e167d2048eb8f5347309a6bbe10/Repository/ResolutionManager.php#L58-L71 |
yswery/PHP-DNS-SERVER | src/RdataEncoder.php | RdataEncoder.a | public static function a(string $rdata): string
{
if (!filter_var($rdata, FILTER_VALIDATE_IP)) {
throw new \InvalidArgumentException(sprintf('The IP address "%s" is invalid.', $rdata));
}
return inet_pton($rdata);
} | php | public static function a(string $rdata): string
{
if (!filter_var($rdata, FILTER_VALIDATE_IP)) {
throw new \InvalidArgumentException(sprintf('The IP address "%s" is invalid.', $rdata));
}
return inet_pton($rdata);
} | [
"public",
"static",
"function",
"a",
"(",
"string",
"$",
"rdata",
")",
":",
"string",
"{",
"if",
"(",
"!",
"filter_var",
"(",
"$",
"rdata",
",",
"FILTER_VALIDATE_IP",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"... | Used for A and AAAA records.
@param string $rdata
@return string | [
"Used",
"for",
"A",
"and",
"AAAA",
"records",
"."
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/RdataEncoder.php#L55-L62 |
yswery/PHP-DNS-SERVER | src/RdataEncoder.php | RdataEncoder.soa | public static function soa(array $rdata): string
{
return
Encoder::encodeDomainName($rdata['mname']).
Encoder::encodeDomainName($rdata['rname']).
pack(
'NNNNN',
$rdata['serial'],
$rdata['refresh'],
$rdata['retry'],
$rdata['expire'],
$rdata['minimum']
);
} | php | public static function soa(array $rdata): string
{
return
Encoder::encodeDomainName($rdata['mname']).
Encoder::encodeDomainName($rdata['rname']).
pack(
'NNNNN',
$rdata['serial'],
$rdata['refresh'],
$rdata['retry'],
$rdata['expire'],
$rdata['minimum']
);
} | [
"public",
"static",
"function",
"soa",
"(",
"array",
"$",
"rdata",
")",
":",
"string",
"{",
"return",
"Encoder",
"::",
"encodeDomainName",
"(",
"$",
"rdata",
"[",
"'mname'",
"]",
")",
".",
"Encoder",
"::",
"encodeDomainName",
"(",
"$",
"rdata",
"[",
"'rn... | Exclusively for SOA records.
@param array $rdata
@return string | [
"Exclusively",
"for",
"SOA",
"records",
"."
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/RdataEncoder.php#L83-L96 |
yswery/PHP-DNS-SERVER | src/RdataEncoder.php | RdataEncoder.txt | public static function txt(string $rdata): string
{
$rdata = substr($rdata, 0, 255);
return chr(strlen($rdata)).$rdata;
} | php | public static function txt(string $rdata): string
{
$rdata = substr($rdata, 0, 255);
return chr(strlen($rdata)).$rdata;
} | [
"public",
"static",
"function",
"txt",
"(",
"string",
"$",
"rdata",
")",
":",
"string",
"{",
"$",
"rdata",
"=",
"substr",
"(",
"$",
"rdata",
",",
"0",
",",
"255",
")",
";",
"return",
"chr",
"(",
"strlen",
"(",
"$",
"rdata",
")",
")",
".",
"$",
... | Exclusively for TXT records.
@param string $rdata
@return string | [
"Exclusively",
"for",
"TXT",
"records",
"."
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/RdataEncoder.php#L117-L122 |
yswery/PHP-DNS-SERVER | src/RdataEncoder.php | RdataEncoder.srv | public static function srv(array $rdata): string
{
return pack('nnn', (int) $rdata['priority'], (int) $rdata['weight'], (int) $rdata['port']).
Encoder::encodeDomainName($rdata['target']);
} | php | public static function srv(array $rdata): string
{
return pack('nnn', (int) $rdata['priority'], (int) $rdata['weight'], (int) $rdata['port']).
Encoder::encodeDomainName($rdata['target']);
} | [
"public",
"static",
"function",
"srv",
"(",
"array",
"$",
"rdata",
")",
":",
"string",
"{",
"return",
"pack",
"(",
"'nnn'",
",",
"(",
"int",
")",
"$",
"rdata",
"[",
"'priority'",
"]",
",",
"(",
"int",
")",
"$",
"rdata",
"[",
"'weight'",
"]",
",",
... | Exclusively for SRV records.
@param array $rdata
@return string | [
"Exclusively",
"for",
"SRV",
"records",
"."
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/RdataEncoder.php#L131-L135 |
yswery/PHP-DNS-SERVER | src/Message.php | Message.addQuestion | public function addQuestion(ResourceRecord $resourceRecord): Message
{
if (!$resourceRecord->isQuestion()) {
throw new \InvalidArgumentException('Resource Record provided is not a question.');
}
$this->questions[] = $resourceRecord;
$this->header->setQuestionCount(count($this->questions));
return $this;
} | php | public function addQuestion(ResourceRecord $resourceRecord): Message
{
if (!$resourceRecord->isQuestion()) {
throw new \InvalidArgumentException('Resource Record provided is not a question.');
}
$this->questions[] = $resourceRecord;
$this->header->setQuestionCount(count($this->questions));
return $this;
} | [
"public",
"function",
"addQuestion",
"(",
"ResourceRecord",
"$",
"resourceRecord",
")",
":",
"Message",
"{",
"if",
"(",
"!",
"$",
"resourceRecord",
"->",
"isQuestion",
"(",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Resource Record p... | @param ResourceRecord $resourceRecord
@throws \InvalidArgumentException
@return Message | [
"@param",
"ResourceRecord",
"$resourceRecord"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Message.php#L93-L103 |
yswery/PHP-DNS-SERVER | src/Message.php | Message.addAnswer | public function addAnswer(ResourceRecord $resourceRecord): Message
{
$this->answers[] = $resourceRecord;
$this->header->setAnswerCount(count($this->answers));
return $this;
} | php | public function addAnswer(ResourceRecord $resourceRecord): Message
{
$this->answers[] = $resourceRecord;
$this->header->setAnswerCount(count($this->answers));
return $this;
} | [
"public",
"function",
"addAnswer",
"(",
"ResourceRecord",
"$",
"resourceRecord",
")",
":",
"Message",
"{",
"$",
"this",
"->",
"answers",
"[",
"]",
"=",
"$",
"resourceRecord",
";",
"$",
"this",
"->",
"header",
"->",
"setAnswerCount",
"(",
"count",
"(",
"$",... | @param ResourceRecord $resourceRecord
@return Message | [
"@param",
"ResourceRecord",
"$resourceRecord"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Message.php#L118-L124 |
yswery/PHP-DNS-SERVER | src/Message.php | Message.addAuthoritative | public function addAuthoritative(ResourceRecord $resourceRecord): Message
{
$this->authoritatives[] = $resourceRecord;
$this->header->setNameServerCount(count($this->authoritatives));
return $this;
} | php | public function addAuthoritative(ResourceRecord $resourceRecord): Message
{
$this->authoritatives[] = $resourceRecord;
$this->header->setNameServerCount(count($this->authoritatives));
return $this;
} | [
"public",
"function",
"addAuthoritative",
"(",
"ResourceRecord",
"$",
"resourceRecord",
")",
":",
"Message",
"{",
"$",
"this",
"->",
"authoritatives",
"[",
"]",
"=",
"$",
"resourceRecord",
";",
"$",
"this",
"->",
"header",
"->",
"setNameServerCount",
"(",
"cou... | @param ResourceRecord $resourceRecord
@return Message | [
"@param",
"ResourceRecord",
"$resourceRecord"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Message.php#L139-L145 |
yswery/PHP-DNS-SERVER | src/Message.php | Message.addAdditional | public function addAdditional(ResourceRecord $resourceRecord): Message
{
$this->additionals[] = $resourceRecord;
$this->header->setAdditionalRecordsCount(count($this->additionals));
return $this;
} | php | public function addAdditional(ResourceRecord $resourceRecord): Message
{
$this->additionals[] = $resourceRecord;
$this->header->setAdditionalRecordsCount(count($this->additionals));
return $this;
} | [
"public",
"function",
"addAdditional",
"(",
"ResourceRecord",
"$",
"resourceRecord",
")",
":",
"Message",
"{",
"$",
"this",
"->",
"additionals",
"[",
"]",
"=",
"$",
"resourceRecord",
";",
"$",
"this",
"->",
"header",
"->",
"setAdditionalRecordsCount",
"(",
"co... | @param ResourceRecord $resourceRecord
@return Message | [
"@param",
"ResourceRecord",
"$resourceRecord"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Message.php#L160-L166 |
yswery/PHP-DNS-SERVER | src/Message.php | Message.setQuestions | public function setQuestions(array $resourceRecords): Message
{
$this->questions = [];
foreach ($resourceRecords as $resourceRecord) {
$this->addQuestion($resourceRecord);
}
return $this;
} | php | public function setQuestions(array $resourceRecords): Message
{
$this->questions = [];
foreach ($resourceRecords as $resourceRecord) {
$this->addQuestion($resourceRecord);
}
return $this;
} | [
"public",
"function",
"setQuestions",
"(",
"array",
"$",
"resourceRecords",
")",
":",
"Message",
"{",
"$",
"this",
"->",
"questions",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"resourceRecords",
"as",
"$",
"resourceRecord",
")",
"{",
"$",
"this",
"->",
"a... | @param array $resourceRecords
@return Message | [
"@param",
"array",
"$resourceRecords"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Message.php#L173-L181 |
yswery/PHP-DNS-SERVER | src/Message.php | Message.setAnswers | public function setAnswers(array $resourceRecords): Message
{
$this->answers = $resourceRecords;
$this->header->setAnswerCount(count($this->answers));
return $this;
} | php | public function setAnswers(array $resourceRecords): Message
{
$this->answers = $resourceRecords;
$this->header->setAnswerCount(count($this->answers));
return $this;
} | [
"public",
"function",
"setAnswers",
"(",
"array",
"$",
"resourceRecords",
")",
":",
"Message",
"{",
"$",
"this",
"->",
"answers",
"=",
"$",
"resourceRecords",
";",
"$",
"this",
"->",
"header",
"->",
"setAnswerCount",
"(",
"count",
"(",
"$",
"this",
"->",
... | @param array $resourceRecords
@return Message | [
"@param",
"array",
"$resourceRecords"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Message.php#L188-L194 |
yswery/PHP-DNS-SERVER | src/Message.php | Message.setAuthoritatives | public function setAuthoritatives(array $resourceRecords): Message
{
$this->authoritatives = $resourceRecords;
$this->header->setNameServerCount(count($this->authoritatives));
return $this;
} | php | public function setAuthoritatives(array $resourceRecords): Message
{
$this->authoritatives = $resourceRecords;
$this->header->setNameServerCount(count($this->authoritatives));
return $this;
} | [
"public",
"function",
"setAuthoritatives",
"(",
"array",
"$",
"resourceRecords",
")",
":",
"Message",
"{",
"$",
"this",
"->",
"authoritatives",
"=",
"$",
"resourceRecords",
";",
"$",
"this",
"->",
"header",
"->",
"setNameServerCount",
"(",
"count",
"(",
"$",
... | @param array $resourceRecords
@return Message | [
"@param",
"array",
"$resourceRecords"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Message.php#L201-L207 |
yswery/PHP-DNS-SERVER | src/Message.php | Message.setAdditionals | public function setAdditionals(array $resourceRecords): Message
{
$this->additionals = $resourceRecords;
$this->header->setAdditionalRecordsCount(count($this->additionals));
return $this;
} | php | public function setAdditionals(array $resourceRecords): Message
{
$this->additionals = $resourceRecords;
$this->header->setAdditionalRecordsCount(count($this->additionals));
return $this;
} | [
"public",
"function",
"setAdditionals",
"(",
"array",
"$",
"resourceRecords",
")",
":",
"Message",
"{",
"$",
"this",
"->",
"additionals",
"=",
"$",
"resourceRecords",
";",
"$",
"this",
"->",
"header",
"->",
"setAdditionalRecordsCount",
"(",
"count",
"(",
"$",
... | @param array $resourceRecords
@return Message | [
"@param",
"array",
"$resourceRecords"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Message.php#L214-L220 |
yswery/PHP-DNS-SERVER | src/Resolver/SystemResolver.php | SystemResolver.getAnswer | public function getAnswer(array $queries): array
{
$answer = [];
foreach ($queries as $query) {
$answer = array_merge($answer, $this->getRecordsRecursively($query));
}
return $answer;
} | php | public function getAnswer(array $queries): array
{
$answer = [];
foreach ($queries as $query) {
$answer = array_merge($answer, $this->getRecordsRecursively($query));
}
return $answer;
} | [
"public",
"function",
"getAnswer",
"(",
"array",
"$",
"queries",
")",
":",
"array",
"{",
"$",
"answer",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"queries",
"as",
"$",
"query",
")",
"{",
"$",
"answer",
"=",
"array_merge",
"(",
"$",
"answer",
",",
"$... | @param ResourceRecord[] $queries
@return ResourceRecord[]
@throws UnsupportedTypeException | [
"@param",
"ResourceRecord",
"[]",
"$queries"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Resolver/SystemResolver.php#L42-L50 |
yswery/PHP-DNS-SERVER | src/Resolver/SystemResolver.php | SystemResolver.getRecordsRecursively | private function getRecordsRecursively(ResourceRecord $query): array
{
$records = dns_get_record($query->getName(), $this->IANA2PHP($query->getType()));
$result = [];
foreach ($records as $record) {
$result[] = (new ResourceRecord())
->setName($query->getName())
->setClass($query->getClass())
->setTtl($record['ttl'])
->setRdata($this->extractPhpRdata($record))
->setType($query->getType());
}
return $result;
} | php | private function getRecordsRecursively(ResourceRecord $query): array
{
$records = dns_get_record($query->getName(), $this->IANA2PHP($query->getType()));
$result = [];
foreach ($records as $record) {
$result[] = (new ResourceRecord())
->setName($query->getName())
->setClass($query->getClass())
->setTtl($record['ttl'])
->setRdata($this->extractPhpRdata($record))
->setType($query->getType());
}
return $result;
} | [
"private",
"function",
"getRecordsRecursively",
"(",
"ResourceRecord",
"$",
"query",
")",
":",
"array",
"{",
"$",
"records",
"=",
"dns_get_record",
"(",
"$",
"query",
"->",
"getName",
"(",
")",
",",
"$",
"this",
"->",
"IANA2PHP",
"(",
"$",
"query",
"->",
... | Resolve the $query using the system configured local DNS.
@param ResourceRecord $query
@return ResourceRecord[]
@throws UnsupportedTypeException | [
"Resolve",
"the",
"$query",
"using",
"the",
"system",
"configured",
"local",
"DNS",
"."
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Resolver/SystemResolver.php#L61-L76 |
yswery/PHP-DNS-SERVER | src/Resolver/SystemResolver.php | SystemResolver.extractPhpRdata | protected function extractPhpRdata(array $resourceRecord)
{
$type = RecordTypeEnum::getTypeFromName($resourceRecord['type']);
switch ($type) {
case RecordTypeEnum::TYPE_A:
return $resourceRecord['ip'];
case RecordTypeEnum::TYPE_AAAA:
return $resourceRecord['ipv6'];
case RecordTypeEnum::TYPE_NS:
case RecordTypeEnum::TYPE_CNAME:
case RecordTypeEnum::TYPE_PTR:
return $resourceRecord['target'];
case RecordTypeEnum::TYPE_SOA:
return [
'mname' => $resourceRecord['mname'],
'rname' => $resourceRecord['rname'],
'serial' => $resourceRecord['serial'],
'refresh' => $resourceRecord['refresh'],
'retry' => $resourceRecord['retry'],
'expire' => $resourceRecord['expire'],
'minimum' => $resourceRecord['minimum-ttl'],
];
case RecordTypeEnum::TYPE_MX:
return [
'preference' => $resourceRecord['pri'],
'exchange' => $resourceRecord['host'],
];
case RecordTypeEnum::TYPE_TXT:
return $resourceRecord['txt'];
case RecordTypeEnum::TYPE_SRV:
return [
'priority' => $resourceRecord['pri'],
'port' => $resourceRecord['port'],
'weight' => $resourceRecord['weight'],
'target' => $resourceRecord['target'],
];
default:
throw new UnsupportedTypeException(
sprintf('Record type "%s" is not a supported type.', RecordTypeEnum::getName($type))
);
}
} | php | protected function extractPhpRdata(array $resourceRecord)
{
$type = RecordTypeEnum::getTypeFromName($resourceRecord['type']);
switch ($type) {
case RecordTypeEnum::TYPE_A:
return $resourceRecord['ip'];
case RecordTypeEnum::TYPE_AAAA:
return $resourceRecord['ipv6'];
case RecordTypeEnum::TYPE_NS:
case RecordTypeEnum::TYPE_CNAME:
case RecordTypeEnum::TYPE_PTR:
return $resourceRecord['target'];
case RecordTypeEnum::TYPE_SOA:
return [
'mname' => $resourceRecord['mname'],
'rname' => $resourceRecord['rname'],
'serial' => $resourceRecord['serial'],
'refresh' => $resourceRecord['refresh'],
'retry' => $resourceRecord['retry'],
'expire' => $resourceRecord['expire'],
'minimum' => $resourceRecord['minimum-ttl'],
];
case RecordTypeEnum::TYPE_MX:
return [
'preference' => $resourceRecord['pri'],
'exchange' => $resourceRecord['host'],
];
case RecordTypeEnum::TYPE_TXT:
return $resourceRecord['txt'];
case RecordTypeEnum::TYPE_SRV:
return [
'priority' => $resourceRecord['pri'],
'port' => $resourceRecord['port'],
'weight' => $resourceRecord['weight'],
'target' => $resourceRecord['target'],
];
default:
throw new UnsupportedTypeException(
sprintf('Record type "%s" is not a supported type.', RecordTypeEnum::getName($type))
);
}
} | [
"protected",
"function",
"extractPhpRdata",
"(",
"array",
"$",
"resourceRecord",
")",
"{",
"$",
"type",
"=",
"RecordTypeEnum",
"::",
"getTypeFromName",
"(",
"$",
"resourceRecord",
"[",
"'type'",
"]",
")",
";",
"switch",
"(",
"$",
"type",
")",
"{",
"case",
... | @param array $resourceRecord
@return array|string
@throws UnsupportedTypeException | [
"@param",
"array",
"$resourceRecord"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Resolver/SystemResolver.php#L85-L127 |
yswery/PHP-DNS-SERVER | src/Resolver/SystemResolver.php | SystemResolver.IANA2PHP | private function IANA2PHP(int $type): int
{
$constantName = 'DNS_'.RecordTypeEnum::getName($type);
if (!defined($constantName)) {
throw new UnsupportedTypeException(sprintf('Record type "%d" is not a supported type.', $type));
}
$phpType = constant($constantName);
if (!is_int($phpType)) {
throw new \InvalidArgumentException(sprintf('Constant "%s" is not an integer.', $constantName));
}
return $phpType;
} | php | private function IANA2PHP(int $type): int
{
$constantName = 'DNS_'.RecordTypeEnum::getName($type);
if (!defined($constantName)) {
throw new UnsupportedTypeException(sprintf('Record type "%d" is not a supported type.', $type));
}
$phpType = constant($constantName);
if (!is_int($phpType)) {
throw new \InvalidArgumentException(sprintf('Constant "%s" is not an integer.', $constantName));
}
return $phpType;
} | [
"private",
"function",
"IANA2PHP",
"(",
"int",
"$",
"type",
")",
":",
"int",
"{",
"$",
"constantName",
"=",
"'DNS_'",
".",
"RecordTypeEnum",
"::",
"getName",
"(",
"$",
"type",
")",
";",
"if",
"(",
"!",
"defined",
"(",
"$",
"constantName",
")",
")",
"... | Maps an IANA Rdata type to the built-in PHP DNS constant.
@example $this->IANA_to_PHP(5) //Returns DNS_CNAME int(16)
@param int $type the IANA RTYPE
@return int the built-in PHP DNS_<type> constant or `false` if the type is not defined
@throws UnsupportedTypeException|\InvalidArgumentException | [
"Maps",
"an",
"IANA",
"Rdata",
"type",
"to",
"the",
"built",
"-",
"in",
"PHP",
"DNS",
"constant",
"."
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Resolver/SystemResolver.php#L140-L154 |
yswery/PHP-DNS-SERVER | src/Server.php | Server.onMessage | public function onMessage(string $message, string $address, SocketInterface $socket)
{
try {
$this->dispatch(Events::MESSAGE, new MessageEvent($socket, $address, $message));
$socket->send($this->handleQueryFromStream($message), $address);
} catch (\Exception $exception) {
$this->dispatch(Events::SERVER_EXCEPTION, new ServerExceptionEvent($exception));
}
} | php | public function onMessage(string $message, string $address, SocketInterface $socket)
{
try {
$this->dispatch(Events::MESSAGE, new MessageEvent($socket, $address, $message));
$socket->send($this->handleQueryFromStream($message), $address);
} catch (\Exception $exception) {
$this->dispatch(Events::SERVER_EXCEPTION, new ServerExceptionEvent($exception));
}
} | [
"public",
"function",
"onMessage",
"(",
"string",
"$",
"message",
",",
"string",
"$",
"address",
",",
"SocketInterface",
"$",
"socket",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"dispatch",
"(",
"Events",
"::",
"MESSAGE",
",",
"new",
"MessageEvent",
"(",
... | This methods gets called each time a query is received.
@param string $message
@param string $address
@param SocketInterface $socket | [
"This",
"methods",
"gets",
"called",
"each",
"time",
"a",
"query",
"is",
"received",
"."
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Server.php#L101-L109 |
yswery/PHP-DNS-SERVER | src/Server.php | Server.handleQueryFromStream | public function handleQueryFromStream(string $buffer): string
{
$message = Decoder::decodeMessage($buffer);
$this->dispatch(Events::QUERY_RECEIVE, new QueryReceiveEvent($message));
$responseMessage = clone $message;
$responseMessage->getHeader()
->setResponse(true)
->setRecursionAvailable($this->resolver->allowsRecursion())
->setAuthoritative($this->isAuthoritative($message->getQuestions()));
try {
$answers = $this->resolver->getAnswer($responseMessage->getQuestions());
$responseMessage->setAnswers($answers);
$this->needsAdditionalRecords($responseMessage);
$this->dispatch(Events::QUERY_RESPONSE, new QueryResponseEvent($responseMessage));
return Encoder::encodeMessage($responseMessage);
} catch (UnsupportedTypeException $e) {
$responseMessage
->setAnswers([])
->getHeader()->setRcode(Header::RCODE_NOT_IMPLEMENTED);
$this->dispatch(Events::QUERY_RESPONSE, new QueryResponseEvent($responseMessage));
return Encoder::encodeMessage($responseMessage);
}
} | php | public function handleQueryFromStream(string $buffer): string
{
$message = Decoder::decodeMessage($buffer);
$this->dispatch(Events::QUERY_RECEIVE, new QueryReceiveEvent($message));
$responseMessage = clone $message;
$responseMessage->getHeader()
->setResponse(true)
->setRecursionAvailable($this->resolver->allowsRecursion())
->setAuthoritative($this->isAuthoritative($message->getQuestions()));
try {
$answers = $this->resolver->getAnswer($responseMessage->getQuestions());
$responseMessage->setAnswers($answers);
$this->needsAdditionalRecords($responseMessage);
$this->dispatch(Events::QUERY_RESPONSE, new QueryResponseEvent($responseMessage));
return Encoder::encodeMessage($responseMessage);
} catch (UnsupportedTypeException $e) {
$responseMessage
->setAnswers([])
->getHeader()->setRcode(Header::RCODE_NOT_IMPLEMENTED);
$this->dispatch(Events::QUERY_RESPONSE, new QueryResponseEvent($responseMessage));
return Encoder::encodeMessage($responseMessage);
}
} | [
"public",
"function",
"handleQueryFromStream",
"(",
"string",
"$",
"buffer",
")",
":",
"string",
"{",
"$",
"message",
"=",
"Decoder",
"::",
"decodeMessage",
"(",
"$",
"buffer",
")",
";",
"$",
"this",
"->",
"dispatch",
"(",
"Events",
"::",
"QUERY_RECEIVE",
... | Decode a message and return an encoded response.
@param string $buffer
@return string
@throws UnsupportedTypeException | [
"Decode",
"a",
"message",
"and",
"return",
"an",
"encoded",
"response",
"."
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Server.php#L120-L146 |
yswery/PHP-DNS-SERVER | src/Server.php | Server.needsAdditionalRecords | private function needsAdditionalRecords(Message $message): void
{
foreach ($message->getAnswers() as $answer) {
$name = null;
switch ($answer->getType()) {
case RecordTypeEnum::TYPE_NS:
$name = $answer->getRdata();
break;
case RecordTypeEnum::TYPE_MX:
$name = $answer->getRdata()['exchange'];
break;
case RecordTypeEnum::TYPE_SRV:
$name = $answer->getRdata()['target'];
break;
}
if (null === $name) {
continue;
}
$query = [
(new ResourceRecord())
->setQuestion(true)
->setType(RecordTypeEnum::TYPE_A)
->setName($name),
(new ResourceRecord())
->setQuestion(true)
->setType(RecordTypeEnum::TYPE_AAAA)
->setName($name),
];
foreach ($this->resolver->getAnswer($query) as $additional) {
$message->addAdditional($additional);
}
}
} | php | private function needsAdditionalRecords(Message $message): void
{
foreach ($message->getAnswers() as $answer) {
$name = null;
switch ($answer->getType()) {
case RecordTypeEnum::TYPE_NS:
$name = $answer->getRdata();
break;
case RecordTypeEnum::TYPE_MX:
$name = $answer->getRdata()['exchange'];
break;
case RecordTypeEnum::TYPE_SRV:
$name = $answer->getRdata()['target'];
break;
}
if (null === $name) {
continue;
}
$query = [
(new ResourceRecord())
->setQuestion(true)
->setType(RecordTypeEnum::TYPE_A)
->setName($name),
(new ResourceRecord())
->setQuestion(true)
->setType(RecordTypeEnum::TYPE_AAAA)
->setName($name),
];
foreach ($this->resolver->getAnswer($query) as $additional) {
$message->addAdditional($additional);
}
}
} | [
"private",
"function",
"needsAdditionalRecords",
"(",
"Message",
"$",
"message",
")",
":",
"void",
"{",
"foreach",
"(",
"$",
"message",
"->",
"getAnswers",
"(",
")",
"as",
"$",
"answer",
")",
"{",
"$",
"name",
"=",
"null",
";",
"switch",
"(",
"$",
"ans... | Populate the additional records of a message if required.
@param Message $message | [
"Populate",
"the",
"additional",
"records",
"of",
"a",
"message",
"if",
"required",
"."
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Server.php#L185-L221 |
yswery/PHP-DNS-SERVER | src/Server.php | Server.isAuthoritative | private function isAuthoritative(array $query): bool
{
if (empty($query)) {
return false;
}
$authoritative = true;
foreach ($query as $rr) {
$authoritative &= $this->resolver->isAuthority($rr->getName());
}
return $authoritative;
} | php | private function isAuthoritative(array $query): bool
{
if (empty($query)) {
return false;
}
$authoritative = true;
foreach ($query as $rr) {
$authoritative &= $this->resolver->isAuthority($rr->getName());
}
return $authoritative;
} | [
"private",
"function",
"isAuthoritative",
"(",
"array",
"$",
"query",
")",
":",
"bool",
"{",
"if",
"(",
"empty",
"(",
"$",
"query",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"authoritative",
"=",
"true",
";",
"foreach",
"(",
"$",
"query",
"as"... | @param ResourceRecord[] $query
@return bool | [
"@param",
"ResourceRecord",
"[]",
"$query"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Server.php#L228-L240 |
yswery/PHP-DNS-SERVER | src/Resolver/JsonResolver.php | JsonResolver.processZone | protected function processZone(array $zone): array
{
$parent = rtrim($zone['domain'], '.').'.';
$defaultTtl = $zone['default-ttl'];
$rrs = $zone['resource-records'];
$resourceRecords = [];
foreach ($rrs as $rr) {
$name = $rr['name'] ?? $parent;
$class = isset($rr['class']) ? ClassEnum::getClassFromName($rr['class']) : $this->defaultClass;
$resourceRecords[] = (new ResourceRecord())
->setName($this->handleName($name, $parent))
->setClass($class)
->setType($type = RecordTypeEnum::getTypeFromName($rr['type']))
->setTtl($rr['ttl'] ?? $defaultTtl)
->setRdata($this->extractRdata($rr, $type, $parent));
}
return $resourceRecords;
} | php | protected function processZone(array $zone): array
{
$parent = rtrim($zone['domain'], '.').'.';
$defaultTtl = $zone['default-ttl'];
$rrs = $zone['resource-records'];
$resourceRecords = [];
foreach ($rrs as $rr) {
$name = $rr['name'] ?? $parent;
$class = isset($rr['class']) ? ClassEnum::getClassFromName($rr['class']) : $this->defaultClass;
$resourceRecords[] = (new ResourceRecord())
->setName($this->handleName($name, $parent))
->setClass($class)
->setType($type = RecordTypeEnum::getTypeFromName($rr['type']))
->setTtl($rr['ttl'] ?? $defaultTtl)
->setRdata($this->extractRdata($rr, $type, $parent));
}
return $resourceRecords;
} | [
"protected",
"function",
"processZone",
"(",
"array",
"$",
"zone",
")",
":",
"array",
"{",
"$",
"parent",
"=",
"rtrim",
"(",
"$",
"zone",
"[",
"'domain'",
"]",
",",
"'.'",
")",
".",
"'.'",
";",
"$",
"defaultTtl",
"=",
"$",
"zone",
"[",
"'default-ttl'... | @param array $zone
@return ResourceRecord[]
@throws UnsupportedTypeException | [
"@param",
"array",
"$zone"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Resolver/JsonResolver.php#L59-L79 |
yswery/PHP-DNS-SERVER | src/Resolver/JsonResolver.php | JsonResolver.isLegacyFormat | protected function isLegacyFormat(array $zone): bool
{
$keys = array_map(function ($value) {
return strtolower($value);
}, array_keys($zone));
return
(false === array_search('domain', $keys, true)) ||
(false === array_search('resource-records', $keys, true));
} | php | protected function isLegacyFormat(array $zone): bool
{
$keys = array_map(function ($value) {
return strtolower($value);
}, array_keys($zone));
return
(false === array_search('domain', $keys, true)) ||
(false === array_search('resource-records', $keys, true));
} | [
"protected",
"function",
"isLegacyFormat",
"(",
"array",
"$",
"zone",
")",
":",
"bool",
"{",
"$",
"keys",
"=",
"array_map",
"(",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"strtolower",
"(",
"$",
"value",
")",
";",
"}",
",",
"array_keys",
"(",
... | Determine if a $zone is in the legacy format.
@param array $zone
@return bool | [
"Determine",
"if",
"a",
"$zone",
"is",
"in",
"the",
"legacy",
"format",
"."
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Resolver/JsonResolver.php#L88-L97 |
yswery/PHP-DNS-SERVER | src/Resolver/JsonResolver.php | JsonResolver.processLegacyZone | protected function processLegacyZone(array $zones): array
{
$resourceRecords = [];
foreach ($zones as $domain => $types) {
$domain = rtrim($domain, '.').'.';
foreach ($types as $type => $data) {
$data = (array) $data;
$type = RecordTypeEnum::getTypeFromName($type);
foreach ($data as $rdata) {
$resourceRecords[] = (new ResourceRecord())
->setName($domain)
->setType($type)
->setClass($this->defaultClass)
->setTtl($this->defaultTtl)
->setRdata($rdata);
}
}
}
return $resourceRecords;
} | php | protected function processLegacyZone(array $zones): array
{
$resourceRecords = [];
foreach ($zones as $domain => $types) {
$domain = rtrim($domain, '.').'.';
foreach ($types as $type => $data) {
$data = (array) $data;
$type = RecordTypeEnum::getTypeFromName($type);
foreach ($data as $rdata) {
$resourceRecords[] = (new ResourceRecord())
->setName($domain)
->setType($type)
->setClass($this->defaultClass)
->setTtl($this->defaultTtl)
->setRdata($rdata);
}
}
}
return $resourceRecords;
} | [
"protected",
"function",
"processLegacyZone",
"(",
"array",
"$",
"zones",
")",
":",
"array",
"{",
"$",
"resourceRecords",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"zones",
"as",
"$",
"domain",
"=>",
"$",
"types",
")",
"{",
"$",
"domain",
"=",
"rtrim",
... | @param array $zones
@return array | [
"@param",
"array",
"$zones"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Resolver/JsonResolver.php#L104-L124 |
yswery/PHP-DNS-SERVER | src/Resolver/AbstractResolver.php | AbstractResolver.getAnswer | public function getAnswer(array $queries): array
{
$answers = [];
foreach ($queries as $query) {
$answer = $this->resourceRecords[$query->getName()][$query->getType()][$query->getClass()] ?? [];
if (empty($answer)) {
$answer = $this->findWildcardEntry($query);
}
$answers = array_merge($answers, $answer);
}
return $answers;
} | php | public function getAnswer(array $queries): array
{
$answers = [];
foreach ($queries as $query) {
$answer = $this->resourceRecords[$query->getName()][$query->getType()][$query->getClass()] ?? [];
if (empty($answer)) {
$answer = $this->findWildcardEntry($query);
}
$answers = array_merge($answers, $answer);
}
return $answers;
} | [
"public",
"function",
"getAnswer",
"(",
"array",
"$",
"queries",
")",
":",
"array",
"{",
"$",
"answers",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"queries",
"as",
"$",
"query",
")",
"{",
"$",
"answer",
"=",
"$",
"this",
"->",
"resourceRecords",
"[",
... | @param ResourceRecord[] $queries
@return array | [
"@param",
"ResourceRecord",
"[]",
"$queries"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Resolver/AbstractResolver.php#L48-L61 |
yswery/PHP-DNS-SERVER | src/Resolver/AbstractResolver.php | AbstractResolver.isWildcardDomain | public function isWildcardDomain(string $domain): bool
{
$domain = rtrim($domain, '.').'.';
$pattern = '/^\*\.(?:[a-zA-Z0-9\-\_]+\.)*$/';
return (bool) preg_match($pattern, $domain);
} | php | public function isWildcardDomain(string $domain): bool
{
$domain = rtrim($domain, '.').'.';
$pattern = '/^\*\.(?:[a-zA-Z0-9\-\_]+\.)*$/';
return (bool) preg_match($pattern, $domain);
} | [
"public",
"function",
"isWildcardDomain",
"(",
"string",
"$",
"domain",
")",
":",
"bool",
"{",
"$",
"domain",
"=",
"rtrim",
"(",
"$",
"domain",
",",
"'.'",
")",
".",
"'.'",
";",
"$",
"pattern",
"=",
"'/^\\*\\.(?:[a-zA-Z0-9\\-\\_]+\\.)*$/'",
";",
"return",
... | Determine if a domain is a wildcard domain.
@param string $domain
@return bool | [
"Determine",
"if",
"a",
"domain",
"is",
"a",
"wildcard",
"domain",
"."
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Resolver/AbstractResolver.php#L86-L92 |
yswery/PHP-DNS-SERVER | src/Resolver/AbstractResolver.php | AbstractResolver.addWildcardRecord | protected function addWildcardRecord(ResourceRecord $resourceRecord): void
{
$labels = explode('.', rtrim($resourceRecord->getName(), '.'));
$labels = array_reverse($labels);
$array = &$this->wildcardRecords;
foreach ($labels as $label) {
if ('*' === $label) {
$array[$label][$resourceRecord->getClass()][$resourceRecord->getType()][] = $resourceRecord;
break;
}
$array = &$array[$label];
}
} | php | protected function addWildcardRecord(ResourceRecord $resourceRecord): void
{
$labels = explode('.', rtrim($resourceRecord->getName(), '.'));
$labels = array_reverse($labels);
$array = &$this->wildcardRecords;
foreach ($labels as $label) {
if ('*' === $label) {
$array[$label][$resourceRecord->getClass()][$resourceRecord->getType()][] = $resourceRecord;
break;
}
$array = &$array[$label];
}
} | [
"protected",
"function",
"addWildcardRecord",
"(",
"ResourceRecord",
"$",
"resourceRecord",
")",
":",
"void",
"{",
"$",
"labels",
"=",
"explode",
"(",
"'.'",
",",
"rtrim",
"(",
"$",
"resourceRecord",
"->",
"getName",
"(",
")",
",",
"'.'",
")",
")",
";",
... | Add a wildcard ResourceRecord.
@param ResourceRecord $resourceRecord | [
"Add",
"a",
"wildcard",
"ResourceRecord",
"."
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Resolver/AbstractResolver.php#L113-L127 |
yswery/PHP-DNS-SERVER | src/Resolver/AbstractResolver.php | AbstractResolver.findWildcardEntry | protected function findWildcardEntry(ResourceRecord $query): array
{
$labels = explode('.', rtrim($query->getName(), '.'));
$labels = array_reverse($labels);
/** @var ResourceRecord[] $wildcards */
$wildcards = [];
$array = &$this->wildcardRecords;
foreach ($labels as $label) {
if (array_key_exists($label, $array)) {
$array = &$array[$label];
continue;
}
if (array_key_exists('*', $array)) {
$wildcards = $array['*'][$query->getClass()][$query->getType()] ?? [];
}
}
$answers = [];
foreach ($wildcards as $wildcard) {
$rr = clone $wildcard;
$rr->setName($query->getName());
$answers[] = $rr;
}
return $answers;
} | php | protected function findWildcardEntry(ResourceRecord $query): array
{
$labels = explode('.', rtrim($query->getName(), '.'));
$labels = array_reverse($labels);
/** @var ResourceRecord[] $wildcards */
$wildcards = [];
$array = &$this->wildcardRecords;
foreach ($labels as $label) {
if (array_key_exists($label, $array)) {
$array = &$array[$label];
continue;
}
if (array_key_exists('*', $array)) {
$wildcards = $array['*'][$query->getClass()][$query->getType()] ?? [];
}
}
$answers = [];
foreach ($wildcards as $wildcard) {
$rr = clone $wildcard;
$rr->setName($query->getName());
$answers[] = $rr;
}
return $answers;
} | [
"protected",
"function",
"findWildcardEntry",
"(",
"ResourceRecord",
"$",
"query",
")",
":",
"array",
"{",
"$",
"labels",
"=",
"explode",
"(",
"'.'",
",",
"rtrim",
"(",
"$",
"query",
"->",
"getName",
"(",
")",
",",
"'.'",
")",
")",
";",
"$",
"labels",
... | @param ResourceRecord $query
@return array | [
"@param",
"ResourceRecord",
"$query"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Resolver/AbstractResolver.php#L134-L161 |
yswery/PHP-DNS-SERVER | src/Resolver/AbstractResolver.php | AbstractResolver.handleName | protected function handleName(string $name, string $parent)
{
if ('@' === $name || '' === $name) {
return $parent;
}
if ('.' !== substr($name, -1, 1)) {
return $name.'.'.$parent;
}
return $name;
} | php | protected function handleName(string $name, string $parent)
{
if ('@' === $name || '' === $name) {
return $parent;
}
if ('.' !== substr($name, -1, 1)) {
return $name.'.'.$parent;
}
return $name;
} | [
"protected",
"function",
"handleName",
"(",
"string",
"$",
"name",
",",
"string",
"$",
"parent",
")",
"{",
"if",
"(",
"'@'",
"===",
"$",
"name",
"||",
"''",
"===",
"$",
"name",
")",
"{",
"return",
"$",
"parent",
";",
"}",
"if",
"(",
"'.'",
"!==",
... | Add the parent domain to names that are not fully qualified.
AbstractResolver::handleName('www', 'example.com.') //Outputs 'www.example.com.'
AbstractResolver::handleName('@', 'example.com.') //Outputs 'example.com.'
AbstractResolver::handleName('ns1.example.com.', 'example.com.') //Outputs 'ns1.example.com.'
@param $name
@param $parent
@return string | [
"Add",
"the",
"parent",
"domain",
"to",
"names",
"that",
"are",
"not",
"fully",
"qualified",
"."
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Resolver/AbstractResolver.php#L175-L186 |
yswery/PHP-DNS-SERVER | src/Resolver/AbstractResolver.php | AbstractResolver.extractRdata | protected function extractRdata(array $resourceRecord, int $type, string $parent)
{
switch ($type) {
case RecordTypeEnum::TYPE_A:
case RecordTypeEnum::TYPE_AAAA:
return $resourceRecord['address'];
case RecordTypeEnum::TYPE_NS:
case RecordTypeEnum::TYPE_CNAME:
case RecordTypeEnum::TYPE_PTR:
return $this->handleName($resourceRecord['target'], $parent);
case RecordTypeEnum::TYPE_SOA:
return [
'mname' => $this->handleName($resourceRecord['mname'], $parent),
'rname' => $this->handleName($resourceRecord['rname'], $parent),
'serial' => $resourceRecord['serial'],
'refresh' => $resourceRecord['refresh'],
'retry' => $resourceRecord['retry'],
'expire' => $resourceRecord['expire'],
'minimum' => $resourceRecord['minimum'],
];
case RecordTypeEnum::TYPE_MX:
return [
'preference' => $resourceRecord['preference'],
'exchange' => $this->handleName($resourceRecord['exchange'], $parent),
];
case RecordTypeEnum::TYPE_TXT:
return $resourceRecord['text'];
case RecordTypeEnum::TYPE_SRV:
return [
'priority' => (int) $resourceRecord['priority'],
'weight' => (int) $resourceRecord['weight'],
'port' => (int) $resourceRecord['port'],
'target' => $this->handleName($resourceRecord['target'], $parent),
];
case RecordTypeEnum::TYPE_AXFR:
case RecordTypeEnum::TYPE_ANY:
return '';
default:
throw new UnsupportedTypeException(
sprintf('Resource Record type "%s" is not a supported type.', RecordTypeEnum::getName($type))
);
}
} | php | protected function extractRdata(array $resourceRecord, int $type, string $parent)
{
switch ($type) {
case RecordTypeEnum::TYPE_A:
case RecordTypeEnum::TYPE_AAAA:
return $resourceRecord['address'];
case RecordTypeEnum::TYPE_NS:
case RecordTypeEnum::TYPE_CNAME:
case RecordTypeEnum::TYPE_PTR:
return $this->handleName($resourceRecord['target'], $parent);
case RecordTypeEnum::TYPE_SOA:
return [
'mname' => $this->handleName($resourceRecord['mname'], $parent),
'rname' => $this->handleName($resourceRecord['rname'], $parent),
'serial' => $resourceRecord['serial'],
'refresh' => $resourceRecord['refresh'],
'retry' => $resourceRecord['retry'],
'expire' => $resourceRecord['expire'],
'minimum' => $resourceRecord['minimum'],
];
case RecordTypeEnum::TYPE_MX:
return [
'preference' => $resourceRecord['preference'],
'exchange' => $this->handleName($resourceRecord['exchange'], $parent),
];
case RecordTypeEnum::TYPE_TXT:
return $resourceRecord['text'];
case RecordTypeEnum::TYPE_SRV:
return [
'priority' => (int) $resourceRecord['priority'],
'weight' => (int) $resourceRecord['weight'],
'port' => (int) $resourceRecord['port'],
'target' => $this->handleName($resourceRecord['target'], $parent),
];
case RecordTypeEnum::TYPE_AXFR:
case RecordTypeEnum::TYPE_ANY:
return '';
default:
throw new UnsupportedTypeException(
sprintf('Resource Record type "%s" is not a supported type.', RecordTypeEnum::getName($type))
);
}
} | [
"protected",
"function",
"extractRdata",
"(",
"array",
"$",
"resourceRecord",
",",
"int",
"$",
"type",
",",
"string",
"$",
"parent",
")",
"{",
"switch",
"(",
"$",
"type",
")",
"{",
"case",
"RecordTypeEnum",
"::",
"TYPE_A",
":",
"case",
"RecordTypeEnum",
":... | @param array $resourceRecord
@param int $type
@param string $parent
@return mixed
@throws UnsupportedTypeException | [
"@param",
"array",
"$resourceRecord",
"@param",
"int",
"$type",
"@param",
"string",
"$parent"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Resolver/AbstractResolver.php#L197-L239 |
yswery/PHP-DNS-SERVER | src/Decoder.php | Decoder.decodeMessage | public static function decodeMessage(string $message): Message
{
$offset = 0;
$header = self::decodeHeader($message, $offset);
$messageObject = new Message($header);
$messageObject->setQuestions(self::decodeResourceRecords($message, $header->getQuestionCount(), $offset, true));
$messageObject->setAnswers(self::decodeResourceRecords($message, $header->getAnswerCount(), $offset));
$messageObject->setAuthoritatives(self::decodeResourceRecords($message, $header->getNameServerCount(), $offset));
$messageObject->setAdditionals(self::decodeResourceRecords($message, $header->getAdditionalRecordsCount(), $offset));
return $messageObject;
} | php | public static function decodeMessage(string $message): Message
{
$offset = 0;
$header = self::decodeHeader($message, $offset);
$messageObject = new Message($header);
$messageObject->setQuestions(self::decodeResourceRecords($message, $header->getQuestionCount(), $offset, true));
$messageObject->setAnswers(self::decodeResourceRecords($message, $header->getAnswerCount(), $offset));
$messageObject->setAuthoritatives(self::decodeResourceRecords($message, $header->getNameServerCount(), $offset));
$messageObject->setAdditionals(self::decodeResourceRecords($message, $header->getAdditionalRecordsCount(), $offset));
return $messageObject;
} | [
"public",
"static",
"function",
"decodeMessage",
"(",
"string",
"$",
"message",
")",
":",
"Message",
"{",
"$",
"offset",
"=",
"0",
";",
"$",
"header",
"=",
"self",
"::",
"decodeHeader",
"(",
"$",
"message",
",",
"$",
"offset",
")",
";",
"$",
"messageOb... | @param string $message
@return Message | [
"@param",
"string",
"$message"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Decoder.php#L21-L32 |
yswery/PHP-DNS-SERVER | src/Decoder.php | Decoder.decodeDomainName | public static function decodeDomainName(string $string, int &$offset = 0): string
{
$len = ord($string[$offset]);
++$offset;
if (0 === $len) {
return '.';
}
$domainName = '';
while (0 !== $len) {
$domainName .= substr($string, $offset, $len).'.';
$offset += $len;
$len = ord($string[$offset]);
++$offset;
}
return $domainName;
} | php | public static function decodeDomainName(string $string, int &$offset = 0): string
{
$len = ord($string[$offset]);
++$offset;
if (0 === $len) {
return '.';
}
$domainName = '';
while (0 !== $len) {
$domainName .= substr($string, $offset, $len).'.';
$offset += $len;
$len = ord($string[$offset]);
++$offset;
}
return $domainName;
} | [
"public",
"static",
"function",
"decodeDomainName",
"(",
"string",
"$",
"string",
",",
"int",
"&",
"$",
"offset",
"=",
"0",
")",
":",
"string",
"{",
"$",
"len",
"=",
"ord",
"(",
"$",
"string",
"[",
"$",
"offset",
"]",
")",
";",
"++",
"$",
"offset",... | @param string $string
@param int $offset
@return string | [
"@param",
"string",
"$string",
"@param",
"int",
"$offset"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Decoder.php#L40-L58 |
yswery/PHP-DNS-SERVER | src/Decoder.php | Decoder.decodeResourceRecords | public static function decodeResourceRecords(string $pkt, int $count = 1, int &$offset = 0, bool $isQuestion = false): array
{
$resourceRecords = [];
for ($i = 0; $i < $count; ++$i) {
($rr = new ResourceRecord())
->setQuestion($isQuestion)
->setName(self::decodeDomainName($pkt, $offset));
if ($rr->isQuestion()) {
$values = unpack('ntype/nclass', substr($pkt, $offset, 4));
$rr->setType($values['type'])->setClass($values['class']);
$offset += 4;
} else {
$values = unpack('ntype/nclass/Nttl/ndlength', substr($pkt, $offset, 10));
$rr->setType($values['type'])->setClass($values['class'])->setTtl($values['ttl']);
$offset += 10;
//Ignore unsupported types.
try {
$rr->setRdata(RdataDecoder::decodeRdata($rr->getType(), substr($pkt, $offset, $values['dlength'])));
} catch (UnsupportedTypeException $e) {
$offset += $values['dlength'];
continue;
}
$offset += $values['dlength'];
}
$resourceRecords[] = $rr;
}
return $resourceRecords;
} | php | public static function decodeResourceRecords(string $pkt, int $count = 1, int &$offset = 0, bool $isQuestion = false): array
{
$resourceRecords = [];
for ($i = 0; $i < $count; ++$i) {
($rr = new ResourceRecord())
->setQuestion($isQuestion)
->setName(self::decodeDomainName($pkt, $offset));
if ($rr->isQuestion()) {
$values = unpack('ntype/nclass', substr($pkt, $offset, 4));
$rr->setType($values['type'])->setClass($values['class']);
$offset += 4;
} else {
$values = unpack('ntype/nclass/Nttl/ndlength', substr($pkt, $offset, 10));
$rr->setType($values['type'])->setClass($values['class'])->setTtl($values['ttl']);
$offset += 10;
//Ignore unsupported types.
try {
$rr->setRdata(RdataDecoder::decodeRdata($rr->getType(), substr($pkt, $offset, $values['dlength'])));
} catch (UnsupportedTypeException $e) {
$offset += $values['dlength'];
continue;
}
$offset += $values['dlength'];
}
$resourceRecords[] = $rr;
}
return $resourceRecords;
} | [
"public",
"static",
"function",
"decodeResourceRecords",
"(",
"string",
"$",
"pkt",
",",
"int",
"$",
"count",
"=",
"1",
",",
"int",
"&",
"$",
"offset",
"=",
"0",
",",
"bool",
"$",
"isQuestion",
"=",
"false",
")",
":",
"array",
"{",
"$",
"resourceRecord... | @param string $pkt
@param int $offset
@param int $count The number of resource records to decode
@param bool $isQuestion Is the resource record from the question section
@return ResourceRecord[] | [
"@param",
"string",
"$pkt",
"@param",
"int",
"$offset",
"@param",
"int",
"$count",
"The",
"number",
"of",
"resource",
"records",
"to",
"decode",
"@param",
"bool",
"$isQuestion",
"Is",
"the",
"resource",
"record",
"from",
"the",
"question",
"section"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Decoder.php#L68-L100 |
yswery/PHP-DNS-SERVER | src/Decoder.php | Decoder.decodeHeader | public static function decodeHeader(string $pkt, int &$offset = 0): Header
{
$data = unpack('nid/nflags/nqdcount/nancount/nnscount/narcount', $pkt);
$flags = self::decodeFlags($data['flags']);
$offset += 12;
return (new Header())
->setId($data['id'])
->setResponse($flags['qr'])
->setOpcode($flags['opcode'])
->setAuthoritative($flags['aa'])
->setTruncated($flags['tc'])
->setRecursionDesired($flags['rd'])
->setRecursionAvailable($flags['ra'])
->setZ($flags['z'])
->setRcode($flags['rcode'])
->setQuestionCount($data['qdcount'])
->setAnswerCount($data['ancount'])
->setNameServerCount($data['nscount'])
->setAdditionalRecordsCount($data['arcount']);
} | php | public static function decodeHeader(string $pkt, int &$offset = 0): Header
{
$data = unpack('nid/nflags/nqdcount/nancount/nnscount/narcount', $pkt);
$flags = self::decodeFlags($data['flags']);
$offset += 12;
return (new Header())
->setId($data['id'])
->setResponse($flags['qr'])
->setOpcode($flags['opcode'])
->setAuthoritative($flags['aa'])
->setTruncated($flags['tc'])
->setRecursionDesired($flags['rd'])
->setRecursionAvailable($flags['ra'])
->setZ($flags['z'])
->setRcode($flags['rcode'])
->setQuestionCount($data['qdcount'])
->setAnswerCount($data['ancount'])
->setNameServerCount($data['nscount'])
->setAdditionalRecordsCount($data['arcount']);
} | [
"public",
"static",
"function",
"decodeHeader",
"(",
"string",
"$",
"pkt",
",",
"int",
"&",
"$",
"offset",
"=",
"0",
")",
":",
"Header",
"{",
"$",
"data",
"=",
"unpack",
"(",
"'nid/nflags/nqdcount/nancount/nnscount/narcount'",
",",
"$",
"pkt",
")",
";",
"$... | @param string $pkt
@param int $offset
@return Header | [
"@param",
"string",
"$pkt",
"@param",
"int",
"$offset"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Decoder.php#L108-L128 |
yswery/PHP-DNS-SERVER | src/Decoder.php | Decoder.decodeFlags | private static function decodeFlags($flags): array
{
return [
'qr' => $flags >> 15 & 0x1,
'opcode' => $flags >> 11 & 0xf,
'aa' => $flags >> 10 & 0x1,
'tc' => $flags >> 9 & 0x1,
'rd' => $flags >> 8 & 0x1,
'ra' => $flags >> 7 & 0x1,
'z' => $flags >> 4 & 0x7,
'rcode' => $flags & 0xf,
];
} | php | private static function decodeFlags($flags): array
{
return [
'qr' => $flags >> 15 & 0x1,
'opcode' => $flags >> 11 & 0xf,
'aa' => $flags >> 10 & 0x1,
'tc' => $flags >> 9 & 0x1,
'rd' => $flags >> 8 & 0x1,
'ra' => $flags >> 7 & 0x1,
'z' => $flags >> 4 & 0x7,
'rcode' => $flags & 0xf,
];
} | [
"private",
"static",
"function",
"decodeFlags",
"(",
"$",
"flags",
")",
":",
"array",
"{",
"return",
"[",
"'qr'",
"=>",
"$",
"flags",
">>",
"15",
"&",
"0x1",
",",
"'opcode'",
"=>",
"$",
"flags",
">>",
"11",
"&",
"0xf",
",",
"'aa'",
"=>",
"$",
"flag... | @param string $flags
@return array | [
"@param",
"string",
"$flags"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Decoder.php#L135-L147 |
yswery/PHP-DNS-SERVER | src/RecordTypeEnum.php | RecordTypeEnum.getName | public static function getName(int $type): string
{
if (!self::isValid($type)) {
throw new \InvalidArgumentException(sprintf('The integer "%d" does not correspond to a valid type', $type));
}
return self::$names[$type];
} | php | public static function getName(int $type): string
{
if (!self::isValid($type)) {
throw new \InvalidArgumentException(sprintf('The integer "%d" does not correspond to a valid type', $type));
}
return self::$names[$type];
} | [
"public",
"static",
"function",
"getName",
"(",
"int",
"$",
"type",
")",
":",
"string",
"{",
"if",
"(",
"!",
"self",
"::",
"isValid",
"(",
"$",
"type",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'The integer \"... | Get the name of an RDATA type. E.g. RecordTypeEnum::getName(6) return 'SOA'.
@param int $type The index of the type
@return string
@throws \InvalidArgumentException | [
"Get",
"the",
"name",
"of",
"an",
"RDATA",
"type",
".",
"E",
".",
"g",
".",
"RecordTypeEnum",
"::",
"getName",
"(",
"6",
")",
"return",
"SOA",
"."
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/RecordTypeEnum.php#L122-L129 |
yswery/PHP-DNS-SERVER | src/RecordTypeEnum.php | RecordTypeEnum.getTypeFromName | public static function getTypeFromName(string $name): int
{
$type = array_search(strtoupper(trim($name)), self::$names);
if (false === $type || !is_int($type)) {
throw new \InvalidArgumentException(sprintf('RData type "%s" is not defined.', $name));
}
return $type;
} | php | public static function getTypeFromName(string $name): int
{
$type = array_search(strtoupper(trim($name)), self::$names);
if (false === $type || !is_int($type)) {
throw new \InvalidArgumentException(sprintf('RData type "%s" is not defined.', $name));
}
return $type;
} | [
"public",
"static",
"function",
"getTypeFromName",
"(",
"string",
"$",
"name",
")",
":",
"int",
"{",
"$",
"type",
"=",
"array_search",
"(",
"strtoupper",
"(",
"trim",
"(",
"$",
"name",
")",
")",
",",
"self",
"::",
"$",
"names",
")",
";",
"if",
"(",
... | Return the integer value of an RDATA type. E.g. getTypeFromName('MX') returns 15.
@param string $name The name of the record type, e.g. = 'A' or 'MX' or 'SOA'
@return int
@throws \InvalidArgumentException | [
"Return",
"the",
"integer",
"value",
"of",
"an",
"RDATA",
"type",
".",
"E",
".",
"g",
".",
"getTypeFromName",
"(",
"MX",
")",
"returns",
"15",
"."
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/RecordTypeEnum.php#L140-L148 |
yswery/PHP-DNS-SERVER | src/Resolver/XmlResolver.php | XmlResolver.process | private function process($xml): array
{
$parent = (string) $xml->{'name'};
$defaultTtl = (int) $xml->{'default-ttl'};
$resourceRecords = [];
foreach ($xml->{'resource-records'}->{'resource-record'} as $rr) {
$name = (string) $rr->{'name'} ?? $parent;
$class = isset($rr->{'class'}) ? ClassEnum::getClassFromName($rr->{'class'}) : $this->defaultClass;
$ttl = isset($rr->{'ttl'}) ? (int) $rr->{'ttl'} : $defaultTtl;
$resourceRecords[] = (new ResourceRecord())
->setName($this->handleName($name, $parent))
->setClass($class)
->setType($type = RecordTypeEnum::getTypeFromName($rr->{'type'}))
->setTtl($ttl)
->setRdata($this->extractRdata($this->simpleXmlToArray($rr->{'rdata'}), $type, $parent));
}
return $resourceRecords;
} | php | private function process($xml): array
{
$parent = (string) $xml->{'name'};
$defaultTtl = (int) $xml->{'default-ttl'};
$resourceRecords = [];
foreach ($xml->{'resource-records'}->{'resource-record'} as $rr) {
$name = (string) $rr->{'name'} ?? $parent;
$class = isset($rr->{'class'}) ? ClassEnum::getClassFromName($rr->{'class'}) : $this->defaultClass;
$ttl = isset($rr->{'ttl'}) ? (int) $rr->{'ttl'} : $defaultTtl;
$resourceRecords[] = (new ResourceRecord())
->setName($this->handleName($name, $parent))
->setClass($class)
->setType($type = RecordTypeEnum::getTypeFromName($rr->{'type'}))
->setTtl($ttl)
->setRdata($this->extractRdata($this->simpleXmlToArray($rr->{'rdata'}), $type, $parent));
}
return $resourceRecords;
} | [
"private",
"function",
"process",
"(",
"$",
"xml",
")",
":",
"array",
"{",
"$",
"parent",
"=",
"(",
"string",
")",
"$",
"xml",
"->",
"{",
"'name'",
"}",
";",
"$",
"defaultTtl",
"=",
"(",
"int",
")",
"$",
"xml",
"->",
"{",
"'default-ttl'",
"}",
";... | @param object $xml
@return ResourceRecord[]
@throws UnsupportedTypeException | [
"@param",
"object",
"$xml"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Resolver/XmlResolver.php#L48-L68 |
yswery/PHP-DNS-SERVER | src/Resolver/XmlResolver.php | XmlResolver.simpleXmlToArray | private function simpleXmlToArray(\SimpleXMLElement $xmlObject): array
{
$array = [];
foreach ($xmlObject->children() as $node) {
$array[$node->getName()] = is_array($node) ? $this->simpleXmlToArray($node) : (string) $node;
}
return $array;
} | php | private function simpleXmlToArray(\SimpleXMLElement $xmlObject): array
{
$array = [];
foreach ($xmlObject->children() as $node) {
$array[$node->getName()] = is_array($node) ? $this->simpleXmlToArray($node) : (string) $node;
}
return $array;
} | [
"private",
"function",
"simpleXmlToArray",
"(",
"\\",
"SimpleXMLElement",
"$",
"xmlObject",
")",
":",
"array",
"{",
"$",
"array",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"xmlObject",
"->",
"children",
"(",
")",
"as",
"$",
"node",
")",
"{",
"$",
"array... | Convert a SimpleXML object to an associative array.
@param \SimpleXMLElement $xmlObject
@return array | [
"Convert",
"a",
"SimpleXML",
"object",
"to",
"an",
"associative",
"array",
"."
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Resolver/XmlResolver.php#L77-L85 |
yswery/PHP-DNS-SERVER | src/Resolver/StackableResolver.php | StackableResolver.getAnswer | public function getAnswer(array $question): array
{
foreach ($this->resolvers as $resolver) {
$answer = $resolver->getAnswer($question);
if (!empty($answer)) {
return $answer;
}
}
return [];
} | php | public function getAnswer(array $question): array
{
foreach ($this->resolvers as $resolver) {
$answer = $resolver->getAnswer($question);
if (!empty($answer)) {
return $answer;
}
}
return [];
} | [
"public",
"function",
"getAnswer",
"(",
"array",
"$",
"question",
")",
":",
"array",
"{",
"foreach",
"(",
"$",
"this",
"->",
"resolvers",
"as",
"$",
"resolver",
")",
"{",
"$",
"answer",
"=",
"$",
"resolver",
"->",
"getAnswer",
"(",
"$",
"question",
")"... | @param ResourceRecord[] $question
@return array | [
"@param",
"ResourceRecord",
"[]",
"$question"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Resolver/StackableResolver.php#L33-L43 |
yswery/PHP-DNS-SERVER | src/Resolver/StackableResolver.php | StackableResolver.allowsRecursion | public function allowsRecursion(): bool
{
foreach ($this->resolvers as $resolver) {
if ($resolver->allowsRecursion()) {
return true;
}
}
return false;
} | php | public function allowsRecursion(): bool
{
foreach ($this->resolvers as $resolver) {
if ($resolver->allowsRecursion()) {
return true;
}
}
return false;
} | [
"public",
"function",
"allowsRecursion",
"(",
")",
":",
"bool",
"{",
"foreach",
"(",
"$",
"this",
"->",
"resolvers",
"as",
"$",
"resolver",
")",
"{",
"if",
"(",
"$",
"resolver",
"->",
"allowsRecursion",
"(",
")",
")",
"{",
"return",
"true",
";",
"}",
... | Check if any of the resolvers supports recursion.
@return bool true if any resolver supports recursion | [
"Check",
"if",
"any",
"of",
"the",
"resolvers",
"supports",
"recursion",
"."
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Resolver/StackableResolver.php#L50-L59 |
yswery/PHP-DNS-SERVER | src/Resolver/StackableResolver.php | StackableResolver.isAuthority | public function isAuthority($domain): bool
{
foreach ($this->resolvers as $resolver) {
if ($resolver->isAuthority($domain)) {
return true;
}
}
return false;
} | php | public function isAuthority($domain): bool
{
foreach ($this->resolvers as $resolver) {
if ($resolver->isAuthority($domain)) {
return true;
}
}
return false;
} | [
"public",
"function",
"isAuthority",
"(",
"$",
"domain",
")",
":",
"bool",
"{",
"foreach",
"(",
"$",
"this",
"->",
"resolvers",
"as",
"$",
"resolver",
")",
"{",
"if",
"(",
"$",
"resolver",
"->",
"isAuthority",
"(",
"$",
"domain",
")",
")",
"{",
"retu... | /*
Check if any resolver knows about a domain
@param string $domain the domain to check for
@return boolean true if some resolver holds info about $domain | [
"/",
"*",
"Check",
"if",
"any",
"resolver",
"knows",
"about",
"a",
"domain"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Resolver/StackableResolver.php#L67-L76 |
yswery/PHP-DNS-SERVER | src/Encoder.php | Encoder.encodeMessage | public static function encodeMessage(Message $message): string
{
return
self::encodeHeader($message->getHeader()).
self::encodeResourceRecords($message->getQuestions()).
self::encodeResourceRecords($message->getAnswers()).
self::encodeResourceRecords($message->getAuthoritatives()).
self::encodeResourceRecords($message->getAdditionals());
} | php | public static function encodeMessage(Message $message): string
{
return
self::encodeHeader($message->getHeader()).
self::encodeResourceRecords($message->getQuestions()).
self::encodeResourceRecords($message->getAnswers()).
self::encodeResourceRecords($message->getAuthoritatives()).
self::encodeResourceRecords($message->getAdditionals());
} | [
"public",
"static",
"function",
"encodeMessage",
"(",
"Message",
"$",
"message",
")",
":",
"string",
"{",
"return",
"self",
"::",
"encodeHeader",
"(",
"$",
"message",
"->",
"getHeader",
"(",
")",
")",
".",
"self",
"::",
"encodeResourceRecords",
"(",
"$",
"... | @param Message $message
@return string
@throws UnsupportedTypeException | [
"@param",
"Message",
"$message"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Encoder.php#L23-L31 |
yswery/PHP-DNS-SERVER | src/Encoder.php | Encoder.encodeDomainName | public static function encodeDomainName($domain): string
{
if ('.' === $domain) {
return chr(0);
}
$domain = rtrim($domain, '.').'.';
$res = '';
foreach (explode('.', $domain) as $label) {
$res .= chr(strlen($label)).$label;
}
return $res;
} | php | public static function encodeDomainName($domain): string
{
if ('.' === $domain) {
return chr(0);
}
$domain = rtrim($domain, '.').'.';
$res = '';
foreach (explode('.', $domain) as $label) {
$res .= chr(strlen($label)).$label;
}
return $res;
} | [
"public",
"static",
"function",
"encodeDomainName",
"(",
"$",
"domain",
")",
":",
"string",
"{",
"if",
"(",
"'.'",
"===",
"$",
"domain",
")",
"{",
"return",
"chr",
"(",
"0",
")",
";",
"}",
"$",
"domain",
"=",
"rtrim",
"(",
"$",
"domain",
",",
"'.'"... | Encode a domain name as a sequence of labels.
@param $domain
@return string | [
"Encode",
"a",
"domain",
"name",
"as",
"a",
"sequence",
"of",
"labels",
"."
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Encoder.php#L40-L54 |
yswery/PHP-DNS-SERVER | src/Encoder.php | Encoder.encodeResourceRecord | public static function encodeResourceRecord(ResourceRecord $rr): string
{
$encoded = self::encodeDomainName($rr->getName());
if ($rr->isQuestion()) {
return $encoded.pack('nn', $rr->getType(), $rr->getClass());
}
$data = RdataEncoder::encodeRdata($rr->getType(), $rr->getRdata());
$encoded .= pack('nnNn', $rr->getType(), $rr->getClass(), $rr->getTtl(), strlen($data));
return $encoded.$data;
} | php | public static function encodeResourceRecord(ResourceRecord $rr): string
{
$encoded = self::encodeDomainName($rr->getName());
if ($rr->isQuestion()) {
return $encoded.pack('nn', $rr->getType(), $rr->getClass());
}
$data = RdataEncoder::encodeRdata($rr->getType(), $rr->getRdata());
$encoded .= pack('nnNn', $rr->getType(), $rr->getClass(), $rr->getTtl(), strlen($data));
return $encoded.$data;
} | [
"public",
"static",
"function",
"encodeResourceRecord",
"(",
"ResourceRecord",
"$",
"rr",
")",
":",
"string",
"{",
"$",
"encoded",
"=",
"self",
"::",
"encodeDomainName",
"(",
"$",
"rr",
"->",
"getName",
"(",
")",
")",
";",
"if",
"(",
"$",
"rr",
"->",
"... | @param ResourceRecord $rr
@return string
@throws UnsupportedTypeException | [
"@param",
"ResourceRecord",
"$rr"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Encoder.php#L77-L88 |
yswery/PHP-DNS-SERVER | src/Encoder.php | Encoder.encodeHeader | public static function encodeHeader(Header $header): string
{
return pack(
'nnnnnn',
$header->getId(),
self::encodeFlags($header),
$header->getQuestionCount(),
$header->getAnswerCount(),
$header->getNameServerCount(),
$header->getAdditionalRecordsCount()
);
} | php | public static function encodeHeader(Header $header): string
{
return pack(
'nnnnnn',
$header->getId(),
self::encodeFlags($header),
$header->getQuestionCount(),
$header->getAnswerCount(),
$header->getNameServerCount(),
$header->getAdditionalRecordsCount()
);
} | [
"public",
"static",
"function",
"encodeHeader",
"(",
"Header",
"$",
"header",
")",
":",
"string",
"{",
"return",
"pack",
"(",
"'nnnnnn'",
",",
"$",
"header",
"->",
"getId",
"(",
")",
",",
"self",
"::",
"encodeFlags",
"(",
"$",
"header",
")",
",",
"$",
... | @param Header $header
@return string | [
"@param",
"Header",
"$header"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Encoder.php#L95-L106 |
yswery/PHP-DNS-SERVER | src/Encoder.php | Encoder.encodeFlags | private static function encodeFlags(Header $header): int
{
return 0x0 |
($header->isResponse() & 0x1) << 15 |
($header->getOpcode() & 0xf) << 11 |
($header->isAuthoritative() & 0x1) << 10 |
($header->isTruncated() & 0x1) << 9 |
($header->isRecursionDesired() & 0x1) << 8 |
($header->isRecursionAvailable() & 0x1) << 7 |
($header->getZ() & 0x7) << 4 |
($header->getRcode() & 0xf);
} | php | private static function encodeFlags(Header $header): int
{
return 0x0 |
($header->isResponse() & 0x1) << 15 |
($header->getOpcode() & 0xf) << 11 |
($header->isAuthoritative() & 0x1) << 10 |
($header->isTruncated() & 0x1) << 9 |
($header->isRecursionDesired() & 0x1) << 8 |
($header->isRecursionAvailable() & 0x1) << 7 |
($header->getZ() & 0x7) << 4 |
($header->getRcode() & 0xf);
} | [
"private",
"static",
"function",
"encodeFlags",
"(",
"Header",
"$",
"header",
")",
":",
"int",
"{",
"return",
"0x0",
"|",
"(",
"$",
"header",
"->",
"isResponse",
"(",
")",
"&",
"0x1",
")",
"<<",
"15",
"|",
"(",
"$",
"header",
"->",
"getOpcode",
"(",
... | Encode the bit field of the Header between "ID" and "QDCOUNT".
@param Header $header
@return int | [
"Encode",
"the",
"bit",
"field",
"of",
"the",
"Header",
"between",
"ID",
"and",
"QDCOUNT",
"."
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/Encoder.php#L115-L126 |
yswery/PHP-DNS-SERVER | src/ClassEnum.php | ClassEnum.getClassFromName | public static function getClassFromName(string $name): int
{
$class = array_search(strtoupper($name), self::$classes, true);
if (false === $class || !is_int($class)) {
throw new \InvalidArgumentException(sprintf('Class: "%s" is not defined.', $name));
}
return $class;
} | php | public static function getClassFromName(string $name): int
{
$class = array_search(strtoupper($name), self::$classes, true);
if (false === $class || !is_int($class)) {
throw new \InvalidArgumentException(sprintf('Class: "%s" is not defined.', $name));
}
return $class;
} | [
"public",
"static",
"function",
"getClassFromName",
"(",
"string",
"$",
"name",
")",
":",
"int",
"{",
"$",
"class",
"=",
"array_search",
"(",
"strtoupper",
"(",
"$",
"name",
")",
",",
"self",
"::",
"$",
"classes",
",",
"true",
")",
";",
"if",
"(",
"f... | @param string $name
@return int | [
"@param",
"string",
"$name"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/ClassEnum.php#L64-L73 |
yswery/PHP-DNS-SERVER | src/RdataDecoder.php | RdataDecoder.decodeRdata | public static function decodeRdata(int $type, string $rdata)
{
if (!array_key_exists($type, self::$methodMap)) {
throw new UnsupportedTypeException(
sprintf('Record type "%s" is not a supported type.', RecordTypeEnum::getName($type))
);
}
return call_user_func(['self', self::$methodMap[$type]], $rdata);
} | php | public static function decodeRdata(int $type, string $rdata)
{
if (!array_key_exists($type, self::$methodMap)) {
throw new UnsupportedTypeException(
sprintf('Record type "%s" is not a supported type.', RecordTypeEnum::getName($type))
);
}
return call_user_func(['self', self::$methodMap[$type]], $rdata);
} | [
"public",
"static",
"function",
"decodeRdata",
"(",
"int",
"$",
"type",
",",
"string",
"$",
"rdata",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"type",
",",
"self",
"::",
"$",
"methodMap",
")",
")",
"{",
"throw",
"new",
"UnsupportedTypeExcep... | @param int $type
@param string $rdata
@return array|string
@throws UnsupportedTypeException | [
"@param",
"int",
"$type",
"@param",
"string",
"$rdata"
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/RdataDecoder.php#L42-L51 |
yswery/PHP-DNS-SERVER | src/RdataDecoder.php | RdataDecoder.soa | public static function soa(string $rdata): array
{
$offset = 0;
return array_merge(
[
'mname' => Decoder::decodeDomainName($rdata, $offset),
'rname' => Decoder::decodeDomainName($rdata, $offset),
],
unpack('Nserial/Nrefresh/Nretry/Nexpire/Nminimum', substr($rdata, $offset))
);
} | php | public static function soa(string $rdata): array
{
$offset = 0;
return array_merge(
[
'mname' => Decoder::decodeDomainName($rdata, $offset),
'rname' => Decoder::decodeDomainName($rdata, $offset),
],
unpack('Nserial/Nrefresh/Nretry/Nexpire/Nminimum', substr($rdata, $offset))
);
} | [
"public",
"static",
"function",
"soa",
"(",
"string",
"$",
"rdata",
")",
":",
"array",
"{",
"$",
"offset",
"=",
"0",
";",
"return",
"array_merge",
"(",
"[",
"'mname'",
"=>",
"Decoder",
"::",
"decodeDomainName",
"(",
"$",
"rdata",
",",
"$",
"offset",
")... | Exclusively for SOA records.
@param string $rdata
@return array | [
"Exclusively",
"for",
"SOA",
"records",
"."
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/RdataDecoder.php#L84-L95 |
yswery/PHP-DNS-SERVER | src/RdataDecoder.php | RdataDecoder.txt | public static function txt(string $rdata): string
{
$len = ord($rdata[0]);
if ((strlen($rdata) + 1) < $len) {
return '';
}
return substr($rdata, 1, $len);
} | php | public static function txt(string $rdata): string
{
$len = ord($rdata[0]);
if ((strlen($rdata) + 1) < $len) {
return '';
}
return substr($rdata, 1, $len);
} | [
"public",
"static",
"function",
"txt",
"(",
"string",
"$",
"rdata",
")",
":",
"string",
"{",
"$",
"len",
"=",
"ord",
"(",
"$",
"rdata",
"[",
"0",
"]",
")",
";",
"if",
"(",
"(",
"strlen",
"(",
"$",
"rdata",
")",
"+",
"1",
")",
"<",
"$",
"len",... | Exclusively for TXT records.
@param string $rdata
@return string | [
"Exclusively",
"for",
"TXT",
"records",
"."
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/RdataDecoder.php#L119-L127 |
yswery/PHP-DNS-SERVER | src/RdataDecoder.php | RdataDecoder.srv | public static function srv(string $rdata): array
{
$offset = 6;
$values = unpack('npriority/nweight/nport', $rdata);
$values['target'] = Decoder::decodeDomainName($rdata, $offset);
return $values;
} | php | public static function srv(string $rdata): array
{
$offset = 6;
$values = unpack('npriority/nweight/nport', $rdata);
$values['target'] = Decoder::decodeDomainName($rdata, $offset);
return $values;
} | [
"public",
"static",
"function",
"srv",
"(",
"string",
"$",
"rdata",
")",
":",
"array",
"{",
"$",
"offset",
"=",
"6",
";",
"$",
"values",
"=",
"unpack",
"(",
"'npriority/nweight/nport'",
",",
"$",
"rdata",
")",
";",
"$",
"values",
"[",
"'target'",
"]",
... | Exclusively for SRV records.
@param string $rdata
@return array | [
"Exclusively",
"for",
"SRV",
"records",
"."
] | train | https://github.com/yswery/PHP-DNS-SERVER/blob/6d192b3a7ab56252977f0e84925c19a6cdf3fd11/src/RdataDecoder.php#L136-L143 |
Josantonius/PHP-Session | src/Session.php | Session.init | public static function init($lifeTime = 0)
{
if (self::$sessionStarted == false) {
session_set_cookie_params($lifeTime);
session_start();
return self::$sessionStarted = true;
}
return false;
} | php | public static function init($lifeTime = 0)
{
if (self::$sessionStarted == false) {
session_set_cookie_params($lifeTime);
session_start();
return self::$sessionStarted = true;
}
return false;
} | [
"public",
"static",
"function",
"init",
"(",
"$",
"lifeTime",
"=",
"0",
")",
"{",
"if",
"(",
"self",
"::",
"$",
"sessionStarted",
"==",
"false",
")",
"{",
"session_set_cookie_params",
"(",
"$",
"lifeTime",
")",
";",
"session_start",
"(",
")",
";",
"retur... | If session has not started, start sessions.
@param int $lifeTime → lifetime of session in seconds
@return bool | [
"If",
"session",
"has",
"not",
"started",
"start",
"sessions",
"."
] | train | https://github.com/Josantonius/PHP-Session/blob/08b09ad43927d172963d15da29259bcdf90a8f43/src/Session.php#L64-L74 |
Josantonius/PHP-Session | src/Session.php | Session.set | public static function set($key, $value = false)
{
if (is_array($key) && $value == false) {
foreach ($key as $name => $value) {
$_SESSION[self::$prefix . $name] = $value;
}
} else {
$_SESSION[self::$prefix . $key] = $value;
}
return true;
} | php | public static function set($key, $value = false)
{
if (is_array($key) && $value == false) {
foreach ($key as $name => $value) {
$_SESSION[self::$prefix . $name] = $value;
}
} else {
$_SESSION[self::$prefix . $key] = $value;
}
return true;
} | [
"public",
"static",
"function",
"set",
"(",
"$",
"key",
",",
"$",
"value",
"=",
"false",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"key",
")",
"&&",
"$",
"value",
"==",
"false",
")",
"{",
"foreach",
"(",
"$",
"key",
"as",
"$",
"name",
"=>",
"$... | Add value to a session.
@param string $key → name the data to save
@param mixed $value → the data to save
@return bool true | [
"Add",
"value",
"to",
"a",
"session",
"."
] | train | https://github.com/Josantonius/PHP-Session/blob/08b09ad43927d172963d15da29259bcdf90a8f43/src/Session.php#L84-L95 |
Josantonius/PHP-Session | src/Session.php | Session.pull | public static function pull($key)
{
if (isset($_SESSION[self::$prefix . $key])) {
$value = $_SESSION[self::$prefix . $key];
unset($_SESSION[self::$prefix . $key]);
return $value;
}
return null;
} | php | public static function pull($key)
{
if (isset($_SESSION[self::$prefix . $key])) {
$value = $_SESSION[self::$prefix . $key];
unset($_SESSION[self::$prefix . $key]);
return $value;
}
return null;
} | [
"public",
"static",
"function",
"pull",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"_SESSION",
"[",
"self",
"::",
"$",
"prefix",
".",
"$",
"key",
"]",
")",
")",
"{",
"$",
"value",
"=",
"$",
"_SESSION",
"[",
"self",
"::",
"$",
"pre... | Extract session item, delete session item and finally return the item.
@param string $key → item to extract
@return mixed|null → return item or null when key does not exists | [
"Extract",
"session",
"item",
"delete",
"session",
"item",
"and",
"finally",
"return",
"the",
"item",
"."
] | train | https://github.com/Josantonius/PHP-Session/blob/08b09ad43927d172963d15da29259bcdf90a8f43/src/Session.php#L104-L114 |
Josantonius/PHP-Session | src/Session.php | Session.get | public static function get($key = '', $secondkey = false)
{
$name = self::$prefix . $key;
if (empty($key)) {
return isset($_SESSION) ? $_SESSION : null;
} elseif ($secondkey == true) {
if (isset($_SESSION[$name][$secondkey])) {
return $_SESSION[$name][$secondkey];
}
}
return isset($_SESSION[$name]) ? $_SESSION[$name] : null;
} | php | public static function get($key = '', $secondkey = false)
{
$name = self::$prefix . $key;
if (empty($key)) {
return isset($_SESSION) ? $_SESSION : null;
} elseif ($secondkey == true) {
if (isset($_SESSION[$name][$secondkey])) {
return $_SESSION[$name][$secondkey];
}
}
return isset($_SESSION[$name]) ? $_SESSION[$name] : null;
} | [
"public",
"static",
"function",
"get",
"(",
"$",
"key",
"=",
"''",
",",
"$",
"secondkey",
"=",
"false",
")",
"{",
"$",
"name",
"=",
"self",
"::",
"$",
"prefix",
".",
"$",
"key",
";",
"if",
"(",
"empty",
"(",
"$",
"key",
")",
")",
"{",
"return",... | Get item from session.
@param string $key → item to look for in session
@param string|bool $secondkey → if used then use as a second key
@return mixed|null → key value, or null if key doesn't exists | [
"Get",
"item",
"from",
"session",
"."
] | train | https://github.com/Josantonius/PHP-Session/blob/08b09ad43927d172963d15da29259bcdf90a8f43/src/Session.php#L124-L137 |
Josantonius/PHP-Session | src/Session.php | Session.destroy | public static function destroy($key = '', $prefix = false)
{
if (self::$sessionStarted == true) {
if ($key == '' && $prefix == false) {
session_unset();
session_destroy();
} elseif ($prefix == true) {
foreach ($_SESSION as $index => $value) {
if (strpos($index, self::$prefix) === 0) {
unset($_SESSION[$index]);
}
}
} else {
unset($_SESSION[self::$prefix . $key]);
}
return true;
}
return false;
} | php | public static function destroy($key = '', $prefix = false)
{
if (self::$sessionStarted == true) {
if ($key == '' && $prefix == false) {
session_unset();
session_destroy();
} elseif ($prefix == true) {
foreach ($_SESSION as $index => $value) {
if (strpos($index, self::$prefix) === 0) {
unset($_SESSION[$index]);
}
}
} else {
unset($_SESSION[self::$prefix . $key]);
}
return true;
}
return false;
} | [
"public",
"static",
"function",
"destroy",
"(",
"$",
"key",
"=",
"''",
",",
"$",
"prefix",
"=",
"false",
")",
"{",
"if",
"(",
"self",
"::",
"$",
"sessionStarted",
"==",
"true",
")",
"{",
"if",
"(",
"$",
"key",
"==",
"''",
"&&",
"$",
"prefix",
"==... | Empties and destroys the session.
@param string $key → session name to destroy
@param bool $prefix → if true clear all sessions for current prefix
@return bool | [
"Empties",
"and",
"destroys",
"the",
"session",
"."
] | train | https://github.com/Josantonius/PHP-Session/blob/08b09ad43927d172963d15da29259bcdf90a8f43/src/Session.php#L169-L189 |
yzalis/Identicon | src/Identicon/Generator/ImageMagickGenerator.php | ImageMagickGenerator.getImageResource | public function getImageResource($string, $size = null, $color = null, $backgroundColor = null)
{
$this
->setString($string)
->setSize($size)
->setColor($color)
->setBackgroundColor($backgroundColor)
->generateImage();
return $this->generatedImage;
} | php | public function getImageResource($string, $size = null, $color = null, $backgroundColor = null)
{
$this
->setString($string)
->setSize($size)
->setColor($color)
->setBackgroundColor($backgroundColor)
->generateImage();
return $this->generatedImage;
} | [
"public",
"function",
"getImageResource",
"(",
"$",
"string",
",",
"$",
"size",
"=",
"null",
",",
"$",
"color",
"=",
"null",
",",
"$",
"backgroundColor",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"setString",
"(",
"$",
"string",
")",
"->",
"setSize",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/yzalis/Identicon/blob/1484165cfe9c50a239139380b4e8ac444841962f/src/Identicon/Generator/ImageMagickGenerator.php#L87-L97 |
yzalis/Identicon | src/Identicon/Generator/BaseGenerator.php | BaseGenerator.setColor | public function setColor($color)
{
if (null === $color) {
return $this;
}
$this->color = $this->convertColor($color);
return $this;
} | php | public function setColor($color)
{
if (null === $color) {
return $this;
}
$this->color = $this->convertColor($color);
return $this;
} | [
"public",
"function",
"setColor",
"(",
"$",
"color",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"color",
")",
"{",
"return",
"$",
"this",
";",
"}",
"$",
"this",
"->",
"color",
"=",
"$",
"this",
"->",
"convertColor",
"(",
"$",
"color",
")",
";",
"re... | Set the image color.
@param string|array $color The color in hexa (3 or 6 chars) or rgb array
@return $this | [
"Set",
"the",
"image",
"color",
"."
] | train | https://github.com/yzalis/Identicon/blob/1484165cfe9c50a239139380b4e8ac444841962f/src/Identicon/Generator/BaseGenerator.php#L54-L63 |
yzalis/Identicon | src/Identicon/Generator/BaseGenerator.php | BaseGenerator.setBackgroundColor | public function setBackgroundColor($backgroundColor)
{
if (null === $backgroundColor) {
return $this;
}
$this->backgroundColor = $this->convertColor($backgroundColor);
return $this;
} | php | public function setBackgroundColor($backgroundColor)
{
if (null === $backgroundColor) {
return $this;
}
$this->backgroundColor = $this->convertColor($backgroundColor);
return $this;
} | [
"public",
"function",
"setBackgroundColor",
"(",
"$",
"backgroundColor",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"backgroundColor",
")",
"{",
"return",
"$",
"this",
";",
"}",
"$",
"this",
"->",
"backgroundColor",
"=",
"$",
"this",
"->",
"convertColor",
"(... | Set the image background color.
@param string|array $backgroundColor The color in hexa (3 or 6 chars) or rgb array
@return $this | [
"Set",
"the",
"image",
"background",
"color",
"."
] | train | https://github.com/yzalis/Identicon/blob/1484165cfe9c50a239139380b4e8ac444841962f/src/Identicon/Generator/BaseGenerator.php#L72-L81 |
yzalis/Identicon | src/Identicon/Generator/BaseGenerator.php | BaseGenerator.convertColor | private function convertColor($color)
{
if (is_array($color)) {
return $color;
}
if (preg_match('/^#?([a-z\d])([a-z\d])([a-z\d])$/i', $color, $matches)) {
$color = $matches[1].$matches[1];
$color .= $matches[2].$matches[2];
$color .= $matches[3].$matches[3];
}
preg_match('/#?([a-z\d]{2})([a-z\d]{2})([a-z\d]{2})$/i', $color, $matches);
return array_map(function ($value) {
return hexdec($value);
}, array_slice($matches, 1, 3));
} | php | private function convertColor($color)
{
if (is_array($color)) {
return $color;
}
if (preg_match('/^#?([a-z\d])([a-z\d])([a-z\d])$/i', $color, $matches)) {
$color = $matches[1].$matches[1];
$color .= $matches[2].$matches[2];
$color .= $matches[3].$matches[3];
}
preg_match('/#?([a-z\d]{2})([a-z\d]{2})([a-z\d]{2})$/i', $color, $matches);
return array_map(function ($value) {
return hexdec($value);
}, array_slice($matches, 1, 3));
} | [
"private",
"function",
"convertColor",
"(",
"$",
"color",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"color",
")",
")",
"{",
"return",
"$",
"color",
";",
"}",
"if",
"(",
"preg_match",
"(",
"'/^#?([a-z\\d])([a-z\\d])([a-z\\d])$/i'",
",",
"$",
"color",
",",
... | @param array|string $color
@return array | [
"@param",
"array|string",
"$color"
] | train | https://github.com/yzalis/Identicon/blob/1484165cfe9c50a239139380b4e8ac444841962f/src/Identicon/Generator/BaseGenerator.php#L88-L105 |
yzalis/Identicon | src/Identicon/Generator/BaseGenerator.php | BaseGenerator.convertHashToArrayOfBoolean | private function convertHashToArrayOfBoolean()
{
preg_match_all('/(\w)(\w)/', $this->hash, $chars);
foreach ($chars[1] as $i => $char) {
$index = (int) ($i / 3);
$data = $this->convertHexaToBoolean($char);
$items = [
0 => [0, 4],
1 => [1, 3],
2 => [2],
];
foreach ($items[$i % 3] as $item) {
$this->arrayOfSquare[$index][$item] = $data;
}
ksort($this->arrayOfSquare[$index]);
}
$this->color = array_map(function ($data) {
return hexdec($data) * 16;
}, array_reverse($chars[1]));
return $this;
} | php | private function convertHashToArrayOfBoolean()
{
preg_match_all('/(\w)(\w)/', $this->hash, $chars);
foreach ($chars[1] as $i => $char) {
$index = (int) ($i / 3);
$data = $this->convertHexaToBoolean($char);
$items = [
0 => [0, 4],
1 => [1, 3],
2 => [2],
];
foreach ($items[$i % 3] as $item) {
$this->arrayOfSquare[$index][$item] = $data;
}
ksort($this->arrayOfSquare[$index]);
}
$this->color = array_map(function ($data) {
return hexdec($data) * 16;
}, array_reverse($chars[1]));
return $this;
} | [
"private",
"function",
"convertHashToArrayOfBoolean",
"(",
")",
"{",
"preg_match_all",
"(",
"'/(\\w)(\\w)/'",
",",
"$",
"this",
"->",
"hash",
",",
"$",
"chars",
")",
";",
"foreach",
"(",
"$",
"chars",
"[",
"1",
"]",
"as",
"$",
"i",
"=>",
"$",
"char",
"... | Convert the hash into an multidimensional array of boolean.
@return $this | [
"Convert",
"the",
"hash",
"into",
"an",
"multidimensional",
"array",
"of",
"boolean",
"."
] | train | https://github.com/yzalis/Identicon/blob/1484165cfe9c50a239139380b4e8ac444841962f/src/Identicon/Generator/BaseGenerator.php#L132-L158 |
yzalis/Identicon | src/Identicon/Generator/BaseGenerator.php | BaseGenerator.setString | public function setString($string)
{
if (null === $string) {
throw new Exception('The string cannot be null.');
}
$this->hash = md5($string);
$this->convertHashToArrayOfBoolean();
return $this;
} | php | public function setString($string)
{
if (null === $string) {
throw new Exception('The string cannot be null.');
}
$this->hash = md5($string);
$this->convertHashToArrayOfBoolean();
return $this;
} | [
"public",
"function",
"setString",
"(",
"$",
"string",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"string",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'The string cannot be null.'",
")",
";",
"}",
"$",
"this",
"->",
"hash",
"=",
"md5",
"(",
"$",
"strin... | Generate a hash from the original string.
@param string $string
@throws \Exception
@return $this | [
"Generate",
"a",
"hash",
"from",
"the",
"original",
"string",
"."
] | train | https://github.com/yzalis/Identicon/blob/1484165cfe9c50a239139380b4e8ac444841962f/src/Identicon/Generator/BaseGenerator.php#L199-L210 |
yzalis/Identicon | src/Identicon/Generator/BaseGenerator.php | BaseGenerator.setSize | public function setSize($size)
{
if (null === $size) {
return $this;
}
$this->size = $size;
$this->pixelRatio = (int) round($size / 5);
return $this;
} | php | public function setSize($size)
{
if (null === $size) {
return $this;
}
$this->size = $size;
$this->pixelRatio = (int) round($size / 5);
return $this;
} | [
"public",
"function",
"setSize",
"(",
"$",
"size",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"size",
")",
"{",
"return",
"$",
"this",
";",
"}",
"$",
"this",
"->",
"size",
"=",
"$",
"size",
";",
"$",
"this",
"->",
"pixelRatio",
"=",
"(",
"int",
"... | Set the image size.
@param int $size
@return $this | [
"Set",
"the",
"image",
"size",
"."
] | train | https://github.com/yzalis/Identicon/blob/1484165cfe9c50a239139380b4e8ac444841962f/src/Identicon/Generator/BaseGenerator.php#L219-L229 |
yzalis/Identicon | src/Identicon/Identicon.php | Identicon.displayImage | public function displayImage($string, $size = 64, $color = null, $backgroundColor = null)
{
header('Content-Type: '.$this->generator->getMimeType());
echo $this->getImageData($string, $size, $color, $backgroundColor);
} | php | public function displayImage($string, $size = 64, $color = null, $backgroundColor = null)
{
header('Content-Type: '.$this->generator->getMimeType());
echo $this->getImageData($string, $size, $color, $backgroundColor);
} | [
"public",
"function",
"displayImage",
"(",
"$",
"string",
",",
"$",
"size",
"=",
"64",
",",
"$",
"color",
"=",
"null",
",",
"$",
"backgroundColor",
"=",
"null",
")",
"{",
"header",
"(",
"'Content-Type: '",
".",
"$",
"this",
"->",
"generator",
"->",
"ge... | Display an Identicon image.
@param string $string
@param int $size
@param string $color
@param string $backgroundColor | [
"Display",
"an",
"Identicon",
"image",
"."
] | train | https://github.com/yzalis/Identicon/blob/1484165cfe9c50a239139380b4e8ac444841962f/src/Identicon/Identicon.php#L54-L58 |
yzalis/Identicon | src/Identicon/Identicon.php | Identicon.getImageResource | public function getImageResource($string, $size = 64, $color = null, $backgroundColor = null)
{
return $this->generator->getImageResource($string, $size, $color, $backgroundColor);
} | php | public function getImageResource($string, $size = 64, $color = null, $backgroundColor = null)
{
return $this->generator->getImageResource($string, $size, $color, $backgroundColor);
} | [
"public",
"function",
"getImageResource",
"(",
"$",
"string",
",",
"$",
"size",
"=",
"64",
",",
"$",
"color",
"=",
"null",
",",
"$",
"backgroundColor",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"generator",
"->",
"getImageResource",
"(",
"$",
... | Get an Identicon PNG image resource.
@param string $string
@param int $size
@param string $color
@param string $backgroundColor
@return string | [
"Get",
"an",
"Identicon",
"PNG",
"image",
"resource",
"."
] | train | https://github.com/yzalis/Identicon/blob/1484165cfe9c50a239139380b4e8ac444841962f/src/Identicon/Identicon.php#L85-L88 |
yzalis/Identicon | src/Identicon/Identicon.php | Identicon.getImageDataUri | public function getImageDataUri($string, $size = 64, $color = null, $backgroundColor = null)
{
return sprintf('data:%s;base64,%s', $this->generator->getMimeType(), base64_encode($this->getImageData($string, $size, $color, $backgroundColor)));
} | php | public function getImageDataUri($string, $size = 64, $color = null, $backgroundColor = null)
{
return sprintf('data:%s;base64,%s', $this->generator->getMimeType(), base64_encode($this->getImageData($string, $size, $color, $backgroundColor)));
} | [
"public",
"function",
"getImageDataUri",
"(",
"$",
"string",
",",
"$",
"size",
"=",
"64",
",",
"$",
"color",
"=",
"null",
",",
"$",
"backgroundColor",
"=",
"null",
")",
"{",
"return",
"sprintf",
"(",
"'data:%s;base64,%s'",
",",
"$",
"this",
"->",
"genera... | Get an Identicon PNG image data as base 64 encoded.
@param string $string
@param int $size
@param string $color
@param string $backgroundColor
@return string | [
"Get",
"an",
"Identicon",
"PNG",
"image",
"data",
"as",
"base",
"64",
"encoded",
"."
] | train | https://github.com/yzalis/Identicon/blob/1484165cfe9c50a239139380b4e8ac444841962f/src/Identicon/Identicon.php#L100-L103 |
yzalis/Identicon | src/Identicon/Generator/SvgGenerator.php | SvgGenerator.getImageBinaryData | public function getImageBinaryData($string, $size = null, $color = null, $backgroundColor = null)
{
return $this->getImageResource($string, $size, $color, $backgroundColor);
} | php | public function getImageBinaryData($string, $size = null, $color = null, $backgroundColor = null)
{
return $this->getImageResource($string, $size, $color, $backgroundColor);
} | [
"public",
"function",
"getImageBinaryData",
"(",
"$",
"string",
",",
"$",
"size",
"=",
"null",
",",
"$",
"color",
"=",
"null",
",",
"$",
"backgroundColor",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"getImageResource",
"(",
"$",
"string",
",",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/yzalis/Identicon/blob/1484165cfe9c50a239139380b4e8ac444841962f/src/Identicon/Generator/SvgGenerator.php#L21-L24 |
yzalis/Identicon | src/Identicon/Generator/GdGenerator.php | GdGenerator.getImageBinaryData | public function getImageBinaryData($string, $size = null, $color = null, $backgroundColor = null)
{
ob_start();
imagepng($this->getImageResource($string, $size, $color, $backgroundColor));
$imageData = ob_get_contents();
ob_end_clean();
return $imageData;
} | php | public function getImageBinaryData($string, $size = null, $color = null, $backgroundColor = null)
{
ob_start();
imagepng($this->getImageResource($string, $size, $color, $backgroundColor));
$imageData = ob_get_contents();
ob_end_clean();
return $imageData;
} | [
"public",
"function",
"getImageBinaryData",
"(",
"$",
"string",
",",
"$",
"size",
"=",
"null",
",",
"$",
"color",
"=",
"null",
",",
"$",
"backgroundColor",
"=",
"null",
")",
"{",
"ob_start",
"(",
")",
";",
"imagepng",
"(",
"$",
"this",
"->",
"getImageR... | {@inheritdoc} | [
"{"
] | train | https://github.com/yzalis/Identicon/blob/1484165cfe9c50a239139380b4e8ac444841962f/src/Identicon/Generator/GdGenerator.php#L66-L74 |
verbb/super-table | src/elements/SuperTableBlockElement.php | SuperTableBlockElement.eagerLoadingMap | public static function eagerLoadingMap(array $sourceElements, string $handle)
{
// Get the block type
$supertableFieldId = ArrayHelper::firstValue($sourceElements)->fieldId;
$blockTypes = SuperTable::$plugin->getService()->getBlockTypesByFieldId($supertableFieldId);
if (!isset($blockTypes[0])) {
// Not a valid block type handle (assuming all $sourceElements are blocks from the same SuperTable field)
return false;
}
$blockType = $blockTypes[0];
// Set the field context
$contentService = Craft::$app->getContent();
$originalFieldContext = $contentService->fieldContext;
$contentService->fieldContext = 'superTableBlockType:' . $blockType->uid;
$map = parent::eagerLoadingMap($sourceElements, $handle);
$contentService->fieldContext = $originalFieldContext;
return $map;
} | php | public static function eagerLoadingMap(array $sourceElements, string $handle)
{
// Get the block type
$supertableFieldId = ArrayHelper::firstValue($sourceElements)->fieldId;
$blockTypes = SuperTable::$plugin->getService()->getBlockTypesByFieldId($supertableFieldId);
if (!isset($blockTypes[0])) {
// Not a valid block type handle (assuming all $sourceElements are blocks from the same SuperTable field)
return false;
}
$blockType = $blockTypes[0];
// Set the field context
$contentService = Craft::$app->getContent();
$originalFieldContext = $contentService->fieldContext;
$contentService->fieldContext = 'superTableBlockType:' . $blockType->uid;
$map = parent::eagerLoadingMap($sourceElements, $handle);
$contentService->fieldContext = $originalFieldContext;
return $map;
} | [
"public",
"static",
"function",
"eagerLoadingMap",
"(",
"array",
"$",
"sourceElements",
",",
"string",
"$",
"handle",
")",
"{",
"// Get the block type",
"$",
"supertableFieldId",
"=",
"ArrayHelper",
"::",
"firstValue",
"(",
"$",
"sourceElements",
")",
"->",
"field... | @inheritdoc
@return SuperTableBlockQuery The newly created [[SuperTableBlockQuery]] instance. | [
"@inheritdoc"
] | train | https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/elements/SuperTableBlockElement.php#L80-L103 |
verbb/super-table | src/variables/SuperTableVariable.php | SuperTableVariable.getRelatedElements | public function getRelatedElements($params = null)
{
// Parse out the field handles
$fieldParams = explode('.', $params['relatedTo']['field']);
// For safety fail early if that didn't work
if (!isset($fieldParams[0]) || !isset($fieldParams[1])) {
return false;
}
$superTableFieldHandle = $fieldParams[0];
$superTableBlockFieldHandle = $fieldParams[1];
// Get the Super Table field and associated block type
$superTableField = Craft::$app->fields->getFieldByHandle($superTableFieldHandle);
$superTableBlockTypes = SuperTable::$plugin->getService()->getBlockTypesByFieldId($superTableField->id);
$superTableBlockType = $superTableBlockTypes[0];
// Loop the fields on the block type and save the first one that matches our handle
$fieldId = false;
foreach ($superTableBlockType->getFields() as $field) {
if ($field->handle === $superTableBlockFieldHandle) {
$fieldId = $field->id;
break;
}
}
// Check we got something and update the relatedTo criteria for our next elements call
if ($fieldId) {
$params['relatedTo']['field'] = $fieldId;
} else {
return false;
}
// Create an element query to find Super Table Blocks
$blockQuery = SuperTableBlockElement::find();
$blockCriteria = [
'relatedTo' => $params['relatedTo']
];
// Check for ownerSite param add to blockCriteria
if (isset($params['ownerSite'])) {
$blockCriteria['ownerSite'] = $params['ownerSite'];
}
Craft::configure($blockQuery, $blockCriteria);
// Get the Super Table Blocks that are related to that field and criteria
$elementIds = $blockQuery->select('ownerId')->column();
// Default to getting Entry elements but let the user override
$elementType = $params['elementType'] ?? Entry::class;
// Start our final criteria with the element ids we just got
$finalCriteria = [
'id' => $elementIds,
];
// Check if the user gave us another criteria model and merge that in
if (isset($params['criteria'])) {
$finalCriteria = array_merge($finalCriteria, $params['criteria']);
}
// Create an element query based on our final criteria, and return
$elementQuery = $elementType::find();
Craft::configure($elementQuery, $finalCriteria);
return $elementQuery;
} | php | public function getRelatedElements($params = null)
{
// Parse out the field handles
$fieldParams = explode('.', $params['relatedTo']['field']);
// For safety fail early if that didn't work
if (!isset($fieldParams[0]) || !isset($fieldParams[1])) {
return false;
}
$superTableFieldHandle = $fieldParams[0];
$superTableBlockFieldHandle = $fieldParams[1];
// Get the Super Table field and associated block type
$superTableField = Craft::$app->fields->getFieldByHandle($superTableFieldHandle);
$superTableBlockTypes = SuperTable::$plugin->getService()->getBlockTypesByFieldId($superTableField->id);
$superTableBlockType = $superTableBlockTypes[0];
// Loop the fields on the block type and save the first one that matches our handle
$fieldId = false;
foreach ($superTableBlockType->getFields() as $field) {
if ($field->handle === $superTableBlockFieldHandle) {
$fieldId = $field->id;
break;
}
}
// Check we got something and update the relatedTo criteria for our next elements call
if ($fieldId) {
$params['relatedTo']['field'] = $fieldId;
} else {
return false;
}
// Create an element query to find Super Table Blocks
$blockQuery = SuperTableBlockElement::find();
$blockCriteria = [
'relatedTo' => $params['relatedTo']
];
// Check for ownerSite param add to blockCriteria
if (isset($params['ownerSite'])) {
$blockCriteria['ownerSite'] = $params['ownerSite'];
}
Craft::configure($blockQuery, $blockCriteria);
// Get the Super Table Blocks that are related to that field and criteria
$elementIds = $blockQuery->select('ownerId')->column();
// Default to getting Entry elements but let the user override
$elementType = $params['elementType'] ?? Entry::class;
// Start our final criteria with the element ids we just got
$finalCriteria = [
'id' => $elementIds,
];
// Check if the user gave us another criteria model and merge that in
if (isset($params['criteria'])) {
$finalCriteria = array_merge($finalCriteria, $params['criteria']);
}
// Create an element query based on our final criteria, and return
$elementQuery = $elementType::find();
Craft::configure($elementQuery, $finalCriteria);
return $elementQuery;
} | [
"public",
"function",
"getRelatedElements",
"(",
"$",
"params",
"=",
"null",
")",
"{",
"// Parse out the field handles",
"$",
"fieldParams",
"=",
"explode",
"(",
"'.'",
",",
"$",
"params",
"[",
"'relatedTo'",
"]",
"[",
"'field'",
"]",
")",
";",
"// For safety ... | Expands the defualt relationship behaviour to include Super Table
fields so that the user can filter by those too.
For example:
```twig
{% set reverseRelatedElements = craft.superTable.getRelatedElements({
relatedTo: {
targetElement: entry,
field: 'superTableFieldHandle.columnHandle',
},
ownerSite: 'siteHandle',
elementType: 'craft\\elements\\Entry',
criteria: {
id: 'not 123',
section: 'someSection',
}
})->all() %}
```
@method getRelatedElements
@param array $params Should contain 'relatedTo' but can also optionally
include 'elementType' and 'criteria'
@return ElementCriteriaModel | [
"Expands",
"the",
"defualt",
"relationship",
"behaviour",
"to",
"include",
"Super",
"Table",
"fields",
"so",
"that",
"the",
"user",
"can",
"filter",
"by",
"those",
"too",
"."
] | train | https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/variables/SuperTableVariable.php#L50-L119 |
verbb/super-table | src/migrations/m180219_000000_sites.php | m180219_000000_sites.safeUp | public function safeUp()
{
// Rename the FK columns
// ---------------------------------------------------------------------
if ($this->db->columnExists('{{%supertableblocks}}', 'ownerLocale__siteId')) {
MigrationHelper::renameColumn('{{%supertableblocks}}', 'ownerLocale__siteId', 'ownerSiteId');
}
// Drop the old FKs
// ---------------------------------------------------------------------
MigrationHelper::dropForeignKeyIfExists('{{%supertableblocks}}', ['ownerLocale'], $this);
// Drop the old indexes
// ---------------------------------------------------------------------
MigrationHelper::dropIndexIfExists('{{%supertableblocks}}', ['ownerLocale'], false, $this);
// Drop the locale columns
// ---------------------------------------------------------------------
if ($this->db->columnExists('{{%supertableblocks}}', 'ownerLocale')) {
$this->dropColumn('{{%supertableblocks}}', 'ownerLocale');
}
// Super Table content tables
// ---------------------------------------------------------------------
$superTableTablePrefix = $this->db->getSchema()->getRawTableName('{{%stc_}}');
foreach ($this->db->getSchema()->getTableNames() as $tableName) {
if (StringHelper::startsWith($tableName, $superTableTablePrefix)) {
// There's actually an issue here in the MigrationHelper::dropAllIndexesOnTable class, not using the current migration
// as context to find existing indexes. This is important, because the indexes have changed from their current names
$this->dropAllForeignKeysOnTable($tableName);
$this->dropAllIndexesOnTable($tableName);
// Rename column
if ($this->db->columnExists($tableName, 'locale__siteId')) {
$this->renameColumn($tableName, 'locale__siteId', 'siteId');
}
// Add them back (like creating a new Matrix would)
$this->createIndex(null, $tableName, ['elementId', 'siteId'], true);
$this->addForeignKey(null, $tableName, ['elementId'], '{{%elements}}', ['id'], 'CASCADE', null);
$this->addForeignKey(null, $tableName, ['siteId'], '{{%sites}}', ['id'], 'CASCADE', 'CASCADE');
// Delete the old column
if ($this->db->columnExists($tableName, 'locale')) {
$this->dropColumn($tableName, 'locale');
}
}
}
Craft::$app->getDb()->getSchema()->refresh();
// Update Super Table/relationship field settings
// ---------------------------------------------------------------------
$fields = (new Query())
->select(['id', 'type', 'translationMethod', 'settings'])
->from(['{{%fields}}'])
->where([
'type' => [
SuperTableField::class,
]
])
->all($this->db);
foreach ($fields as $field) {
$settings = Json::decodeIfJson($field['settings']);
if (!is_array($settings)) {
echo 'Field '.$field['id'].' ('.$field['type'].') settings were invalid JSON: '.$field['settings']."\n";
$settings = [];
}
$localized = ($field['translationMethod'] === 'site');
$settings['localizeBlocks'] = $localized;
$this->update(
'{{%fields}}',
[
'translationMethod' => 'none',
'settings' => Json::encode($settings),
],
['id' => $field['id']],
[],
false);
}
} | php | public function safeUp()
{
// Rename the FK columns
// ---------------------------------------------------------------------
if ($this->db->columnExists('{{%supertableblocks}}', 'ownerLocale__siteId')) {
MigrationHelper::renameColumn('{{%supertableblocks}}', 'ownerLocale__siteId', 'ownerSiteId');
}
// Drop the old FKs
// ---------------------------------------------------------------------
MigrationHelper::dropForeignKeyIfExists('{{%supertableblocks}}', ['ownerLocale'], $this);
// Drop the old indexes
// ---------------------------------------------------------------------
MigrationHelper::dropIndexIfExists('{{%supertableblocks}}', ['ownerLocale'], false, $this);
// Drop the locale columns
// ---------------------------------------------------------------------
if ($this->db->columnExists('{{%supertableblocks}}', 'ownerLocale')) {
$this->dropColumn('{{%supertableblocks}}', 'ownerLocale');
}
// Super Table content tables
// ---------------------------------------------------------------------
$superTableTablePrefix = $this->db->getSchema()->getRawTableName('{{%stc_}}');
foreach ($this->db->getSchema()->getTableNames() as $tableName) {
if (StringHelper::startsWith($tableName, $superTableTablePrefix)) {
// There's actually an issue here in the MigrationHelper::dropAllIndexesOnTable class, not using the current migration
// as context to find existing indexes. This is important, because the indexes have changed from their current names
$this->dropAllForeignKeysOnTable($tableName);
$this->dropAllIndexesOnTable($tableName);
// Rename column
if ($this->db->columnExists($tableName, 'locale__siteId')) {
$this->renameColumn($tableName, 'locale__siteId', 'siteId');
}
// Add them back (like creating a new Matrix would)
$this->createIndex(null, $tableName, ['elementId', 'siteId'], true);
$this->addForeignKey(null, $tableName, ['elementId'], '{{%elements}}', ['id'], 'CASCADE', null);
$this->addForeignKey(null, $tableName, ['siteId'], '{{%sites}}', ['id'], 'CASCADE', 'CASCADE');
// Delete the old column
if ($this->db->columnExists($tableName, 'locale')) {
$this->dropColumn($tableName, 'locale');
}
}
}
Craft::$app->getDb()->getSchema()->refresh();
// Update Super Table/relationship field settings
// ---------------------------------------------------------------------
$fields = (new Query())
->select(['id', 'type', 'translationMethod', 'settings'])
->from(['{{%fields}}'])
->where([
'type' => [
SuperTableField::class,
]
])
->all($this->db);
foreach ($fields as $field) {
$settings = Json::decodeIfJson($field['settings']);
if (!is_array($settings)) {
echo 'Field '.$field['id'].' ('.$field['type'].') settings were invalid JSON: '.$field['settings']."\n";
$settings = [];
}
$localized = ($field['translationMethod'] === 'site');
$settings['localizeBlocks'] = $localized;
$this->update(
'{{%fields}}',
[
'translationMethod' => 'none',
'settings' => Json::encode($settings),
],
['id' => $field['id']],
[],
false);
}
} | [
"public",
"function",
"safeUp",
"(",
")",
"{",
"// Rename the FK columns",
"// ---------------------------------------------------------------------",
"if",
"(",
"$",
"this",
"->",
"db",
"->",
"columnExists",
"(",
"'{{%supertableblocks}}'",
",",
"'ownerLocale__siteId'",
")",
... | ========================================================================= | [
"========================================================================="
] | train | https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/migrations/m180219_000000_sites.php#L20-L113 |
verbb/super-table | src/services/SuperTableMatrixService.php | SuperTableMatrixService._getFieldOptionsForConfigurator | private function _getFieldOptionsForConfigurator(): array
{
$fieldTypes = [];
// Set a temporary namespace for these
$originalNamespace = Craft::$app->getView()->getNamespace();
$namespace = Craft::$app->getView()->namespaceInputName('blockTypes[__BLOCK_TYPE_NESTED__][fields][__FIELD_NESTED__][typesettings]', $originalNamespace);
Craft::$app->getView()->setNamespace($namespace);
foreach (Craft::$app->getFields()->getAllFieldTypes() as $class) {
/** @var Field|string $class */
// No Matrix-Inception, sorry buddy.
if ($class === 'craft\fields\Matrix' || $class === 'verbb\supertable\fields\SuperTableField') {
continue;
}
Craft::$app->getView()->startJsBuffer();
/** @var FieldInterface $field */
$field = new $class();
$settingsBodyHtml = Craft::$app->getView()->namespaceInputs((string)$field->getSettingsHtml());
$settingsFootHtml = Craft::$app->getView()->clearJsBuffer();
$fieldTypes[] = [
'type' => $class,
'name' => $class::displayName(),
'settingsBodyHtml' => $settingsBodyHtml,
'settingsFootHtml' => $settingsFootHtml,
];
}
// Sort them by name
ArrayHelper::multisort($fieldTypes, 'name');
Craft::$app->getView()->setNamespace($originalNamespace);
return $fieldTypes;
} | php | private function _getFieldOptionsForConfigurator(): array
{
$fieldTypes = [];
// Set a temporary namespace for these
$originalNamespace = Craft::$app->getView()->getNamespace();
$namespace = Craft::$app->getView()->namespaceInputName('blockTypes[__BLOCK_TYPE_NESTED__][fields][__FIELD_NESTED__][typesettings]', $originalNamespace);
Craft::$app->getView()->setNamespace($namespace);
foreach (Craft::$app->getFields()->getAllFieldTypes() as $class) {
/** @var Field|string $class */
// No Matrix-Inception, sorry buddy.
if ($class === 'craft\fields\Matrix' || $class === 'verbb\supertable\fields\SuperTableField') {
continue;
}
Craft::$app->getView()->startJsBuffer();
/** @var FieldInterface $field */
$field = new $class();
$settingsBodyHtml = Craft::$app->getView()->namespaceInputs((string)$field->getSettingsHtml());
$settingsFootHtml = Craft::$app->getView()->clearJsBuffer();
$fieldTypes[] = [
'type' => $class,
'name' => $class::displayName(),
'settingsBodyHtml' => $settingsBodyHtml,
'settingsFootHtml' => $settingsFootHtml,
];
}
// Sort them by name
ArrayHelper::multisort($fieldTypes, 'name');
Craft::$app->getView()->setNamespace($originalNamespace);
return $fieldTypes;
} | [
"private",
"function",
"_getFieldOptionsForConfigurator",
"(",
")",
":",
"array",
"{",
"$",
"fieldTypes",
"=",
"[",
"]",
";",
"// Set a temporary namespace for these",
"$",
"originalNamespace",
"=",
"Craft",
"::",
"$",
"app",
"->",
"getView",
"(",
")",
"->",
"ge... | Returns info about each field type for the configurator.
@return array | [
"Returns",
"info",
"about",
"each",
"field",
"type",
"for",
"the",
"configurator",
"."
] | train | https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/services/SuperTableMatrixService.php#L212-L248 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.