repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1 value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
Riimu/Kit-BaseConversion | src/ReplaceConverter.php | ReplaceConverter.getRoot | private function getRoot(NumberBase $source, NumberBase $target)
{
if ($source->hasStringConflict() || $target->hasStringConflict()) {
throw new InvalidNumberBaseException('Number bases do not support string presentation');
}
$root = $source->findCommonRadixRoot($target);
if ($root === false) {
throw new InvalidNumberBaseException('No common root exists between number bases');
}
return $root;
} | php | private function getRoot(NumberBase $source, NumberBase $target)
{
if ($source->hasStringConflict() || $target->hasStringConflict()) {
throw new InvalidNumberBaseException('Number bases do not support string presentation');
}
$root = $source->findCommonRadixRoot($target);
if ($root === false) {
throw new InvalidNumberBaseException('No common root exists between number bases');
}
return $root;
} | [
"private",
"function",
"getRoot",
"(",
"NumberBase",
"$",
"source",
",",
"NumberBase",
"$",
"target",
")",
"{",
"if",
"(",
"$",
"source",
"->",
"hasStringConflict",
"(",
")",
"||",
"$",
"target",
"->",
"hasStringConflict",
"(",
")",
")",
"{",
"throw",
"n... | Determines the common root for the number bases.
@param NumberBase $source Number base used by the provided numbers
@param NumberBase $target Number base used by the returned numbers
@return int The common root for the number bases
@throws InvalidNumberBaseException If the number bases are not supported | [
"Determines",
"the",
"common",
"root",
"for",
"the",
"number",
"bases",
"."
] | e0f486759590b69126c83622edd309217f783324 | https://github.com/Riimu/Kit-BaseConversion/blob/e0f486759590b69126c83622edd309217f783324/src/ReplaceConverter.php#L79-L92 | train |
Riimu/Kit-BaseConversion | src/ReplaceConverter.php | ReplaceConverter.buildConversionTable | private function buildConversionTable()
{
if ($this->source->getRadix() > $this->target->getRadix()) {
return $this->createTable($this->source->getDigitList(), $this->target->getDigitList());
}
return array_flip($this->createTable($this->target->getDigitList(), $this->source->getDigitList()));
} | php | private function buildConversionTable()
{
if ($this->source->getRadix() > $this->target->getRadix()) {
return $this->createTable($this->source->getDigitList(), $this->target->getDigitList());
}
return array_flip($this->createTable($this->target->getDigitList(), $this->source->getDigitList()));
} | [
"private",
"function",
"buildConversionTable",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"source",
"->",
"getRadix",
"(",
")",
">",
"$",
"this",
"->",
"target",
"->",
"getRadix",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"createTable",
"(",
... | Creates string replacement table between source base and target base.
@return array<string,string> String replacement table for converting numbers | [
"Creates",
"string",
"replacement",
"table",
"between",
"source",
"base",
"and",
"target",
"base",
"."
] | e0f486759590b69126c83622edd309217f783324 | https://github.com/Riimu/Kit-BaseConversion/blob/e0f486759590b69126c83622edd309217f783324/src/ReplaceConverter.php#L98-L105 | train |
Riimu/Kit-BaseConversion | src/ReplaceConverter.php | ReplaceConverter.createTable | private function createTable($source, $target)
{
$last = count($target) - 1;
$size = (int) log(count($source), count($target));
$number = array_fill(0, $size, $target[0]);
$next = array_fill(0, $size, 0);
$limit = count($source);
$table = [$source[0] => implode('', $number)];
for ($i = 1; $i < $limit; $i++) {
for ($j = $size - 1; $next[$j] === $last; $j--) {
$number[$j] = $target[0];
$next[$j] = 0;
}
$number[$j] = $target[++$next[$j]];
$table[$source[$i]] = implode('', $number);
}
return $table;
} | php | private function createTable($source, $target)
{
$last = count($target) - 1;
$size = (int) log(count($source), count($target));
$number = array_fill(0, $size, $target[0]);
$next = array_fill(0, $size, 0);
$limit = count($source);
$table = [$source[0] => implode('', $number)];
for ($i = 1; $i < $limit; $i++) {
for ($j = $size - 1; $next[$j] === $last; $j--) {
$number[$j] = $target[0];
$next[$j] = 0;
}
$number[$j] = $target[++$next[$j]];
$table[$source[$i]] = implode('', $number);
}
return $table;
} | [
"private",
"function",
"createTable",
"(",
"$",
"source",
",",
"$",
"target",
")",
"{",
"$",
"last",
"=",
"count",
"(",
"$",
"target",
")",
"-",
"1",
";",
"$",
"size",
"=",
"(",
"int",
")",
"log",
"(",
"count",
"(",
"$",
"source",
")",
",",
"co... | Creates a conversion table between two lists of digits.
@param string[] $source Digits for the number base with larger number of digits
@param string[] $target Digits for the number base with smaller number of digits
@return array<string,string> String replacement table for converting numbers | [
"Creates",
"a",
"conversion",
"table",
"between",
"two",
"lists",
"of",
"digits",
"."
] | e0f486759590b69126c83622edd309217f783324 | https://github.com/Riimu/Kit-BaseConversion/blob/e0f486759590b69126c83622edd309217f783324/src/ReplaceConverter.php#L113-L133 | train |
Riimu/Kit-BaseConversion | src/ReplaceConverter.php | ReplaceConverter.convert | private function convert(array $number, $fractions = false)
{
if (!isset($this->conversionTable)) {
return $this->targetConverter->replace(
$this->sourceConverter->replace($number, $fractions),
$fractions
);
}
return $this->replace($number, $fractions);
} | php | private function convert(array $number, $fractions = false)
{
if (!isset($this->conversionTable)) {
return $this->targetConverter->replace(
$this->sourceConverter->replace($number, $fractions),
$fractions
);
}
return $this->replace($number, $fractions);
} | [
"private",
"function",
"convert",
"(",
"array",
"$",
"number",
",",
"$",
"fractions",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"conversionTable",
")",
")",
"{",
"return",
"$",
"this",
"->",
"targetConverter",
"->",
"repl... | Converts the digits from source base to target base.
@param array $number The digits to convert
@param bool $fractions True if converting fractions, false if not
@return array The digits converted to target base | [
"Converts",
"the",
"digits",
"from",
"source",
"base",
"to",
"target",
"base",
"."
] | e0f486759590b69126c83622edd309217f783324 | https://github.com/Riimu/Kit-BaseConversion/blob/e0f486759590b69126c83622edd309217f783324/src/ReplaceConverter.php#L156-L166 | train |
Riimu/Kit-BaseConversion | src/ReplaceConverter.php | ReplaceConverter.replace | private function replace(array $number, $fractions = false)
{
return $this->zeroTrim($this->target->splitString(strtr(implode('', $this->zeroPad(
$this->source->canonizeDigits($number),
$fractions
)), $this->conversionTable)), $fractions);
} | php | private function replace(array $number, $fractions = false)
{
return $this->zeroTrim($this->target->splitString(strtr(implode('', $this->zeroPad(
$this->source->canonizeDigits($number),
$fractions
)), $this->conversionTable)), $fractions);
} | [
"private",
"function",
"replace",
"(",
"array",
"$",
"number",
",",
"$",
"fractions",
"=",
"false",
")",
"{",
"return",
"$",
"this",
"->",
"zeroTrim",
"(",
"$",
"this",
"->",
"target",
"->",
"splitString",
"(",
"strtr",
"(",
"implode",
"(",
"''",
",",
... | Replace digits using string replacement.
@param array $number The digits to convert
@param bool $fractions True if converting fractions, false if not
@return array The digits converted to target base | [
"Replace",
"digits",
"using",
"string",
"replacement",
"."
] | e0f486759590b69126c83622edd309217f783324 | https://github.com/Riimu/Kit-BaseConversion/blob/e0f486759590b69126c83622edd309217f783324/src/ReplaceConverter.php#L174-L180 | train |
Riimu/Kit-BaseConversion | src/ReplaceConverter.php | ReplaceConverter.zeroPad | private function zeroPad(array $number, $right)
{
$log = (int) log($this->target->getRadix(), $this->source->getRadix());
if ($log > 1 && count($number) % $log) {
$pad = count($number) + ($log - count($number) % $log);
$number = array_pad($number, $right ? $pad : -$pad, $this->source->getDigit(0));
}
return $number;
} | php | private function zeroPad(array $number, $right)
{
$log = (int) log($this->target->getRadix(), $this->source->getRadix());
if ($log > 1 && count($number) % $log) {
$pad = count($number) + ($log - count($number) % $log);
$number = array_pad($number, $right ? $pad : -$pad, $this->source->getDigit(0));
}
return $number;
} | [
"private",
"function",
"zeroPad",
"(",
"array",
"$",
"number",
",",
"$",
"right",
")",
"{",
"$",
"log",
"=",
"(",
"int",
")",
"log",
"(",
"$",
"this",
"->",
"target",
"->",
"getRadix",
"(",
")",
",",
"$",
"this",
"->",
"source",
"->",
"getRadix",
... | Pads the digits to correct count for string replacement.
@param array $number Array of digits to pad
@param bool $right True to pad from right, false to pad from left
@return array Padded array of digits | [
"Pads",
"the",
"digits",
"to",
"correct",
"count",
"for",
"string",
"replacement",
"."
] | e0f486759590b69126c83622edd309217f783324 | https://github.com/Riimu/Kit-BaseConversion/blob/e0f486759590b69126c83622edd309217f783324/src/ReplaceConverter.php#L188-L198 | train |
Riimu/Kit-BaseConversion | src/ReplaceConverter.php | ReplaceConverter.zeroTrim | private function zeroTrim(array $number, $right)
{
$zero = $this->target->getDigit(0);
while (($right ? end($number) : reset($number)) === $zero) {
unset($number[key($number)]);
}
return empty($number) ? [$zero] : array_values($number);
} | php | private function zeroTrim(array $number, $right)
{
$zero = $this->target->getDigit(0);
while (($right ? end($number) : reset($number)) === $zero) {
unset($number[key($number)]);
}
return empty($number) ? [$zero] : array_values($number);
} | [
"private",
"function",
"zeroTrim",
"(",
"array",
"$",
"number",
",",
"$",
"right",
")",
"{",
"$",
"zero",
"=",
"$",
"this",
"->",
"target",
"->",
"getDigit",
"(",
"0",
")",
";",
"while",
"(",
"(",
"$",
"right",
"?",
"end",
"(",
"$",
"number",
")"... | Trims extraneous zeroes from the digit list.
@param array $number Array of digits to trim
@param bool $right True to trim from right, false to trim from left
@return array Trimmed array of digits | [
"Trims",
"extraneous",
"zeroes",
"from",
"the",
"digit",
"list",
"."
] | e0f486759590b69126c83622edd309217f783324 | https://github.com/Riimu/Kit-BaseConversion/blob/e0f486759590b69126c83622edd309217f783324/src/ReplaceConverter.php#L206-L215 | train |
krystal-framework/krystal.framework | src/Krystal/Application/Module/ModuleManager.php | ModuleManager.initialize | public function initialize()
{
$modules = $this->loader->getModules();
if (empty($modules)) {
throw new RuntimeException('No modules found. Initialization halted');
} else {
$this->loadAll($modules);
$this->modules = $modules;
// Validate on demand
$this->validateCoreModuleNames();
}
} | php | public function initialize()
{
$modules = $this->loader->getModules();
if (empty($modules)) {
throw new RuntimeException('No modules found. Initialization halted');
} else {
$this->loadAll($modules);
$this->modules = $modules;
// Validate on demand
$this->validateCoreModuleNames();
}
} | [
"public",
"function",
"initialize",
"(",
")",
"{",
"$",
"modules",
"=",
"$",
"this",
"->",
"loader",
"->",
"getModules",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"modules",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'No modules found. I... | Initializes the module manager
@throws \RuntimeException If no modules found
@return void | [
"Initializes",
"the",
"module",
"manager"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Application/Module/ModuleManager.php#L109-L122 | train |
krystal-framework/krystal.framework | src/Krystal/Application/Module/ModuleManager.php | ModuleManager.getCoreBag | private function getCoreBag()
{
static $coreBag = null;
if (is_null($coreBag)) {
$coreBag = new CoreBag($this->getLoadedModuleNames(), $this->coreModules);
}
return $coreBag;
} | php | private function getCoreBag()
{
static $coreBag = null;
if (is_null($coreBag)) {
$coreBag = new CoreBag($this->getLoadedModuleNames(), $this->coreModules);
}
return $coreBag;
} | [
"private",
"function",
"getCoreBag",
"(",
")",
"{",
"static",
"$",
"coreBag",
"=",
"null",
";",
"if",
"(",
"is_null",
"(",
"$",
"coreBag",
")",
")",
"{",
"$",
"coreBag",
"=",
"new",
"CoreBag",
"(",
"$",
"this",
"->",
"getLoadedModuleNames",
"(",
")",
... | Returns core bag instance
@return \Krystal\Application\Module\CoreBag | [
"Returns",
"core",
"bag",
"instance"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Application/Module/ModuleManager.php#L164-L173 | train |
krystal-framework/krystal.framework | src/Krystal/Application/Module/ModuleManager.php | ModuleManager.validateCoreModuleNames | private function validateCoreModuleNames()
{
if (!empty($this->coreModules)) {
$coreBag = $this->getCoreBag();
if (!$coreBag->hasAllCoreModules()) {
throw new LogicException(sprintf(
'The framework can not start without defined core modules: %s', implode(', ', $coreBag->getMissingCoreModules())
));
}
}
} | php | private function validateCoreModuleNames()
{
if (!empty($this->coreModules)) {
$coreBag = $this->getCoreBag();
if (!$coreBag->hasAllCoreModules()) {
throw new LogicException(sprintf(
'The framework can not start without defined core modules: %s', implode(', ', $coreBag->getMissingCoreModules())
));
}
}
} | [
"private",
"function",
"validateCoreModuleNames",
"(",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"coreModules",
")",
")",
"{",
"$",
"coreBag",
"=",
"$",
"this",
"->",
"getCoreBag",
"(",
")",
";",
"if",
"(",
"!",
"$",
"coreBag",
"->",... | Validates core modules on demand
@throws \LogicException On validation failure
@return void | [
"Validates",
"core",
"modules",
"on",
"demand"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Application/Module/ModuleManager.php#L181-L192 | train |
krystal-framework/krystal.framework | src/Krystal/Application/Module/ModuleManager.php | ModuleManager.getModule | public function getModule($name)
{
if ($this->isLoaded($name)) {
return $this->loaded[$name];
} else {
return $this->loadModuleByName($name);
}
} | php | public function getModule($name)
{
if ($this->isLoaded($name)) {
return $this->loaded[$name];
} else {
return $this->loadModuleByName($name);
}
} | [
"public",
"function",
"getModule",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isLoaded",
"(",
"$",
"name",
")",
")",
"{",
"return",
"$",
"this",
"->",
"loaded",
"[",
"$",
"name",
"]",
";",
"}",
"else",
"{",
"return",
"$",
"this",
... | Returns module instance by its name
@param object $name
@return \Krystal\Application\Module\AbstractModule | [
"Returns",
"module",
"instance",
"by",
"its",
"name"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Application/Module/ModuleManager.php#L211-L218 | train |
krystal-framework/krystal.framework | src/Krystal/Application/Module/ModuleManager.php | ModuleManager.getUnloadedModules | public function getUnloadedModules(array $modules)
{
$unloaded = array();
foreach ($modules as $module) {
if (!$this->isLoaded($module)) {
array_push($unloaded, $module);
}
}
return $unloaded;
} | php | public function getUnloadedModules(array $modules)
{
$unloaded = array();
foreach ($modules as $module) {
if (!$this->isLoaded($module)) {
array_push($unloaded, $module);
}
}
return $unloaded;
} | [
"public",
"function",
"getUnloadedModules",
"(",
"array",
"$",
"modules",
")",
"{",
"$",
"unloaded",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"modules",
"as",
"$",
"module",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isLoaded",
"(",
"$",
... | Returns a collection of unloaded modules
@param array $modules Target collection of required modules
@return array | [
"Returns",
"a",
"collection",
"of",
"unloaded",
"modules"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Application/Module/ModuleManager.php#L237-L248 | train |
krystal-framework/krystal.framework | src/Krystal/Application/Module/ModuleManager.php | ModuleManager.prepareRoutes | private function prepareRoutes($module, array $routes)
{
$result = array();
foreach ($routes as $uriTemplate => $options) {
// Controller is the special case
if (isset($options['controller'])) {
// Override with module-compliant
$options['controller'] = sprintf('%s:%s', $this->grabModuleName($module), $options['controller']);
}
$result[$uriTemplate] = $options;
}
return $result;
} | php | private function prepareRoutes($module, array $routes)
{
$result = array();
foreach ($routes as $uriTemplate => $options) {
// Controller is the special case
if (isset($options['controller'])) {
// Override with module-compliant
$options['controller'] = sprintf('%s:%s', $this->grabModuleName($module), $options['controller']);
}
$result[$uriTemplate] = $options;
}
return $result;
} | [
"private",
"function",
"prepareRoutes",
"(",
"$",
"module",
",",
"array",
"$",
"routes",
")",
"{",
"$",
"result",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"routes",
"as",
"$",
"uriTemplate",
"=>",
"$",
"options",
")",
"{",
"// Controller is the ... | Prepends module name to each route
@param string $module
@param array $routes
@return array | [
"Prepends",
"module",
"name",
"to",
"each",
"route"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Application/Module/ModuleManager.php#L277-L292 | train |
krystal-framework/krystal.framework | src/Krystal/Application/Module/ModuleManager.php | ModuleManager.loadModuleByName | private function loadModuleByName($name)
{
// First of all, make sure a valid module name is being processed
if (!$this->nameValid($name)) {
throw new LogicException(sprintf(
'Invalid module name "%s" is being processed. Module name must start from a capital letter and contain only alphabetic characters', $name
));
}
// Prepare PSR-0 compliant name
$moduleNamespace = sprintf('%s\%s', $name, self::MODULE_CONFIG_FILE);
// Ensure a module exists
if (!class_exists($moduleNamespace)) {
return false;
}
$pathProvider = new PathProvider($this->appConfig->getModulesDir(), $name);
$sl = new ServiceLocator();
$sl->registerArray($this->services);
// Build module instance
$module = new $moduleNamespace($this, $sl, $this->appConfig, $pathProvider, $name);
// Routes must be global, so we'd extract them
if (method_exists($module, 'getRoutes')) {
$this->appendRoutes($this->prepareRoutes($moduleNamespace, $module->getRoutes()));
}
$this->loaded[$name] = $module;
return $module;
} | php | private function loadModuleByName($name)
{
// First of all, make sure a valid module name is being processed
if (!$this->nameValid($name)) {
throw new LogicException(sprintf(
'Invalid module name "%s" is being processed. Module name must start from a capital letter and contain only alphabetic characters', $name
));
}
// Prepare PSR-0 compliant name
$moduleNamespace = sprintf('%s\%s', $name, self::MODULE_CONFIG_FILE);
// Ensure a module exists
if (!class_exists($moduleNamespace)) {
return false;
}
$pathProvider = new PathProvider($this->appConfig->getModulesDir(), $name);
$sl = new ServiceLocator();
$sl->registerArray($this->services);
// Build module instance
$module = new $moduleNamespace($this, $sl, $this->appConfig, $pathProvider, $name);
// Routes must be global, so we'd extract them
if (method_exists($module, 'getRoutes')) {
$this->appendRoutes($this->prepareRoutes($moduleNamespace, $module->getRoutes()));
}
$this->loaded[$name] = $module;
return $module;
} | [
"private",
"function",
"loadModuleByName",
"(",
"$",
"name",
")",
"{",
"// First of all, make sure a valid module name is being processed",
"if",
"(",
"!",
"$",
"this",
"->",
"nameValid",
"(",
"$",
"name",
")",
")",
"{",
"throw",
"new",
"LogicException",
"(",
"spr... | Loads a module by its name
@param string $name Module name
@throws \LogicException If invalid module name is being processed
@return \Krystal\Application\Module\AbstractModule|boolean | [
"Loads",
"a",
"module",
"by",
"its",
"name"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Application/Module/ModuleManager.php#L324-L356 | train |
krystal-framework/krystal.framework | src/Krystal/Application/Module/ModuleManager.php | ModuleManager.removeFromCacheDir | public function removeFromCacheDir($module)
{
// Create a path
$path = $this->appConfig->getModuleCacheDir($module);
return $this->performRemoval($path);
} | php | public function removeFromCacheDir($module)
{
// Create a path
$path = $this->appConfig->getModuleCacheDir($module);
return $this->performRemoval($path);
} | [
"public",
"function",
"removeFromCacheDir",
"(",
"$",
"module",
")",
"{",
"// Create a path",
"$",
"path",
"=",
"$",
"this",
"->",
"appConfig",
"->",
"getModuleCacheDir",
"(",
"$",
"module",
")",
";",
"return",
"$",
"this",
"->",
"performRemoval",
"(",
"$",
... | Removes module data from cache directory
@param string $module
@return boolean | [
"Removes",
"module",
"data",
"from",
"cache",
"directory"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Application/Module/ModuleManager.php#L379-L384 | train |
krystal-framework/krystal.framework | src/Krystal/Application/Module/ModuleManager.php | ModuleManager.removeFromUploadsDir | public function removeFromUploadsDir($module)
{
// Create a path
$path = $this->appConfig->getModuleUploadsDir($module);
return $this->performRemoval($path);
} | php | public function removeFromUploadsDir($module)
{
// Create a path
$path = $this->appConfig->getModuleUploadsDir($module);
return $this->performRemoval($path);
} | [
"public",
"function",
"removeFromUploadsDir",
"(",
"$",
"module",
")",
"{",
"// Create a path",
"$",
"path",
"=",
"$",
"this",
"->",
"appConfig",
"->",
"getModuleUploadsDir",
"(",
"$",
"module",
")",
";",
"return",
"$",
"this",
"->",
"performRemoval",
"(",
"... | Removes module data from uploading directory
@param string $module
@return boolean | [
"Removes",
"module",
"data",
"from",
"uploading",
"directory"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Application/Module/ModuleManager.php#L392-L397 | train |
krystal-framework/krystal.framework | src/Krystal/Application/Module/ModuleManager.php | ModuleManager.removeFromFileSysem | public function removeFromFileSysem($module)
{
if ($this->isCoreModule($module)) {
throw new LogicException(sprintf(
'Trying to remove core module "%s". This is not allowed by design', $module
));
}
$path = sprintf('%s/%s', $this->appConfig->getModulesDir(), $module);
return $this->performRemoval($path);
} | php | public function removeFromFileSysem($module)
{
if ($this->isCoreModule($module)) {
throw new LogicException(sprintf(
'Trying to remove core module "%s". This is not allowed by design', $module
));
}
$path = sprintf('%s/%s', $this->appConfig->getModulesDir(), $module);
return $this->performRemoval($path);
} | [
"public",
"function",
"removeFromFileSysem",
"(",
"$",
"module",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isCoreModule",
"(",
"$",
"module",
")",
")",
"{",
"throw",
"new",
"LogicException",
"(",
"sprintf",
"(",
"'Trying to remove core module \"%s\". This is not al... | Removes a module from file system
@param string $module Module name (as in the folder)
@throws \LogicException If trying to remove core module
@return boolean Depending on success | [
"Removes",
"a",
"module",
"from",
"file",
"system"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Application/Module/ModuleManager.php#L406-L416 | train |
krystal-framework/krystal.framework | src/Krystal/Application/Module/ModuleManager.php | ModuleManager.loadAllTranslations | public function loadAllTranslations($language)
{
foreach ($this->loaded as $module) {
$this->loadModuleTranslation($module, $language);
}
} | php | public function loadAllTranslations($language)
{
foreach ($this->loaded as $module) {
$this->loadModuleTranslation($module, $language);
}
} | [
"public",
"function",
"loadAllTranslations",
"(",
"$",
"language",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"loaded",
"as",
"$",
"module",
")",
"{",
"$",
"this",
"->",
"loadModuleTranslation",
"(",
"$",
"module",
",",
"$",
"language",
")",
";",
"}",
... | Loads module translations
@param string $language
@return void | [
"Loads",
"module",
"translations"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Application/Module/ModuleManager.php#L434-L439 | train |
krystal-framework/krystal.framework | src/Krystal/Application/Module/ModuleManager.php | ModuleManager.loadModuleTranslation | private function loadModuleTranslation(AbstractModule $module, $language)
{
// Translations are optional
if (method_exists($module, 'getTranslations')) {
$translations = $module->getTranslations($language);
// Only array must be provided, otherwise ignore another type
if (is_array($translations)) {
// If that's an array, then append translations
foreach ($translations as $string => $translation) {
$this->translations[$string] = $translation;
}
// And indicate success
return true;
}
}
// Failure by default
return false;
} | php | private function loadModuleTranslation(AbstractModule $module, $language)
{
// Translations are optional
if (method_exists($module, 'getTranslations')) {
$translations = $module->getTranslations($language);
// Only array must be provided, otherwise ignore another type
if (is_array($translations)) {
// If that's an array, then append translations
foreach ($translations as $string => $translation) {
$this->translations[$string] = $translation;
}
// And indicate success
return true;
}
}
// Failure by default
return false;
} | [
"private",
"function",
"loadModuleTranslation",
"(",
"AbstractModule",
"$",
"module",
",",
"$",
"language",
")",
"{",
"// Translations are optional",
"if",
"(",
"method_exists",
"(",
"$",
"module",
",",
"'getTranslations'",
")",
")",
"{",
"$",
"translations",
"=",... | Loads translation message for particular module
@param \Krystal\Application\Module\AbstractModule $module Module instance
@param string $language Language name to be loaded
@return boolean | [
"Loads",
"translation",
"message",
"for",
"particular",
"module"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Application/Module/ModuleManager.php#L448-L468 | train |
brainsonic/AzureDistributionBundle | Deployment/BuildNumber.php | BuildNumber.createInDirectory | static public function createInDirectory($dir)
{
if (! is_dir($dir) || ! is_writable($dir)) {
throw new \InvalidArgumentException("Directory to load build number from is not writable or does not exist: " . $dir);
}
$buildFile = $dir . DIRECTORY_SEPARATOR . "azure_build_number.yml";
if (! file_exists($buildFile)) {
file_put_contents($buildFile, "parameters:\n azure_build: 0");
}
return new self($buildFile);
} | php | static public function createInDirectory($dir)
{
if (! is_dir($dir) || ! is_writable($dir)) {
throw new \InvalidArgumentException("Directory to load build number from is not writable or does not exist: " . $dir);
}
$buildFile = $dir . DIRECTORY_SEPARATOR . "azure_build_number.yml";
if (! file_exists($buildFile)) {
file_put_contents($buildFile, "parameters:\n azure_build: 0");
}
return new self($buildFile);
} | [
"static",
"public",
"function",
"createInDirectory",
"(",
"$",
"dir",
")",
"{",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"dir",
")",
"||",
"!",
"is_writable",
"(",
"$",
"dir",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"Directory ... | Create a new Build Number inside a directory.
The filename will be "azure_build_number.yml". | [
"Create",
"a",
"new",
"Build",
"Number",
"inside",
"a",
"directory",
"."
] | 37ad5e94d0fd7618137fbc670df47b035b0029d7 | https://github.com/brainsonic/AzureDistributionBundle/blob/37ad5e94d0fd7618137fbc670df47b035b0029d7/Deployment/BuildNumber.php#L35-L48 | train |
Tecnocreaciones/ToolsBundle | Service/UnitConverter/UnitType.php | UnitType.findUnit | protected function findUnit($unitName, $validUnits = null) {
$units = $this->getUnits();
$nunits = count($units);
for ($i = 0; $i < $nunits; $i++) {
if (($validUnits != null) && (!array_search($units[$i]['name'], $validUnits) )){
continue;
}
if (($units[$i]['name'] == $unitName) || ($this->aliasMatch($units[$i], $unitName) )){
return $i;
}
}
throw new \InvalidArgumentException(sprintf('Invalid unit "%s" for type "%s"',$unitName, $this->getType()));
} | php | protected function findUnit($unitName, $validUnits = null) {
$units = $this->getUnits();
$nunits = count($units);
for ($i = 0; $i < $nunits; $i++) {
if (($validUnits != null) && (!array_search($units[$i]['name'], $validUnits) )){
continue;
}
if (($units[$i]['name'] == $unitName) || ($this->aliasMatch($units[$i], $unitName) )){
return $i;
}
}
throw new \InvalidArgumentException(sprintf('Invalid unit "%s" for type "%s"',$unitName, $this->getType()));
} | [
"protected",
"function",
"findUnit",
"(",
"$",
"unitName",
",",
"$",
"validUnits",
"=",
"null",
")",
"{",
"$",
"units",
"=",
"$",
"this",
"->",
"getUnits",
"(",
")",
";",
"$",
"nunits",
"=",
"count",
"(",
"$",
"units",
")",
";",
"for",
"(",
"$",
... | Encuentra un nombre de unidad o un alias
@param $unitName Nombre de la unidad
@param $validUnits Unidades que son válidas para nosotros (puede que no queramos convertir a todas las unidades)
@return Índice dentro del array donde está la unidad (si se encuentra) | [
"Encuentra",
"un",
"nombre",
"de",
"unidad",
"o",
"un",
"alias"
] | 8edc159b91ea41d7a880d2ca0860352d7b05370f | https://github.com/Tecnocreaciones/ToolsBundle/blob/8edc159b91ea41d7a880d2ca0860352d7b05370f/Service/UnitConverter/UnitType.php#L60-L72 | train |
krystal-framework/krystal.framework | src/Krystal/Db/Filter/FilterInvoker.php | FilterInvoker.invoke | public function invoke(FilterableServiceInterface $service, $perPageCount, array $parameters = array())
{
$page = $this->getPageNumber();
$sort = $this->getSortingColumn();
$desc = $this->getDesc();
$records = $service->filter($this->getData(), $page, $perPageCount, $sort, $desc, $parameters);
// Tweak pagination if available
if (method_exists($service, 'getPaginator')) {
$paginator = $service->getPaginator();
if ($paginator instanceof PaginatorInterface) {
$paginator->setUrl($this->getPaginationUrl($page, $sort, $desc));
}
}
return $records;
} | php | public function invoke(FilterableServiceInterface $service, $perPageCount, array $parameters = array())
{
$page = $this->getPageNumber();
$sort = $this->getSortingColumn();
$desc = $this->getDesc();
$records = $service->filter($this->getData(), $page, $perPageCount, $sort, $desc, $parameters);
// Tweak pagination if available
if (method_exists($service, 'getPaginator')) {
$paginator = $service->getPaginator();
if ($paginator instanceof PaginatorInterface) {
$paginator->setUrl($this->getPaginationUrl($page, $sort, $desc));
}
}
return $records;
} | [
"public",
"function",
"invoke",
"(",
"FilterableServiceInterface",
"$",
"service",
",",
"$",
"perPageCount",
",",
"array",
"$",
"parameters",
"=",
"array",
"(",
")",
")",
"{",
"$",
"page",
"=",
"$",
"this",
"->",
"getPageNumber",
"(",
")",
";",
"$",
"sor... | Invokes a filter
@param \Krystal\Db\Filter\FilterableServiceInterface $service
@param integer $perPageCount Amount of items to be display per page
@param array $parameters Custom user-defined parameters
@return array | [
"Invokes",
"a",
"filter"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Db/Filter/FilterInvoker.php#L77-L95 | train |
krystal-framework/krystal.framework | src/Krystal/Db/Filter/FilterInvoker.php | FilterInvoker.getPaginationUrl | private function getPaginationUrl($page, $sort, $desc)
{
$placeholder = '(:var)';
$data = array(
self::FILTER_PARAM_PAGE => $placeholder,
self::FILTER_PARAM_DESC => $desc,
self::FILTER_PARAM_SORT => $sort
);
return self::createUrl(array_merge($this->input, $data), $this->route);
} | php | private function getPaginationUrl($page, $sort, $desc)
{
$placeholder = '(:var)';
$data = array(
self::FILTER_PARAM_PAGE => $placeholder,
self::FILTER_PARAM_DESC => $desc,
self::FILTER_PARAM_SORT => $sort
);
return self::createUrl(array_merge($this->input, $data), $this->route);
} | [
"private",
"function",
"getPaginationUrl",
"(",
"$",
"page",
",",
"$",
"sort",
",",
"$",
"desc",
")",
"{",
"$",
"placeholder",
"=",
"'(:var)'",
";",
"$",
"data",
"=",
"array",
"(",
"self",
"::",
"FILTER_PARAM_PAGE",
"=>",
"$",
"placeholder",
",",
"self",... | Returns pagination URL
@param integer $page Current page number
@param string $sort Current sorting column name
@param string $desc
@return string | [
"Returns",
"pagination",
"URL"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Db/Filter/FilterInvoker.php#L122-L133 | train |
krystal-framework/krystal.framework | src/Krystal/Db/Filter/FilterInvoker.php | FilterInvoker.getData | private function getData()
{
if (isset($this->input[self::FILTER_PARAM_NS])) {
$data = $this->input[self::FILTER_PARAM_NS];
} else {
$data = array();
}
return new InputDecorator($data);
} | php | private function getData()
{
if (isset($this->input[self::FILTER_PARAM_NS])) {
$data = $this->input[self::FILTER_PARAM_NS];
} else {
$data = array();
}
return new InputDecorator($data);
} | [
"private",
"function",
"getData",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"input",
"[",
"self",
"::",
"FILTER_PARAM_NS",
"]",
")",
")",
"{",
"$",
"data",
"=",
"$",
"this",
"->",
"input",
"[",
"self",
"::",
"FILTER_PARAM_NS",
"]",
... | Returns data to be supplied to user-defined filtering method
@return \Krystal\Db\Filter\InputDecorator | [
"Returns",
"data",
"to",
"be",
"supplied",
"to",
"user",
"-",
"defined",
"filtering",
"method"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Db/Filter/FilterInvoker.php#L186-L195 | train |
droath/project-x | src/Discovery/ProjectXDiscovery.php | ProjectXDiscovery.performSearch | protected function performSearch()
{
$filename = self::CONFIG_FILENAME . '.yml';
$directories = array_filter(explode('/', getcwd()));
$count = count($directories);
for ($offset = 0; $offset < $count; ++$offset) {
$next_path = '/' . implode('/', array_slice($directories, 0, $count - $offset));
if (file_exists("{$next_path}/{$filename}")) {
$this->projectXPath = "{$next_path}/{$filename}";
break;
}
}
} | php | protected function performSearch()
{
$filename = self::CONFIG_FILENAME . '.yml';
$directories = array_filter(explode('/', getcwd()));
$count = count($directories);
for ($offset = 0; $offset < $count; ++$offset) {
$next_path = '/' . implode('/', array_slice($directories, 0, $count - $offset));
if (file_exists("{$next_path}/{$filename}")) {
$this->projectXPath = "{$next_path}/{$filename}";
break;
}
}
} | [
"protected",
"function",
"performSearch",
"(",
")",
"{",
"$",
"filename",
"=",
"self",
"::",
"CONFIG_FILENAME",
".",
"'.yml'",
";",
"$",
"directories",
"=",
"array_filter",
"(",
"explode",
"(",
"'/'",
",",
"getcwd",
"(",
")",
")",
")",
";",
"$",
"count",... | Perform search for the Project-X configuration.
@return string | [
"Perform",
"search",
"for",
"the",
"Project",
"-",
"X",
"configuration",
"."
] | 85a7a4879bd041f4c5cb565356646e5f5e2435b7 | https://github.com/droath/project-x/blob/85a7a4879bd041f4c5cb565356646e5f5e2435b7/src/Discovery/ProjectXDiscovery.php#L41-L55 | train |
LucidTaZ/minimax | src/engine/Engine.php | Engine.decide | public function decide(GameState $state): GameState
{
if (!$state->getNextPlayer()->equals($this->objectivePlayer)) {
throw new BadMethodCallException('It is not this players turn');
}
if (empty($state->getPossibleMoves())) {
throw new RuntimeException('There are no possible moves');
}
$rootNode = new DecisionNode(
$this->objectivePlayer,
$state,
$this->maxDepth,
NodeType::MAX(),
AlphaBeta::initial()
);
$moveWithEvaluation = $rootNode->traverseGameTree();
$this->analytics = $moveWithEvaluation->analytics;
if ($moveWithEvaluation->move === null) {
throw new LogicException('Could not find move even though there are moves. Is the maxdepth parameter correct?');
}
return $moveWithEvaluation->move;
} | php | public function decide(GameState $state): GameState
{
if (!$state->getNextPlayer()->equals($this->objectivePlayer)) {
throw new BadMethodCallException('It is not this players turn');
}
if (empty($state->getPossibleMoves())) {
throw new RuntimeException('There are no possible moves');
}
$rootNode = new DecisionNode(
$this->objectivePlayer,
$state,
$this->maxDepth,
NodeType::MAX(),
AlphaBeta::initial()
);
$moveWithEvaluation = $rootNode->traverseGameTree();
$this->analytics = $moveWithEvaluation->analytics;
if ($moveWithEvaluation->move === null) {
throw new LogicException('Could not find move even though there are moves. Is the maxdepth parameter correct?');
}
return $moveWithEvaluation->move;
} | [
"public",
"function",
"decide",
"(",
"GameState",
"$",
"state",
")",
":",
"GameState",
"{",
"if",
"(",
"!",
"$",
"state",
"->",
"getNextPlayer",
"(",
")",
"->",
"equals",
"(",
"$",
"this",
"->",
"objectivePlayer",
")",
")",
"{",
"throw",
"new",
"BadMet... | Evaluate possible decisions and take the best one
@param GameState $state Current state of the game for which there needs
to be made a decision. This implicitly means that the objective player
currently must have its turn in the GameState.
@return GameState The state resulting after the engine made its decision. | [
"Evaluate",
"possible",
"decisions",
"and",
"take",
"the",
"best",
"one"
] | 473dbbd7caa0f10e7d0fa092018258a2c7ca3d28 | https://github.com/LucidTaZ/minimax/blob/473dbbd7caa0f10e7d0fa092018258a2c7ca3d28/src/engine/Engine.php#L47-L70 | train |
krystal-framework/krystal.framework | src/Krystal/Http/Client/CurlHttplCrawler.php | CurlHttplCrawler.request | public function request($method, $url, array $data = array(), array $extra = array())
{
switch (strtoupper($method)) {
case 'POST':
return $this->post($url, $data, $extra);
case 'GET':
return $this->get($url, $data, $extra);
case 'PATCH':
return $this->patch($url, $data, $extra);
case 'HEAD':
return $this->head($url, $data, $extra);
case 'PUT':
return $this->put($url, $data, $extra);
case 'DELETE':
return $this->delete($url, $data, $extra);
default:
throw new UnexpectedValueException(sprintf('Unsupported or unknown HTTP method provided "%s"', $method));
}
} | php | public function request($method, $url, array $data = array(), array $extra = array())
{
switch (strtoupper($method)) {
case 'POST':
return $this->post($url, $data, $extra);
case 'GET':
return $this->get($url, $data, $extra);
case 'PATCH':
return $this->patch($url, $data, $extra);
case 'HEAD':
return $this->head($url, $data, $extra);
case 'PUT':
return $this->put($url, $data, $extra);
case 'DELETE':
return $this->delete($url, $data, $extra);
default:
throw new UnexpectedValueException(sprintf('Unsupported or unknown HTTP method provided "%s"', $method));
}
} | [
"public",
"function",
"request",
"(",
"$",
"method",
",",
"$",
"url",
",",
"array",
"$",
"data",
"=",
"array",
"(",
")",
",",
"array",
"$",
"extra",
"=",
"array",
"(",
")",
")",
"{",
"switch",
"(",
"strtoupper",
"(",
"$",
"method",
")",
")",
"{",... | Performs a HTTP request
@param string $method
@param string $url Target URL
@param array $data Data to be sent
@param array $extra Extra options
@param \UnexpectedValueException If unknown HTTP method provided
@return mixed | [
"Performs",
"a",
"HTTP",
"request"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Http/Client/CurlHttplCrawler.php#L28-L46 | train |
krystal-framework/krystal.framework | src/Krystal/Http/Client/CurlHttplCrawler.php | CurlHttplCrawler.get | public function get($url, array $data = array(), array $extra = array())
{
if (!empty($data)) {
$url = $url . '?' . http_build_query($data);
}
$curl = new Curl(array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false
), $extra);
return $curl->exec();
} | php | public function get($url, array $data = array(), array $extra = array())
{
if (!empty($data)) {
$url = $url . '?' . http_build_query($data);
}
$curl = new Curl(array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false
), $extra);
return $curl->exec();
} | [
"public",
"function",
"get",
"(",
"$",
"url",
",",
"array",
"$",
"data",
"=",
"array",
"(",
")",
",",
"array",
"$",
"extra",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"data",
")",
")",
"{",
"$",
"url",
"=",
"$",
"... | Performs HTTP GET request
@param string $url Target URL
@param array $data Data to be sent
@param array $extra Extra options
@return mixed | [
"Performs",
"HTTP",
"GET",
"request"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Http/Client/CurlHttplCrawler.php#L56-L69 | train |
krystal-framework/krystal.framework | src/Krystal/Http/Client/CurlHttplCrawler.php | CurlHttplCrawler.post | public function post($url, $data = array(), array $extra = array())
{
$curl = new Curl(array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_POST => count($data),
CURLOPT_POSTFIELDS => http_build_query($data)
), $extra);
return $curl->exec();
} | php | public function post($url, $data = array(), array $extra = array())
{
$curl = new Curl(array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_POST => count($data),
CURLOPT_POSTFIELDS => http_build_query($data)
), $extra);
return $curl->exec();
} | [
"public",
"function",
"post",
"(",
"$",
"url",
",",
"$",
"data",
"=",
"array",
"(",
")",
",",
"array",
"$",
"extra",
"=",
"array",
"(",
")",
")",
"{",
"$",
"curl",
"=",
"new",
"Curl",
"(",
"array",
"(",
"CURLOPT_URL",
"=>",
"$",
"url",
",",
"CU... | Performs HTTP POST request
@param string $url Target URL
@param array $data Data to be sent
@param array $extra Extra options
@return mixed | [
"Performs",
"HTTP",
"POST",
"request"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Http/Client/CurlHttplCrawler.php#L79-L91 | train |
krystal-framework/krystal.framework | src/Krystal/Http/Client/CurlHttplCrawler.php | CurlHttplCrawler.delete | public function delete($url, array $data = array(), array $extra = array())
{
$curl = new Curl(array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'DELETE',
CURLOPT_POSTFIELDS => http_build_query($data)
), $extra);
return $curl->exec();
} | php | public function delete($url, array $data = array(), array $extra = array())
{
$curl = new Curl(array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'DELETE',
CURLOPT_POSTFIELDS => http_build_query($data)
), $extra);
return $curl->exec();
} | [
"public",
"function",
"delete",
"(",
"$",
"url",
",",
"array",
"$",
"data",
"=",
"array",
"(",
")",
",",
"array",
"$",
"extra",
"=",
"array",
"(",
")",
")",
"{",
"$",
"curl",
"=",
"new",
"Curl",
"(",
"array",
"(",
"CURLOPT_URL",
"=>",
"$",
"url",... | Performs HTTP DELETE request
@param string $url Target URL
@param array $data Data to be sent
@param array $extra Extra options
@return mixed | [
"Performs",
"HTTP",
"DELETE",
"request"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Http/Client/CurlHttplCrawler.php#L121-L131 | train |
krystal-framework/krystal.framework | src/Krystal/Http/Client/CurlHttplCrawler.php | CurlHttplCrawler.head | public function head($url, array $data = array(), array $extra = array())
{
if (!empty($data)) {
$url = $url . '?' . http_build_query($data);
}
$curl = new Curl(array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_NOBODY => true,
CURLOPT_POSTFIELDS => http_build_query($data)
), $extra);
return $curl->exec();
} | php | public function head($url, array $data = array(), array $extra = array())
{
if (!empty($data)) {
$url = $url . '?' . http_build_query($data);
}
$curl = new Curl(array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_NOBODY => true,
CURLOPT_POSTFIELDS => http_build_query($data)
), $extra);
return $curl->exec();
} | [
"public",
"function",
"head",
"(",
"$",
"url",
",",
"array",
"$",
"data",
"=",
"array",
"(",
")",
",",
"array",
"$",
"extra",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"data",
")",
")",
"{",
"$",
"url",
"=",
"$",
... | Performs HTTP HEAD request
@param string $url Target URL
@param array $data Data to be sent
@param array $extra Extra options
@return mixed | [
"Performs",
"HTTP",
"HEAD",
"request"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Http/Client/CurlHttplCrawler.php#L161-L175 | train |
stefk/JVal | src/Utils.php | Utils.loadJsonFromFile | public static function loadJsonFromFile($filePath)
{
if (!file_exists($filePath)) {
throw new \RuntimeException("File '{$filePath}' doesn't exist");
}
$content = json_decode(file_get_contents($filePath));
if (json_last_error() !== JSON_ERROR_NONE) {
throw new JsonDecodeException(sprintf(
'Cannot decode JSON from file "%s" (error: %s)',
$filePath,
static::lastJsonErrorMessage()
));
}
return $content;
} | php | public static function loadJsonFromFile($filePath)
{
if (!file_exists($filePath)) {
throw new \RuntimeException("File '{$filePath}' doesn't exist");
}
$content = json_decode(file_get_contents($filePath));
if (json_last_error() !== JSON_ERROR_NONE) {
throw new JsonDecodeException(sprintf(
'Cannot decode JSON from file "%s" (error: %s)',
$filePath,
static::lastJsonErrorMessage()
));
}
return $content;
} | [
"public",
"static",
"function",
"loadJsonFromFile",
"(",
"$",
"filePath",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"filePath",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"\"File '{$filePath}' doesn't exist\"",
")",
";",
"}",
"$",
... | Returns the JSON-decoded content of a file.
@param $filePath
@return mixed
@throws \RuntimeException
@throws JsonDecodeException | [
"Returns",
"the",
"JSON",
"-",
"decoded",
"content",
"of",
"a",
"file",
"."
] | 1c26dd2c16e5273d1c0565ff6c9dc51e6316c564 | https://github.com/stefk/JVal/blob/1c26dd2c16e5273d1c0565ff6c9dc51e6316c564/src/Utils.php#L84-L101 | train |
solspace/craft3-commons | src/Helpers/CryptoHelper.php | CryptoHelper.getUniqueToken | public static function getUniqueToken(int $length = 40): string
{
$token = '';
$codeAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$codeAlphabet .= 'abcdefghijklmnopqrstuvwxyz';
$codeAlphabet .= '0123456789';
$max = strlen($codeAlphabet); // edited
for ($i = 0; $i < $length; $i++) {
$token .= $codeAlphabet[self::getSecureRandomInt(0, $max - 1)];
}
return $token;
} | php | public static function getUniqueToken(int $length = 40): string
{
$token = '';
$codeAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$codeAlphabet .= 'abcdefghijklmnopqrstuvwxyz';
$codeAlphabet .= '0123456789';
$max = strlen($codeAlphabet); // edited
for ($i = 0; $i < $length; $i++) {
$token .= $codeAlphabet[self::getSecureRandomInt(0, $max - 1)];
}
return $token;
} | [
"public",
"static",
"function",
"getUniqueToken",
"(",
"int",
"$",
"length",
"=",
"40",
")",
":",
"string",
"{",
"$",
"token",
"=",
"''",
";",
"$",
"codeAlphabet",
"=",
"'ABCDEFGHIJKLMNOPQRSTUVWXYZ'",
";",
"$",
"codeAlphabet",
".=",
"'abcdefghijklmnopqrstuvwxyz'... | Generate a unique token
@param int $length
@return string | [
"Generate",
"a",
"unique",
"token"
] | 2de20a76e83efe3ed615a2a102dfef18e2295420 | https://github.com/solspace/craft3-commons/blob/2de20a76e83efe3ed615a2a102dfef18e2295420/src/Helpers/CryptoHelper.php#L20-L33 | train |
i-lateral/silverstripe-checkout | code/tools/StringDecryptor.php | StringDecryptor.decode | public function decode()
{
// Fix plus to space conversion issue
$this->data = str_replace(' ', '+', $this->data);
// Do decoding
$this->data = base64_decode($this->data);
return $this;
} | php | public function decode()
{
// Fix plus to space conversion issue
$this->data = str_replace(' ', '+', $this->data);
// Do decoding
$this->data = base64_decode($this->data);
return $this;
} | [
"public",
"function",
"decode",
"(",
")",
"{",
"// Fix plus to space conversion issue",
"$",
"this",
"->",
"data",
"=",
"str_replace",
"(",
"' '",
",",
"'+'",
",",
"$",
"this",
"->",
"data",
")",
";",
"// Do decoding",
"$",
"this",
"->",
"data",
"=",
"base... | Base 64 encode the data, ready for transit
@return self | [
"Base",
"64",
"encode",
"the",
"data",
"ready",
"for",
"transit"
] | 2089b57ac2b7feb86dccde8a6864ae70ce463497 | https://github.com/i-lateral/silverstripe-checkout/blob/2089b57ac2b7feb86dccde8a6864ae70ce463497/code/tools/StringDecryptor.php#L122-L131 | train |
i-lateral/silverstripe-checkout | code/tools/StringDecryptor.php | StringDecryptor.simplexor | private function simplexor()
{
$KeyList = array();
$output = "";
// Convert $Key into array of ASCII values
for ($i = 0; $i < strlen($this->hash); $i++) {
$KeyList[$i] = ord(substr($this->hash, $i, 1));
}
// Step through string a character at a time
for ($i = 0; $i < strlen($this->data); $i++) {
$output.= chr(ord(substr($this->data, $i, 1)) ^ ($KeyList[$i % strlen($this->hash)]));
}
// Return the result
return $output;
} | php | private function simplexor()
{
$KeyList = array();
$output = "";
// Convert $Key into array of ASCII values
for ($i = 0; $i < strlen($this->hash); $i++) {
$KeyList[$i] = ord(substr($this->hash, $i, 1));
}
// Step through string a character at a time
for ($i = 0; $i < strlen($this->data); $i++) {
$output.= chr(ord(substr($this->data, $i, 1)) ^ ($KeyList[$i % strlen($this->hash)]));
}
// Return the result
return $output;
} | [
"private",
"function",
"simplexor",
"(",
")",
"{",
"$",
"KeyList",
"=",
"array",
"(",
")",
";",
"$",
"output",
"=",
"\"\"",
";",
"// Convert $Key into array of ASCII values",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"strlen",
"(",
"$",
"this... | SimpleXor encryption algorithm
return self | [
"SimpleXor",
"encryption",
"algorithm"
] | 2089b57ac2b7feb86dccde8a6864ae70ce463497 | https://github.com/i-lateral/silverstripe-checkout/blob/2089b57ac2b7feb86dccde8a6864ae70ce463497/code/tools/StringDecryptor.php#L155-L172 | train |
inc2734/mimizuku-core | src/App/Model/Page_Templates.php | Page_Templates.get | public function get() {
foreach ( $this->page_template_files as $name => $page_template_path ) {
if ( isset( $this->wrappers[ $name ] ) ) {
continue;
}
if ( ! isset( $this->wrapper_files[ $name ] ) ) {
continue;
}
$label = $this->_get_template_label( $page_template_path );
if ( ! $label ) {
continue;
}
// @codingStandardsIgnoreStart
$this->wrappers[ $name ] = translate( $label, wp_get_theme( get_template() )->get( 'TextDomain' ) );
// @codingStandardsIgnoreEnd
}
return $this->wrappers;
} | php | public function get() {
foreach ( $this->page_template_files as $name => $page_template_path ) {
if ( isset( $this->wrappers[ $name ] ) ) {
continue;
}
if ( ! isset( $this->wrapper_files[ $name ] ) ) {
continue;
}
$label = $this->_get_template_label( $page_template_path );
if ( ! $label ) {
continue;
}
// @codingStandardsIgnoreStart
$this->wrappers[ $name ] = translate( $label, wp_get_theme( get_template() )->get( 'TextDomain' ) );
// @codingStandardsIgnoreEnd
}
return $this->wrappers;
} | [
"public",
"function",
"get",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"page_template_files",
"as",
"$",
"name",
"=>",
"$",
"page_template_path",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"wrappers",
"[",
"$",
"name",
"]",
")",
")... | Return available wrapper templates name
@return array | [
"Return",
"available",
"wrapper",
"templates",
"name"
] | d192a01f4a730e53bced3dfcd0ef29fbecc80330 | https://github.com/inc2734/mimizuku-core/blob/d192a01f4a730e53bced3dfcd0ef29fbecc80330/src/App/Model/Page_Templates.php#L44-L65 | train |
inc2734/mimizuku-core | src/App/Model/Page_Templates.php | Page_Templates._get_wrapper_files | protected function _get_wrapper_files() {
$wrapper_files = [];
foreach ( WP_View_Controller\Helper\config( 'layout' ) as $wrapper_dir ) {
foreach ( glob( get_theme_file_path( $wrapper_dir . '/*' ) ) as $wrapper_path ) {
$name = basename( $wrapper_path, '.php' );
if ( 'blank' === $name || 'blank-fluid' === $name ) {
continue;
}
if ( isset( $wrapper_files[ $name ] ) ) {
continue;
}
$wrapper_files[ $name ] = $wrapper_path;
}
}
return $wrapper_files;
} | php | protected function _get_wrapper_files() {
$wrapper_files = [];
foreach ( WP_View_Controller\Helper\config( 'layout' ) as $wrapper_dir ) {
foreach ( glob( get_theme_file_path( $wrapper_dir . '/*' ) ) as $wrapper_path ) {
$name = basename( $wrapper_path, '.php' );
if ( 'blank' === $name || 'blank-fluid' === $name ) {
continue;
}
if ( isset( $wrapper_files[ $name ] ) ) {
continue;
}
$wrapper_files[ $name ] = $wrapper_path;
}
}
return $wrapper_files;
} | [
"protected",
"function",
"_get_wrapper_files",
"(",
")",
"{",
"$",
"wrapper_files",
"=",
"[",
"]",
";",
"foreach",
"(",
"WP_View_Controller",
"\\",
"Helper",
"\\",
"config",
"(",
"'layout'",
")",
"as",
"$",
"wrapper_dir",
")",
"{",
"foreach",
"(",
"glob",
... | Return wrapper templates path
@return array | [
"Return",
"wrapper",
"templates",
"path"
] | d192a01f4a730e53bced3dfcd0ef29fbecc80330 | https://github.com/inc2734/mimizuku-core/blob/d192a01f4a730e53bced3dfcd0ef29fbecc80330/src/App/Model/Page_Templates.php#L93-L110 | train |
inc2734/mimizuku-core | src/App/Model/Page_Templates.php | Page_Templates._get_page_template_files | protected function _get_page_template_files() {
$page_template_files = [];
foreach ( WP_View_Controller\Helper\config( 'page-templates' ) as $page_template_dir ) {
foreach ( glob( get_theme_file_path( $page_template_dir . '/*' ) ) as $page_template_path ) {
$name = basename( $page_template_path, '.php' );
if ( 'blank' === $name || 'blank-fluid' === $name ) {
continue;
}
if ( isset( $page_template_files[ $name ] ) ) {
continue;
}
$page_template_files[ $name ] = $page_template_path;
}
}
return $page_template_files;
} | php | protected function _get_page_template_files() {
$page_template_files = [];
foreach ( WP_View_Controller\Helper\config( 'page-templates' ) as $page_template_dir ) {
foreach ( glob( get_theme_file_path( $page_template_dir . '/*' ) ) as $page_template_path ) {
$name = basename( $page_template_path, '.php' );
if ( 'blank' === $name || 'blank-fluid' === $name ) {
continue;
}
if ( isset( $page_template_files[ $name ] ) ) {
continue;
}
$page_template_files[ $name ] = $page_template_path;
}
}
return $page_template_files;
} | [
"protected",
"function",
"_get_page_template_files",
"(",
")",
"{",
"$",
"page_template_files",
"=",
"[",
"]",
";",
"foreach",
"(",
"WP_View_Controller",
"\\",
"Helper",
"\\",
"config",
"(",
"'page-templates'",
")",
"as",
"$",
"page_template_dir",
")",
"{",
"for... | Return page templates path
@return array | [
"Return",
"page",
"templates",
"path"
] | d192a01f4a730e53bced3dfcd0ef29fbecc80330 | https://github.com/inc2734/mimizuku-core/blob/d192a01f4a730e53bced3dfcd0ef29fbecc80330/src/App/Model/Page_Templates.php#L117-L134 | train |
krystal-framework/krystal.framework | src/Krystal/Image/Processor/GD/ImageFile.php | ImageFile.getImageInfo | final protected function getImageInfo($file)
{
$image = getimagesize($file);
if ($image !== false) {
return array(
'width' => $image[0],
'height' => $image[1],
'type' => $image[2],
'mime' => $image['mime'],
'bits' => isset($image['bits']) ? $image['bits'] : null
);
} else {
return false;
}
} | php | final protected function getImageInfo($file)
{
$image = getimagesize($file);
if ($image !== false) {
return array(
'width' => $image[0],
'height' => $image[1],
'type' => $image[2],
'mime' => $image['mime'],
'bits' => isset($image['bits']) ? $image['bits'] : null
);
} else {
return false;
}
} | [
"final",
"protected",
"function",
"getImageInfo",
"(",
"$",
"file",
")",
"{",
"$",
"image",
"=",
"getimagesize",
"(",
"$",
"file",
")",
";",
"if",
"(",
"$",
"image",
"!==",
"false",
")",
"{",
"return",
"array",
"(",
"'width'",
"=>",
"$",
"image",
"["... | Returns image info
@param string $file Path to the image from either URL or a filesystem
@return array|boolean False on failure | [
"Returns",
"image",
"info"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Image/Processor/GD/ImageFile.php#L166-L181 | train |
krystal-framework/krystal.framework | src/Krystal/Image/Processor/GD/ImageFile.php | ImageFile.createImageFromFile | final protected function createImageFromFile($file, $type)
{
switch ($type) {
case \IMAGETYPE_GIF:
return imagecreatefromgif($file);
case \IMAGETYPE_JPEG:
return imagecreatefromjpeg($file);
case \IMAGETYPE_PNG:
return imagecreatefrompng($file);
default:
throw new LogicException(sprintf('Can not create image from "%s"', $file));
}
} | php | final protected function createImageFromFile($file, $type)
{
switch ($type) {
case \IMAGETYPE_GIF:
return imagecreatefromgif($file);
case \IMAGETYPE_JPEG:
return imagecreatefromjpeg($file);
case \IMAGETYPE_PNG:
return imagecreatefrompng($file);
default:
throw new LogicException(sprintf('Can not create image from "%s"', $file));
}
} | [
"final",
"protected",
"function",
"createImageFromFile",
"(",
"$",
"file",
",",
"$",
"type",
")",
"{",
"switch",
"(",
"$",
"type",
")",
"{",
"case",
"\\",
"IMAGETYPE_GIF",
":",
"return",
"imagecreatefromgif",
"(",
"$",
"file",
")",
";",
"case",
"\\",
"IM... | Loads an image into the memory from a file-system or URL
@param string $file
@throws \LogicException When attempting to create from unsupported format
@return resource | [
"Loads",
"an",
"image",
"into",
"the",
"memory",
"from",
"a",
"file",
"-",
"system",
"or",
"URL"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Image/Processor/GD/ImageFile.php#L190-L205 | train |
krystal-framework/krystal.framework | src/Krystal/Image/Processor/GD/ImageFile.php | ImageFile.load | final protected function load($file)
{
$info = $this->getImageInfo($file);
if ($info !== false) {
$this->image = $this->createImageFromFile($file, $info['type']);
$this->width = $info['width'];
$this->height = $info['height'];
$this->type = $info['type'];
$this->mime = $info['mime'];
// Calculate required memory space in bytes
$this->requiredMemorySpace = $info['width'] * $info['height'] * $info['bits'];
return true;
} else {
return false;
}
} | php | final protected function load($file)
{
$info = $this->getImageInfo($file);
if ($info !== false) {
$this->image = $this->createImageFromFile($file, $info['type']);
$this->width = $info['width'];
$this->height = $info['height'];
$this->type = $info['type'];
$this->mime = $info['mime'];
// Calculate required memory space in bytes
$this->requiredMemorySpace = $info['width'] * $info['height'] * $info['bits'];
return true;
} else {
return false;
}
} | [
"final",
"protected",
"function",
"load",
"(",
"$",
"file",
")",
"{",
"$",
"info",
"=",
"$",
"this",
"->",
"getImageInfo",
"(",
"$",
"file",
")",
";",
"if",
"(",
"$",
"info",
"!==",
"false",
")",
"{",
"$",
"this",
"->",
"image",
"=",
"$",
"this",... | Loads the image into the memory
@param string $file
@return boolean | [
"Loads",
"the",
"image",
"into",
"the",
"memory"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Image/Processor/GD/ImageFile.php#L238-L256 | train |
krystal-framework/krystal.framework | src/Krystal/Image/Processor/GD/ImageFile.php | ImageFile.save | final public function save($path, $quality = 75, $type = null)
{
// If no optional type is provided, then use current one
if ($type === null) {
$type = $this->type;
}
switch ($type) {
case \IMAGETYPE_GIF:
$result = imagegif($this->image, $path);
break;
case \IMAGETYPE_JPEG:
$result = imagejpeg($this->image, $path, $quality);
break;
case \IMAGETYPE_PNG:
$result = imagepng($this->image, $path, 9);
break;
default:
throw new LogicException(sprintf(
'Can not save image format (%s) to %s', $type, $path
));
}
$this->done();
// Returns boolean value indicating success or failure
return $result;
} | php | final public function save($path, $quality = 75, $type = null)
{
// If no optional type is provided, then use current one
if ($type === null) {
$type = $this->type;
}
switch ($type) {
case \IMAGETYPE_GIF:
$result = imagegif($this->image, $path);
break;
case \IMAGETYPE_JPEG:
$result = imagejpeg($this->image, $path, $quality);
break;
case \IMAGETYPE_PNG:
$result = imagepng($this->image, $path, 9);
break;
default:
throw new LogicException(sprintf(
'Can not save image format (%s) to %s', $type, $path
));
}
$this->done();
// Returns boolean value indicating success or failure
return $result;
} | [
"final",
"public",
"function",
"save",
"(",
"$",
"path",
",",
"$",
"quality",
"=",
"75",
",",
"$",
"type",
"=",
"null",
")",
"{",
"// If no optional type is provided, then use current one",
"if",
"(",
"$",
"type",
"===",
"null",
")",
"{",
"$",
"type",
"=",... | Saves an image to a file
@param string $path Full absolute path on the file system to save the image
@param integer $quality Image quality Medium quality by default
@param string $format Can be optionally saved in another format
@throws \LogicException if can't save to the target format
@return boolean | [
"Saves",
"an",
"image",
"to",
"a",
"file"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Image/Processor/GD/ImageFile.php#L278-L307 | train |
krystal-framework/krystal.framework | src/Krystal/Image/Processor/GD/ImageFile.php | ImageFile.render | final public function render($quality = 75)
{
header("Content-type: ".image_type_to_mime_type($this->type));
switch ($this->type) {
case \IMAGETYPE_GIF:
imagegif($this->image, null);
break;
case \IMAGETYPE_JPEG:
imagejpeg($this->image, null, $quality);
break;
case \IMAGETYPE_PNG:
imagepng($this->image, null, 9);
break;
default:
throw new LogicException(sprintf('Can not create image from "%s"', $this->file));
}
$this->done();
exit(1);
} | php | final public function render($quality = 75)
{
header("Content-type: ".image_type_to_mime_type($this->type));
switch ($this->type) {
case \IMAGETYPE_GIF:
imagegif($this->image, null);
break;
case \IMAGETYPE_JPEG:
imagejpeg($this->image, null, $quality);
break;
case \IMAGETYPE_PNG:
imagepng($this->image, null, 9);
break;
default:
throw new LogicException(sprintf('Can not create image from "%s"', $this->file));
}
$this->done();
exit(1);
} | [
"final",
"public",
"function",
"render",
"(",
"$",
"quality",
"=",
"75",
")",
"{",
"header",
"(",
"\"Content-type: \"",
".",
"image_type_to_mime_type",
"(",
"$",
"this",
"->",
"type",
")",
")",
";",
"switch",
"(",
"$",
"this",
"->",
"type",
")",
"{",
"... | Renders the image in a browser directly
@param integer $quality Image quality
@throws \LogicException If can't render from the target image's type
@return void | [
"Renders",
"the",
"image",
"in",
"a",
"browser",
"directly"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Image/Processor/GD/ImageFile.php#L326-L349 | train |
droath/project-x | src/Task/GitHubTasks.php | GitHubTasks.githubAuth | public function githubAuth()
{
if ($this->hasAuth()) {
$this->io()->warning(
'A personal GitHub access token has already been setup.'
);
return;
}
$this->io()->note("A personal GitHub access token is required.\n\n" .
'If you need help setting up a access token follow the GitHub guide:' .
' https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/');
$user = $this->ask('GitHub username:');
$pass = $this->askHidden('GitHub token (hidden):');
$status = $this->gitHubUserAuth()
->setUser($user)
->setToken($pass)
->save();
if (!$status) {
$this->io()->success(
"You've successfully added your personal GitHub access token."
);
}
} | php | public function githubAuth()
{
if ($this->hasAuth()) {
$this->io()->warning(
'A personal GitHub access token has already been setup.'
);
return;
}
$this->io()->note("A personal GitHub access token is required.\n\n" .
'If you need help setting up a access token follow the GitHub guide:' .
' https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/');
$user = $this->ask('GitHub username:');
$pass = $this->askHidden('GitHub token (hidden):');
$status = $this->gitHubUserAuth()
->setUser($user)
->setToken($pass)
->save();
if (!$status) {
$this->io()->success(
"You've successfully added your personal GitHub access token."
);
}
} | [
"public",
"function",
"githubAuth",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"hasAuth",
"(",
")",
")",
"{",
"$",
"this",
"->",
"io",
"(",
")",
"->",
"warning",
"(",
"'A personal GitHub access token has already been setup.'",
")",
";",
"return",
";",
"}... | Authenticate GitHub user. | [
"Authenticate",
"GitHub",
"user",
"."
] | 85a7a4879bd041f4c5cb565356646e5f5e2435b7 | https://github.com/droath/project-x/blob/85a7a4879bd041f4c5cb565356646e5f5e2435b7/src/Task/GitHubTasks.php#L23-L49 | train |
droath/project-x | src/Task/GitHubTasks.php | GitHubTasks.githubIssueStart | public function githubIssueStart()
{
$listings = $this
->getIssueListing();
$issue = $this->doAsk(
new ChoiceQuestion('Select GitHub issue:', $listings)
);
$user = $this->getUser();
$number = array_search($issue, $listings);
$this
->taskGitHubIssueAssignees($this->getToken())
->setAccount($this->getAccount())
->setRepository($this->getRepository())
->number($number)
->addAssignee($user)
->run();
$this->say(
sprintf('GH-%d issue was assigned to %s on GitHub.', $number, $user)
);
if ($this->ask('Create Git branch? (yes/no) [no] ')) {
$branch = $this->normailizeBranchName("$number-$issue");
$command = $this->hasGitFlow()
? "flow feature start '$branch'"
: "checkout -b '$branch'";
$this->taskGitStack()
->stopOnFail()
->exec($command)
->run();
}
} | php | public function githubIssueStart()
{
$listings = $this
->getIssueListing();
$issue = $this->doAsk(
new ChoiceQuestion('Select GitHub issue:', $listings)
);
$user = $this->getUser();
$number = array_search($issue, $listings);
$this
->taskGitHubIssueAssignees($this->getToken())
->setAccount($this->getAccount())
->setRepository($this->getRepository())
->number($number)
->addAssignee($user)
->run();
$this->say(
sprintf('GH-%d issue was assigned to %s on GitHub.', $number, $user)
);
if ($this->ask('Create Git branch? (yes/no) [no] ')) {
$branch = $this->normailizeBranchName("$number-$issue");
$command = $this->hasGitFlow()
? "flow feature start '$branch'"
: "checkout -b '$branch'";
$this->taskGitStack()
->stopOnFail()
->exec($command)
->run();
}
} | [
"public",
"function",
"githubIssueStart",
"(",
")",
"{",
"$",
"listings",
"=",
"$",
"this",
"->",
"getIssueListing",
"(",
")",
";",
"$",
"issue",
"=",
"$",
"this",
"->",
"doAsk",
"(",
"new",
"ChoiceQuestion",
"(",
"'Select GitHub issue:'",
",",
"$",
"listi... | Start working a GitHub issue. | [
"Start",
"working",
"a",
"GitHub",
"issue",
"."
] | 85a7a4879bd041f4c5cb565356646e5f5e2435b7 | https://github.com/droath/project-x/blob/85a7a4879bd041f4c5cb565356646e5f5e2435b7/src/Task/GitHubTasks.php#L62-L96 | train |
droath/project-x | src/Task/GitHubTasks.php | GitHubTasks.githubLighthouseStatus | public function githubLighthouseStatus($sha, $opts = [
'hostname' => null,
'protocol' => 'http',
'performance' => false,
'performance-score' => 50,
'accessibility' => false,
'accessibility-score' => 50,
'best-practices' => false,
'best-practices-score' => 50,
'progressive-web-app' => false,
'progressive-web-app-score' => 50,
])
{
$host = ProjectX::getProjectConfig()
->getHost();
$protocol = $opts['protocol'];
$hostname = isset($opts['hostname'])
? $opts['hostname']
: (isset($host['name']) ? $host['name'] : 'localhost');
$url = "$protocol://$hostname";
$path = new \SplFileInfo("/tmp/projectx-lighthouse-$sha.json");
$this->taskGoogleLighthouse()
->setUrl($url)
->chromeFlags([
'--headless',
'--no-sandbox'
])
->setOutput('json')
->setOutputPath($path)
->run();
if (!file_exists($path)) {
throw new \RuntimeException(
'Unable to locate the Google lighthouse results.'
);
}
$selected = array_filter([
'performance',
'accessibility',
'best-practices',
'progressive-web-app'
], function ($key) use ($opts) {
return $opts[$key] === true;
});
$report_data = $this->findLighthouseScoreReportData(
$path,
$selected
);
$state = $this->determineLighthouseState($report_data, $opts);
$this->taskGitHubRepoStatusesCreate($this->getToken())
->setAccount($this->getAccount())
->setRepository($this->getRepository())
->setSha($sha)
->setParamState($state)
->setParamDescription('Google Lighthouse Tests')
->setParamContext('project-x/lighthouse')
->run();
} | php | public function githubLighthouseStatus($sha, $opts = [
'hostname' => null,
'protocol' => 'http',
'performance' => false,
'performance-score' => 50,
'accessibility' => false,
'accessibility-score' => 50,
'best-practices' => false,
'best-practices-score' => 50,
'progressive-web-app' => false,
'progressive-web-app-score' => 50,
])
{
$host = ProjectX::getProjectConfig()
->getHost();
$protocol = $opts['protocol'];
$hostname = isset($opts['hostname'])
? $opts['hostname']
: (isset($host['name']) ? $host['name'] : 'localhost');
$url = "$protocol://$hostname";
$path = new \SplFileInfo("/tmp/projectx-lighthouse-$sha.json");
$this->taskGoogleLighthouse()
->setUrl($url)
->chromeFlags([
'--headless',
'--no-sandbox'
])
->setOutput('json')
->setOutputPath($path)
->run();
if (!file_exists($path)) {
throw new \RuntimeException(
'Unable to locate the Google lighthouse results.'
);
}
$selected = array_filter([
'performance',
'accessibility',
'best-practices',
'progressive-web-app'
], function ($key) use ($opts) {
return $opts[$key] === true;
});
$report_data = $this->findLighthouseScoreReportData(
$path,
$selected
);
$state = $this->determineLighthouseState($report_data, $opts);
$this->taskGitHubRepoStatusesCreate($this->getToken())
->setAccount($this->getAccount())
->setRepository($this->getRepository())
->setSha($sha)
->setParamState($state)
->setParamDescription('Google Lighthouse Tests')
->setParamContext('project-x/lighthouse')
->run();
} | [
"public",
"function",
"githubLighthouseStatus",
"(",
"$",
"sha",
",",
"$",
"opts",
"=",
"[",
"'hostname'",
"=>",
"null",
",",
"'protocol'",
"=>",
"'http'",
",",
"'performance'",
"=>",
"false",
",",
"'performance-score'",
"=>",
"50",
",",
"'accessibility'",
"=>... | GitHub lighthouse status check.
@param string $sha
@param array $opts
@option string $url Set the URL hostname.
@option string $protocol Set the URL protocol http or https.
@option bool $performance Validate performance score.
@option bool $performance-score Set the performance score requirement.
@option bool $accessibility Validate accessibility score.
@option bool $accessibility-score Set the accessibility score requirement.
@option bool $best-practices Validate best-practices score.
@option bool $best-practices-score Set the best-practices score requirement.
@option bool $progressive-web-app Validate progressive-web-app score.
@option bool $progressive-web-app-score Set the progressive-web-app score requirement. | [
"GitHub",
"lighthouse",
"status",
"check",
"."
] | 85a7a4879bd041f4c5cb565356646e5f5e2435b7 | https://github.com/droath/project-x/blob/85a7a4879bd041f4c5cb565356646e5f5e2435b7/src/Task/GitHubTasks.php#L114-L176 | train |
droath/project-x | src/Task/GitHubTasks.php | GitHubTasks.determineLighthouseState | protected function determineLighthouseState(array $values, array $opts)
{
$state = 'success';
foreach ($values as $key => $info) {
$required_score = isset($opts["$key-score"])
? ($opts["$key-score"] <= 100 ? $opts["$key-score"] : 100)
: 50;
if ($info['score'] < $required_score
&& $info['score'] !== $required_score) {
return 'failure';
}
}
return $state;
} | php | protected function determineLighthouseState(array $values, array $opts)
{
$state = 'success';
foreach ($values as $key => $info) {
$required_score = isset($opts["$key-score"])
? ($opts["$key-score"] <= 100 ? $opts["$key-score"] : 100)
: 50;
if ($info['score'] < $required_score
&& $info['score'] !== $required_score) {
return 'failure';
}
}
return $state;
} | [
"protected",
"function",
"determineLighthouseState",
"(",
"array",
"$",
"values",
",",
"array",
"$",
"opts",
")",
"{",
"$",
"state",
"=",
"'success'",
";",
"foreach",
"(",
"$",
"values",
"as",
"$",
"key",
"=>",
"$",
"info",
")",
"{",
"$",
"required_score... | Determine Google lighthouse state.
@param array $values
An array of formatted values.
@param array $opts
An array of command options.
@return string
The google lighthouse state based on the evaluation. | [
"Determine",
"Google",
"lighthouse",
"state",
"."
] | 85a7a4879bd041f4c5cb565356646e5f5e2435b7 | https://github.com/droath/project-x/blob/85a7a4879bd041f4c5cb565356646e5f5e2435b7/src/Task/GitHubTasks.php#L189-L205 | train |
droath/project-x | src/Task/GitHubTasks.php | GitHubTasks.findLighthouseScoreReportData | protected function findLighthouseScoreReportData(\SplFileInfo $path, array $selected)
{
$data = [];
$json = json_decode(file_get_contents($path), true);
foreach ($json['reportCategories'] as $report) {
if (!isset($report['name']) || !isset($report['score'])) {
continue;
}
$label = $report['name'];
$key = Utility::cleanString(
strtolower(strtr($label, ' ', '_')),
'/[^a-zA-Z\_]/'
);
if (!in_array($key, $selected)) {
continue;
}
$data[$key] = [
'name' => $label,
'score' => round($report['score'])
];
}
return $data;
} | php | protected function findLighthouseScoreReportData(\SplFileInfo $path, array $selected)
{
$data = [];
$json = json_decode(file_get_contents($path), true);
foreach ($json['reportCategories'] as $report) {
if (!isset($report['name']) || !isset($report['score'])) {
continue;
}
$label = $report['name'];
$key = Utility::cleanString(
strtolower(strtr($label, ' ', '_')),
'/[^a-zA-Z\_]/'
);
if (!in_array($key, $selected)) {
continue;
}
$data[$key] = [
'name' => $label,
'score' => round($report['score'])
];
}
return $data;
} | [
"protected",
"function",
"findLighthouseScoreReportData",
"(",
"\\",
"SplFileInfo",
"$",
"path",
",",
"array",
"$",
"selected",
")",
"{",
"$",
"data",
"=",
"[",
"]",
";",
"$",
"json",
"=",
"json_decode",
"(",
"file_get_contents",
"(",
"$",
"path",
")",
","... | Find Google lighthouse score report data.
@param \SplFileInfo $path
The path the Google lighthouse report.
@param array $selected
An array of sections to retrieve scores for.
@return array
An array of section data with name, and scores. | [
"Find",
"Google",
"lighthouse",
"score",
"report",
"data",
"."
] | 85a7a4879bd041f4c5cb565356646e5f5e2435b7 | https://github.com/droath/project-x/blob/85a7a4879bd041f4c5cb565356646e5f5e2435b7/src/Task/GitHubTasks.php#L218-L244 | train |
droath/project-x | src/Task/GitHubTasks.php | GitHubTasks.outputGitHubIssues | protected function outputGitHubIssues()
{
$issues = $this
->taskGitHubIssueList(
$this->getToken(),
$this->getAccount(),
$this->getRepository()
)
->run();
unset($issues['time']);
$table = (new Table($this->output))
->setHeaders(['Issue', 'Title', 'State', 'Assignee', 'Labels', 'Author']);
$rows = [];
foreach ($issues as $issue) {
$labels = isset($issue['labels'])
? $this->formatLabelNames($issue['labels'])
: null;
$assignee = isset($issue['assignee']['login'])
? $issue['assignee']['login']
: 'none';
$rows[] = [
$issue['number'],
$issue['title'],
$issue['state'],
$assignee,
$labels,
$issue['user']['login'],
];
}
$table->setRows($rows);
$table->render();
return $this;
} | php | protected function outputGitHubIssues()
{
$issues = $this
->taskGitHubIssueList(
$this->getToken(),
$this->getAccount(),
$this->getRepository()
)
->run();
unset($issues['time']);
$table = (new Table($this->output))
->setHeaders(['Issue', 'Title', 'State', 'Assignee', 'Labels', 'Author']);
$rows = [];
foreach ($issues as $issue) {
$labels = isset($issue['labels'])
? $this->formatLabelNames($issue['labels'])
: null;
$assignee = isset($issue['assignee']['login'])
? $issue['assignee']['login']
: 'none';
$rows[] = [
$issue['number'],
$issue['title'],
$issue['state'],
$assignee,
$labels,
$issue['user']['login'],
];
}
$table->setRows($rows);
$table->render();
return $this;
} | [
"protected",
"function",
"outputGitHubIssues",
"(",
")",
"{",
"$",
"issues",
"=",
"$",
"this",
"->",
"taskGitHubIssueList",
"(",
"$",
"this",
"->",
"getToken",
"(",
")",
",",
"$",
"this",
"->",
"getAccount",
"(",
")",
",",
"$",
"this",
"->",
"getReposito... | Output GitHub issue table.
@return self | [
"Output",
"GitHub",
"issue",
"table",
"."
] | 85a7a4879bd041f4c5cb565356646e5f5e2435b7 | https://github.com/droath/project-x/blob/85a7a4879bd041f4c5cb565356646e5f5e2435b7/src/Task/GitHubTasks.php#L252-L290 | train |
droath/project-x | src/Task/GitHubTasks.php | GitHubTasks.getIssueListing | protected function getIssueListing()
{
$issues = $this
->taskGitHubIssueList(
$this->getToken(),
$this->getAccount(),
$this->getRepository()
)
->run();
$listing = [];
foreach ($issues as $issue) {
if (!isset($issue['title'])) {
continue;
}
$number = $issue['number'];
$listing[$number] = $issue['title'];
}
return $listing;
} | php | protected function getIssueListing()
{
$issues = $this
->taskGitHubIssueList(
$this->getToken(),
$this->getAccount(),
$this->getRepository()
)
->run();
$listing = [];
foreach ($issues as $issue) {
if (!isset($issue['title'])) {
continue;
}
$number = $issue['number'];
$listing[$number] = $issue['title'];
}
return $listing;
} | [
"protected",
"function",
"getIssueListing",
"(",
")",
"{",
"$",
"issues",
"=",
"$",
"this",
"->",
"taskGitHubIssueList",
"(",
"$",
"this",
"->",
"getToken",
"(",
")",
",",
"$",
"this",
"->",
"getAccount",
"(",
")",
",",
"$",
"this",
"->",
"getRepository"... | Get GitHub issue listing.
@return array | [
"Get",
"GitHub",
"issue",
"listing",
"."
] | 85a7a4879bd041f4c5cb565356646e5f5e2435b7 | https://github.com/droath/project-x/blob/85a7a4879bd041f4c5cb565356646e5f5e2435b7/src/Task/GitHubTasks.php#L297-L317 | train |
droath/project-x | src/Task/GitHubTasks.php | GitHubTasks.formatLabelNames | protected function formatLabelNames(array $labels)
{
if (empty($labels)) {
return;
}
$names = [];
foreach ($labels as $label) {
if (!isset($label['name'])) {
continue;
}
$names[] = $label['name'];
}
return implode(', ', $names);
} | php | protected function formatLabelNames(array $labels)
{
if (empty($labels)) {
return;
}
$names = [];
foreach ($labels as $label) {
if (!isset($label['name'])) {
continue;
}
$names[] = $label['name'];
}
return implode(', ', $names);
} | [
"protected",
"function",
"formatLabelNames",
"(",
"array",
"$",
"labels",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"labels",
")",
")",
"{",
"return",
";",
"}",
"$",
"names",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"labels",
"as",
"$",
"label",
")",... | Format GitHub labels.
@param array $labels
An array of labels returned from API resource.
@return string
A comma separated list of GitHub labels. | [
"Format",
"GitHub",
"labels",
"."
] | 85a7a4879bd041f4c5cb565356646e5f5e2435b7 | https://github.com/droath/project-x/blob/85a7a4879bd041f4c5cb565356646e5f5e2435b7/src/Task/GitHubTasks.php#L328-L343 | train |
krystal-framework/krystal.framework | src/Krystal/Autoloader/PSR4.php | PSR4.addNamespaces | public function addNamespaces(array $namespaces)
{
foreach ($namespaces as $prefix => $baseDir) {
$this->addNamespace($prefix, $baseDir);
}
} | php | public function addNamespaces(array $namespaces)
{
foreach ($namespaces as $prefix => $baseDir) {
$this->addNamespace($prefix, $baseDir);
}
} | [
"public",
"function",
"addNamespaces",
"(",
"array",
"$",
"namespaces",
")",
"{",
"foreach",
"(",
"$",
"namespaces",
"as",
"$",
"prefix",
"=>",
"$",
"baseDir",
")",
"{",
"$",
"this",
"->",
"addNamespace",
"(",
"$",
"prefix",
",",
"$",
"baseDir",
")",
"... | Adds a collection to the stack
@param array $namespaces
@return void | [
"Adds",
"a",
"collection",
"to",
"the",
"stack"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Autoloader/PSR4.php#L39-L44 | train |
jarnix/nofussframework | Nf/Env.php | Env.init | public static function init($locale, $environment, $version)
{
$envFilename = Registry::get('applicationPath') . '/.env';
if (file_exists($envFilename)) {
$env = Ini::parse($envFilename, true, $locale . '-' . $environment . '-' . $version, 'common', false);
$env = self::mergeEnvVariables($env);
} else {
$env = new \StdClass();
}
self::$data = Ini::bindArrayToObject($env);
} | php | public static function init($locale, $environment, $version)
{
$envFilename = Registry::get('applicationPath') . '/.env';
if (file_exists($envFilename)) {
$env = Ini::parse($envFilename, true, $locale . '-' . $environment . '-' . $version, 'common', false);
$env = self::mergeEnvVariables($env);
} else {
$env = new \StdClass();
}
self::$data = Ini::bindArrayToObject($env);
} | [
"public",
"static",
"function",
"init",
"(",
"$",
"locale",
",",
"$",
"environment",
",",
"$",
"version",
")",
"{",
"$",
"envFilename",
"=",
"Registry",
"::",
"get",
"(",
"'applicationPath'",
")",
".",
"'/.env'",
";",
"if",
"(",
"file_exists",
"(",
"$",
... | reads the .env file, merges the environment on top of the optional .env file, returns the merged "config" | [
"reads",
"the",
".",
"env",
"file",
"merges",
"the",
"environment",
"on",
"top",
"of",
"the",
"optional",
".",
"env",
"file",
"returns",
"the",
"merged",
"config"
] | 2177ebefd408bd9545ac64345b47cde1ff3cdccb | https://github.com/jarnix/nofussframework/blob/2177ebefd408bd9545ac64345b47cde1ff3cdccb/Nf/Env.php#L12-L22 | train |
brainsonic/AzureDistributionBundle | Blob/Stream.php | Stream.register | static public function register(BlobRestProxy $proxy, $name = 'azure')
{
stream_register_wrapper($name, __CLASS__);
self::$clients[$name] = $proxy;
} | php | static public function register(BlobRestProxy $proxy, $name = 'azure')
{
stream_register_wrapper($name, __CLASS__);
self::$clients[$name] = $proxy;
} | [
"static",
"public",
"function",
"register",
"(",
"BlobRestProxy",
"$",
"proxy",
",",
"$",
"name",
"=",
"'azure'",
")",
"{",
"stream_register_wrapper",
"(",
"$",
"name",
",",
"__CLASS__",
")",
";",
"self",
"::",
"$",
"clients",
"[",
"$",
"name",
"]",
"=",... | Register the given blob rest proxy as client for a stream wrapper.
@param BlobRestProxy $proxy
@param string $name | [
"Register",
"the",
"given",
"blob",
"rest",
"proxy",
"as",
"client",
"for",
"a",
"stream",
"wrapper",
"."
] | 37ad5e94d0fd7618137fbc670df47b035b0029d7 | https://github.com/brainsonic/AzureDistributionBundle/blob/37ad5e94d0fd7618137fbc670df47b035b0029d7/Blob/Stream.php#L86-L90 | train |
brainsonic/AzureDistributionBundle | Blob/Stream.php | Stream.getClient | static public function getClient($name)
{
if (! isset(self::$clients[$name])) {
throw new BlobException("There is no client registered for stream type '" . $name . "://");
}
return self::$clients[$name];
} | php | static public function getClient($name)
{
if (! isset(self::$clients[$name])) {
throw new BlobException("There is no client registered for stream type '" . $name . "://");
}
return self::$clients[$name];
} | [
"static",
"public",
"function",
"getClient",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"clients",
"[",
"$",
"name",
"]",
")",
")",
"{",
"throw",
"new",
"BlobException",
"(",
"\"There is no client registered for stream type ... | Get the client for an azure stream name.
@param string $name
@return BlobRestProxy | [
"Get",
"the",
"client",
"for",
"an",
"azure",
"stream",
"name",
"."
] | 37ad5e94d0fd7618137fbc670df47b035b0029d7 | https://github.com/brainsonic/AzureDistributionBundle/blob/37ad5e94d0fd7618137fbc670df47b035b0029d7/Blob/Stream.php#L109-L116 | train |
brainsonic/AzureDistributionBundle | Blob/Stream.php | Stream.getStorageClient | private function getStorageClient($path = '')
{
if ($this->storageClient === null) {
$url = explode(':', $path);
if (! $url) {
throw new BlobException('Could not parse path "' . $path . '".');
}
$this->storageClient = self::getClient($url[0]);
if (! $this->storageClient) {
throw new BlobException('No storage client registered for stream type "' . $url[0] . '://".');
}
}
return $this->storageClient;
} | php | private function getStorageClient($path = '')
{
if ($this->storageClient === null) {
$url = explode(':', $path);
if (! $url) {
throw new BlobException('Could not parse path "' . $path . '".');
}
$this->storageClient = self::getClient($url[0]);
if (! $this->storageClient) {
throw new BlobException('No storage client registered for stream type "' . $url[0] . '://".');
}
}
return $this->storageClient;
} | [
"private",
"function",
"getStorageClient",
"(",
"$",
"path",
"=",
"''",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"storageClient",
"===",
"null",
")",
"{",
"$",
"url",
"=",
"explode",
"(",
"':'",
",",
"$",
"path",
")",
";",
"if",
"(",
"!",
"$",
"ur... | Retrieve storage client for this stream type
@param string $path
@return BlobClient | [
"Retrieve",
"storage",
"client",
"for",
"this",
"stream",
"type"
] | 37ad5e94d0fd7618137fbc670df47b035b0029d7 | https://github.com/brainsonic/AzureDistributionBundle/blob/37ad5e94d0fd7618137fbc670df47b035b0029d7/Blob/Stream.php#L124-L141 | train |
brainsonic/AzureDistributionBundle | Blob/Stream.php | Stream.stream_write | public function stream_write($data)
{
if (! $this->temporaryFileHandle) {
return 0;
}
$len = strlen($data);
fwrite($this->temporaryFileHandle, $data, $len);
return $len;
} | php | public function stream_write($data)
{
if (! $this->temporaryFileHandle) {
return 0;
}
$len = strlen($data);
fwrite($this->temporaryFileHandle, $data, $len);
return $len;
} | [
"public",
"function",
"stream_write",
"(",
"$",
"data",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"temporaryFileHandle",
")",
"{",
"return",
"0",
";",
"}",
"$",
"len",
"=",
"strlen",
"(",
"$",
"data",
")",
";",
"fwrite",
"(",
"$",
"this",
"->",
... | Write to the stream
@param string $data
@return integer | [
"Write",
"to",
"the",
"stream"
] | 37ad5e94d0fd7618137fbc670df47b035b0029d7 | https://github.com/brainsonic/AzureDistributionBundle/blob/37ad5e94d0fd7618137fbc670df47b035b0029d7/Blob/Stream.php#L198-L207 | train |
brainsonic/AzureDistributionBundle | Blob/Stream.php | Stream.url_stat | public function url_stat($path, $flags)
{
$stat = array();
$stat['dev'] = 0;
$stat['ino'] = 0;
$stat['mode'] = 0;
$stat['nlink'] = 0;
$stat['uid'] = 0;
$stat['gid'] = 0;
$stat['rdev'] = 0;
$stat['size'] = 0;
$stat['atime'] = 0;
$stat['mtime'] = 0;
$stat['ctime'] = 0;
$stat['blksize'] = 0;
$stat['blocks'] = 0;
$info = null;
try {
$metadata = $this->getStorageClient($path)->getBlobProperties($this->getContainerName($path), $this->getFileName($path));
$stat['size'] = $metadata->getProperties()->getContentLength();
// Set the modification time and last modified to the Last-Modified header.
$lastmodified = $metadata->getProperties()
->getLastModified()
->format('U');
$stat['mtime'] = $lastmodified;
$stat['ctime'] = $lastmodified;
// Entry is a regular file.
$stat['mode'] = 0100000;
return array_values($stat) + $stat;
} catch (Exception $ex) {
// Unexisting file...
return false;
}
} | php | public function url_stat($path, $flags)
{
$stat = array();
$stat['dev'] = 0;
$stat['ino'] = 0;
$stat['mode'] = 0;
$stat['nlink'] = 0;
$stat['uid'] = 0;
$stat['gid'] = 0;
$stat['rdev'] = 0;
$stat['size'] = 0;
$stat['atime'] = 0;
$stat['mtime'] = 0;
$stat['ctime'] = 0;
$stat['blksize'] = 0;
$stat['blocks'] = 0;
$info = null;
try {
$metadata = $this->getStorageClient($path)->getBlobProperties($this->getContainerName($path), $this->getFileName($path));
$stat['size'] = $metadata->getProperties()->getContentLength();
// Set the modification time and last modified to the Last-Modified header.
$lastmodified = $metadata->getProperties()
->getLastModified()
->format('U');
$stat['mtime'] = $lastmodified;
$stat['ctime'] = $lastmodified;
// Entry is a regular file.
$stat['mode'] = 0100000;
return array_values($stat) + $stat;
} catch (Exception $ex) {
// Unexisting file...
return false;
}
} | [
"public",
"function",
"url_stat",
"(",
"$",
"path",
",",
"$",
"flags",
")",
"{",
"$",
"stat",
"=",
"array",
"(",
")",
";",
"$",
"stat",
"[",
"'dev'",
"]",
"=",
"0",
";",
"$",
"stat",
"[",
"'ino'",
"]",
"=",
"0",
";",
"$",
"stat",
"[",
"'mode'... | Return array of URL variables
@param string $path
@param integer $flags
@return array | [
"Return",
"array",
"of",
"URL",
"variables"
] | 37ad5e94d0fd7618137fbc670df47b035b0029d7 | https://github.com/brainsonic/AzureDistributionBundle/blob/37ad5e94d0fd7618137fbc670df47b035b0029d7/Blob/Stream.php#L397-L434 | train |
brainsonic/AzureDistributionBundle | Blob/Stream.php | Stream.dir_readdir | public function dir_readdir()
{
$object = current($this->blobs);
if ($object !== false) {
next($this->blobs);
return $object->getName();
}
return false;
} | php | public function dir_readdir()
{
$object = current($this->blobs);
if ($object !== false) {
next($this->blobs);
return $object->getName();
}
return false;
} | [
"public",
"function",
"dir_readdir",
"(",
")",
"{",
"$",
"object",
"=",
"current",
"(",
"$",
"this",
"->",
"blobs",
")",
";",
"if",
"(",
"$",
"object",
"!==",
"false",
")",
"{",
"next",
"(",
"$",
"this",
"->",
"blobs",
")",
";",
"return",
"$",
"o... | Return the next filename in the directory
@return string | [
"Return",
"the",
"next",
"filename",
"in",
"the",
"directory"
] | 37ad5e94d0fd7618137fbc670df47b035b0029d7 | https://github.com/brainsonic/AzureDistributionBundle/blob/37ad5e94d0fd7618137fbc670df47b035b0029d7/Blob/Stream.php#L505-L513 | train |
solspace/craft3-commons | src/Resources/CpAssetBundle.php | CpAssetBundle.init | final public function init()
{
$this->sourcePath = $this->getSourcePath();
$this->depends = [CpAsset::class];
$this->js = $this->getScripts();
$this->css = $this->getStylesheets();
parent::init();
} | php | final public function init()
{
$this->sourcePath = $this->getSourcePath();
$this->depends = [CpAsset::class];
$this->js = $this->getScripts();
$this->css = $this->getStylesheets();
parent::init();
} | [
"final",
"public",
"function",
"init",
"(",
")",
"{",
"$",
"this",
"->",
"sourcePath",
"=",
"$",
"this",
"->",
"getSourcePath",
"(",
")",
";",
"$",
"this",
"->",
"depends",
"=",
"[",
"CpAsset",
"::",
"class",
"]",
";",
"$",
"this",
"->",
"js",
"=",... | Initialize the source path and scripts | [
"Initialize",
"the",
"source",
"path",
"and",
"scripts"
] | 2de20a76e83efe3ed615a2a102dfef18e2295420 | https://github.com/solspace/craft3-commons/blob/2de20a76e83efe3ed615a2a102dfef18e2295420/src/Resources/CpAssetBundle.php#L13-L22 | train |
brainsonic/AzureDistributionBundle | Deployment/ServiceConfiguration.php | ServiceConfiguration.addRole | public function addRole($name)
{
$namespaceUri = $this->dom->lookupNamespaceUri($this->dom->namespaceURI);
$roleNode = $this->dom->createElementNS($namespaceUri, 'Role');
$roleNode->setAttribute('name', $name);
$instancesNode = $this->dom->createElementNS($namespaceUri, 'Instances');
$instancesNode->setAttribute('count', '2');
$configurationSettings = $this->dom->createElementNS($namespaceUri, 'ConfigurationSettings');
$roleNode->appendChild($instancesNode);
$roleNode->appendChild($configurationSettings);
$this->dom->documentElement->appendChild($roleNode);
$this->save();
} | php | public function addRole($name)
{
$namespaceUri = $this->dom->lookupNamespaceUri($this->dom->namespaceURI);
$roleNode = $this->dom->createElementNS($namespaceUri, 'Role');
$roleNode->setAttribute('name', $name);
$instancesNode = $this->dom->createElementNS($namespaceUri, 'Instances');
$instancesNode->setAttribute('count', '2');
$configurationSettings = $this->dom->createElementNS($namespaceUri, 'ConfigurationSettings');
$roleNode->appendChild($instancesNode);
$roleNode->appendChild($configurationSettings);
$this->dom->documentElement->appendChild($roleNode);
$this->save();
} | [
"public",
"function",
"addRole",
"(",
"$",
"name",
")",
"{",
"$",
"namespaceUri",
"=",
"$",
"this",
"->",
"dom",
"->",
"lookupNamespaceUri",
"(",
"$",
"this",
"->",
"dom",
"->",
"namespaceURI",
")",
";",
"$",
"roleNode",
"=",
"$",
"this",
"->",
"dom",
... | Add a role to service configuration
@param string $name | [
"Add",
"a",
"role",
"to",
"service",
"configuration"
] | 37ad5e94d0fd7618137fbc670df47b035b0029d7 | https://github.com/brainsonic/AzureDistributionBundle/blob/37ad5e94d0fd7618137fbc670df47b035b0029d7/Deployment/ServiceConfiguration.php#L70-L88 | train |
brainsonic/AzureDistributionBundle | Deployment/ServiceConfiguration.php | ServiceConfiguration.copyForDeployment | public function copyForDeployment($targetPath, $development = true)
{
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->loadXML($this->dom->saveXML());
$xpath = new \DOMXpath($dom);
$xpath->registerNamespace('sc', $dom->lookupNamespaceUri($dom->namespaceURI));
$settings = $xpath->evaluate('//sc:ConfigurationSettings/sc:Setting[@name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString"]');
foreach ($settings as $setting) {
if ($development) {
$setting->setAttribute('value', 'UseDevelopmentStorage=true');
} else
if (strlen($setting->getAttribute('value')) === 0) {
if ($this->storage) {
$setting->setAttribute('value', sprintf('DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s', $this->storage['accountName'], $this->storage['accountKey']));
} else {
throw new \RuntimeException(<<<EXC
ServiceConfiguration.csdef: Missing value for
'Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString'.
You have to modify the app/azure/ServiceConfiguration.csdef to contain
a value for the diagnostics connection string or better configure
'windows_azure_distribution.diagnostics.accountName' and
'windows_azure_distribution.diagnostics.accountKey' in your
app/config/config.yml
If you don't want to enable diagnostics you should delete the
connection string elements from ServiceConfiguration.csdef file.
EXC
);
}
}
}
$dom->save($targetPath . '/ServiceConfiguration.cscfg');
} | php | public function copyForDeployment($targetPath, $development = true)
{
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->loadXML($this->dom->saveXML());
$xpath = new \DOMXpath($dom);
$xpath->registerNamespace('sc', $dom->lookupNamespaceUri($dom->namespaceURI));
$settings = $xpath->evaluate('//sc:ConfigurationSettings/sc:Setting[@name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString"]');
foreach ($settings as $setting) {
if ($development) {
$setting->setAttribute('value', 'UseDevelopmentStorage=true');
} else
if (strlen($setting->getAttribute('value')) === 0) {
if ($this->storage) {
$setting->setAttribute('value', sprintf('DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s', $this->storage['accountName'], $this->storage['accountKey']));
} else {
throw new \RuntimeException(<<<EXC
ServiceConfiguration.csdef: Missing value for
'Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString'.
You have to modify the app/azure/ServiceConfiguration.csdef to contain
a value for the diagnostics connection string or better configure
'windows_azure_distribution.diagnostics.accountName' and
'windows_azure_distribution.diagnostics.accountKey' in your
app/config/config.yml
If you don't want to enable diagnostics you should delete the
connection string elements from ServiceConfiguration.csdef file.
EXC
);
}
}
}
$dom->save($targetPath . '/ServiceConfiguration.cscfg');
} | [
"public",
"function",
"copyForDeployment",
"(",
"$",
"targetPath",
",",
"$",
"development",
"=",
"true",
")",
"{",
"$",
"dom",
"=",
"new",
"\\",
"DOMDocument",
"(",
"'1.0'",
",",
"'UTF-8'",
")",
";",
"$",
"dom",
"->",
"loadXML",
"(",
"$",
"this",
"->",... | Copy ServiceConfiguration over to build directory given with target path
and modify some of the settings to point to development settings.
@param string $targetPath
@return void | [
"Copy",
"ServiceConfiguration",
"over",
"to",
"build",
"directory",
"given",
"with",
"target",
"path",
"and",
"modify",
"some",
"of",
"the",
"settings",
"to",
"point",
"to",
"development",
"settings",
"."
] | 37ad5e94d0fd7618137fbc670df47b035b0029d7 | https://github.com/brainsonic/AzureDistributionBundle/blob/37ad5e94d0fd7618137fbc670df47b035b0029d7/Deployment/ServiceConfiguration.php#L104-L139 | train |
brainsonic/AzureDistributionBundle | Deployment/ServiceConfiguration.php | ServiceConfiguration.setConfigurationSetting | public function setConfigurationSetting($roleName, $name, $value)
{
$namespaceUri = $this->dom->lookupNamespaceUri($this->dom->namespaceURI);
$xpath = new \DOMXpath($this->dom);
$xpath->registerNamespace('sc', $namespaceUri);
$xpathExpression = '//sc:Role[@name="' . $roleName . '"]//sc:ConfigurationSettings//sc:Setting[@name="' . $name . '"]';
$settingList = $xpath->evaluate($xpathExpression);
if ($settingList->length == 1) {
$settingNode = $settingList->item(0);
} else {
$settingNode = $this->dom->createElementNS($namespaceUri, 'Setting');
$settingNode->setAttribute('name', $name);
$configSettingList = $xpath->evaluate('//sc:Role[@name="' . $roleName . '"]/sc:ConfigurationSettings');
if ($configSettingList->length == 0) {
throw new \RuntimeException("Cannot find <ConfigurationSettings /> in Role '" . $roleName . "'.");
}
$configSettings = $configSettingList->item(0);
$configSettings->appendChild($settingNode);
}
$settingNode->setAttribute('value', $value);
$this->save();
} | php | public function setConfigurationSetting($roleName, $name, $value)
{
$namespaceUri = $this->dom->lookupNamespaceUri($this->dom->namespaceURI);
$xpath = new \DOMXpath($this->dom);
$xpath->registerNamespace('sc', $namespaceUri);
$xpathExpression = '//sc:Role[@name="' . $roleName . '"]//sc:ConfigurationSettings//sc:Setting[@name="' . $name . '"]';
$settingList = $xpath->evaluate($xpathExpression);
if ($settingList->length == 1) {
$settingNode = $settingList->item(0);
} else {
$settingNode = $this->dom->createElementNS($namespaceUri, 'Setting');
$settingNode->setAttribute('name', $name);
$configSettingList = $xpath->evaluate('//sc:Role[@name="' . $roleName . '"]/sc:ConfigurationSettings');
if ($configSettingList->length == 0) {
throw new \RuntimeException("Cannot find <ConfigurationSettings /> in Role '" . $roleName . "'.");
}
$configSettings = $configSettingList->item(0);
$configSettings->appendChild($settingNode);
}
$settingNode->setAttribute('value', $value);
$this->save();
} | [
"public",
"function",
"setConfigurationSetting",
"(",
"$",
"roleName",
",",
"$",
"name",
",",
"$",
"value",
")",
"{",
"$",
"namespaceUri",
"=",
"$",
"this",
"->",
"dom",
"->",
"lookupNamespaceUri",
"(",
"$",
"this",
"->",
"dom",
"->",
"namespaceURI",
")",
... | Add a configuration setting to the ServiceConfiguration.cscfg
@param string $name
@param string $value | [
"Add",
"a",
"configuration",
"setting",
"to",
"the",
"ServiceConfiguration",
".",
"cscfg"
] | 37ad5e94d0fd7618137fbc670df47b035b0029d7 | https://github.com/brainsonic/AzureDistributionBundle/blob/37ad5e94d0fd7618137fbc670df47b035b0029d7/Deployment/ServiceConfiguration.php#L147-L175 | train |
brainsonic/AzureDistributionBundle | Deployment/ServiceConfiguration.php | ServiceConfiguration.addCertificate | public function addCertificate($roleName, RemoteDesktopCertificate $certificate)
{
$namespaceUri = $this->dom->lookupNamespaceUri($this->dom->namespaceURI);
$xpath = new \DOMXpath($this->dom);
$xpath->registerNamespace('sc', $namespaceUri);
$xpathExpression = '//sc:Role[@name="' . $roleName . '"]//sc:Certificates';
$certificateList = $xpath->evaluate($xpathExpression);
if ($certificateList->length == 1) {
$certificatesNode = $certificateList->item(0);
$certificateNodeToDelete = null;
foreach ($certificatesNode->childNodes as $certificateNode) {
if (!$certificateNode instanceof \DOMElement) {
continue;
}
if ('Microsoft.WindowsAzure.Plugins.RemoteAccess.PasswordEncryption' == $certificateNode->getAttribute('name')) {
$certificateNodeToDelete = $certificateNode;
}
}
if (!is_null($certificateNodeToDelete)) {
$certificatesNode->removeChild($certificateNodeToDelete);
}
} else {
$certificatesNode = $this->dom->createElementNS($namespaceUri, 'Certificates');
$roleNodeList = $xpath->evaluate('//sc:Role[@name="' . $roleName . '"]');
if ($roleNodeList->length == 0) {
throw new \RuntimeException("No Role found with name '" . $roleName . "'.");
}
$roleNode = $roleNodeList->item(0);
$roleNode->appendChild($certificatesNode);
}
$certificateNode = $this->dom->createElementNS($namespaceUri, 'Certificate');
$certificateNode->setAttribute('name', 'Microsoft.WindowsAzure.Plugins.RemoteAccess.PasswordEncryption');
$certificateNode->setAttribute('thumbprint', $certificate->getThumbprint());
$certificateNode->setAttribute('thumbprintAlgorithm', 'sha1');
$certificatesNode->appendChild($certificateNode);
$this->save();
} | php | public function addCertificate($roleName, RemoteDesktopCertificate $certificate)
{
$namespaceUri = $this->dom->lookupNamespaceUri($this->dom->namespaceURI);
$xpath = new \DOMXpath($this->dom);
$xpath->registerNamespace('sc', $namespaceUri);
$xpathExpression = '//sc:Role[@name="' . $roleName . '"]//sc:Certificates';
$certificateList = $xpath->evaluate($xpathExpression);
if ($certificateList->length == 1) {
$certificatesNode = $certificateList->item(0);
$certificateNodeToDelete = null;
foreach ($certificatesNode->childNodes as $certificateNode) {
if (!$certificateNode instanceof \DOMElement) {
continue;
}
if ('Microsoft.WindowsAzure.Plugins.RemoteAccess.PasswordEncryption' == $certificateNode->getAttribute('name')) {
$certificateNodeToDelete = $certificateNode;
}
}
if (!is_null($certificateNodeToDelete)) {
$certificatesNode->removeChild($certificateNodeToDelete);
}
} else {
$certificatesNode = $this->dom->createElementNS($namespaceUri, 'Certificates');
$roleNodeList = $xpath->evaluate('//sc:Role[@name="' . $roleName . '"]');
if ($roleNodeList->length == 0) {
throw new \RuntimeException("No Role found with name '" . $roleName . "'.");
}
$roleNode = $roleNodeList->item(0);
$roleNode->appendChild($certificatesNode);
}
$certificateNode = $this->dom->createElementNS($namespaceUri, 'Certificate');
$certificateNode->setAttribute('name', 'Microsoft.WindowsAzure.Plugins.RemoteAccess.PasswordEncryption');
$certificateNode->setAttribute('thumbprint', $certificate->getThumbprint());
$certificateNode->setAttribute('thumbprintAlgorithm', 'sha1');
$certificatesNode->appendChild($certificateNode);
$this->save();
} | [
"public",
"function",
"addCertificate",
"(",
"$",
"roleName",
",",
"RemoteDesktopCertificate",
"$",
"certificate",
")",
"{",
"$",
"namespaceUri",
"=",
"$",
"this",
"->",
"dom",
"->",
"lookupNamespaceUri",
"(",
"$",
"this",
"->",
"dom",
"->",
"namespaceURI",
")... | Add Certificate to the Role
@param string $roleName
@param RemoteDesktopCertificate $certificate | [
"Add",
"Certificate",
"to",
"the",
"Role"
] | 37ad5e94d0fd7618137fbc670df47b035b0029d7 | https://github.com/brainsonic/AzureDistributionBundle/blob/37ad5e94d0fd7618137fbc670df47b035b0029d7/Deployment/ServiceConfiguration.php#L183-L228 | train |
nabu-3/provider-apache-httpd | CApacheHTTPManagerApp.php | CApacheHTTPManagerApp.prepareStandaloneMode | private function prepareStandaloneMode()
{
$param_path = nbCLICheckOption('p', 'path', ':', false);
if ($param_path && is_dir($param_path)) {
$this->mode = CNabuEngine::ENGINE_MODE_STANDALONE;
$this->host_path = $param_path;
} else {
echo "Invalid host path provided for Standalone Engine Mode.\n";
echo "Please revise your params and try again.\n";
}
} | php | private function prepareStandaloneMode()
{
$param_path = nbCLICheckOption('p', 'path', ':', false);
if ($param_path && is_dir($param_path)) {
$this->mode = CNabuEngine::ENGINE_MODE_STANDALONE;
$this->host_path = $param_path;
} else {
echo "Invalid host path provided for Standalone Engine Mode.\n";
echo "Please revise your params and try again.\n";
}
} | [
"private",
"function",
"prepareStandaloneMode",
"(",
")",
"{",
"$",
"param_path",
"=",
"nbCLICheckOption",
"(",
"'p'",
",",
"'path'",
",",
"':'",
",",
"false",
")",
";",
"if",
"(",
"$",
"param_path",
"&&",
"is_dir",
"(",
"$",
"param_path",
")",
")",
"{",... | Prepare Apache HTTP Server to run as Standalone mode. | [
"Prepare",
"Apache",
"HTTP",
"Server",
"to",
"run",
"as",
"Standalone",
"mode",
"."
] | 122f6190f9fb25baae12f4efb70f01241c1417c8 | https://github.com/nabu-3/provider-apache-httpd/blob/122f6190f9fb25baae12f4efb70f01241c1417c8/CApacheHTTPManagerApp.php#L65-L75 | train |
nabu-3/provider-apache-httpd | CApacheHTTPManagerApp.php | CApacheHTTPManagerApp.prepareHostedMode | private function prepareHostedMode()
{
$param_server = nbCLICheckOption('s', 'server', ':', false);
if (strlen($param_server) === 0) {
$param_server = self::DEFAULT_HOSTED_KEY;
$this->mode = CNabuEngine::ENGINE_MODE_HOSTED;
$this->server_key = $param_server;
} else {
echo "Invalid server key provided for Hosted Engine Mode.\n";
echo "Please revise your options and try again.\n";
}
} | php | private function prepareHostedMode()
{
$param_server = nbCLICheckOption('s', 'server', ':', false);
if (strlen($param_server) === 0) {
$param_server = self::DEFAULT_HOSTED_KEY;
$this->mode = CNabuEngine::ENGINE_MODE_HOSTED;
$this->server_key = $param_server;
} else {
echo "Invalid server key provided for Hosted Engine Mode.\n";
echo "Please revise your options and try again.\n";
}
} | [
"private",
"function",
"prepareHostedMode",
"(",
")",
"{",
"$",
"param_server",
"=",
"nbCLICheckOption",
"(",
"'s'",
",",
"'server'",
",",
"':'",
",",
"false",
")",
";",
"if",
"(",
"strlen",
"(",
"$",
"param_server",
")",
"===",
"0",
")",
"{",
"$",
"pa... | Prepare Apache HTTP Server to run as Hosted mode. | [
"Prepare",
"Apache",
"HTTP",
"Server",
"to",
"run",
"as",
"Hosted",
"mode",
"."
] | 122f6190f9fb25baae12f4efb70f01241c1417c8 | https://github.com/nabu-3/provider-apache-httpd/blob/122f6190f9fb25baae12f4efb70f01241c1417c8/CApacheHTTPManagerApp.php#L78-L89 | train |
nabu-3/provider-apache-httpd | CApacheHTTPManagerApp.php | CApacheHTTPManagerApp.prepareClusteredMode | private function prepareClusteredMode()
{
$param_server = nbCLICheckOption('s', 'server', ':', false);
if (strlen($param_server) === 0) {
echo "Missed --server or -s option.\n";
echo "Please revise your options and try again.\n";
} else {
$this->mode = CNabuEngine::ENGINE_MODE_CLUSTERED;
$this->server_key = $param_server;
}
} | php | private function prepareClusteredMode()
{
$param_server = nbCLICheckOption('s', 'server', ':', false);
if (strlen($param_server) === 0) {
echo "Missed --server or -s option.\n";
echo "Please revise your options and try again.\n";
} else {
$this->mode = CNabuEngine::ENGINE_MODE_CLUSTERED;
$this->server_key = $param_server;
}
} | [
"private",
"function",
"prepareClusteredMode",
"(",
")",
"{",
"$",
"param_server",
"=",
"nbCLICheckOption",
"(",
"'s'",
",",
"'server'",
",",
"':'",
",",
"false",
")",
";",
"if",
"(",
"strlen",
"(",
"$",
"param_server",
")",
"===",
"0",
")",
"{",
"echo",... | Prepare Apache HTTP Server to run as Cluster mode. | [
"Prepare",
"Apache",
"HTTP",
"Server",
"to",
"run",
"as",
"Cluster",
"mode",
"."
] | 122f6190f9fb25baae12f4efb70f01241c1417c8 | https://github.com/nabu-3/provider-apache-httpd/blob/122f6190f9fb25baae12f4efb70f01241c1417c8/CApacheHTTPManagerApp.php#L92-L102 | train |
nabu-3/provider-apache-httpd | CApacheHTTPManagerApp.php | CApacheHTTPManagerApp.runStandalone | private function runStandalone()
{
$nb_server = new CNabuBuiltInServer();
$nb_server->setVirtualHostsPath($this->host_path);
$nb_site = new CNabuBuiltInSite();
$nb_site->setBasePath('');
$nb_site->setUseFramework('T');
$apache_server = new CApacheHTTPServer($nb_server, $nb_site);
if ($apache_server->locateApacheServer()) {
$this->displayServerConfig($apache_server);
if ($this->checkHostFolders($this->host_path)) {
$apache_server->createStandaloneConfiguration();
}
}
} | php | private function runStandalone()
{
$nb_server = new CNabuBuiltInServer();
$nb_server->setVirtualHostsPath($this->host_path);
$nb_site = new CNabuBuiltInSite();
$nb_site->setBasePath('');
$nb_site->setUseFramework('T');
$apache_server = new CApacheHTTPServer($nb_server, $nb_site);
if ($apache_server->locateApacheServer()) {
$this->displayServerConfig($apache_server);
if ($this->checkHostFolders($this->host_path)) {
$apache_server->createStandaloneConfiguration();
}
}
} | [
"private",
"function",
"runStandalone",
"(",
")",
"{",
"$",
"nb_server",
"=",
"new",
"CNabuBuiltInServer",
"(",
")",
";",
"$",
"nb_server",
"->",
"setVirtualHostsPath",
"(",
"$",
"this",
"->",
"host_path",
")",
";",
"$",
"nb_site",
"=",
"new",
"CNabuBuiltInS... | Runs the Apache HTTP Server as Standalone mode. | [
"Runs",
"the",
"Apache",
"HTTP",
"Server",
"as",
"Standalone",
"mode",
"."
] | 122f6190f9fb25baae12f4efb70f01241c1417c8 | https://github.com/nabu-3/provider-apache-httpd/blob/122f6190f9fb25baae12f4efb70f01241c1417c8/CApacheHTTPManagerApp.php#L125-L142 | train |
nabu-3/provider-apache-httpd | CApacheHTTPManagerApp.php | CApacheHTTPManagerApp.runHosted | private function runHosted()
{
$nb_server = CNabuServer::findByKey($this->server_key);
$apache_server = new CApacheHTTPServer($nb_server);
if ($apache_server->locateApacheServer()) {
$this->displayServerConfig($apache_server);
$apache_server->createHostedConfiguration();
}
} | php | private function runHosted()
{
$nb_server = CNabuServer::findByKey($this->server_key);
$apache_server = new CApacheHTTPServer($nb_server);
if ($apache_server->locateApacheServer()) {
$this->displayServerConfig($apache_server);
$apache_server->createHostedConfiguration();
}
} | [
"private",
"function",
"runHosted",
"(",
")",
"{",
"$",
"nb_server",
"=",
"CNabuServer",
"::",
"findByKey",
"(",
"$",
"this",
"->",
"server_key",
")",
";",
"$",
"apache_server",
"=",
"new",
"CApacheHTTPServer",
"(",
"$",
"nb_server",
")",
";",
"if",
"(",
... | Runs the Apache HTTP Server as Hosted mode. | [
"Runs",
"the",
"Apache",
"HTTP",
"Server",
"as",
"Hosted",
"mode",
"."
] | 122f6190f9fb25baae12f4efb70f01241c1417c8 | https://github.com/nabu-3/provider-apache-httpd/blob/122f6190f9fb25baae12f4efb70f01241c1417c8/CApacheHTTPManagerApp.php#L145-L154 | train |
nabu-3/provider-apache-httpd | CApacheHTTPManagerApp.php | CApacheHTTPManagerApp.runClustered | private function runClustered()
{
$nb_server = CNabuServer::findByKey($this->server_key);
if (!is_object($nb_server)) {
throw new ENabuCoreException(ENabuCoreException::ERROR_SERVER_NOT_FOUND, array($this->server_key, '*', '*'));
}
$apache_server = new CApacheHTTPServer($nb_server);
if ($apache_server->locateApacheServer()) {
$this->displayServerConfig($apache_server);
$apache_server->createClusteredConfiguration();
}
} | php | private function runClustered()
{
$nb_server = CNabuServer::findByKey($this->server_key);
if (!is_object($nb_server)) {
throw new ENabuCoreException(ENabuCoreException::ERROR_SERVER_NOT_FOUND, array($this->server_key, '*', '*'));
}
$apache_server = new CApacheHTTPServer($nb_server);
if ($apache_server->locateApacheServer()) {
$this->displayServerConfig($apache_server);
$apache_server->createClusteredConfiguration();
}
} | [
"private",
"function",
"runClustered",
"(",
")",
"{",
"$",
"nb_server",
"=",
"CNabuServer",
"::",
"findByKey",
"(",
"$",
"this",
"->",
"server_key",
")",
";",
"if",
"(",
"!",
"is_object",
"(",
"$",
"nb_server",
")",
")",
"{",
"throw",
"new",
"ENabuCoreEx... | Runs the Apache HTTP Server as Clustered mode. | [
"Runs",
"the",
"Apache",
"HTTP",
"Server",
"as",
"Clustered",
"mode",
"."
] | 122f6190f9fb25baae12f4efb70f01241c1417c8 | https://github.com/nabu-3/provider-apache-httpd/blob/122f6190f9fb25baae12f4efb70f01241c1417c8/CApacheHTTPManagerApp.php#L157-L170 | train |
nabu-3/provider-apache-httpd | CApacheHTTPManagerApp.php | CApacheHTTPManagerApp.checkHostFolders | private function checkHostFolders(string $path) : bool
{
echo "Checking folders of host...\n";
$retval =
$this->checkFolder($path, 'private') ||
$this->checkFolder($path, 'httpdocs') ||
$this->checkFolder($path, 'httpsdocs') ||
$this->checkFolder($path, 'phputils') ||
$this->checkFolder($path, 'templates');
echo "OK\n";
return $retval;
} | php | private function checkHostFolders(string $path) : bool
{
echo "Checking folders of host...\n";
$retval =
$this->checkFolder($path, 'private') ||
$this->checkFolder($path, 'httpdocs') ||
$this->checkFolder($path, 'httpsdocs') ||
$this->checkFolder($path, 'phputils') ||
$this->checkFolder($path, 'templates');
echo "OK\n";
return $retval;
} | [
"private",
"function",
"checkHostFolders",
"(",
"string",
"$",
"path",
")",
":",
"bool",
"{",
"echo",
"\"Checking folders of host...\\n\"",
";",
"$",
"retval",
"=",
"$",
"this",
"->",
"checkFolder",
"(",
"$",
"path",
",",
"'private'",
")",
"||",
"$",
"this",... | Check if Host Folders exists.
@param string $path Base path to check.
@return bool Returns true if success. | [
"Check",
"if",
"Host",
"Folders",
"exists",
"."
] | 122f6190f9fb25baae12f4efb70f01241c1417c8 | https://github.com/nabu-3/provider-apache-httpd/blob/122f6190f9fb25baae12f4efb70f01241c1417c8/CApacheHTTPManagerApp.php#L188-L200 | train |
nabu-3/provider-apache-httpd | CApacheHTTPManagerApp.php | CApacheHTTPManagerApp.checkFolder | private function checkFolder(string $path, string $folder, bool $create = false) : bool
{
$retval = false;
$target = $path . (is_string($folder) && strlen($folder) > 0 ? DIRECTORY_SEPARATOR . $folder : '');
echo " ... checking folder $target ...";
if (is_dir($target)) {
echo "EXISTS\n";
$retval = true;
} elseif ($create) {
if ($retval = mkdir($target)) {
echo "CREATED\n";
} else {
echo "ERROR\n";
}
} else {
echo "NOT PRESENT\n";
}
return $retval;
} | php | private function checkFolder(string $path, string $folder, bool $create = false) : bool
{
$retval = false;
$target = $path . (is_string($folder) && strlen($folder) > 0 ? DIRECTORY_SEPARATOR . $folder : '');
echo " ... checking folder $target ...";
if (is_dir($target)) {
echo "EXISTS\n";
$retval = true;
} elseif ($create) {
if ($retval = mkdir($target)) {
echo "CREATED\n";
} else {
echo "ERROR\n";
}
} else {
echo "NOT PRESENT\n";
}
return $retval;
} | [
"private",
"function",
"checkFolder",
"(",
"string",
"$",
"path",
",",
"string",
"$",
"folder",
",",
"bool",
"$",
"create",
"=",
"false",
")",
":",
"bool",
"{",
"$",
"retval",
"=",
"false",
";",
"$",
"target",
"=",
"$",
"path",
".",
"(",
"is_string",... | Check if a folder exists inside a path.
@param string $path Base path to check folder.
@param string $folder Folder to be checked.
@param bool $create If true creates the folder if not exists.
@return bool Returns true if success. In case of creation of folder, returns false if folder cannot be created. | [
"Check",
"if",
"a",
"folder",
"exists",
"inside",
"a",
"path",
"."
] | 122f6190f9fb25baae12f4efb70f01241c1417c8 | https://github.com/nabu-3/provider-apache-httpd/blob/122f6190f9fb25baae12f4efb70f01241c1417c8/CApacheHTTPManagerApp.php#L208-L229 | train |
droath/project-x | src/Engine/DockerFrontendServiceTrait.php | DockerFrontendServiceTrait.alterService | protected function alterService(DockerService $service)
{
if ($this->internal) {
$links = [];
$name = $this->getName();
$host = ProjectX::getProjectConfig()
->getHost();
if (isset($host['name'])) {
$links[] = "traefik.{$name}.frontend.rule=Host:{$host['name']}";
}
$service->setNetworks([
'internal',
DockerEngineType::TRAEFIK_NETWORK
])->setLabels(array_merge([
'traefik.enable=true',
"traefik.{$name}.frontend.backend={$name}",
"traefik.{$name}.port={$this->ports()[0]}",
'traefik.docker.network=' . DockerEngineType::TRAEFIK_NETWORK,
], $links));
} else {
$service->setPorts($this->getPorts());
}
return $service;
} | php | protected function alterService(DockerService $service)
{
if ($this->internal) {
$links = [];
$name = $this->getName();
$host = ProjectX::getProjectConfig()
->getHost();
if (isset($host['name'])) {
$links[] = "traefik.{$name}.frontend.rule=Host:{$host['name']}";
}
$service->setNetworks([
'internal',
DockerEngineType::TRAEFIK_NETWORK
])->setLabels(array_merge([
'traefik.enable=true',
"traefik.{$name}.frontend.backend={$name}",
"traefik.{$name}.port={$this->ports()[0]}",
'traefik.docker.network=' . DockerEngineType::TRAEFIK_NETWORK,
], $links));
} else {
$service->setPorts($this->getPorts());
}
return $service;
} | [
"protected",
"function",
"alterService",
"(",
"DockerService",
"$",
"service",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"internal",
")",
"{",
"$",
"links",
"=",
"[",
"]",
";",
"$",
"name",
"=",
"$",
"this",
"->",
"getName",
"(",
")",
";",
"$",
"host... | Alter the service object.
@param DockerService $service
The docker service object.
@return DockerService
The alter service. | [
"Alter",
"the",
"service",
"object",
"."
] | 85a7a4879bd041f4c5cb565356646e5f5e2435b7 | https://github.com/droath/project-x/blob/85a7a4879bd041f4c5cb565356646e5f5e2435b7/src/Engine/DockerFrontendServiceTrait.php#L53-L78 | train |
phpcq/author-validation | src/Command/CheckAuthor.php | CheckAuthor.createSourceExtractors | protected function createSourceExtractors(
InputInterface $input,
OutputInterface $output,
$config,
CacheInterface $cachePool
) {
// Remark: a plugin system would be really nice here, so others could simply hook themselves into the checking.
$extractors = [];
foreach ([
'bower' => AuthorExtractor\BowerAuthorExtractor::class,
'composer' => AuthorExtractor\ComposerAuthorExtractor::class,
'packages' => AuthorExtractor\NodeAuthorExtractor::class,
'php-files' => AuthorExtractor\PhpDocAuthorExtractor::class,
] as $option => $class) {
if ($input->getOption($option)) {
$extractors[$option] = new $class($config, $output, $cachePool);
}
}
return $extractors;
} | php | protected function createSourceExtractors(
InputInterface $input,
OutputInterface $output,
$config,
CacheInterface $cachePool
) {
// Remark: a plugin system would be really nice here, so others could simply hook themselves into the checking.
$extractors = [];
foreach ([
'bower' => AuthorExtractor\BowerAuthorExtractor::class,
'composer' => AuthorExtractor\ComposerAuthorExtractor::class,
'packages' => AuthorExtractor\NodeAuthorExtractor::class,
'php-files' => AuthorExtractor\PhpDocAuthorExtractor::class,
] as $option => $class) {
if ($input->getOption($option)) {
$extractors[$option] = new $class($config, $output, $cachePool);
}
}
return $extractors;
} | [
"protected",
"function",
"createSourceExtractors",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
",",
"$",
"config",
",",
"CacheInterface",
"$",
"cachePool",
")",
"{",
"// Remark: a plugin system would be really nice here, so others could simply ... | Create all source extractors as specified on the command line.
@param InputInterface $input The input interface.
@param OutputInterface $output The output interface to use for logging.
@param Config $config The configuration.
@param CacheInterface $cachePool The cache.
@return AuthorExtractor[] | [
"Create",
"all",
"source",
"extractors",
"as",
"specified",
"on",
"the",
"command",
"line",
"."
] | 1e22f6133dcadea486a7961274f4e611b5ef4c0c | https://github.com/phpcq/author-validation/blob/1e22f6133dcadea486a7961274f4e611b5ef4c0c/src/Command/CheckAuthor.php#L167-L187 | train |
phpcq/author-validation | src/Command/CheckAuthor.php | CheckAuthor.handleExtractors | private function handleExtractors($extractors, AuthorExtractor $reference, AuthorListComparator $comparator)
{
$failed = false;
foreach ($extractors as $extractor) {
$failed = !$comparator->compare($extractor, $reference) || $failed;
}
return $failed;
} | php | private function handleExtractors($extractors, AuthorExtractor $reference, AuthorListComparator $comparator)
{
$failed = false;
foreach ($extractors as $extractor) {
$failed = !$comparator->compare($extractor, $reference) || $failed;
}
return $failed;
} | [
"private",
"function",
"handleExtractors",
"(",
"$",
"extractors",
",",
"AuthorExtractor",
"$",
"reference",
",",
"AuthorListComparator",
"$",
"comparator",
")",
"{",
"$",
"failed",
"=",
"false",
";",
"foreach",
"(",
"$",
"extractors",
"as",
"$",
"extractor",
... | Process the given extractors.
@param AuthorExtractor[] $extractors The extractors.
@param AuthorExtractor $reference The extractor to use as reference.
@param AuthorListComparator $comparator The comparator to use.
@return bool | [
"Process",
"the",
"given",
"extractors",
"."
] | 1e22f6133dcadea486a7961274f4e611b5ef4c0c | https://github.com/phpcq/author-validation/blob/1e22f6133dcadea486a7961274f4e611b5ef4c0c/src/Command/CheckAuthor.php#L198-L207 | train |
phpcq/author-validation | src/Command/CheckAuthor.php | CheckAuthor.enableDeprecatedNoProgressBar | private function enableDeprecatedNoProgressBar(InputInterface $input)
{
if (!$input->getOption('no-progress-bar')) {
return;
}
// @codingStandardsIgnoreStart
@trigger_error(
'The command option --no-progress-bar is deprecated since 1.4 and where removed in 2.0.
Use --no-progress instead.',
E_USER_DEPRECATED
);
// @codingStandardsIgnoreEnd
$input->setOption('no-progress', true);
} | php | private function enableDeprecatedNoProgressBar(InputInterface $input)
{
if (!$input->getOption('no-progress-bar')) {
return;
}
// @codingStandardsIgnoreStart
@trigger_error(
'The command option --no-progress-bar is deprecated since 1.4 and where removed in 2.0.
Use --no-progress instead.',
E_USER_DEPRECATED
);
// @codingStandardsIgnoreEnd
$input->setOption('no-progress', true);
} | [
"private",
"function",
"enableDeprecatedNoProgressBar",
"(",
"InputInterface",
"$",
"input",
")",
"{",
"if",
"(",
"!",
"$",
"input",
"->",
"getOption",
"(",
"'no-progress-bar'",
")",
")",
"{",
"return",
";",
"}",
"// @codingStandardsIgnoreStart",
"@",
"trigger_err... | Enable the deprecated no progress bar option.
@param InputInterface $input The input.
@return void
@deprecated This is deprecated since 1.4 and where removed in 2.0. Use the option no-progress instead. | [
"Enable",
"the",
"deprecated",
"no",
"progress",
"bar",
"option",
"."
] | 1e22f6133dcadea486a7961274f4e611b5ef4c0c | https://github.com/phpcq/author-validation/blob/1e22f6133dcadea486a7961274f4e611b5ef4c0c/src/Command/CheckAuthor.php#L304-L319 | train |
phpcq/author-validation | src/Command/CheckAuthor.php | CheckAuthor.createGitAuthorExtractor | private function createGitAuthorExtractor($scope, Config $config, $error, $cache, GitRepository $git)
{
if ($scope === 'project') {
return new GitProjectAuthorExtractor($config, $error, $cache);
} else {
$extractor = new GitAuthorExtractor($config, $error, $cache);
$extractor->collectFilesWithCommits($git);
return $extractor;
}
} | php | private function createGitAuthorExtractor($scope, Config $config, $error, $cache, GitRepository $git)
{
if ($scope === 'project') {
return new GitProjectAuthorExtractor($config, $error, $cache);
} else {
$extractor = new GitAuthorExtractor($config, $error, $cache);
$extractor->collectFilesWithCommits($git);
return $extractor;
}
} | [
"private",
"function",
"createGitAuthorExtractor",
"(",
"$",
"scope",
",",
"Config",
"$",
"config",
",",
"$",
"error",
",",
"$",
"cache",
",",
"GitRepository",
"$",
"git",
")",
"{",
"if",
"(",
"$",
"scope",
"===",
"'project'",
")",
"{",
"return",
"new",
... | Create git author extractor for demanded scope.
@param string $scope Git author scope.
@param Config $config Author extractor config.
@param OutputInterface $error Error output.
@param CacheInterface $cache The cache.
@param GitRepository $git The git repository.
@return GitAuthorExtractor|GitProjectAuthorExtractor | [
"Create",
"git",
"author",
"extractor",
"for",
"demanded",
"scope",
"."
] | 1e22f6133dcadea486a7961274f4e611b5ef4c0c | https://github.com/phpcq/author-validation/blob/1e22f6133dcadea486a7961274f4e611b5ef4c0c/src/Command/CheckAuthor.php#L332-L343 | train |
i-lateral/silverstripe-checkout | code/model/Discount.php | Discount.generateRandomString | private static function generateRandomString($length = 10)
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$string = '';
for ($i = 0; $i < $length; $i++) {
$string .= $characters[rand(0, strlen($characters) - 1)];
}
return $string;
} | php | private static function generateRandomString($length = 10)
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$string = '';
for ($i = 0; $i < $length; $i++) {
$string .= $characters[rand(0, strlen($characters) - 1)];
}
return $string;
} | [
"private",
"static",
"function",
"generateRandomString",
"(",
"$",
"length",
"=",
"10",
")",
"{",
"$",
"characters",
"=",
"'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'",
";",
"$",
"string",
"=",
"''",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",... | Generate a random string that we can use for the code by default
@return string | [
"Generate",
"a",
"random",
"string",
"that",
"we",
"can",
"use",
"for",
"the",
"code",
"by",
"default"
] | 2089b57ac2b7feb86dccde8a6864ae70ce463497 | https://github.com/i-lateral/silverstripe-checkout/blob/2089b57ac2b7feb86dccde8a6864ae70ce463497/code/model/Discount.php#L34-L44 | train |
i-lateral/silverstripe-checkout | code/model/Discount.php | Discount.AddLink | public function AddLink()
{
$link = Controller::join_links(
Director::absoluteBaseURL(),
ShoppingCart::config()->url_segment,
"usediscount",
$this->Code
);
return $link;
} | php | public function AddLink()
{
$link = Controller::join_links(
Director::absoluteBaseURL(),
ShoppingCart::config()->url_segment,
"usediscount",
$this->Code
);
return $link;
} | [
"public",
"function",
"AddLink",
"(",
")",
"{",
"$",
"link",
"=",
"Controller",
"::",
"join_links",
"(",
"Director",
"::",
"absoluteBaseURL",
"(",
")",
",",
"ShoppingCart",
"::",
"config",
"(",
")",
"->",
"url_segment",
",",
"\"usediscount\"",
",",
"$",
"t... | Return a URL that allows this code to be added to a cart
automatically
@return String | [
"Return",
"a",
"URL",
"that",
"allows",
"this",
"code",
"to",
"be",
"added",
"to",
"a",
"cart",
"automatically"
] | 2089b57ac2b7feb86dccde8a6864ae70ce463497 | https://github.com/i-lateral/silverstripe-checkout/blob/2089b57ac2b7feb86dccde8a6864ae70ce463497/code/model/Discount.php#L60-L70 | train |
CanalTP/SamCoreBundle | Controller/AbstractController.php | AbstractController.addFlashMessage | protected function addFlashMessage($type, $transKey, $transOpts = array(), $domain = 'messages')
{
$this->get('session')
->getFlashBag()
->add(
$type,
$this->get('translator')->trans($transKey, $transOpts, $domain)
);
} | php | protected function addFlashMessage($type, $transKey, $transOpts = array(), $domain = 'messages')
{
$this->get('session')
->getFlashBag()
->add(
$type,
$this->get('translator')->trans($transKey, $transOpts, $domain)
);
} | [
"protected",
"function",
"addFlashMessage",
"(",
"$",
"type",
",",
"$",
"transKey",
",",
"$",
"transOpts",
"=",
"array",
"(",
")",
",",
"$",
"domain",
"=",
"'messages'",
")",
"{",
"$",
"this",
"->",
"get",
"(",
"'session'",
")",
"->",
"getFlashBag",
"(... | Ajout le message flash dans la session.
@param string $type (alert|error|info|success)
@param string $transKey la clé de traduction
@param array $transOpts $options de substitution
@param string $domain domaine de traduction
@return void | [
"Ajout",
"le",
"message",
"flash",
"dans",
"la",
"session",
"."
] | a68d3e91f7574006c613eece56d8614950e0af84 | https://github.com/CanalTP/SamCoreBundle/blob/a68d3e91f7574006c613eece56d8614950e0af84/Controller/AbstractController.php#L41-L49 | train |
krystal-framework/krystal.framework | src/Krystal/Validate/File/Constraint/Extension.php | Extension.hasValidExtension | private function hasValidExtension($filename)
{
// Current extension
$extension = mb_strtolower(pathinfo($filename, \PATHINFO_EXTENSION), 'UTF-8');
// Make sure all extensions are in lowercase
foreach ($this->extensions as &$expected) {
$expected = mb_strtolower($expected, 'UTF-8');
}
return in_array($extension, $this->extensions);
} | php | private function hasValidExtension($filename)
{
// Current extension
$extension = mb_strtolower(pathinfo($filename, \PATHINFO_EXTENSION), 'UTF-8');
// Make sure all extensions are in lowercase
foreach ($this->extensions as &$expected) {
$expected = mb_strtolower($expected, 'UTF-8');
}
return in_array($extension, $this->extensions);
} | [
"private",
"function",
"hasValidExtension",
"(",
"$",
"filename",
")",
"{",
"// Current extension",
"$",
"extension",
"=",
"mb_strtolower",
"(",
"pathinfo",
"(",
"$",
"filename",
",",
"\\",
"PATHINFO_EXTENSION",
")",
",",
"'UTF-8'",
")",
";",
"// Make sure all ext... | Whether an extension belongs in collection
@param string $filename
@return boolean True if has, False otherwise | [
"Whether",
"an",
"extension",
"belongs",
"in",
"collection"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Validate/File/Constraint/Extension.php#L60-L71 | train |
fxpio/fxp-form-extensions | Form/ChoiceList/Loader/LoaderUtil.php | LoaderUtil.paginateChoices | public static function paginateChoices(AjaxChoiceLoaderInterface $choiceLoader, array $choices)
{
list($startTo, $endTo) = static::getRangeValues($choiceLoader);
// group
if (\is_array(current($choices))) {
return static::paginateGroupChoices($choices, $startTo, $endTo);
}
return static::paginateSimpleChoices($choices, $startTo, $endTo);
} | php | public static function paginateChoices(AjaxChoiceLoaderInterface $choiceLoader, array $choices)
{
list($startTo, $endTo) = static::getRangeValues($choiceLoader);
// group
if (\is_array(current($choices))) {
return static::paginateGroupChoices($choices, $startTo, $endTo);
}
return static::paginateSimpleChoices($choices, $startTo, $endTo);
} | [
"public",
"static",
"function",
"paginateChoices",
"(",
"AjaxChoiceLoaderInterface",
"$",
"choiceLoader",
",",
"array",
"$",
"choices",
")",
"{",
"list",
"(",
"$",
"startTo",
",",
"$",
"endTo",
")",
"=",
"static",
"::",
"getRangeValues",
"(",
"$",
"choiceLoade... | Paginate the flatten choices.
@param AjaxChoiceLoaderInterface $choiceLoader The choice loader
@param array $choices The choices
@return array The paginated choices | [
"Paginate",
"the",
"flatten",
"choices",
"."
] | ef09edf557b109187d38248b0976df31e5583b5b | https://github.com/fxpio/fxp-form-extensions/blob/ef09edf557b109187d38248b0976df31e5583b5b/Form/ChoiceList/Loader/LoaderUtil.php#L27-L37 | train |
fxpio/fxp-form-extensions | Form/ChoiceList/Loader/LoaderUtil.php | LoaderUtil.getRangeValues | protected static function getRangeValues(AjaxChoiceLoaderInterface $choiceLoader)
{
$startTo = ($choiceLoader->getPageNumber() - 1) * $choiceLoader->getPageSize();
$startTo = $startTo < 0 ? 0 : $startTo;
$endTo = $startTo + $choiceLoader->getPageSize();
if (0 >= $choiceLoader->getPageSize()) {
$endTo = $choiceLoader->getSize();
}
if ($endTo > $choiceLoader->getSize()) {
$endTo = $choiceLoader->getSize();
}
return [$startTo, $endTo];
} | php | protected static function getRangeValues(AjaxChoiceLoaderInterface $choiceLoader)
{
$startTo = ($choiceLoader->getPageNumber() - 1) * $choiceLoader->getPageSize();
$startTo = $startTo < 0 ? 0 : $startTo;
$endTo = $startTo + $choiceLoader->getPageSize();
if (0 >= $choiceLoader->getPageSize()) {
$endTo = $choiceLoader->getSize();
}
if ($endTo > $choiceLoader->getSize()) {
$endTo = $choiceLoader->getSize();
}
return [$startTo, $endTo];
} | [
"protected",
"static",
"function",
"getRangeValues",
"(",
"AjaxChoiceLoaderInterface",
"$",
"choiceLoader",
")",
"{",
"$",
"startTo",
"=",
"(",
"$",
"choiceLoader",
"->",
"getPageNumber",
"(",
")",
"-",
"1",
")",
"*",
"$",
"choiceLoader",
"->",
"getPageSize",
... | Gets range values.
@param AjaxChoiceLoaderInterface $choiceLoader The ajax choice loader
@return int[] The startTo and endTo | [
"Gets",
"range",
"values",
"."
] | ef09edf557b109187d38248b0976df31e5583b5b | https://github.com/fxpio/fxp-form-extensions/blob/ef09edf557b109187d38248b0976df31e5583b5b/Form/ChoiceList/Loader/LoaderUtil.php#L46-L61 | train |
fxpio/fxp-form-extensions | Form/ChoiceList/Loader/LoaderUtil.php | LoaderUtil.paginateSimpleChoices | protected static function paginateSimpleChoices(array $choices, $startTo, $endTo)
{
$paginatedChoices = [];
$index = 0;
foreach ($choices as $key => $choice) {
if ($index >= $startTo && $index < $endTo) {
$paginatedChoices[$key] = $choice;
}
++$index;
}
return $paginatedChoices;
} | php | protected static function paginateSimpleChoices(array $choices, $startTo, $endTo)
{
$paginatedChoices = [];
$index = 0;
foreach ($choices as $key => $choice) {
if ($index >= $startTo && $index < $endTo) {
$paginatedChoices[$key] = $choice;
}
++$index;
}
return $paginatedChoices;
} | [
"protected",
"static",
"function",
"paginateSimpleChoices",
"(",
"array",
"$",
"choices",
",",
"$",
"startTo",
",",
"$",
"endTo",
")",
"{",
"$",
"paginatedChoices",
"=",
"[",
"]",
";",
"$",
"index",
"=",
"0",
";",
"foreach",
"(",
"$",
"choices",
"as",
... | Paginate the flatten simple choices.
@param array $choices The choices
@param int $startTo The start index of pagination
@param int $endTo The end index of pagination
@return array The paginated choices | [
"Paginate",
"the",
"flatten",
"simple",
"choices",
"."
] | ef09edf557b109187d38248b0976df31e5583b5b | https://github.com/fxpio/fxp-form-extensions/blob/ef09edf557b109187d38248b0976df31e5583b5b/Form/ChoiceList/Loader/LoaderUtil.php#L72-L86 | train |
fxpio/fxp-form-extensions | Form/ChoiceList/Loader/LoaderUtil.php | LoaderUtil.paginateGroupChoices | protected static function paginateGroupChoices(array $choices, $startTo, $endTo)
{
$paginatedChoices = [];
$index = 0;
foreach ($choices as $groupName => $groupChoices) {
foreach ($groupChoices as $key => $choice) {
if ($index >= $startTo && $index < $endTo) {
$paginatedChoices[$groupName][$key] = $choice;
}
++$index;
}
}
return $paginatedChoices;
} | php | protected static function paginateGroupChoices(array $choices, $startTo, $endTo)
{
$paginatedChoices = [];
$index = 0;
foreach ($choices as $groupName => $groupChoices) {
foreach ($groupChoices as $key => $choice) {
if ($index >= $startTo && $index < $endTo) {
$paginatedChoices[$groupName][$key] = $choice;
}
++$index;
}
}
return $paginatedChoices;
} | [
"protected",
"static",
"function",
"paginateGroupChoices",
"(",
"array",
"$",
"choices",
",",
"$",
"startTo",
",",
"$",
"endTo",
")",
"{",
"$",
"paginatedChoices",
"=",
"[",
"]",
";",
"$",
"index",
"=",
"0",
";",
"foreach",
"(",
"$",
"choices",
"as",
"... | Paginate the flatten group choices.
@param array $choices The choices
@param int $startTo The start index of pagination
@param int $endTo The end index of pagination
@return array The paginated choices | [
"Paginate",
"the",
"flatten",
"group",
"choices",
"."
] | ef09edf557b109187d38248b0976df31e5583b5b | https://github.com/fxpio/fxp-form-extensions/blob/ef09edf557b109187d38248b0976df31e5583b5b/Form/ChoiceList/Loader/LoaderUtil.php#L97-L113 | train |
aphiria/serialization | src/Encoding/EncodingContext.php | EncodingContext.isCircularReference | public function isCircularReference(object $object): bool
{
$objectHashId = spl_object_hash($object);
if (isset($this->circularReferenceHashTable[$objectHashId])) {
return true;
}
$this->circularReferenceHashTable[$objectHashId] = true;
return false;
} | php | public function isCircularReference(object $object): bool
{
$objectHashId = spl_object_hash($object);
if (isset($this->circularReferenceHashTable[$objectHashId])) {
return true;
}
$this->circularReferenceHashTable[$objectHashId] = true;
return false;
} | [
"public",
"function",
"isCircularReference",
"(",
"object",
"$",
"object",
")",
":",
"bool",
"{",
"$",
"objectHashId",
"=",
"spl_object_hash",
"(",
"$",
"object",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"circularReferenceHashTable",
"[",
"$",
... | Checks if the input object indicates that we've hit a circular reference
@param object $object The object to check
@return bool True if the input object indicates a circular reference, otherwise false | [
"Checks",
"if",
"the",
"input",
"object",
"indicates",
"that",
"we",
"ve",
"hit",
"a",
"circular",
"reference"
] | ae9144ce24a810f1c546421b18829f80826c70e0 | https://github.com/aphiria/serialization/blob/ae9144ce24a810f1c546421b18829f80826c70e0/src/Encoding/EncodingContext.php#L29-L40 | train |
Torann/localization-helpers | src/Commands/ImportCommand.php | ImportCommand.ensureFileExists | protected function ensureFileExists($path)
{
if (file_exists($path) === false) {
// Create directory
@mkdir(dirname($path), 0777, true);
// Make the language file
touch($path);
}
} | php | protected function ensureFileExists($path)
{
if (file_exists($path) === false) {
// Create directory
@mkdir(dirname($path), 0777, true);
// Make the language file
touch($path);
}
} | [
"protected",
"function",
"ensureFileExists",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"file_exists",
"(",
"$",
"path",
")",
"===",
"false",
")",
"{",
"// Create directory",
"@",
"mkdir",
"(",
"dirname",
"(",
"$",
"path",
")",
",",
"0777",
",",
"true",
")... | Create the language file if one does not exist.
@param string $path | [
"Create",
"the",
"language",
"file",
"if",
"one",
"does",
"not",
"exist",
"."
] | cf307ad328a6b5f7c54bce5d0d3867d4d623505f | https://github.com/Torann/localization-helpers/blob/cf307ad328a6b5f7c54bce5d0d3867d4d623505f/src/Commands/ImportCommand.php#L151-L161 | train |
bookboon/api-php | src/Entity/Review.php | Review.getByBookId | public static function getByBookId(Bookboon $bookboon, string $bookId) : BookboonResponse
{
if (Entity::isValidUUID($bookId) === false) {
throw new BadUUIDException();
}
$bResponse = $bookboon->rawRequest("/books/$bookId/review");
$bResponse->setEntityStore(
new EntityStore(Review::getEntitiesFromArray($bResponse->getReturnArray()))
);
return $bResponse;
} | php | public static function getByBookId(Bookboon $bookboon, string $bookId) : BookboonResponse
{
if (Entity::isValidUUID($bookId) === false) {
throw new BadUUIDException();
}
$bResponse = $bookboon->rawRequest("/books/$bookId/review");
$bResponse->setEntityStore(
new EntityStore(Review::getEntitiesFromArray($bResponse->getReturnArray()))
);
return $bResponse;
} | [
"public",
"static",
"function",
"getByBookId",
"(",
"Bookboon",
"$",
"bookboon",
",",
"string",
"$",
"bookId",
")",
":",
"BookboonResponse",
"{",
"if",
"(",
"Entity",
"::",
"isValidUUID",
"(",
"$",
"bookId",
")",
"===",
"false",
")",
"{",
"throw",
"new",
... | Get Reviews for specified Book.
@param Bookboon $bookboon
@param string $bookId
@return BookboonResponse
@throws BadUUIDException
@throws \Bookboon\Api\Exception\UsageException | [
"Get",
"Reviews",
"for",
"specified",
"Book",
"."
] | dc386b94dd21589606335a5d16a5300c226ecc21 | https://github.com/bookboon/api-php/blob/dc386b94dd21589606335a5d16a5300c226ecc21/src/Entity/Review.php#L22-L35 | train |
bookboon/api-php | src/Entity/Review.php | Review.submit | public function submit(Bookboon $bookboon, string $bookId) : void
{
if (Entity::isValidUUID($bookId)) {
$bookboon->rawRequest("/books/$bookId/review", $this->getData(), ClientInterface::HTTP_POST);
}
} | php | public function submit(Bookboon $bookboon, string $bookId) : void
{
if (Entity::isValidUUID($bookId)) {
$bookboon->rawRequest("/books/$bookId/review", $this->getData(), ClientInterface::HTTP_POST);
}
} | [
"public",
"function",
"submit",
"(",
"Bookboon",
"$",
"bookboon",
",",
"string",
"$",
"bookId",
")",
":",
"void",
"{",
"if",
"(",
"Entity",
"::",
"isValidUUID",
"(",
"$",
"bookId",
")",
")",
"{",
"$",
"bookboon",
"->",
"rawRequest",
"(",
"\"/books/$bookI... | submit a book review helper method.
@param Bookboon $bookboon
@param string $bookId
@throws \Bookboon\Api\Exception\UsageException
@return void | [
"submit",
"a",
"book",
"review",
"helper",
"method",
"."
] | dc386b94dd21589606335a5d16a5300c226ecc21 | https://github.com/bookboon/api-php/blob/dc386b94dd21589606335a5d16a5300c226ecc21/src/Entity/Review.php#L57-L62 | train |
stefk/JVal | src/Resolver.php | Resolver.initialize | public function initialize(stdClass $schema, Uri $uri)
{
$this->registerSchema($schema, $uri);
$this->stack = [[$uri, $schema]];
} | php | public function initialize(stdClass $schema, Uri $uri)
{
$this->registerSchema($schema, $uri);
$this->stack = [[$uri, $schema]];
} | [
"public",
"function",
"initialize",
"(",
"stdClass",
"$",
"schema",
",",
"Uri",
"$",
"uri",
")",
"{",
"$",
"this",
"->",
"registerSchema",
"(",
"$",
"schema",
",",
"$",
"uri",
")",
";",
"$",
"this",
"->",
"stack",
"=",
"[",
"[",
"$",
"uri",
",",
... | Initializes the resolver with a root schema, on which resolutions will be based.
@param stdClass $schema
@param Uri $uri | [
"Initializes",
"the",
"resolver",
"with",
"a",
"root",
"schema",
"on",
"which",
"resolutions",
"will",
"be",
"based",
"."
] | 1c26dd2c16e5273d1c0565ff6c9dc51e6316c564 | https://github.com/stefk/JVal/blob/1c26dd2c16e5273d1c0565ff6c9dc51e6316c564/src/Resolver.php#L60-L64 | train |
stefk/JVal | src/Resolver.php | Resolver.resolve | public function resolve(stdClass $reference)
{
$baseUri = $this->getCurrentUri();
$uri = new Uri($reference->{'$ref'});
if (!$uri->isAbsolute()) {
$uri->resolveAgainst($baseUri);
}
$identifier = $uri->getPrimaryResourceIdentifier();
if (!isset($this->schemas[$identifier])) {
$schema = $this->fetchSchemaAt($identifier);
$this->registerSchema($schema, $uri);
} else {
$schema = $this->schemas[$identifier];
}
$resolved = $this->resolvePointer($schema, $uri);
if ($resolved === $reference) {
throw new SelfReferencingPointerException();
}
if (!is_object($resolved)) {
throw new InvalidPointerTargetException([$uri->getRawUri()]);
}
return [$uri, $resolved];
} | php | public function resolve(stdClass $reference)
{
$baseUri = $this->getCurrentUri();
$uri = new Uri($reference->{'$ref'});
if (!$uri->isAbsolute()) {
$uri->resolveAgainst($baseUri);
}
$identifier = $uri->getPrimaryResourceIdentifier();
if (!isset($this->schemas[$identifier])) {
$schema = $this->fetchSchemaAt($identifier);
$this->registerSchema($schema, $uri);
} else {
$schema = $this->schemas[$identifier];
}
$resolved = $this->resolvePointer($schema, $uri);
if ($resolved === $reference) {
throw new SelfReferencingPointerException();
}
if (!is_object($resolved)) {
throw new InvalidPointerTargetException([$uri->getRawUri()]);
}
return [$uri, $resolved];
} | [
"public",
"function",
"resolve",
"(",
"stdClass",
"$",
"reference",
")",
"{",
"$",
"baseUri",
"=",
"$",
"this",
"->",
"getCurrentUri",
"(",
")",
";",
"$",
"uri",
"=",
"new",
"Uri",
"(",
"$",
"reference",
"->",
"{",
"'$ref'",
"}",
")",
";",
"if",
"(... | Resolves a schema reference according to the JSON Reference
specification draft. Returns an array containing the resolved
URI and the resolved schema.
@param stdClass $reference
@throws InvalidPointerTargetException
@throws SelfReferencingPointerException
@return array | [
"Resolves",
"a",
"schema",
"reference",
"according",
"to",
"the",
"JSON",
"Reference",
"specification",
"draft",
".",
"Returns",
"an",
"array",
"containing",
"the",
"resolved",
"URI",
"and",
"the",
"resolved",
"schema",
"."
] | 1c26dd2c16e5273d1c0565ff6c9dc51e6316c564 | https://github.com/stefk/JVal/blob/1c26dd2c16e5273d1c0565ff6c9dc51e6316c564/src/Resolver.php#L159-L188 | train |
stefk/JVal | src/Resolver.php | Resolver.registerSchema | private function registerSchema(stdClass $schema, Uri $uri)
{
if (!isset($this->schemas[$uri->getPrimaryResourceIdentifier()])) {
$this->schemas[$uri->getPrimaryResourceIdentifier()] = $schema;
}
} | php | private function registerSchema(stdClass $schema, Uri $uri)
{
if (!isset($this->schemas[$uri->getPrimaryResourceIdentifier()])) {
$this->schemas[$uri->getPrimaryResourceIdentifier()] = $schema;
}
} | [
"private",
"function",
"registerSchema",
"(",
"stdClass",
"$",
"schema",
",",
"Uri",
"$",
"uri",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"schemas",
"[",
"$",
"uri",
"->",
"getPrimaryResourceIdentifier",
"(",
")",
"]",
")",
")",
"{",
... | Caches a schema reference for future use.
@param stdClass $schema
@param Uri $uri | [
"Caches",
"a",
"schema",
"reference",
"for",
"future",
"use",
"."
] | 1c26dd2c16e5273d1c0565ff6c9dc51e6316c564 | https://github.com/stefk/JVal/blob/1c26dd2c16e5273d1c0565ff6c9dc51e6316c564/src/Resolver.php#L196-L201 | train |
stefk/JVal | src/Resolver.php | Resolver.fetchSchemaAt | private function fetchSchemaAt($uri)
{
if ($hook = $this->preFetchHook) {
$uri = $hook($uri);
}
set_error_handler(function ($severity, $error) use ($uri) {
restore_error_handler();
throw new UnfetchableUriException([$uri, $error, $severity]);
});
$content = file_get_contents($uri);
restore_error_handler();
$schema = json_decode($content);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new JsonDecodeException(sprintf(
'Cannot decode JSON from URI "%s" (error: %s)',
$uri,
Utils::lastJsonErrorMessage()
));
}
if (!is_object($schema)) {
throw new InvalidRemoteSchemaException([$uri]);
}
return $schema;
} | php | private function fetchSchemaAt($uri)
{
if ($hook = $this->preFetchHook) {
$uri = $hook($uri);
}
set_error_handler(function ($severity, $error) use ($uri) {
restore_error_handler();
throw new UnfetchableUriException([$uri, $error, $severity]);
});
$content = file_get_contents($uri);
restore_error_handler();
$schema = json_decode($content);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new JsonDecodeException(sprintf(
'Cannot decode JSON from URI "%s" (error: %s)',
$uri,
Utils::lastJsonErrorMessage()
));
}
if (!is_object($schema)) {
throw new InvalidRemoteSchemaException([$uri]);
}
return $schema;
} | [
"private",
"function",
"fetchSchemaAt",
"(",
"$",
"uri",
")",
"{",
"if",
"(",
"$",
"hook",
"=",
"$",
"this",
"->",
"preFetchHook",
")",
"{",
"$",
"uri",
"=",
"$",
"hook",
"(",
"$",
"uri",
")",
";",
"}",
"set_error_handler",
"(",
"function",
"(",
"$... | Fetches a remote schema and ensures it is valid.
@param string $uri
@throws InvalidRemoteSchemaException
@throws JsonDecodeException
@return stdClass | [
"Fetches",
"a",
"remote",
"schema",
"and",
"ensures",
"it",
"is",
"valid",
"."
] | 1c26dd2c16e5273d1c0565ff6c9dc51e6316c564 | https://github.com/stefk/JVal/blob/1c26dd2c16e5273d1c0565ff6c9dc51e6316c564/src/Resolver.php#L213-L242 | train |
stefk/JVal | src/Resolver.php | Resolver.resolvePointer | private function resolvePointer(stdClass $schema, Uri $pointerUri)
{
$segments = $pointerUri->getPointerSegments();
$pointer = $pointerUri->getRawPointer();
$currentNode = $schema;
for ($i = 0, $max = count($segments); $i < $max; ++$i) {
if (is_object($currentNode)) {
if (property_exists($currentNode, $segments[$i])) {
$currentNode = $currentNode->{$segments[$i]};
continue;
}
throw new UnresolvedPointerPropertyException([$segments[$i], $i, $pointer]);
}
if (is_array($currentNode)) {
if (!preg_match('/^\d+$/', $segments[$i])) {
throw new InvalidPointerIndexException([$segments[$i], $i, $pointer]);
}
if (!isset($currentNode[$index = (int) $segments[$i]])) {
throw new UnresolvedPointerIndexException([$segments[$i], $i, $pointer]);
}
$currentNode = $currentNode[$index];
continue;
}
throw new InvalidSegmentTypeException([$i, $pointer]);
}
return $currentNode;
} | php | private function resolvePointer(stdClass $schema, Uri $pointerUri)
{
$segments = $pointerUri->getPointerSegments();
$pointer = $pointerUri->getRawPointer();
$currentNode = $schema;
for ($i = 0, $max = count($segments); $i < $max; ++$i) {
if (is_object($currentNode)) {
if (property_exists($currentNode, $segments[$i])) {
$currentNode = $currentNode->{$segments[$i]};
continue;
}
throw new UnresolvedPointerPropertyException([$segments[$i], $i, $pointer]);
}
if (is_array($currentNode)) {
if (!preg_match('/^\d+$/', $segments[$i])) {
throw new InvalidPointerIndexException([$segments[$i], $i, $pointer]);
}
if (!isset($currentNode[$index = (int) $segments[$i]])) {
throw new UnresolvedPointerIndexException([$segments[$i], $i, $pointer]);
}
$currentNode = $currentNode[$index];
continue;
}
throw new InvalidSegmentTypeException([$i, $pointer]);
}
return $currentNode;
} | [
"private",
"function",
"resolvePointer",
"(",
"stdClass",
"$",
"schema",
",",
"Uri",
"$",
"pointerUri",
")",
"{",
"$",
"segments",
"=",
"$",
"pointerUri",
"->",
"getPointerSegments",
"(",
")",
";",
"$",
"pointer",
"=",
"$",
"pointerUri",
"->",
"getRawPointer... | Resolves a JSON pointer according to RFC 6901.
@param stdClass $schema
@param Uri $pointerUri
@return mixed
@throws InvalidPointerIndexException
@throws InvalidSegmentTypeException
@throws UnresolvedPointerIndexException
@throws UnresolvedPointerPropertyException | [
"Resolves",
"a",
"JSON",
"pointer",
"according",
"to",
"RFC",
"6901",
"."
] | 1c26dd2c16e5273d1c0565ff6c9dc51e6316c564 | https://github.com/stefk/JVal/blob/1c26dd2c16e5273d1c0565ff6c9dc51e6316c564/src/Resolver.php#L257-L290 | train |
krystal-framework/krystal.framework | src/Krystal/Db/Sql/QueryBuilder.php | QueryBuilder.guessCountQuery | public function guessCountQuery($column, $alias)
{
return str_replace($this->selected, $this->createFunction('COUNT', array($column), $alias), $this->getQueryString());
} | php | public function guessCountQuery($column, $alias)
{
return str_replace($this->selected, $this->createFunction('COUNT', array($column), $alias), $this->getQueryString());
} | [
"public",
"function",
"guessCountQuery",
"(",
"$",
"column",
",",
"$",
"alias",
")",
"{",
"return",
"str_replace",
"(",
"$",
"this",
"->",
"selected",
",",
"$",
"this",
"->",
"createFunction",
"(",
"'COUNT'",
",",
"array",
"(",
"$",
"column",
")",
",",
... | Guesses count query
@param string $column Column to be selected
@param string $alias
@return string Guessed count query | [
"Guesses",
"count",
"query"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Db/Sql/QueryBuilder.php#L97-L100 | train |
krystal-framework/krystal.framework | src/Krystal/Db/Sql/QueryBuilder.php | QueryBuilder.isFilterable | public function isFilterable($state, $target)
{
// Empty string
if ($state === true && empty($target) && $target !== '0') {
return false;
}
// Pure wildcards must be treated as empty values
if ($state == true && ($target == '%%' || $target == '%')) {
return false;
}
// Start checking from very common usage case
if ($state == true && $target == '0') {
return true;
}
// If empty array supplied
if (is_array($target) && empty($target)) {
return false;
}
$result = false;
if ($state === false) {
$result = true;
} else {
if (is_string($target) && $target != '0' && !empty($target)) {
$result = true;
}
if (is_array($target)) {
// If empty array is passed, that means it's time to stop right here
if (empty($target)) {
$result = false;
} else {
// Otherwise go on
$count = 0;
foreach ($target as $value) {
if (!empty($value)) {
$count++;
}
}
// All values must not be empty
if ($count == count($target)) {
$result = true;
}
}
}
}
return $result;
} | php | public function isFilterable($state, $target)
{
// Empty string
if ($state === true && empty($target) && $target !== '0') {
return false;
}
// Pure wildcards must be treated as empty values
if ($state == true && ($target == '%%' || $target == '%')) {
return false;
}
// Start checking from very common usage case
if ($state == true && $target == '0') {
return true;
}
// If empty array supplied
if (is_array($target) && empty($target)) {
return false;
}
$result = false;
if ($state === false) {
$result = true;
} else {
if (is_string($target) && $target != '0' && !empty($target)) {
$result = true;
}
if (is_array($target)) {
// If empty array is passed, that means it's time to stop right here
if (empty($target)) {
$result = false;
} else {
// Otherwise go on
$count = 0;
foreach ($target as $value) {
if (!empty($value)) {
$count++;
}
}
// All values must not be empty
if ($count == count($target)) {
$result = true;
}
}
}
}
return $result;
} | [
"public",
"function",
"isFilterable",
"(",
"$",
"state",
",",
"$",
"target",
")",
"{",
"// Empty string",
"if",
"(",
"$",
"state",
"===",
"true",
"&&",
"empty",
"(",
"$",
"target",
")",
"&&",
"$",
"target",
"!==",
"'0'",
")",
"{",
"return",
"false",
... | Checks whether it's worth filtering
@param boolean $state
@param string|array $target
@return boolean | [
"Checks",
"whether",
"it",
"s",
"worth",
"filtering"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Db/Sql/QueryBuilder.php#L144-L199 | train |
krystal-framework/krystal.framework | src/Krystal/Db/Sql/QueryBuilder.php | QueryBuilder.createFunction | private function createFunction($func, array $arguments = array(), $alias = null)
{
// Prepare function arguments
foreach ($arguments as $index => $argument) {
if ($argument instanceof RawSqlFragmentInterface) {
$item = $argument->getFragment();
} else {
$item = $this->quote($argument);
}
// Update item collection
$arguments[$index] = $item;
}
$fragment = sprintf(' %s(%s) ', $func, implode(', ', $arguments));
// Generate alias if provided
if (!is_null($alias)) {
$fragment .= sprintf(' AS %s ', $this->quote($alias));
}
// Append a comma if there was a function call before
if ($this->hasFunctionCall === true) {
$this->append(', ');
}
$this->hasFunctionCall = true;
return $fragment;
} | php | private function createFunction($func, array $arguments = array(), $alias = null)
{
// Prepare function arguments
foreach ($arguments as $index => $argument) {
if ($argument instanceof RawSqlFragmentInterface) {
$item = $argument->getFragment();
} else {
$item = $this->quote($argument);
}
// Update item collection
$arguments[$index] = $item;
}
$fragment = sprintf(' %s(%s) ', $func, implode(', ', $arguments));
// Generate alias if provided
if (!is_null($alias)) {
$fragment .= sprintf(' AS %s ', $this->quote($alias));
}
// Append a comma if there was a function call before
if ($this->hasFunctionCall === true) {
$this->append(', ');
}
$this->hasFunctionCall = true;
return $fragment;
} | [
"private",
"function",
"createFunction",
"(",
"$",
"func",
",",
"array",
"$",
"arguments",
"=",
"array",
"(",
")",
",",
"$",
"alias",
"=",
"null",
")",
"{",
"// Prepare function arguments",
"foreach",
"(",
"$",
"arguments",
"as",
"$",
"index",
"=>",
"$",
... | Generates SQL function fragment
@param string $func Function name
@param array $arguments Optional function arguments
@param string $alias Optional alias
@return string | [
"Generates",
"SQL",
"function",
"fragment"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Db/Sql/QueryBuilder.php#L233-L261 | train |
krystal-framework/krystal.framework | src/Krystal/Db/Sql/QueryBuilder.php | QueryBuilder.needsQuoting | private function needsQuoting($target)
{
$isSqlFunction = strpos($target, '(') !== false || strpos($target, ')') !== false;
$isColumn = strpos($target, '.') !== false;
$hasQuotes = strpos($target, '`') !== false; // Whether already has quotes
return !(is_numeric($target) || $isColumn || $isSqlFunction || $hasQuotes);
} | php | private function needsQuoting($target)
{
$isSqlFunction = strpos($target, '(') !== false || strpos($target, ')') !== false;
$isColumn = strpos($target, '.') !== false;
$hasQuotes = strpos($target, '`') !== false; // Whether already has quotes
return !(is_numeric($target) || $isColumn || $isSqlFunction || $hasQuotes);
} | [
"private",
"function",
"needsQuoting",
"(",
"$",
"target",
")",
"{",
"$",
"isSqlFunction",
"=",
"strpos",
"(",
"$",
"target",
",",
"'('",
")",
"!==",
"false",
"||",
"strpos",
"(",
"$",
"target",
",",
"')'",
")",
"!==",
"false",
";",
"$",
"isColumn",
... | Checks whether it's worth applying a wrapper for a target
@param string $target
@return boolean | [
"Checks",
"whether",
"it",
"s",
"worth",
"applying",
"a",
"wrapper",
"for",
"a",
"target"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Db/Sql/QueryBuilder.php#L303-L310 | train |
krystal-framework/krystal.framework | src/Krystal/Db/Sql/QueryBuilder.php | QueryBuilder.quote | private function quote($target)
{
$wrapper = function($column) {
return sprintf('`%s`', $column);
};
if (is_array($target)) {
foreach($target as &$column) {
$column = $this->needsQuoting($column) ? $wrapper($column) : $column;
}
} else if (is_scalar($target)) {
$target = $this->needsQuoting($target) ? $wrapper($target) : $target;
} else {
throw new InvalidArgumentException(sprintf(
'Unknown type for wrapping supplied "%s"', gettype($target)
));
}
return $target;
} | php | private function quote($target)
{
$wrapper = function($column) {
return sprintf('`%s`', $column);
};
if (is_array($target)) {
foreach($target as &$column) {
$column = $this->needsQuoting($column) ? $wrapper($column) : $column;
}
} else if (is_scalar($target)) {
$target = $this->needsQuoting($target) ? $wrapper($target) : $target;
} else {
throw new InvalidArgumentException(sprintf(
'Unknown type for wrapping supplied "%s"', gettype($target)
));
}
return $target;
} | [
"private",
"function",
"quote",
"(",
"$",
"target",
")",
"{",
"$",
"wrapper",
"=",
"function",
"(",
"$",
"column",
")",
"{",
"return",
"sprintf",
"(",
"'`%s`'",
",",
"$",
"column",
")",
";",
"}",
";",
"if",
"(",
"is_array",
"(",
"$",
"target",
")",... | Wraps a string into back-ticks
@param string|array $target Target column name to be wrapped
@throws \InvalidArgumentException If unknown type supplied
@return string | [
"Wraps",
"a",
"string",
"into",
"back",
"-",
"ticks"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Db/Sql/QueryBuilder.php#L319-L340 | train |
krystal-framework/krystal.framework | src/Krystal/Db/Sql/QueryBuilder.php | QueryBuilder.insert | public function insert($table, array $data, $ignore = false)
{
if (empty($data)) {
throw new LogicException('You have not provided a data to be inserted');
}
$keys = array();
$values = array_values($data);
foreach (array_keys($data) as $key) {
$keys[] = $this->quote($key);
}
// Handle ignore case
if ($ignore === true) {
$ignore = 'IGNORE';
} else {
$ignore = '';
}
// Build and append query we made
$this->append(sprintf('INSERT %s INTO %s (%s) VALUES (%s)', $ignore, $this->quote($table), implode(', ', $keys), implode(', ', $values)));
return $this;
} | php | public function insert($table, array $data, $ignore = false)
{
if (empty($data)) {
throw new LogicException('You have not provided a data to be inserted');
}
$keys = array();
$values = array_values($data);
foreach (array_keys($data) as $key) {
$keys[] = $this->quote($key);
}
// Handle ignore case
if ($ignore === true) {
$ignore = 'IGNORE';
} else {
$ignore = '';
}
// Build and append query we made
$this->append(sprintf('INSERT %s INTO %s (%s) VALUES (%s)', $ignore, $this->quote($table), implode(', ', $keys), implode(', ', $values)));
return $this;
} | [
"public",
"function",
"insert",
"(",
"$",
"table",
",",
"array",
"$",
"data",
",",
"$",
"ignore",
"=",
"false",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"data",
")",
")",
"{",
"throw",
"new",
"LogicException",
"(",
"'You have not provided a data to be inser... | Builds INSERT query
This regular insert query for most cases. It's not aware of ON DUPLICATE KEY
@param string $table
@param array $data Simply key value pair (without placeholders)
@param boolean $ignore Whether to ignore when PK collisions occur
@throws \LogicException if $data array is empty
@return \Krystal\Db\Sql\QueryBuilder | [
"Builds",
"INSERT",
"query",
"This",
"regular",
"insert",
"query",
"for",
"most",
"cases",
".",
"It",
"s",
"not",
"aware",
"of",
"ON",
"DUPLICATE",
"KEY"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Db/Sql/QueryBuilder.php#L364-L387 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.