repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6 values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1 value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
getopt-php/getopt-php | src/Option.php | Option.setArgument | public function setArgument(Argument $arg)
{
if ($this->mode == GetOpt::NO_ARGUMENT) {
throw new \InvalidArgumentException("Option should not have any argument");
}
$this->argument = clone $arg; // he can reuse his arg but we need a unique arg
$this->argument->multiple($this->mode === GetOpt::MULTIPLE_ARGUMENT);
$this->argument->setOption($this);
return $this;
} | php | public function setArgument(Argument $arg)
{
if ($this->mode == GetOpt::NO_ARGUMENT) {
throw new \InvalidArgumentException("Option should not have any argument");
}
$this->argument = clone $arg; // he can reuse his arg but we need a unique arg
$this->argument->multiple($this->mode === GetOpt::MULTIPLE_ARGUMENT);
$this->argument->setOption($this);
return $this;
} | [
"public",
"function",
"setArgument",
"(",
"Argument",
"$",
"arg",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"mode",
"==",
"GetOpt",
"::",
"NO_ARGUMENT",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"Option should not have any argument\"",
")"... | Sets the argument object directly.
@param Argument $arg
@return Option this object (for chaining calls) | [
"Sets",
"the",
"argument",
"object",
"directly",
"."
] | train | https://github.com/getopt-php/getopt-php/blob/9df490db25bd192d074f5de4210e232a8ddbeda0/src/Option.php#L135-L144 |
getopt-php/getopt-php | src/Option.php | Option.setShort | public function setShort($short)
{
if (!(is_null($short) || preg_match("/^[a-zA-Z0-9?!§$%#]$/", $short))) {
throw new \InvalidArgumentException(sprintf(
'Short option must be null or one of [a-zA-Z0-9?!§$%%#], found \'%s\'',
$short
));
}
$this->short = $short;
return $this;
} | php | public function setShort($short)
{
if (!(is_null($short) || preg_match("/^[a-zA-Z0-9?!§$%#]$/", $short))) {
throw new \InvalidArgumentException(sprintf(
'Short option must be null or one of [a-zA-Z0-9?!§$%%#], found \'%s\'',
$short
));
}
$this->short = $short;
return $this;
} | [
"public",
"function",
"setShort",
"(",
"$",
"short",
")",
"{",
"if",
"(",
"!",
"(",
"is_null",
"(",
"$",
"short",
")",
"||",
"preg_match",
"(",
"\"/^[a-zA-Z0-9?!§$%#]$/\",",
" ",
"s",
"hort)",
")",
")",
" ",
"",
"throw",
"new",
"\\",
"InvalidArgumentExce... | Change the short name
@param string $short
@return Option this object (for chaining calls) | [
"Change",
"the",
"short",
"name"
] | train | https://github.com/getopt-php/getopt-php/blob/9df490db25bd192d074f5de4210e232a8ddbeda0/src/Option.php#L152-L162 |
getopt-php/getopt-php | src/Option.php | Option.setMode | public function setMode($mode)
{
if (!in_array($mode, [
GetOpt::NO_ARGUMENT,
GetOpt::OPTIONAL_ARGUMENT,
GetOpt::REQUIRED_ARGUMENT,
GetOpt::MULTIPLE_ARGUMENT,
], true)) {
throw new \InvalidArgumentException(sprintf(
'Option mode must be one of %s, %s, %s and %s',
'GetOpt::NO_ARGUMENT',
'GetOpt::OPTIONAL_ARGUMENT',
'GetOpt::REQUIRED_ARGUMENT',
'GetOpt::MULTIPLE_ARGUMENT'
));
}
$this->mode = $mode;
return $this;
} | php | public function setMode($mode)
{
if (!in_array($mode, [
GetOpt::NO_ARGUMENT,
GetOpt::OPTIONAL_ARGUMENT,
GetOpt::REQUIRED_ARGUMENT,
GetOpt::MULTIPLE_ARGUMENT,
], true)) {
throw new \InvalidArgumentException(sprintf(
'Option mode must be one of %s, %s, %s and %s',
'GetOpt::NO_ARGUMENT',
'GetOpt::OPTIONAL_ARGUMENT',
'GetOpt::REQUIRED_ARGUMENT',
'GetOpt::MULTIPLE_ARGUMENT'
));
}
$this->mode = $mode;
return $this;
} | [
"public",
"function",
"setMode",
"(",
"$",
"mode",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"mode",
",",
"[",
"GetOpt",
"::",
"NO_ARGUMENT",
",",
"GetOpt",
"::",
"OPTIONAL_ARGUMENT",
",",
"GetOpt",
"::",
"REQUIRED_ARGUMENT",
",",
"GetOpt",
"::",
"... | Change the mode
@param $mode
@return Option this object (for chaining calls) | [
"Change",
"the",
"mode"
] | train | https://github.com/getopt-php/getopt-php/blob/9df490db25bd192d074f5de4210e232a8ddbeda0/src/Option.php#L234-L252 |
getopt-php/getopt-php | src/Option.php | Option.setValue | public function setValue($value = null)
{
if ($value === null) {
if (in_array($this->mode, [ GetOpt::REQUIRED_ARGUMENT, GetOpt::MULTIPLE_ARGUMENT ])) {
throw new Missing(sprintf(
GetOpt::translate('option-argument-missing'),
$this->getName()
));
}
$value = $this->argument->getValue() +1;
}
$this->argument->setValue($value);
return $this;
} | php | public function setValue($value = null)
{
if ($value === null) {
if (in_array($this->mode, [ GetOpt::REQUIRED_ARGUMENT, GetOpt::MULTIPLE_ARGUMENT ])) {
throw new Missing(sprintf(
GetOpt::translate('option-argument-missing'),
$this->getName()
));
}
$value = $this->argument->getValue() +1;
}
$this->argument->setValue($value);
return $this;
} | [
"public",
"function",
"setValue",
"(",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"value",
"===",
"null",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"this",
"->",
"mode",
",",
"[",
"GetOpt",
"::",
"REQUIRED_ARGUMENT",
",",
"GetOpt",
"::",
... | Internal method to set the current value
@param mixed $value
@return $this | [
"Internal",
"method",
"to",
"set",
"the",
"current",
"value"
] | train | https://github.com/getopt-php/getopt-php/blob/9df490db25bd192d074f5de4210e232a8ddbeda0/src/Option.php#L288-L304 |
getopt-php/getopt-php | src/Option.php | Option.getValue | public function getValue()
{
$value = $this->argument->getValue();
return $value === null || $value === [] ? $this->argument->getDefaultValue() : $value;
} | php | public function getValue()
{
$value = $this->argument->getValue();
return $value === null || $value === [] ? $this->argument->getDefaultValue() : $value;
} | [
"public",
"function",
"getValue",
"(",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"argument",
"->",
"getValue",
"(",
")",
";",
"return",
"$",
"value",
"===",
"null",
"||",
"$",
"value",
"===",
"[",
"]",
"?",
"$",
"this",
"->",
"argument",
"->"... | Get the current value
@return mixed | [
"Get",
"the",
"current",
"value"
] | train | https://github.com/getopt-php/getopt-php/blob/9df490db25bd192d074f5de4210e232a8ddbeda0/src/Option.php#L311-L315 |
getopt-php/getopt-php | src/Argument.php | Argument.setValue | public function setValue($value)
{
if ($this->validation && !$this->validates($value)) {
throw new Invalid($this->getValidationMessage($value));
}
if ($this->isMultiple()) {
$this->value = $this->value === null ? [ $value ] : array_merge($this->value, [ $value ]);
} else {
$this->value = $value;
}
return $this;
} | php | public function setValue($value)
{
if ($this->validation && !$this->validates($value)) {
throw new Invalid($this->getValidationMessage($value));
}
if ($this->isMultiple()) {
$this->value = $this->value === null ? [ $value ] : array_merge($this->value, [ $value ]);
} else {
$this->value = $value;
}
return $this;
} | [
"public",
"function",
"setValue",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"validation",
"&&",
"!",
"$",
"this",
"->",
"validates",
"(",
"$",
"value",
")",
")",
"{",
"throw",
"new",
"Invalid",
"(",
"$",
"this",
"->",
"getValidationM... | Internal method to set the current value
@param $value
@return $this | [
"Internal",
"method",
"to",
"set",
"the",
"current",
"value"
] | train | https://github.com/getopt-php/getopt-php/blob/9df490db25bd192d074f5de4210e232a8ddbeda0/src/Argument.php#L149-L162 |
getopt-php/getopt-php | src/Argument.php | Argument.describe | public function describe()
{
return $this->option ? $this->option->describe() :
sprintf('%s \'%s\'', GetOpt::translate(static::TRANSLATION_KEY), $this->getName());
} | php | public function describe()
{
return $this->option ? $this->option->describe() :
sprintf('%s \'%s\'', GetOpt::translate(static::TRANSLATION_KEY), $this->getName());
} | [
"public",
"function",
"describe",
"(",
")",
"{",
"return",
"$",
"this",
"->",
"option",
"?",
"$",
"this",
"->",
"option",
"->",
"describe",
"(",
")",
":",
"sprintf",
"(",
"'%s \\'%s\\''",
",",
"GetOpt",
"::",
"translate",
"(",
"static",
"::",
"TRANSLATIO... | Returns a human readable string representation of the object
@return string | [
"Returns",
"a",
"human",
"readable",
"string",
"representation",
"of",
"the",
"object"
] | train | https://github.com/getopt-php/getopt-php/blob/9df490db25bd192d074f5de4210e232a8ddbeda0/src/Argument.php#L238-L242 |
getopt-php/getopt-php | src/Operand.php | Operand.getValue | public function getValue()
{
$value = parent::getValue();
return $value === null || $value === [] ? $this->getDefaultValue() : $value;
} | php | public function getValue()
{
$value = parent::getValue();
return $value === null || $value === [] ? $this->getDefaultValue() : $value;
} | [
"public",
"function",
"getValue",
"(",
")",
"{",
"$",
"value",
"=",
"parent",
"::",
"getValue",
"(",
")",
";",
"return",
"$",
"value",
"===",
"null",
"||",
"$",
"value",
"===",
"[",
"]",
"?",
"$",
"this",
"->",
"getDefaultValue",
"(",
")",
":",
"$"... | Get the current value
@return mixed | [
"Get",
"the",
"current",
"value"
] | train | https://github.com/getopt-php/getopt-php/blob/9df490db25bd192d074f5de4210e232a8ddbeda0/src/Operand.php#L88-L92 |
getopt-php/getopt-php | src/OptionParser.php | OptionParser.parseArray | public static function parseArray(array $array)
{
if (empty($array)) {
throw new \InvalidArgumentException('Invalid option array (at least a name has to be given)');
}
$rowSize = count($array);
if ($rowSize < 3) {
$array = self::completeOptionArray($array);
}
$option = new Option($array[0], $array[1], $array[2]);
if ($rowSize >= 4) {
$option->setDescription($array[3]);
}
if ($rowSize >= 5 && $array[2] != GetOpt::NO_ARGUMENT) {
$option->setArgument(new Argument($array[4]));
}
return $option;
} | php | public static function parseArray(array $array)
{
if (empty($array)) {
throw new \InvalidArgumentException('Invalid option array (at least a name has to be given)');
}
$rowSize = count($array);
if ($rowSize < 3) {
$array = self::completeOptionArray($array);
}
$option = new Option($array[0], $array[1], $array[2]);
if ($rowSize >= 4) {
$option->setDescription($array[3]);
}
if ($rowSize >= 5 && $array[2] != GetOpt::NO_ARGUMENT) {
$option->setArgument(new Argument($array[4]));
}
return $option;
} | [
"public",
"static",
"function",
"parseArray",
"(",
"array",
"$",
"array",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"array",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Invalid option array (at least a name has to be given)'",
")",
";",
... | Processes an option array. The array should be conform to the format
(short, long, mode [, description [, default]]). See documentation for details.
Developer note: Please don't add any further elements to the array. Future features should be configured only
through the Option class's methods.
@param array $array
@return Option | [
"Processes",
"an",
"option",
"array",
".",
"The",
"array",
"should",
"be",
"conform",
"to",
"the",
"format",
"(",
"short",
"long",
"mode",
"[",
"description",
"[",
"default",
"]]",
")",
".",
"See",
"documentation",
"for",
"details",
"."
] | train | https://github.com/getopt-php/getopt-php/blob/9df490db25bd192d074f5de4210e232a8ddbeda0/src/OptionParser.php#L65-L87 |
getopt-php/getopt-php | src/OptionParser.php | OptionParser.completeOptionArray | protected static function completeOptionArray(array $row)
{
$short = (strlen($row[0]) == 1) ? $row[0] : null;
$long = null;
if (is_null($short)) {
$long = $row[0];
} elseif (count($row) > 1 && $row[1][0] !== ':') {
$long = $row[1];
}
$mode = self::$defaultMode;
if (count($row) == 2 && $row[1][0] === ':') {
$mode = $row[1];
}
return [ $short, $long, $mode ];
} | php | protected static function completeOptionArray(array $row)
{
$short = (strlen($row[0]) == 1) ? $row[0] : null;
$long = null;
if (is_null($short)) {
$long = $row[0];
} elseif (count($row) > 1 && $row[1][0] !== ':') {
$long = $row[1];
}
$mode = self::$defaultMode;
if (count($row) == 2 && $row[1][0] === ':') {
$mode = $row[1];
}
return [ $short, $long, $mode ];
} | [
"protected",
"static",
"function",
"completeOptionArray",
"(",
"array",
"$",
"row",
")",
"{",
"$",
"short",
"=",
"(",
"strlen",
"(",
"$",
"row",
"[",
"0",
"]",
")",
"==",
"1",
")",
"?",
"$",
"row",
"[",
"0",
"]",
":",
"null",
";",
"$",
"long",
... | When using arrays, instead of a full option spec ([short, long, type]) users can leave out one or more of
these parts and have GetOpt fill them in intelligently:
- If either the short or the long option string is left out, the first element of the given array is interpreted
as either short (if it has length 1) or long, and the other one is set to null.
- If the type is left out, it is set to NO_ARGUMENT.
@param array $row
@return array | [
"When",
"using",
"arrays",
"instead",
"of",
"a",
"full",
"option",
"spec",
"(",
"[",
"short",
"long",
"type",
"]",
")",
"users",
"can",
"leave",
"out",
"one",
"or",
"more",
"of",
"these",
"parts",
"and",
"have",
"GetOpt",
"fill",
"them",
"in",
"intelli... | train | https://github.com/getopt-php/getopt-php/blob/9df490db25bd192d074f5de4210e232a8ddbeda0/src/OptionParser.php#L99-L116 |
getopt-php/getopt-php | src/WithOptions.php | WithOptions.addOptions | public function addOptions($options)
{
if (is_string($options)) {
$options = OptionParser::parseString($options);
}
if (!is_array($options)) {
throw new \InvalidArgumentException('GetOpt(): argument must be string or array');
}
foreach ($options as $option) {
$this->addOption($option);
}
return $this;
} | php | public function addOptions($options)
{
if (is_string($options)) {
$options = OptionParser::parseString($options);
}
if (!is_array($options)) {
throw new \InvalidArgumentException('GetOpt(): argument must be string or array');
}
foreach ($options as $option) {
$this->addOption($option);
}
return $this;
} | [
"public",
"function",
"addOptions",
"(",
"$",
"options",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"options",
")",
")",
"{",
"$",
"options",
"=",
"OptionParser",
"::",
"parseString",
"(",
"$",
"options",
")",
";",
"}",
"if",
"(",
"!",
"is_array",
"... | Add $options to the list of options
$options can be a string as for phps `getopt()` function, an array of Option instances or an array of arrays.
You can also mix Option instances and arrays. Eg.:
$getopt->addOptions([
['?', 'help', GetOpt::NO_ARGUMENT, 'Show this help'],
new Option('v', 'verbose'),
(new Option(null, 'version'))->setDescription('Print version and exit'),
Option::create('q', 'quiet')->setDescription('Don\'t write any output')
]);
@see OptionParser::parseArray() fo see how to use arrays
@param string|array|Option[] $options
@return self | [
"Add",
"$options",
"to",
"the",
"list",
"of",
"options"
] | train | https://github.com/getopt-php/getopt-php/blob/9df490db25bd192d074f5de4210e232a8ddbeda0/src/WithOptions.php#L30-L45 |
getopt-php/getopt-php | src/WithOptions.php | WithOptions.addOption | public function addOption($option)
{
if (!$option instanceof Option) {
if (is_string($option)) {
$options = OptionParser::parseString($option);
// this is addOption - so we use only the first one
$option = $options[0];
} elseif (is_array($option)) {
$option = OptionParser::parseArray($option);
} else {
throw new \InvalidArgumentException(sprintf(
'$option has to be a string, an array or an Option. %s given',
gettype($option)
));
}
}
if ($this->conflicts($option)) {
throw new \InvalidArgumentException('$option`s short and long name have to be unique');
}
$this->options[] = $option;
$short = $option->getShort();
$long = $option->getLong();
if ($short) {
$this->optionMapping[$short] = $option;
}
if ($long) {
$this->optionMapping[$long] = $option;
}
return $this;
} | php | public function addOption($option)
{
if (!$option instanceof Option) {
if (is_string($option)) {
$options = OptionParser::parseString($option);
// this is addOption - so we use only the first one
$option = $options[0];
} elseif (is_array($option)) {
$option = OptionParser::parseArray($option);
} else {
throw new \InvalidArgumentException(sprintf(
'$option has to be a string, an array or an Option. %s given',
gettype($option)
));
}
}
if ($this->conflicts($option)) {
throw new \InvalidArgumentException('$option`s short and long name have to be unique');
}
$this->options[] = $option;
$short = $option->getShort();
$long = $option->getLong();
if ($short) {
$this->optionMapping[$short] = $option;
}
if ($long) {
$this->optionMapping[$long] = $option;
}
return $this;
} | [
"public",
"function",
"addOption",
"(",
"$",
"option",
")",
"{",
"if",
"(",
"!",
"$",
"option",
"instanceof",
"Option",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"option",
")",
")",
"{",
"$",
"options",
"=",
"OptionParser",
"::",
"parseString",
"(",
... | Add $option to the list of options
$option can also be a string in format of php`s `getopt()` function. But only the first option will be added.
Otherwise it has to be an array or an Option instance.
@see GetOpt::addOptions() for more details
@param string|array|Option $option
@return self | [
"Add",
"$option",
"to",
"the",
"list",
"of",
"options"
] | train | https://github.com/getopt-php/getopt-php/blob/9df490db25bd192d074f5de4210e232a8ddbeda0/src/WithOptions.php#L58-L90 |
getopt-php/getopt-php | src/WithOptions.php | WithOptions.conflicts | public function conflicts(Option $option)
{
$short = $option->getShort();
$long = $option->getLong();
return $short && isset($this->optionMapping[$short]) || $long && isset($this->optionMapping[$long]);
} | php | public function conflicts(Option $option)
{
$short = $option->getShort();
$long = $option->getLong();
return $short && isset($this->optionMapping[$short]) || $long && isset($this->optionMapping[$long]);
} | [
"public",
"function",
"conflicts",
"(",
"Option",
"$",
"option",
")",
"{",
"$",
"short",
"=",
"$",
"option",
"->",
"getShort",
"(",
")",
";",
"$",
"long",
"=",
"$",
"option",
"->",
"getLong",
"(",
")",
";",
"return",
"$",
"short",
"&&",
"isset",
"(... | Check if option conflicts with defined options.
@param Option $option
@return bool | [
"Check",
"if",
"option",
"conflicts",
"with",
"defined",
"options",
"."
] | train | https://github.com/getopt-php/getopt-php/blob/9df490db25bd192d074f5de4210e232a8ddbeda0/src/WithOptions.php#L98-L103 |
getopt-php/getopt-php | src/WithOptions.php | WithOptions.getOption | public function getOption($name)
{
return isset($this->optionMapping[$name]) ? $this->optionMapping[$name] : null;
} | php | public function getOption($name)
{
return isset($this->optionMapping[$name]) ? $this->optionMapping[$name] : null;
} | [
"public",
"function",
"getOption",
"(",
"$",
"name",
")",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"optionMapping",
"[",
"$",
"name",
"]",
")",
"?",
"$",
"this",
"->",
"optionMapping",
"[",
"$",
"name",
"]",
":",
"null",
";",
"}"
] | Get an option by $name
@param string $name Short or long name of the option
@return Option | [
"Get",
"an",
"option",
"by",
"$name"
] | train | https://github.com/getopt-php/getopt-php/blob/9df490db25bd192d074f5de4210e232a8ddbeda0/src/WithOptions.php#L121-L124 |
getopt-php/getopt-php | src/WithOperands.php | WithOperands.addOperand | public function addOperand(Operand $operand)
{
if ($operand->isRequired()) {
foreach ($this->operands as $previousOperand) {
$previousOperand->required();
}
}
if ($this->hasOperands()) {
/** @var Operand $lastOperand */
$lastOperand = array_slice($this->operands, -1)[0];
if ($lastOperand->isMultiple()) {
throw new \InvalidArgumentException(sprintf(
'Operand %s is multiple - no more operands allowed',
$lastOperand->getName()
));
}
}
$this->operands[] = $operand;
return $this;
} | php | public function addOperand(Operand $operand)
{
if ($operand->isRequired()) {
foreach ($this->operands as $previousOperand) {
$previousOperand->required();
}
}
if ($this->hasOperands()) {
/** @var Operand $lastOperand */
$lastOperand = array_slice($this->operands, -1)[0];
if ($lastOperand->isMultiple()) {
throw new \InvalidArgumentException(sprintf(
'Operand %s is multiple - no more operands allowed',
$lastOperand->getName()
));
}
}
$this->operands[] = $operand;
return $this;
} | [
"public",
"function",
"addOperand",
"(",
"Operand",
"$",
"operand",
")",
"{",
"if",
"(",
"$",
"operand",
"->",
"isRequired",
"(",
")",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"operands",
"as",
"$",
"previousOperand",
")",
"{",
"$",
"previousOperand"... | Add an $operand
@param Operand $operand
@return self | [
"Add",
"an",
"$operand"
] | train | https://github.com/getopt-php/getopt-php/blob/9df490db25bd192d074f5de4210e232a8ddbeda0/src/WithOperands.php#L31-L53 |
getopt-php/getopt-php | src/WithOperands.php | WithOperands.getOperand | public function getOperand($index)
{
if (is_string($index)) {
$name = $index;
foreach ($this->operands as $operand) {
if ($operand->getName() === $name) {
return $operand;
}
}
return null;
}
return isset($this->operands[$index]) ? $this->operands[$index] : null;
} | php | public function getOperand($index)
{
if (is_string($index)) {
$name = $index;
foreach ($this->operands as $operand) {
if ($operand->getName() === $name) {
return $operand;
}
}
return null;
}
return isset($this->operands[$index]) ? $this->operands[$index] : null;
} | [
"public",
"function",
"getOperand",
"(",
"$",
"index",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"index",
")",
")",
"{",
"$",
"name",
"=",
"$",
"index",
";",
"foreach",
"(",
"$",
"this",
"->",
"operands",
"as",
"$",
"operand",
")",
"{",
"if",
"... | Returns the nth operand (starting with 0), or null if it does not exist.
When $index is a string it returns the current value or the default value for the named operand.
@param int|string $index
@return Operand | [
"Returns",
"the",
"nth",
"operand",
"(",
"starting",
"with",
"0",
")",
"or",
"null",
"if",
"it",
"does",
"not",
"exist",
"."
] | train | https://github.com/getopt-php/getopt-php/blob/9df490db25bd192d074f5de4210e232a8ddbeda0/src/WithOperands.php#L73-L86 |
getopt-php/getopt-php | src/Help.php | Help.set | public function set($setting, $value)
{
switch ($setting) {
case 'optionsTemplate':
case 'commandsTemplate':
case 'usageTemplate':
call_user_func([$this, 'set' . ucfirst($setting)], $value);
break;
default:
$this->settings[$setting] = $value;
break;
}
return $this;
} | php | public function set($setting, $value)
{
switch ($setting) {
case 'optionsTemplate':
case 'commandsTemplate':
case 'usageTemplate':
call_user_func([$this, 'set' . ucfirst($setting)], $value);
break;
default:
$this->settings[$setting] = $value;
break;
}
return $this;
} | [
"public",
"function",
"set",
"(",
"$",
"setting",
",",
"$",
"value",
")",
"{",
"switch",
"(",
"$",
"setting",
")",
"{",
"case",
"'optionsTemplate'",
":",
"case",
"'commandsTemplate'",
":",
"case",
"'usageTemplate'",
":",
"call_user_func",
"(",
"[",
"$",
"t... | Set $setting to $value
@param string $setting
@param mixed $value
@return $this | [
"Set",
"$setting",
"to",
"$value"
] | train | https://github.com/getopt-php/getopt-php/blob/9df490db25bd192d074f5de4210e232a8ddbeda0/src/Help.php#L69-L83 |
getopt-php/getopt-php | src/Help.php | Help.setTexts | public function setTexts(array $texts)
{
$this->texts = array_map(function ($text) {
return preg_replace('/\R/', PHP_EOL, $text);
}, array_merge($this->texts, $texts));
return $this;
} | php | public function setTexts(array $texts)
{
$this->texts = array_map(function ($text) {
return preg_replace('/\R/', PHP_EOL, $text);
}, array_merge($this->texts, $texts));
return $this;
} | [
"public",
"function",
"setTexts",
"(",
"array",
"$",
"texts",
")",
"{",
"$",
"this",
"->",
"texts",
"=",
"array_map",
"(",
"function",
"(",
"$",
"text",
")",
"{",
"return",
"preg_replace",
"(",
"'/\\R/'",
",",
"PHP_EOL",
",",
"$",
"text",
")",
";",
"... | Overwrite texts with $texts
Texts is an associative array of strings. For a list of keys @see $texts.
@param array $texts
@see $texts
@return $this | [
"Overwrite",
"texts",
"with",
"$texts"
] | train | https://github.com/getopt-php/getopt-php/blob/9df490db25bd192d074f5de4210e232a8ddbeda0/src/Help.php#L94-L100 |
getopt-php/getopt-php | src/Help.php | Help.getText | protected function getText($key)
{
return isset($this->texts[$key]) ? $this->texts[$key] : GetOpt::translate($key);
} | php | protected function getText($key)
{
return isset($this->texts[$key]) ? $this->texts[$key] : GetOpt::translate($key);
} | [
"protected",
"function",
"getText",
"(",
"$",
"key",
")",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"texts",
"[",
"$",
"key",
"]",
")",
"?",
"$",
"this",
"->",
"texts",
"[",
"$",
"key",
"]",
":",
"GetOpt",
"::",
"translate",
"(",
"$",
"key"... | Get the text for $key
@param $key
@return string | [
"Get",
"the",
"text",
"for",
"$key"
] | train | https://github.com/getopt-php/getopt-php/blob/9df490db25bd192d074f5de4210e232a8ddbeda0/src/Help.php#L108-L111 |
getopt-php/getopt-php | src/Help.php | Help.render | public function render(GetOpt $getopt, array $data = [])
{
$this->getOpt = $getopt;
foreach ($data as $setting => $value) {
$this->set($setting, $value);
}
// we always append the usage
if ($this->usageTemplate) {
$data['getopt'] = $getopt;
$data['command'] = $getopt->getCommand();
$helpText = $this->renderTemplate($this->usageTemplate, $data);
} else {
$helpText = $this->renderUsage();
}
if ($getopt->hasOperands() && empty($this->settings[self::HIDE_OPERANDS])) {
$helpText .= $this->renderOperands();
}
// when we have options we add them too
if ($getopt->hasOptions()) {
if ($this->optionsTemplate) {
$data['options'] = $getopt->getOptionObjects();
$helpText .= $this->renderTemplate($this->optionsTemplate, $data);
} else {
$helpText .= $this->renderOptions();
}
}
// when we have commands we render commands template
if (!$getopt->getCommand() && $getopt->hasCommands()) {
if ($this->commandsTemplate) {
$data['commands'] = $getopt->getCommands();
$helpText .= $this->renderTemplate($this->commandsTemplate, $data);
} else {
$helpText .= $this->renderCommands();
}
}
return $helpText;
} | php | public function render(GetOpt $getopt, array $data = [])
{
$this->getOpt = $getopt;
foreach ($data as $setting => $value) {
$this->set($setting, $value);
}
// we always append the usage
if ($this->usageTemplate) {
$data['getopt'] = $getopt;
$data['command'] = $getopt->getCommand();
$helpText = $this->renderTemplate($this->usageTemplate, $data);
} else {
$helpText = $this->renderUsage();
}
if ($getopt->hasOperands() && empty($this->settings[self::HIDE_OPERANDS])) {
$helpText .= $this->renderOperands();
}
// when we have options we add them too
if ($getopt->hasOptions()) {
if ($this->optionsTemplate) {
$data['options'] = $getopt->getOptionObjects();
$helpText .= $this->renderTemplate($this->optionsTemplate, $data);
} else {
$helpText .= $this->renderOptions();
}
}
// when we have commands we render commands template
if (!$getopt->getCommand() && $getopt->hasCommands()) {
if ($this->commandsTemplate) {
$data['commands'] = $getopt->getCommands();
$helpText .= $this->renderTemplate($this->commandsTemplate, $data);
} else {
$helpText .= $this->renderCommands();
}
}
return $helpText;
} | [
"public",
"function",
"render",
"(",
"GetOpt",
"$",
"getopt",
",",
"array",
"$",
"data",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"getOpt",
"=",
"$",
"getopt",
";",
"foreach",
"(",
"$",
"data",
"as",
"$",
"setting",
"=>",
"$",
"value",
")",
"{... | Get the help text for $getopt
@param GetOpt $getopt
@param array $data Additional data for templates
@return string | [
"Get",
"the",
"help",
"text",
"for",
"$getopt"
] | train | https://github.com/getopt-php/getopt-php/blob/9df490db25bd192d074f5de4210e232a8ddbeda0/src/Help.php#L120-L161 |
sonata-project/SonataEasyExtendsBundle | src/Bundle/BundleMetadata.php | BundleMetadata.buildInformation | protected function buildInformation()
{
$information = explode('\\', $this->getClass());
if (!$this->isExtendable()) {
$this->valid = false;
return;
}
if (3 !== \count($information)) {
$this->valid = false;
return;
}
if ($information[0].$information[1] !== $information[2]) {
$this->valid = false;
return;
}
$this->name = $information[\count($information) - 1];
$this->vendor = $information[0];
$this->namespace = sprintf('%s\\%s', $this->vendor, $information[1]);
$this->extendedDirectory =
str_replace(':vendor', $this->vendor, $this->configuration['application_dir']).
\DIRECTORY_SEPARATOR.
$information[1];
$this->extendedNamespace = sprintf(
'%s%s\\%s',
$this->configuration['namespace_prefix'],
str_replace(':vendor', $this->vendor, $this->configuration['namespace']),
$information[1]
);
$this->application = explode('\\', $this->configuration['namespace'])[0];
$this->valid = true;
$this->ormMetadata = new OrmMetadata($this);
$this->odmMetadata = new OdmMetadata($this);
$this->phpcrMetadata = new PhpcrMetadata($this);
} | php | protected function buildInformation()
{
$information = explode('\\', $this->getClass());
if (!$this->isExtendable()) {
$this->valid = false;
return;
}
if (3 !== \count($information)) {
$this->valid = false;
return;
}
if ($information[0].$information[1] !== $information[2]) {
$this->valid = false;
return;
}
$this->name = $information[\count($information) - 1];
$this->vendor = $information[0];
$this->namespace = sprintf('%s\\%s', $this->vendor, $information[1]);
$this->extendedDirectory =
str_replace(':vendor', $this->vendor, $this->configuration['application_dir']).
\DIRECTORY_SEPARATOR.
$information[1];
$this->extendedNamespace = sprintf(
'%s%s\\%s',
$this->configuration['namespace_prefix'],
str_replace(':vendor', $this->vendor, $this->configuration['namespace']),
$information[1]
);
$this->application = explode('\\', $this->configuration['namespace'])[0];
$this->valid = true;
$this->ormMetadata = new OrmMetadata($this);
$this->odmMetadata = new OdmMetadata($this);
$this->phpcrMetadata = new PhpcrMetadata($this);
} | [
"protected",
"function",
"buildInformation",
"(",
")",
"{",
"$",
"information",
"=",
"explode",
"(",
"'\\\\'",
",",
"$",
"this",
"->",
"getClass",
"(",
")",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"isExtendable",
"(",
")",
")",
"{",
"$",
"this",... | build basic information and check if the bundle respect the following convention
Vendor/BundleNameBundle/VendorBundleNameBundle.
if the bundle does not respect this convention then the easy extends command will ignore
this bundle | [
"build",
"basic",
"information",
"and",
"check",
"if",
"the",
"bundle",
"respect",
"the",
"following",
"convention",
"Vendor",
"/",
"BundleNameBundle",
"/",
"VendorBundleNameBundle",
"."
] | train | https://github.com/sonata-project/SonataEasyExtendsBundle/blob/10bd46159b274d7a9726e80375eacafd05595c56/src/Bundle/BundleMetadata.php#L209-L250 |
sonata-project/SonataEasyExtendsBundle | src/Generator/OdmGenerator.php | OdmGenerator.generate | public function generate(OutputInterface $output, BundleMetadata $bundleMetadata)
{
$this->generateMappingDocumentFiles($output, $bundleMetadata);
$this->generateDocumentFiles($output, $bundleMetadata);
$this->generateDocumentRepositoryFiles($output, $bundleMetadata);
} | php | public function generate(OutputInterface $output, BundleMetadata $bundleMetadata)
{
$this->generateMappingDocumentFiles($output, $bundleMetadata);
$this->generateDocumentFiles($output, $bundleMetadata);
$this->generateDocumentRepositoryFiles($output, $bundleMetadata);
} | [
"public",
"function",
"generate",
"(",
"OutputInterface",
"$",
"output",
",",
"BundleMetadata",
"$",
"bundleMetadata",
")",
"{",
"$",
"this",
"->",
"generateMappingDocumentFiles",
"(",
"$",
"output",
",",
"$",
"bundleMetadata",
")",
";",
"$",
"this",
"->",
"ge... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataEasyExtendsBundle/blob/10bd46159b274d7a9726e80375eacafd05595c56/src/Generator/OdmGenerator.php#L40-L45 |
sonata-project/SonataEasyExtendsBundle | src/Command/GenerateCommand.php | GenerateCommand.configure | protected function configure()
{
$this
->setName('sonata:easy-extends:generate')
->setHelp(<<<'EOT'
The <info>easy-extends:generate:entities</info> command generating a valid bundle structure from a Vendor Bundle.
<info>ie: ./app/console sonata:easy-extends:generate SonataUserBundle</info>
EOT
);
$this->setDescription('Create entities used by Sonata\'s bundles');
$this->addArgument('bundle', InputArgument::IS_ARRAY, 'The bundle name to "easy-extends"');
$this->addOption('dest', 'd', InputOption::VALUE_OPTIONAL, 'The base folder where the Application will be created', false);
$this->addOption('namespace', 'ns', InputOption::VALUE_OPTIONAL, 'The namespace for the classes', false);
$this->addOption('namespace_prefix', 'nsp', InputOption::VALUE_OPTIONAL, 'The namespace prefix for the classes', false);
} | php | protected function configure()
{
$this
->setName('sonata:easy-extends:generate')
->setHelp(<<<'EOT'
The <info>easy-extends:generate:entities</info> command generating a valid bundle structure from a Vendor Bundle.
<info>ie: ./app/console sonata:easy-extends:generate SonataUserBundle</info>
EOT
);
$this->setDescription('Create entities used by Sonata\'s bundles');
$this->addArgument('bundle', InputArgument::IS_ARRAY, 'The bundle name to "easy-extends"');
$this->addOption('dest', 'd', InputOption::VALUE_OPTIONAL, 'The base folder where the Application will be created', false);
$this->addOption('namespace', 'ns', InputOption::VALUE_OPTIONAL, 'The namespace for the classes', false);
$this->addOption('namespace_prefix', 'nsp', InputOption::VALUE_OPTIONAL, 'The namespace prefix for the classes', false);
} | [
"protected",
"function",
"configure",
"(",
")",
"{",
"$",
"this",
"->",
"setName",
"(",
"'sonata:easy-extends:generate'",
")",
"->",
"setHelp",
"(",
"<<<'EOT'\nThe <info>easy-extends:generate:entities</info> command generating a valid bundle structure from a Vendor Bundle.\n\n <info... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataEasyExtendsBundle/blob/10bd46159b274d7a9726e80375eacafd05595c56/src/Command/GenerateCommand.php#L34-L51 |
sonata-project/SonataEasyExtendsBundle | src/Command/GenerateCommand.php | GenerateCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$destOption = $input->getOption('dest');
if ($destOption) {
$dest = realpath($destOption);
if (false === $dest) {
throw new \RuntimeException(sprintf('The provided destination folder \'%s\' does not exist!', $destOption));
}
} else {
$dest = $this->getContainer()->get('kernel')->getRootDir();
}
$namespace = $input->getOption('namespace');
if ($namespace) {
if (!preg_match('/^(?:(?:[[:alnum:]]+|:vendor)\\\\?)+$/', $namespace)) {
throw new \InvalidArgumentException('The provided namespace \'%s\' is not a valid namespace!', $namespace);
}
} else {
$namespace = 'Application\:vendor';
}
$configuration = [
'application_dir' => sprintf('%s%s%s', $dest, \DIRECTORY_SEPARATOR, str_replace('\\', \DIRECTORY_SEPARATOR, $namespace)),
'namespace' => $namespace,
'namespace_prefix' => '',
];
if ($namespacePrefix = $input->getOption('namespace_prefix')) {
$configuration['namespace_prefix'] = rtrim($namespacePrefix, '\\').'\\';
}
$bundleNames = $input->getArgument('bundle');
if (empty($bundleNames)) {
$output->writeln('');
$output->writeln('<error>You must provide a bundle name!</error>');
$output->writeln('');
$output->writeln(' Bundles availables :');
/** @var BundleInterface $bundle */
foreach ($this->getContainer()->get('kernel')->getBundles() as $bundle) {
$bundleMetadata = new BundleMetadata($bundle, $configuration);
if (!$bundleMetadata->isExtendable()) {
continue;
}
$output->writeln(sprintf(' - %s', $bundle->getName()));
}
$output->writeln('');
} else {
foreach ($bundleNames as $bundleName) {
$processed = $this->generate($bundleName, $configuration, $output);
if (!$processed) {
throw new \RuntimeException(sprintf(
'<error>The bundle \'%s\' does not exist or is not registered in the kernel!</error>',
$bundleName
));
}
}
}
$output->writeln('done!');
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$destOption = $input->getOption('dest');
if ($destOption) {
$dest = realpath($destOption);
if (false === $dest) {
throw new \RuntimeException(sprintf('The provided destination folder \'%s\' does not exist!', $destOption));
}
} else {
$dest = $this->getContainer()->get('kernel')->getRootDir();
}
$namespace = $input->getOption('namespace');
if ($namespace) {
if (!preg_match('/^(?:(?:[[:alnum:]]+|:vendor)\\\\?)+$/', $namespace)) {
throw new \InvalidArgumentException('The provided namespace \'%s\' is not a valid namespace!', $namespace);
}
} else {
$namespace = 'Application\:vendor';
}
$configuration = [
'application_dir' => sprintf('%s%s%s', $dest, \DIRECTORY_SEPARATOR, str_replace('\\', \DIRECTORY_SEPARATOR, $namespace)),
'namespace' => $namespace,
'namespace_prefix' => '',
];
if ($namespacePrefix = $input->getOption('namespace_prefix')) {
$configuration['namespace_prefix'] = rtrim($namespacePrefix, '\\').'\\';
}
$bundleNames = $input->getArgument('bundle');
if (empty($bundleNames)) {
$output->writeln('');
$output->writeln('<error>You must provide a bundle name!</error>');
$output->writeln('');
$output->writeln(' Bundles availables :');
/** @var BundleInterface $bundle */
foreach ($this->getContainer()->get('kernel')->getBundles() as $bundle) {
$bundleMetadata = new BundleMetadata($bundle, $configuration);
if (!$bundleMetadata->isExtendable()) {
continue;
}
$output->writeln(sprintf(' - %s', $bundle->getName()));
}
$output->writeln('');
} else {
foreach ($bundleNames as $bundleName) {
$processed = $this->generate($bundleName, $configuration, $output);
if (!$processed) {
throw new \RuntimeException(sprintf(
'<error>The bundle \'%s\' does not exist or is not registered in the kernel!</error>',
$bundleName
));
}
}
}
$output->writeln('done!');
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"destOption",
"=",
"$",
"input",
"->",
"getOption",
"(",
"'dest'",
")",
";",
"if",
"(",
"$",
"destOption",
")",
"{",
"$",
"dest... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataEasyExtendsBundle/blob/10bd46159b274d7a9726e80375eacafd05595c56/src/Command/GenerateCommand.php#L56-L120 |
sonata-project/SonataEasyExtendsBundle | src/Command/GenerateCommand.php | GenerateCommand.generate | protected function generate($bundleName, array $configuration, $output)
{
$processed = false;
/** @var BundleInterface $bundle */
foreach ($this->getContainer()->get('kernel')->getBundles() as $bundle) {
if ($bundle->getName() !== $bundleName) {
continue;
}
$processed = true;
$bundleMetadata = new BundleMetadata($bundle, $configuration);
// generate the bundle file.
if (!$bundleMetadata->isExtendable()) {
$output->writeln(sprintf('Ignoring bundle : "<comment>%s</comment>"', $bundleMetadata->getClass()));
continue;
}
// generate the bundle file
if (!$bundleMetadata->isValid()) {
$output->writeln(sprintf(
'%s : <comment>wrong directory structure</comment>',
$bundleMetadata->getClass()
));
continue;
}
$output->writeln(sprintf('Processing bundle : "<info>%s</info>"', $bundleMetadata->getName()));
$this->getContainer()->get('sonata.easy_extends.generator.bundle')
->generate($output, $bundleMetadata);
$output->writeln(sprintf('Processing Doctrine ORM : "<info>%s</info>"', $bundleMetadata->getName()));
$this->getContainer()->get('sonata.easy_extends.generator.orm')
->generate($output, $bundleMetadata);
$output->writeln(sprintf('Processing Doctrine ODM : "<info>%s</info>"', $bundleMetadata->getName()));
$this->getContainer()->get('sonata.easy_extends.generator.odm')
->generate($output, $bundleMetadata);
$output->writeln(sprintf('Processing Doctrine PHPCR : "<info>%s</info>"', $bundleMetadata->getName()));
$this->getContainer()->get('sonata.easy_extends.generator.phpcr')
->generate($output, $bundleMetadata);
$output->writeln(sprintf('Processing Serializer config : "<info>%s</info>"', $bundleMetadata->getName()));
$this->getContainer()->get('sonata.easy_extends.generator.serializer')
->generate($output, $bundleMetadata);
$output->writeln('');
}
return $processed;
} | php | protected function generate($bundleName, array $configuration, $output)
{
$processed = false;
/** @var BundleInterface $bundle */
foreach ($this->getContainer()->get('kernel')->getBundles() as $bundle) {
if ($bundle->getName() !== $bundleName) {
continue;
}
$processed = true;
$bundleMetadata = new BundleMetadata($bundle, $configuration);
// generate the bundle file.
if (!$bundleMetadata->isExtendable()) {
$output->writeln(sprintf('Ignoring bundle : "<comment>%s</comment>"', $bundleMetadata->getClass()));
continue;
}
// generate the bundle file
if (!$bundleMetadata->isValid()) {
$output->writeln(sprintf(
'%s : <comment>wrong directory structure</comment>',
$bundleMetadata->getClass()
));
continue;
}
$output->writeln(sprintf('Processing bundle : "<info>%s</info>"', $bundleMetadata->getName()));
$this->getContainer()->get('sonata.easy_extends.generator.bundle')
->generate($output, $bundleMetadata);
$output->writeln(sprintf('Processing Doctrine ORM : "<info>%s</info>"', $bundleMetadata->getName()));
$this->getContainer()->get('sonata.easy_extends.generator.orm')
->generate($output, $bundleMetadata);
$output->writeln(sprintf('Processing Doctrine ODM : "<info>%s</info>"', $bundleMetadata->getName()));
$this->getContainer()->get('sonata.easy_extends.generator.odm')
->generate($output, $bundleMetadata);
$output->writeln(sprintf('Processing Doctrine PHPCR : "<info>%s</info>"', $bundleMetadata->getName()));
$this->getContainer()->get('sonata.easy_extends.generator.phpcr')
->generate($output, $bundleMetadata);
$output->writeln(sprintf('Processing Serializer config : "<info>%s</info>"', $bundleMetadata->getName()));
$this->getContainer()->get('sonata.easy_extends.generator.serializer')
->generate($output, $bundleMetadata);
$output->writeln('');
}
return $processed;
} | [
"protected",
"function",
"generate",
"(",
"$",
"bundleName",
",",
"array",
"$",
"configuration",
",",
"$",
"output",
")",
"{",
"$",
"processed",
"=",
"false",
";",
"/** @var BundleInterface $bundle */",
"foreach",
"(",
"$",
"this",
"->",
"getContainer",
"(",
"... | Generates a bundle entities from a bundle name.
@param string $bundleName
@param array $configuration
@param OutputInterface $output
@return bool | [
"Generates",
"a",
"bundle",
"entities",
"from",
"a",
"bundle",
"name",
"."
] | train | https://github.com/sonata-project/SonataEasyExtendsBundle/blob/10bd46159b274d7a9726e80375eacafd05595c56/src/Command/GenerateCommand.php#L131-L186 |
sonata-project/SonataEasyExtendsBundle | src/Mapper/DoctrineCollector.php | DoctrineCollector.addDiscriminator | public function addDiscriminator($class, $key, $discriminatorClass)
{
if (!isset($this->discriminators[$class])) {
$this->discriminators[$class] = [];
}
if (!isset($this->discriminators[$class][$key])) {
$this->discriminators[$class][$key] = $discriminatorClass;
}
} | php | public function addDiscriminator($class, $key, $discriminatorClass)
{
if (!isset($this->discriminators[$class])) {
$this->discriminators[$class] = [];
}
if (!isset($this->discriminators[$class][$key])) {
$this->discriminators[$class][$key] = $discriminatorClass;
}
} | [
"public",
"function",
"addDiscriminator",
"(",
"$",
"class",
",",
"$",
"key",
",",
"$",
"discriminatorClass",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"discriminators",
"[",
"$",
"class",
"]",
")",
")",
"{",
"$",
"this",
"->",
"disc... | Add a discriminator to a class.
@param string $class The Class
@param string $key Key is the database value and values are the classes
@param string $discriminatorClass The mapped class | [
"Add",
"a",
"discriminator",
"to",
"a",
"class",
"."
] | train | https://github.com/sonata-project/SonataEasyExtendsBundle/blob/10bd46159b274d7a9726e80375eacafd05595c56/src/Mapper/DoctrineCollector.php#L82-L91 |
sonata-project/SonataEasyExtendsBundle | src/Mapper/DoctrineCollector.php | DoctrineCollector.addOverride | final public function addOverride($class, $type, array $options)
{
if (!isset($this->overrides[$class])) {
$this->overrides[$class] = [];
}
if (!isset($this->overrides[$class][$type])) {
$this->overrides[$class][$type] = [];
}
$this->overrides[$class][$type][] = $options;
} | php | final public function addOverride($class, $type, array $options)
{
if (!isset($this->overrides[$class])) {
$this->overrides[$class] = [];
}
if (!isset($this->overrides[$class][$type])) {
$this->overrides[$class][$type] = [];
}
$this->overrides[$class][$type][] = $options;
} | [
"final",
"public",
"function",
"addOverride",
"(",
"$",
"class",
",",
"$",
"type",
",",
"array",
"$",
"options",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"overrides",
"[",
"$",
"class",
"]",
")",
")",
"{",
"$",
"this",
"->",
"ov... | Adds new override.
@param string $class
@param string $type
@param array $options | [
"Adds",
"new",
"override",
"."
] | train | https://github.com/sonata-project/SonataEasyExtendsBundle/blob/10bd46159b274d7a9726e80375eacafd05595c56/src/Mapper/DoctrineCollector.php#L178-L189 |
sonata-project/SonataEasyExtendsBundle | src/Generator/OrmGenerator.php | OrmGenerator.generate | public function generate(OutputInterface $output, BundleMetadata $bundleMetadata)
{
$this->generateMappingEntityFiles($output, $bundleMetadata);
$this->generateEntityFiles($output, $bundleMetadata);
$this->generateEntityRepositoryFiles($output, $bundleMetadata);
} | php | public function generate(OutputInterface $output, BundleMetadata $bundleMetadata)
{
$this->generateMappingEntityFiles($output, $bundleMetadata);
$this->generateEntityFiles($output, $bundleMetadata);
$this->generateEntityRepositoryFiles($output, $bundleMetadata);
} | [
"public",
"function",
"generate",
"(",
"OutputInterface",
"$",
"output",
",",
"BundleMetadata",
"$",
"bundleMetadata",
")",
"{",
"$",
"this",
"->",
"generateMappingEntityFiles",
"(",
"$",
"output",
",",
"$",
"bundleMetadata",
")",
";",
"$",
"this",
"->",
"gene... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataEasyExtendsBundle/blob/10bd46159b274d7a9726e80375eacafd05595c56/src/Generator/OrmGenerator.php#L40-L45 |
sonata-project/SonataEasyExtendsBundle | src/Generator/SerializerGenerator.php | SerializerGenerator.generate | public function generate(OutputInterface $output, BundleMetadata $bundleMetadata)
{
$this->generateOrmSerializer($output, $bundleMetadata);
$this->generateOdmSerializer($output, $bundleMetadata);
$this->generatePhpcrSerializer($output, $bundleMetadata);
} | php | public function generate(OutputInterface $output, BundleMetadata $bundleMetadata)
{
$this->generateOrmSerializer($output, $bundleMetadata);
$this->generateOdmSerializer($output, $bundleMetadata);
$this->generatePhpcrSerializer($output, $bundleMetadata);
} | [
"public",
"function",
"generate",
"(",
"OutputInterface",
"$",
"output",
",",
"BundleMetadata",
"$",
"bundleMetadata",
")",
"{",
"$",
"this",
"->",
"generateOrmSerializer",
"(",
"$",
"output",
",",
"$",
"bundleMetadata",
")",
";",
"$",
"this",
"->",
"generateO... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataEasyExtendsBundle/blob/10bd46159b274d7a9726e80375eacafd05595c56/src/Generator/SerializerGenerator.php#L40-L45 |
sonata-project/SonataEasyExtendsBundle | src/DependencyInjection/Compiler/AddMapperInformationCompilerPass.php | AddMapperInformationCompilerPass.process | public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('doctrine')) {
$container->removeDefinition('sonata.easy_extends.doctrine.mapper');
return;
}
$mapper = $container->getDefinition('sonata.easy_extends.doctrine.mapper');
foreach (DoctrineCollector::getInstance()->getAssociations() as $class => $associations) {
foreach ($associations as $field => $options) {
$mapper->addMethodCall('addAssociation', [$class, $field, $options]);
}
}
foreach (DoctrineCollector::getInstance()->getDiscriminatorColumns() as $class => $columnDefinition) {
$mapper->addMethodCall('addDiscriminatorColumn', [$class, $columnDefinition]);
}
foreach (DoctrineCollector::getInstance()->getDiscriminators() as $class => $discriminators) {
foreach ($discriminators as $key => $discriminatorClass) {
$mapper->addMethodCall('addDiscriminator', [$class, $key, $discriminatorClass]);
}
}
foreach (DoctrineCollector::getInstance()->getInheritanceTypes() as $class => $type) {
$mapper->addMethodCall('addInheritanceType', [$class, $type]);
}
foreach (DoctrineCollector::getInstance()->getIndexes() as $class => $indexes) {
foreach ($indexes as $field => $options) {
$mapper->addMethodCall('addIndex', [$class, $field, $options]);
}
}
foreach (DoctrineCollector::getInstance()->getUniques() as $class => $uniques) {
foreach ($uniques as $field => $options) {
$mapper->addMethodCall('addUnique', [$class, $field, $options]);
}
}
foreach (DoctrineCollector::getInstance()->getOverrides() as $class => $overrides) {
foreach ($overrides as $type => $options) {
$mapper->addMethodCall('addOverride', [$class, $type, $options]);
}
}
DoctrineCollector::getInstance()->clear();
} | php | public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('doctrine')) {
$container->removeDefinition('sonata.easy_extends.doctrine.mapper');
return;
}
$mapper = $container->getDefinition('sonata.easy_extends.doctrine.mapper');
foreach (DoctrineCollector::getInstance()->getAssociations() as $class => $associations) {
foreach ($associations as $field => $options) {
$mapper->addMethodCall('addAssociation', [$class, $field, $options]);
}
}
foreach (DoctrineCollector::getInstance()->getDiscriminatorColumns() as $class => $columnDefinition) {
$mapper->addMethodCall('addDiscriminatorColumn', [$class, $columnDefinition]);
}
foreach (DoctrineCollector::getInstance()->getDiscriminators() as $class => $discriminators) {
foreach ($discriminators as $key => $discriminatorClass) {
$mapper->addMethodCall('addDiscriminator', [$class, $key, $discriminatorClass]);
}
}
foreach (DoctrineCollector::getInstance()->getInheritanceTypes() as $class => $type) {
$mapper->addMethodCall('addInheritanceType', [$class, $type]);
}
foreach (DoctrineCollector::getInstance()->getIndexes() as $class => $indexes) {
foreach ($indexes as $field => $options) {
$mapper->addMethodCall('addIndex', [$class, $field, $options]);
}
}
foreach (DoctrineCollector::getInstance()->getUniques() as $class => $uniques) {
foreach ($uniques as $field => $options) {
$mapper->addMethodCall('addUnique', [$class, $field, $options]);
}
}
foreach (DoctrineCollector::getInstance()->getOverrides() as $class => $overrides) {
foreach ($overrides as $type => $options) {
$mapper->addMethodCall('addOverride', [$class, $type, $options]);
}
}
DoctrineCollector::getInstance()->clear();
} | [
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"if",
"(",
"!",
"$",
"container",
"->",
"hasDefinition",
"(",
"'doctrine'",
")",
")",
"{",
"$",
"container",
"->",
"removeDefinition",
"(",
"'sonata.easy_extends.doctrine.mapper'... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataEasyExtendsBundle/blob/10bd46159b274d7a9726e80375eacafd05595c56/src/DependencyInjection/Compiler/AddMapperInformationCompilerPass.php#L28-L77 |
sonata-project/SonataEasyExtendsBundle | src/Mapper/DoctrineORMMapper.php | DoctrineORMMapper.addOverride | final public function addOverride($class, $type, array $options)
{
if (!isset($this->overrides[$class])) {
$this->overrides[$class] = [];
}
$this->overrides[$class][$type] = $options;
} | php | final public function addOverride($class, $type, array $options)
{
if (!isset($this->overrides[$class])) {
$this->overrides[$class] = [];
}
$this->overrides[$class][$type] = $options;
} | [
"final",
"public",
"function",
"addOverride",
"(",
"$",
"class",
",",
"$",
"type",
",",
"array",
"$",
"options",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"overrides",
"[",
"$",
"class",
"]",
")",
")",
"{",
"$",
"this",
"->",
"ov... | Adds new ORM override.
@param string $class
@param string $type
@param array $options | [
"Adds",
"new",
"ORM",
"override",
"."
] | train | https://github.com/sonata-project/SonataEasyExtendsBundle/blob/10bd46159b274d7a9726e80375eacafd05595c56/src/Mapper/DoctrineORMMapper.php#L192-L199 |
sonata-project/SonataEasyExtendsBundle | src/Mapper/DoctrineORMMapper.php | DoctrineORMMapper.loadDiscriminatorColumns | private function loadDiscriminatorColumns(ClassMetadataInfo $metadata)
{
if (!\array_key_exists($metadata->name, $this->discriminatorColumns)) {
return;
}
try {
if (isset($this->discriminatorColumns[$metadata->name])) {
$arrayDiscriminatorColumns = $this->discriminatorColumns[$metadata->name];
if (isset($metadata->discriminatorColumn)) {
$arrayDiscriminatorColumns = array_merge($metadata->discriminatorColumn, $this->discriminatorColumns[$metadata->name]);
}
$metadata->setDiscriminatorColumn($arrayDiscriminatorColumns);
}
} catch (\ReflectionException $e) {
throw new \RuntimeException(sprintf('Error with class %s : %s', $metadata->name, $e->getMessage()), 404, $e);
}
} | php | private function loadDiscriminatorColumns(ClassMetadataInfo $metadata)
{
if (!\array_key_exists($metadata->name, $this->discriminatorColumns)) {
return;
}
try {
if (isset($this->discriminatorColumns[$metadata->name])) {
$arrayDiscriminatorColumns = $this->discriminatorColumns[$metadata->name];
if (isset($metadata->discriminatorColumn)) {
$arrayDiscriminatorColumns = array_merge($metadata->discriminatorColumn, $this->discriminatorColumns[$metadata->name]);
}
$metadata->setDiscriminatorColumn($arrayDiscriminatorColumns);
}
} catch (\ReflectionException $e) {
throw new \RuntimeException(sprintf('Error with class %s : %s', $metadata->name, $e->getMessage()), 404, $e);
}
} | [
"private",
"function",
"loadDiscriminatorColumns",
"(",
"ClassMetadataInfo",
"$",
"metadata",
")",
"{",
"if",
"(",
"!",
"\\",
"array_key_exists",
"(",
"$",
"metadata",
"->",
"name",
",",
"$",
"this",
"->",
"discriminatorColumns",
")",
")",
"{",
"return",
";",
... | @param ClassMetadataInfo $metadata
@throws \RuntimeException | [
"@param",
"ClassMetadataInfo",
"$metadata"
] | train | https://github.com/sonata-project/SonataEasyExtendsBundle/blob/10bd46159b274d7a9726e80375eacafd05595c56/src/Mapper/DoctrineORMMapper.php#L250-L267 |
sonata-project/SonataEasyExtendsBundle | src/Generator/BundleGenerator.php | BundleGenerator.generate | public function generate(OutputInterface $output, BundleMetadata $bundleMetadata)
{
$this->generateBundleDirectory($output, $bundleMetadata);
$this->generateBundleFile($output, $bundleMetadata);
} | php | public function generate(OutputInterface $output, BundleMetadata $bundleMetadata)
{
$this->generateBundleDirectory($output, $bundleMetadata);
$this->generateBundleFile($output, $bundleMetadata);
} | [
"public",
"function",
"generate",
"(",
"OutputInterface",
"$",
"output",
",",
"BundleMetadata",
"$",
"bundleMetadata",
")",
"{",
"$",
"this",
"->",
"generateBundleDirectory",
"(",
"$",
"output",
",",
"$",
"bundleMetadata",
")",
";",
"$",
"this",
"->",
"generat... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataEasyExtendsBundle/blob/10bd46159b274d7a9726e80375eacafd05595c56/src/Generator/BundleGenerator.php#L34-L38 |
sonata-project/SonataEasyExtendsBundle | src/Command/DumpMappingCommand.php | DumpMappingCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$factory = $this->getContainer()->get('doctrine')->getManager($input->getArgument('manager'))->getMetadataFactory();
$metadata = $factory->getMetadataFor($input->getArgument('model'));
$cme = new ClassMetadataExporter();
$exporter = $cme->getExporter('php');
$output->writeln($exporter->exportClassMetadata($metadata));
$output->writeln('Done!');
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$factory = $this->getContainer()->get('doctrine')->getManager($input->getArgument('manager'))->getMetadataFactory();
$metadata = $factory->getMetadataFor($input->getArgument('model'));
$cme = new ClassMetadataExporter();
$exporter = $cme->getExporter('php');
$output->writeln($exporter->exportClassMetadata($metadata));
$output->writeln('Done!');
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"factory",
"=",
"$",
"this",
"->",
"getContainer",
"(",
")",
"->",
"get",
"(",
"'doctrine'",
")",
"->",
"getManager",
"(",
"$",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataEasyExtendsBundle/blob/10bd46159b274d7a9726e80375eacafd05595c56/src/Command/DumpMappingCommand.php#L44-L55 |
php-enqueue/amqp-tools | RabbitMqDlxDelayStrategy.php | RabbitMqDlxDelayStrategy.delayMessage | public function delayMessage(AmqpContext $context, AmqpDestination $dest, AmqpMessage $message, int $delay): void
{
$properties = $message->getProperties();
// The x-death header must be removed because of the bug in RabbitMQ.
// It was reported that the bug is fixed since 3.5.4 but I tried with 3.6.1 and the bug still there.
// https://github.com/rabbitmq/rabbitmq-server/issues/216
unset($properties['x-death']);
$delayMessage = $context->createMessage($message->getBody(), $properties, $message->getHeaders());
$delayMessage->setRoutingKey($message->getRoutingKey());
if ($dest instanceof AmqpTopic) {
$routingKey = $message->getRoutingKey() ? '.'.$message->getRoutingKey() : '';
$name = sprintf('enqueue.%s%s.%s.x.delay', $dest->getTopicName(), $routingKey, $delay);
$delayQueue = $context->createQueue($name);
$delayQueue->addFlag(AmqpTopic::FLAG_DURABLE);
$delayQueue->setArgument('x-message-ttl', $delay);
$delayQueue->setArgument('x-dead-letter-exchange', $dest->getTopicName());
$delayQueue->setArgument('x-dead-letter-routing-key', (string) $delayMessage->getRoutingKey());
} elseif ($dest instanceof AmqpQueue) {
$delayQueue = $context->createQueue('enqueue.'.$dest->getQueueName().'.'.$delay.'.delayed');
$delayQueue->addFlag(AmqpTopic::FLAG_DURABLE);
$delayQueue->setArgument('x-message-ttl', $delay);
$delayQueue->setArgument('x-dead-letter-exchange', '');
$delayQueue->setArgument('x-dead-letter-routing-key', $dest->getQueueName());
} else {
throw new InvalidDestinationException(sprintf('The destination must be an instance of %s but got %s.',
AmqpTopic::class.'|'.AmqpQueue::class,
get_class($dest)
));
}
$context->declareQueue($delayQueue);
$context->createProducer()->send($delayQueue, $delayMessage);
} | php | public function delayMessage(AmqpContext $context, AmqpDestination $dest, AmqpMessage $message, int $delay): void
{
$properties = $message->getProperties();
// The x-death header must be removed because of the bug in RabbitMQ.
// It was reported that the bug is fixed since 3.5.4 but I tried with 3.6.1 and the bug still there.
// https://github.com/rabbitmq/rabbitmq-server/issues/216
unset($properties['x-death']);
$delayMessage = $context->createMessage($message->getBody(), $properties, $message->getHeaders());
$delayMessage->setRoutingKey($message->getRoutingKey());
if ($dest instanceof AmqpTopic) {
$routingKey = $message->getRoutingKey() ? '.'.$message->getRoutingKey() : '';
$name = sprintf('enqueue.%s%s.%s.x.delay', $dest->getTopicName(), $routingKey, $delay);
$delayQueue = $context->createQueue($name);
$delayQueue->addFlag(AmqpTopic::FLAG_DURABLE);
$delayQueue->setArgument('x-message-ttl', $delay);
$delayQueue->setArgument('x-dead-letter-exchange', $dest->getTopicName());
$delayQueue->setArgument('x-dead-letter-routing-key', (string) $delayMessage->getRoutingKey());
} elseif ($dest instanceof AmqpQueue) {
$delayQueue = $context->createQueue('enqueue.'.$dest->getQueueName().'.'.$delay.'.delayed');
$delayQueue->addFlag(AmqpTopic::FLAG_DURABLE);
$delayQueue->setArgument('x-message-ttl', $delay);
$delayQueue->setArgument('x-dead-letter-exchange', '');
$delayQueue->setArgument('x-dead-letter-routing-key', $dest->getQueueName());
} else {
throw new InvalidDestinationException(sprintf('The destination must be an instance of %s but got %s.',
AmqpTopic::class.'|'.AmqpQueue::class,
get_class($dest)
));
}
$context->declareQueue($delayQueue);
$context->createProducer()->send($delayQueue, $delayMessage);
} | [
"public",
"function",
"delayMessage",
"(",
"AmqpContext",
"$",
"context",
",",
"AmqpDestination",
"$",
"dest",
",",
"AmqpMessage",
"$",
"message",
",",
"int",
"$",
"delay",
")",
":",
"void",
"{",
"$",
"properties",
"=",
"$",
"message",
"->",
"getProperties",... | {@inheritdoc} | [
"{"
] | train | https://github.com/php-enqueue/amqp-tools/blob/47385a5f3357e9091c0171497f1d41bbf2b917d0/RabbitMqDlxDelayStrategy.php#L19-L56 |
php-enqueue/amqp-tools | ConnectionConfig.php | ConnectionConfig.getOption | public function getOption($name, $default = null)
{
$config = $this->getConfig();
return array_key_exists($name, $config) ? $config[$name] : $default;
} | php | public function getOption($name, $default = null)
{
$config = $this->getConfig();
return array_key_exists($name, $config) ? $config[$name] : $default;
} | [
"public",
"function",
"getOption",
"(",
"$",
"name",
",",
"$",
"default",
"=",
"null",
")",
"{",
"$",
"config",
"=",
"$",
"this",
"->",
"getConfig",
"(",
")",
";",
"return",
"array_key_exists",
"(",
"$",
"name",
",",
"$",
"config",
")",
"?",
"$",
"... | @param string $name
@param mixed $default
@return mixed | [
"@param",
"string",
"$name",
"@param",
"mixed",
"$default"
] | train | https://github.com/php-enqueue/amqp-tools/blob/47385a5f3357e9091c0171497f1d41bbf2b917d0/ConnectionConfig.php#L354-L359 |
php-enqueue/amqp-tools | ConnectionConfig.php | ConnectionConfig.parseDsn | private function parseDsn($dsn)
{
$dsn = Dsn::parseFirst($dsn);
$supportedSchemes = $this->supportedSchemes;
if (false == in_array($dsn->getSchemeProtocol(), $supportedSchemes, true)) {
throw new \LogicException(sprintf(
'The given scheme protocol "%s" is not supported. It must be one of "%s".',
$dsn->getSchemeProtocol(),
implode('", "', $supportedSchemes)
));
}
$sslOn = false;
$isAmqps = 'amqps' === $dsn->getSchemeProtocol();
$isTls = in_array('tls', $dsn->getSchemeExtensions(), true);
$isSsl = in_array('ssl', $dsn->getSchemeExtensions(), true);
if ($isAmqps || $isTls || $isSsl) {
$sslOn = true;
}
$this->schemeExtensions = $dsn->getSchemeExtensions();
$config = array_filter(array_replace($dsn->getQuery(), [
'host' => $dsn->getHost(),
'port' => $dsn->getPort(),
'user' => $dsn->getUser(),
'pass' => $dsn->getPassword(),
'vhost' => null !== ($path = $dsn->getPath()) ?
(0 === strpos($path, '/') ? substr($path, 1) : $path)
: null,
'read_timeout' => $dsn->getFloat('read_timeout'),
'write_timeout' => $dsn->getFloat('write_timeout'),
'connection_timeout' => $dsn->getFloat('connection_timeout'),
'heartbeat' => $dsn->getFloat('heartbeat'),
'persisted' => $dsn->getBool('persisted'),
'lazy' => $dsn->getBool('lazy'),
'qos_global' => $dsn->getBool('qos_global'),
'qos_prefetch_size' => $dsn->getDecimal('qos_prefetch_size'),
'qos_prefetch_count' => $dsn->getDecimal('qos_prefetch_count'),
'ssl_on' => $sslOn,
'ssl_verify' => $dsn->getBool('ssl_verify'),
'ssl_cacert' => $dsn->getString('ssl_cacert'),
'ssl_cert' => $dsn->getString('ssl_cert'),
'ssl_key' => $dsn->getString('ssl_key'),
'ssl_passphrase' => $dsn->getString('ssl_passphrase'),
]), function ($value) { return null !== $value; });
return array_map(function ($value) {
return is_string($value) ? rawurldecode($value) : $value;
}, $config);
} | php | private function parseDsn($dsn)
{
$dsn = Dsn::parseFirst($dsn);
$supportedSchemes = $this->supportedSchemes;
if (false == in_array($dsn->getSchemeProtocol(), $supportedSchemes, true)) {
throw new \LogicException(sprintf(
'The given scheme protocol "%s" is not supported. It must be one of "%s".',
$dsn->getSchemeProtocol(),
implode('", "', $supportedSchemes)
));
}
$sslOn = false;
$isAmqps = 'amqps' === $dsn->getSchemeProtocol();
$isTls = in_array('tls', $dsn->getSchemeExtensions(), true);
$isSsl = in_array('ssl', $dsn->getSchemeExtensions(), true);
if ($isAmqps || $isTls || $isSsl) {
$sslOn = true;
}
$this->schemeExtensions = $dsn->getSchemeExtensions();
$config = array_filter(array_replace($dsn->getQuery(), [
'host' => $dsn->getHost(),
'port' => $dsn->getPort(),
'user' => $dsn->getUser(),
'pass' => $dsn->getPassword(),
'vhost' => null !== ($path = $dsn->getPath()) ?
(0 === strpos($path, '/') ? substr($path, 1) : $path)
: null,
'read_timeout' => $dsn->getFloat('read_timeout'),
'write_timeout' => $dsn->getFloat('write_timeout'),
'connection_timeout' => $dsn->getFloat('connection_timeout'),
'heartbeat' => $dsn->getFloat('heartbeat'),
'persisted' => $dsn->getBool('persisted'),
'lazy' => $dsn->getBool('lazy'),
'qos_global' => $dsn->getBool('qos_global'),
'qos_prefetch_size' => $dsn->getDecimal('qos_prefetch_size'),
'qos_prefetch_count' => $dsn->getDecimal('qos_prefetch_count'),
'ssl_on' => $sslOn,
'ssl_verify' => $dsn->getBool('ssl_verify'),
'ssl_cacert' => $dsn->getString('ssl_cacert'),
'ssl_cert' => $dsn->getString('ssl_cert'),
'ssl_key' => $dsn->getString('ssl_key'),
'ssl_passphrase' => $dsn->getString('ssl_passphrase'),
]), function ($value) { return null !== $value; });
return array_map(function ($value) {
return is_string($value) ? rawurldecode($value) : $value;
}, $config);
} | [
"private",
"function",
"parseDsn",
"(",
"$",
"dsn",
")",
"{",
"$",
"dsn",
"=",
"Dsn",
"::",
"parseFirst",
"(",
"$",
"dsn",
")",
";",
"$",
"supportedSchemes",
"=",
"$",
"this",
"->",
"supportedSchemes",
";",
"if",
"(",
"false",
"==",
"in_array",
"(",
... | @param string $dsn
@return array | [
"@param",
"string",
"$dsn"
] | train | https://github.com/php-enqueue/amqp-tools/blob/47385a5f3357e9091c0171497f1d41bbf2b917d0/ConnectionConfig.php#L380-L431 |
Qafoo/QualityAnalyzer | src/php/Qafoo/Analyzer/Command/Analyze.php | Analyze.copyResultFile | protected function copyResultFile($handler, $file)
{
if (!is_file($file)) {
throw new \OutOfBoundsException("Result file $file is not readable");
}
$extension = 'xml';
if (preg_match('(\.([a-z]+)$)', $file, $match)) {
$extension = $match[1];
}
copy($file, $this->targetDir . '/' . $handler . '.' . $extension);
return "$handler.$extension";
} | php | protected function copyResultFile($handler, $file)
{
if (!is_file($file)) {
throw new \OutOfBoundsException("Result file $file is not readable");
}
$extension = 'xml';
if (preg_match('(\.([a-z]+)$)', $file, $match)) {
$extension = $match[1];
}
copy($file, $this->targetDir . '/' . $handler . '.' . $extension);
return "$handler.$extension";
} | [
"protected",
"function",
"copyResultFile",
"(",
"$",
"handler",
",",
"$",
"file",
")",
"{",
"if",
"(",
"!",
"is_file",
"(",
"$",
"file",
")",
")",
"{",
"throw",
"new",
"\\",
"OutOfBoundsException",
"(",
"\"Result file $file is not readable\"",
")",
";",
"}",... | Copy result file
@param string $handler
@param string $file
@return string
@throws \OutOfBoundsException | [
"Copy",
"result",
"file"
] | train | https://github.com/Qafoo/QualityAnalyzer/blob/b9d98969c02a6bbc827259a08096dae25def4274/src/php/Qafoo/Analyzer/Command/Analyze.php#L167-L181 |
Qafoo/QualityAnalyzer | src/php/Qafoo/Analyzer/Handler/Phploc.php | Phploc.handle | public function handle(Project $project, $existingResult = null)
{
if ($existingResult) {
// @TODO: Verify file is actually sensible?
return $existingResult;
}
$options = array(
'--count-tests',
'--log-xml=' . ($tmpFile = $this->shell->getTempFile('qa', 'xml')),
);
foreach ($project->excludes as $exclude) {
$options[] = '--exclude=' . $exclude;
}
$this->shell->exec('vendor/bin/phploc', array_merge($options, array($project->baseDir)));
return $tmpFile;
} | php | public function handle(Project $project, $existingResult = null)
{
if ($existingResult) {
// @TODO: Verify file is actually sensible?
return $existingResult;
}
$options = array(
'--count-tests',
'--log-xml=' . ($tmpFile = $this->shell->getTempFile('qa', 'xml')),
);
foreach ($project->excludes as $exclude) {
$options[] = '--exclude=' . $exclude;
}
$this->shell->exec('vendor/bin/phploc', array_merge($options, array($project->baseDir)));
return $tmpFile;
} | [
"public",
"function",
"handle",
"(",
"Project",
"$",
"project",
",",
"$",
"existingResult",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"existingResult",
")",
"{",
"// @TODO: Verify file is actually sensible?",
"return",
"$",
"existingResult",
";",
"}",
"$",
"options... | Handle provided directory
Optionally an existing result file can be provided
If a valid file could be generated the file name is supposed to be
returned, otherwise return null.
@param Project $project
@param string $existingResult
@return string | [
"Handle",
"provided",
"directory"
] | train | https://github.com/Qafoo/QualityAnalyzer/blob/b9d98969c02a6bbc827259a08096dae25def4274/src/php/Qafoo/Analyzer/Handler/Phploc.php#L35-L53 |
Qafoo/QualityAnalyzer | src/php/Qafoo/Analyzer/Application.php | Application.getDefaultCommands | protected function getDefaultCommands()
{
$shell = new Shell(dirname(VENDOR_PATH));
$handlers = [
'source' => new Handler\Source($shell),
'coverage' => new Handler\Coverage(),
'pdepend' => new Handler\PDepend($shell),
'dependencies' => new Handler\Dependencies($shell),
'phpmd' => new Handler\PHPMD($shell),
'checkstyle' => new Handler\Checkstyle($shell),
'tests' => new Handler\Tests(),
'cpd' => new Handler\CPD($shell),
'phploc' => new Handler\Phploc($shell),
'git' => new Handler\Git($shell),
'gitDetailed' => new Handler\GitDetailed($shell),
];
return array_merge(
parent::getDefaultCommands(),
[
new Command\Serve(),
new Command\Bundle(),
new Command\Analyze($handlers),
new Command\Analyzers($handlers),
]
);
} | php | protected function getDefaultCommands()
{
$shell = new Shell(dirname(VENDOR_PATH));
$handlers = [
'source' => new Handler\Source($shell),
'coverage' => new Handler\Coverage(),
'pdepend' => new Handler\PDepend($shell),
'dependencies' => new Handler\Dependencies($shell),
'phpmd' => new Handler\PHPMD($shell),
'checkstyle' => new Handler\Checkstyle($shell),
'tests' => new Handler\Tests(),
'cpd' => new Handler\CPD($shell),
'phploc' => new Handler\Phploc($shell),
'git' => new Handler\Git($shell),
'gitDetailed' => new Handler\GitDetailed($shell),
];
return array_merge(
parent::getDefaultCommands(),
[
new Command\Serve(),
new Command\Bundle(),
new Command\Analyze($handlers),
new Command\Analyzers($handlers),
]
);
} | [
"protected",
"function",
"getDefaultCommands",
"(",
")",
"{",
"$",
"shell",
"=",
"new",
"Shell",
"(",
"dirname",
"(",
"VENDOR_PATH",
")",
")",
";",
"$",
"handlers",
"=",
"[",
"'source'",
"=>",
"new",
"Handler",
"\\",
"Source",
"(",
"$",
"shell",
")",
"... | Get default commands
@return \Symfony\Component\Console\Command\Command[] | [
"Get",
"default",
"commands"
] | train | https://github.com/Qafoo/QualityAnalyzer/blob/b9d98969c02a6bbc827259a08096dae25def4274/src/php/Qafoo/Analyzer/Application.php#L17-L45 |
Qafoo/QualityAnalyzer | src/php/Qafoo/Analyzer/Handler/Git.php | Git.handle | public function handle(Project $project, $existingResult = null)
{
$resultFile = $this->shell->getTempFile('qa', 'json');
$result = array(
'3' => $this->countGitChangesPerFile($project, new \DateTime('-3 months')),
'12' => $this->countGitChangesPerFile($project, new \DateTime('-1 year')),
'all' => $this->countGitChangesPerFile($project),
);
file_put_contents($resultFile, json_encode($result));
return $resultFile;
} | php | public function handle(Project $project, $existingResult = null)
{
$resultFile = $this->shell->getTempFile('qa', 'json');
$result = array(
'3' => $this->countGitChangesPerFile($project, new \DateTime('-3 months')),
'12' => $this->countGitChangesPerFile($project, new \DateTime('-1 year')),
'all' => $this->countGitChangesPerFile($project),
);
file_put_contents($resultFile, json_encode($result));
return $resultFile;
} | [
"public",
"function",
"handle",
"(",
"Project",
"$",
"project",
",",
"$",
"existingResult",
"=",
"null",
")",
"{",
"$",
"resultFile",
"=",
"$",
"this",
"->",
"shell",
"->",
"getTempFile",
"(",
"'qa'",
",",
"'json'",
")",
";",
"$",
"result",
"=",
"array... | Handle provided directory
Optionally an existing result file can be provided
If a valid file could be generated the file name is supposed to be
returned, otherwise return null.
@param Project $project
@param string $existingResult
@return string | [
"Handle",
"provided",
"directory"
] | train | https://github.com/Qafoo/QualityAnalyzer/blob/b9d98969c02a6bbc827259a08096dae25def4274/src/php/Qafoo/Analyzer/Handler/Git.php#L35-L46 |
Qafoo/QualityAnalyzer | src/php/Qafoo/Analyzer/Shell.php | Shell.exec | public function exec($command, array $arguments = [], array $okCodes = [0], $workingDir = null)
{
$command = $this->makeAbsolute($command);
$escapedCommand = escapeshellcmd($command) . ' ' . implode(' ', array_map('escapeshellarg', $arguments));
$originalWorkingDir = getcwd();
chdir($workingDir ?: $originalWorkingDir);
exec($escapedCommand, $output, $return);
chdir($originalWorkingDir);
if (!in_array($return, $okCodes)) {
$message = sprintf(
'Command "%s" exited with non zero exit code %s: %s',
$escapedCommand,
$return,
implode(PHP_EOL, $output)
);
throw new \Exception($message);
}
return implode(PHP_EOL, $output);
} | php | public function exec($command, array $arguments = [], array $okCodes = [0], $workingDir = null)
{
$command = $this->makeAbsolute($command);
$escapedCommand = escapeshellcmd($command) . ' ' . implode(' ', array_map('escapeshellarg', $arguments));
$originalWorkingDir = getcwd();
chdir($workingDir ?: $originalWorkingDir);
exec($escapedCommand, $output, $return);
chdir($originalWorkingDir);
if (!in_array($return, $okCodes)) {
$message = sprintf(
'Command "%s" exited with non zero exit code %s: %s',
$escapedCommand,
$return,
implode(PHP_EOL, $output)
);
throw new \Exception($message);
}
return implode(PHP_EOL, $output);
} | [
"public",
"function",
"exec",
"(",
"$",
"command",
",",
"array",
"$",
"arguments",
"=",
"[",
"]",
",",
"array",
"$",
"okCodes",
"=",
"[",
"0",
"]",
",",
"$",
"workingDir",
"=",
"null",
")",
"{",
"$",
"command",
"=",
"$",
"this",
"->",
"makeAbsolute... | Exec shell command
Fails if the command returns with a non zero exit code
@param string $command
@param string[] $arguments
@param int[] $okCodes
@param null $workingDir
@return string
@throws \Exception | [
"Exec",
"shell",
"command"
] | train | https://github.com/Qafoo/QualityAnalyzer/blob/b9d98969c02a6bbc827259a08096dae25def4274/src/php/Qafoo/Analyzer/Shell.php#L36-L58 |
Qafoo/QualityAnalyzer | src/php/Qafoo/Analyzer/Shell.php | Shell.makeAbsolute | protected function makeAbsolute($command)
{
if ((strpos($command, '/') === false) || $command[0] === "/") {
return $command;
}
return $this->baseDir . '/' . $command;
} | php | protected function makeAbsolute($command)
{
if ((strpos($command, '/') === false) || $command[0] === "/") {
return $command;
}
return $this->baseDir . '/' . $command;
} | [
"protected",
"function",
"makeAbsolute",
"(",
"$",
"command",
")",
"{",
"if",
"(",
"(",
"strpos",
"(",
"$",
"command",
",",
"'/'",
")",
"===",
"false",
")",
"||",
"$",
"command",
"[",
"0",
"]",
"===",
"\"/\"",
")",
"{",
"return",
"$",
"command",
";... | Make absolute
@param string $command
@return string | [
"Make",
"absolute"
] | train | https://github.com/Qafoo/QualityAnalyzer/blob/b9d98969c02a6bbc827259a08096dae25def4274/src/php/Qafoo/Analyzer/Shell.php#L67-L74 |
Qafoo/QualityAnalyzer | src/php/Qafoo/Analyzer/Handler/GitDetailed.php | GitDetailed.handle | public function handle(Project $project, $existingResult = null)
{
if (!isset($project->analyzers['pdepend'])) {
return;
}
$pdependResultFile = $project->dataDir . '/' . $project->analyzers['pdepend'];
$document = new \DomDocument();
$document->load($pdependResultFile);
$xPath = new \DomXPath($document);
foreach ($xPath->query('//package') as $packageNode) {
$packageCommits = 0;
foreach ($xPath->query('./class', $packageNode) as $classNode) {
$fileNode = $xPath->query('./file', $classNode)->item(0);
$file = $fileNode->getAttribute('name');
$classCommits = $this->countGitChangesPerFileRange(
$project,
$file,
$classNode->getAttribute('start'),
$classNode->getAttribute('end')
);
$packageCommits += $classCommits;
$classNode->setAttribute('commits', $classCommits);
foreach ($xPath->query('./method', $classNode) as $methodNode) {
$methodCommits = $this->countGitChangesPerFileRange(
$project,
$file,
$methodNode->getAttribute('start'),
$methodNode->getAttribute('end')
);
$methodNode->setAttribute('commits', $methodCommits);
}
}
$packageNode->setAttribute('commits', $packageCommits);
}
$document->save($pdependResultFile);
return null;
} | php | public function handle(Project $project, $existingResult = null)
{
if (!isset($project->analyzers['pdepend'])) {
return;
}
$pdependResultFile = $project->dataDir . '/' . $project->analyzers['pdepend'];
$document = new \DomDocument();
$document->load($pdependResultFile);
$xPath = new \DomXPath($document);
foreach ($xPath->query('//package') as $packageNode) {
$packageCommits = 0;
foreach ($xPath->query('./class', $packageNode) as $classNode) {
$fileNode = $xPath->query('./file', $classNode)->item(0);
$file = $fileNode->getAttribute('name');
$classCommits = $this->countGitChangesPerFileRange(
$project,
$file,
$classNode->getAttribute('start'),
$classNode->getAttribute('end')
);
$packageCommits += $classCommits;
$classNode->setAttribute('commits', $classCommits);
foreach ($xPath->query('./method', $classNode) as $methodNode) {
$methodCommits = $this->countGitChangesPerFileRange(
$project,
$file,
$methodNode->getAttribute('start'),
$methodNode->getAttribute('end')
);
$methodNode->setAttribute('commits', $methodCommits);
}
}
$packageNode->setAttribute('commits', $packageCommits);
}
$document->save($pdependResultFile);
return null;
} | [
"public",
"function",
"handle",
"(",
"Project",
"$",
"project",
",",
"$",
"existingResult",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"project",
"->",
"analyzers",
"[",
"'pdepend'",
"]",
")",
")",
"{",
"return",
";",
"}",
"$",
"pdepen... | Handle provided directory
Optionally an existing result file can be provided
If a valid file could be generated the file name is supposed to be
returned, otherwise return null.
@param Project $project
@param string $existingResult
@return string | [
"Handle",
"provided",
"directory"
] | train | https://github.com/Qafoo/QualityAnalyzer/blob/b9d98969c02a6bbc827259a08096dae25def4274/src/php/Qafoo/Analyzer/Handler/GitDetailed.php#L36-L80 |
Qafoo/QualityAnalyzer | src/php/Qafoo/Analyzer/Handler/GitDetailed.php | GitDetailed.countGitChangesPerFileRange | protected function countGitChangesPerFileRange(Project $project, $file, $from, $to)
{
$options = [
'log',
'--format=format:qacommit: %H',
'--no-patch',
'-L',
"$from,$to:$file",
];
$existingResults = $this->shell->exec('git', $options, [0], $project->baseDir);
return count(
array_filter(
array_map(
'trim',
explode(PHP_EOL, $existingResults)
),
function ($line) {
return (strpos($line, 'qacommit: ') === 0);
}
)
);
} | php | protected function countGitChangesPerFileRange(Project $project, $file, $from, $to)
{
$options = [
'log',
'--format=format:qacommit: %H',
'--no-patch',
'-L',
"$from,$to:$file",
];
$existingResults = $this->shell->exec('git', $options, [0], $project->baseDir);
return count(
array_filter(
array_map(
'trim',
explode(PHP_EOL, $existingResults)
),
function ($line) {
return (strpos($line, 'qacommit: ') === 0);
}
)
);
} | [
"protected",
"function",
"countGitChangesPerFileRange",
"(",
"Project",
"$",
"project",
",",
"$",
"file",
",",
"$",
"from",
",",
"$",
"to",
")",
"{",
"$",
"options",
"=",
"[",
"'log'",
",",
"'--format=format:qacommit: %H'",
",",
"'--no-patch'",
",",
"'-L'",
... | Counts GIT commits per file and range. This is used to track the number
of commits on methods or classes.
@HACK: I did not manage to convice GIT to omit the diff when using `-L…`
– this is why we embed the "qacommit: " string and count its occurence
afterwards. This causes GIT to calculate MANY diffs, which are the
passed to PHP and thrown away using many string operations. This sucks.
@FIX : Can be fixed immediately when we learn how to convince GIT to omit
the diffs / patches. | [
"Counts",
"GIT",
"commits",
"per",
"file",
"and",
"range",
".",
"This",
"is",
"used",
"to",
"track",
"the",
"number",
"of",
"commits",
"on",
"methods",
"or",
"classes",
"."
] | train | https://github.com/Qafoo/QualityAnalyzer/blob/b9d98969c02a6bbc827259a08096dae25def4274/src/php/Qafoo/Analyzer/Handler/GitDetailed.php#L94-L117 |
Qafoo/QualityAnalyzer | src/php/Qafoo/Analyzer/Handler/Source.php | Source.handle | public function handle(Project $project, $existingResult = null)
{
$zipFile = __DIR__ . '/../../../../../data/source.zip';
$archive = new \ZipArchive();
$archive->open($zipFile, \ZipArchive::OVERWRITE | \ZipArchive::CREATE);
$finder = new FinderFacade(array($project->baseDir), $project->excludes, array('*.php'));
foreach ($finder->findFiles() as $existingResult) {
$archive->addFile($existingResult, ltrim(str_replace($project->baseDir, '', $existingResult), '/'));
}
$archive->close();
} | php | public function handle(Project $project, $existingResult = null)
{
$zipFile = __DIR__ . '/../../../../../data/source.zip';
$archive = new \ZipArchive();
$archive->open($zipFile, \ZipArchive::OVERWRITE | \ZipArchive::CREATE);
$finder = new FinderFacade(array($project->baseDir), $project->excludes, array('*.php'));
foreach ($finder->findFiles() as $existingResult) {
$archive->addFile($existingResult, ltrim(str_replace($project->baseDir, '', $existingResult), '/'));
}
$archive->close();
} | [
"public",
"function",
"handle",
"(",
"Project",
"$",
"project",
",",
"$",
"existingResult",
"=",
"null",
")",
"{",
"$",
"zipFile",
"=",
"__DIR__",
".",
"'/../../../../../data/source.zip'",
";",
"$",
"archive",
"=",
"new",
"\\",
"ZipArchive",
"(",
")",
";",
... | Handle provided directory
Optionally an existing result file can be provided
If a valid file could be generated the file name is supposed to be
returned, otherwise return null.
@param Project $project
@param string $existingResult
@return string | [
"Handle",
"provided",
"directory"
] | train | https://github.com/Qafoo/QualityAnalyzer/blob/b9d98969c02a6bbc827259a08096dae25def4274/src/php/Qafoo/Analyzer/Handler/Source.php#L37-L47 |
clue/php-socket-raw | src/Exception.php | Exception.createFromSocketResource | public static function createFromSocketResource($resource, $messagePrefix = 'Socket operation failed')
{
$code = socket_last_error($resource);
socket_clear_error($resource);
return self::createFromCode($code, $messagePrefix);
} | php | public static function createFromSocketResource($resource, $messagePrefix = 'Socket operation failed')
{
$code = socket_last_error($resource);
socket_clear_error($resource);
return self::createFromCode($code, $messagePrefix);
} | [
"public",
"static",
"function",
"createFromSocketResource",
"(",
"$",
"resource",
",",
"$",
"messagePrefix",
"=",
"'Socket operation failed'",
")",
"{",
"$",
"code",
"=",
"socket_last_error",
"(",
"$",
"resource",
")",
";",
"socket_clear_error",
"(",
"$",
"resourc... | Create an Exception after a socket operation on the given $resource failed
@param resource $resource
@param string $messagePrefix
@return self
@uses socket_last_error() to get last socket error code
@uses socket_clear_error() to clear socket error code
@uses self::createFromCode() to automatically construct exception with full error message | [
"Create",
"an",
"Exception",
"after",
"a",
"socket",
"operation",
"on",
"the",
"given",
"$resource",
"failed"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Exception.php#L19-L25 |
clue/php-socket-raw | src/Exception.php | Exception.getErrorMessage | protected static function getErrorMessage($code)
{
$string = socket_strerror($code);
// search constant starting with SOCKET_ for this error code
foreach (get_defined_constants() as $key => $value) {
if($value === $code && strpos($key, 'SOCKET_') === 0) {
$string .= ' (' . $key . ')';
break;
}
}
return $string;
} | php | protected static function getErrorMessage($code)
{
$string = socket_strerror($code);
// search constant starting with SOCKET_ for this error code
foreach (get_defined_constants() as $key => $value) {
if($value === $code && strpos($key, 'SOCKET_') === 0) {
$string .= ' (' . $key . ')';
break;
}
}
return $string;
} | [
"protected",
"static",
"function",
"getErrorMessage",
"(",
"$",
"code",
")",
"{",
"$",
"string",
"=",
"socket_strerror",
"(",
"$",
"code",
")",
";",
"// search constant starting with SOCKET_ for this error code",
"foreach",
"(",
"get_defined_constants",
"(",
")",
"as"... | get error message for given error code
@param int $code error code
@return string
@uses socket_strerror() to translate error code to error message
@uses get_defined_constants() to check for related error constant | [
"get",
"error",
"message",
"for",
"given",
"error",
"code"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Exception.php#L66-L79 |
clue/php-socket-raw | src/Socket.php | Socket.accept | public function accept()
{
$resource = @socket_accept($this->resource);
if ($resource === false) {
throw Exception::createFromGlobalSocketOperation();
}
return new Socket($resource);
} | php | public function accept()
{
$resource = @socket_accept($this->resource);
if ($resource === false) {
throw Exception::createFromGlobalSocketOperation();
}
return new Socket($resource);
} | [
"public",
"function",
"accept",
"(",
")",
"{",
"$",
"resource",
"=",
"@",
"socket_accept",
"(",
"$",
"this",
"->",
"resource",
")",
";",
"if",
"(",
"$",
"resource",
"===",
"false",
")",
"{",
"throw",
"Exception",
"::",
"createFromGlobalSocketOperation",
"(... | accept an incomming connection on this listening socket
@return \Socket\Raw\Socket new connected socket used for communication
@throws Exception on error, if this is not a listening socket or there's no connection pending
@see self::selectRead() to check if this listening socket can accept()
@see Factory::createServer() to create a listening socket
@see self::listen() has to be called first
@uses socket_accept() | [
"accept",
"an",
"incomming",
"connection",
"on",
"this",
"listening",
"socket"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Socket.php#L53-L60 |
clue/php-socket-raw | src/Socket.php | Socket.bind | public function bind($address)
{
$ret = @socket_bind($this->resource, $this->unformatAddress($address, $port), $port);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $this;
} | php | public function bind($address)
{
$ret = @socket_bind($this->resource, $this->unformatAddress($address, $port), $port);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $this;
} | [
"public",
"function",
"bind",
"(",
"$",
"address",
")",
"{",
"$",
"ret",
"=",
"@",
"socket_bind",
"(",
"$",
"this",
"->",
"resource",
",",
"$",
"this",
"->",
"unformatAddress",
"(",
"$",
"address",
",",
"$",
"port",
")",
",",
"$",
"port",
")",
";",... | binds a name/address/path to this socket
has to be called before issuing connect() or listen()
@param string $address either of IPv4:port, hostname:port, [IPv6]:port, unix-path
@return self $this (chainable)
@throws Exception on error
@uses socket_bind() | [
"binds",
"a",
"name",
"/",
"address",
"/",
"path",
"to",
"this",
"socket"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Socket.php#L72-L79 |
clue/php-socket-raw | src/Socket.php | Socket.connect | public function connect($address)
{
$ret = @socket_connect($this->resource, $this->unformatAddress($address, $port), $port);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $this;
} | php | public function connect($address)
{
$ret = @socket_connect($this->resource, $this->unformatAddress($address, $port), $port);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $this;
} | [
"public",
"function",
"connect",
"(",
"$",
"address",
")",
"{",
"$",
"ret",
"=",
"@",
"socket_connect",
"(",
"$",
"this",
"->",
"resource",
",",
"$",
"this",
"->",
"unformatAddress",
"(",
"$",
"address",
",",
"$",
"port",
")",
",",
"$",
"port",
")",
... | initiate a connection to given address
@param string $address either of IPv4:port, hostname:port, [IPv6]:port, unix-path
@return self $this (chainable)
@throws Exception on error
@uses socket_connect() | [
"initiate",
"a",
"connection",
"to",
"given",
"address"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Socket.php#L105-L112 |
clue/php-socket-raw | src/Socket.php | Socket.connectTimeout | public function connectTimeout($address, $timeout)
{
$this->setBlocking(false);
try {
// socket is non-blocking, so connect should emit EINPROGRESS
$this->connect($address);
// socket is already connected immediately?
return $this;
} catch (Exception $e) {
// non-blocking connect() should be EINPROGRESS (or EWOULDBLOCK on Windows) => otherwise re-throw
if ($e->getCode() !== SOCKET_EINPROGRESS && $e->getCode() !== SOCKET_EWOULDBLOCK) {
throw $e;
}
// connection should be completed (or rejected) within timeout
if ($this->selectWrite($timeout) === false) {
throw new Exception('Timed out while waiting for connection', SOCKET_ETIMEDOUT);
}
// confirm connection success (or fail if connected has been rejected)
$this->assertAlive();
return $this;
}
} | php | public function connectTimeout($address, $timeout)
{
$this->setBlocking(false);
try {
// socket is non-blocking, so connect should emit EINPROGRESS
$this->connect($address);
// socket is already connected immediately?
return $this;
} catch (Exception $e) {
// non-blocking connect() should be EINPROGRESS (or EWOULDBLOCK on Windows) => otherwise re-throw
if ($e->getCode() !== SOCKET_EINPROGRESS && $e->getCode() !== SOCKET_EWOULDBLOCK) {
throw $e;
}
// connection should be completed (or rejected) within timeout
if ($this->selectWrite($timeout) === false) {
throw new Exception('Timed out while waiting for connection', SOCKET_ETIMEDOUT);
}
// confirm connection success (or fail if connected has been rejected)
$this->assertAlive();
return $this;
}
} | [
"public",
"function",
"connectTimeout",
"(",
"$",
"address",
",",
"$",
"timeout",
")",
"{",
"$",
"this",
"->",
"setBlocking",
"(",
"false",
")",
";",
"try",
"{",
"// socket is non-blocking, so connect should emit EINPROGRESS",
"$",
"this",
"->",
"connect",
"(",
... | Initiates a new connection to given address, wait for up to $timeout seconds
The given $timeout parameter is an upper bound, a maximum time to wait
for the connection to be either accepted or rejected.
The resulting socket resource will be set to non-blocking mode,
regardless of its previous state and whether this method succedes or
if it fails. Make sure to reset with `setBlocking(true)` if you want to
continue using blocking calls.
@param string $address either of IPv4:port, hostname:port, [IPv6]:port, unix-path
@param float $timeout maximum time to wait (in seconds)
@return self $this (chainable)
@throws Exception on error
@uses self::setBlocking() to enable non-blocking mode
@uses self::connect() to initiate the connection
@uses self::selectWrite() to wait for the connection to complete
@uses self::assertAlive() to check connection state | [
"Initiates",
"a",
"new",
"connection",
"to",
"given",
"address",
"wait",
"for",
"up",
"to",
"$timeout",
"seconds"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Socket.php#L134-L160 |
clue/php-socket-raw | src/Socket.php | Socket.getOption | public function getOption($level, $optname)
{
$value = @socket_get_option($this->resource, $level, $optname);
if ($value === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $value;
} | php | public function getOption($level, $optname)
{
$value = @socket_get_option($this->resource, $level, $optname);
if ($value === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $value;
} | [
"public",
"function",
"getOption",
"(",
"$",
"level",
",",
"$",
"optname",
")",
"{",
"$",
"value",
"=",
"@",
"socket_get_option",
"(",
"$",
"this",
"->",
"resource",
",",
"$",
"level",
",",
"$",
"optname",
")",
";",
"if",
"(",
"$",
"value",
"===",
... | get socket option
@param int $level
@param int $optname
@return mixed
@throws Exception on error
@uses socket_get_option() | [
"get",
"socket",
"option"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Socket.php#L171-L178 |
clue/php-socket-raw | src/Socket.php | Socket.getPeerName | public function getPeerName()
{
$ret = @socket_getpeername($this->resource, $address, $port);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $this->formatAddress($address, $port);
} | php | public function getPeerName()
{
$ret = @socket_getpeername($this->resource, $address, $port);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $this->formatAddress($address, $port);
} | [
"public",
"function",
"getPeerName",
"(",
")",
"{",
"$",
"ret",
"=",
"@",
"socket_getpeername",
"(",
"$",
"this",
"->",
"resource",
",",
"$",
"address",
",",
"$",
"port",
")",
";",
"if",
"(",
"$",
"ret",
"===",
"false",
")",
"{",
"throw",
"Exception"... | get remote side's address/path
@return string
@throws Exception on error
@uses socket_getpeername() | [
"get",
"remote",
"side",
"s",
"address",
"/",
"path"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Socket.php#L187-L194 |
clue/php-socket-raw | src/Socket.php | Socket.getSockName | public function getSockName()
{
$ret = @socket_getsockname($this->resource, $address, $port);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $this->formatAddress($address, $port);
} | php | public function getSockName()
{
$ret = @socket_getsockname($this->resource, $address, $port);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $this->formatAddress($address, $port);
} | [
"public",
"function",
"getSockName",
"(",
")",
"{",
"$",
"ret",
"=",
"@",
"socket_getsockname",
"(",
"$",
"this",
"->",
"resource",
",",
"$",
"address",
",",
"$",
"port",
")",
";",
"if",
"(",
"$",
"ret",
"===",
"false",
")",
"{",
"throw",
"Exception"... | get local side's address/path
@return string
@throws Exception on error
@uses socket_getsockname() | [
"get",
"local",
"side",
"s",
"address",
"/",
"path"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Socket.php#L203-L210 |
clue/php-socket-raw | src/Socket.php | Socket.listen | public function listen($backlog = 0)
{
$ret = @socket_listen($this->resource, $backlog);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $this;
} | php | public function listen($backlog = 0)
{
$ret = @socket_listen($this->resource, $backlog);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $this;
} | [
"public",
"function",
"listen",
"(",
"$",
"backlog",
"=",
"0",
")",
"{",
"$",
"ret",
"=",
"@",
"socket_listen",
"(",
"$",
"this",
"->",
"resource",
",",
"$",
"backlog",
")",
";",
"if",
"(",
"$",
"ret",
"===",
"false",
")",
"{",
"throw",
"Exception"... | start listen for incoming connections
@param int $backlog maximum number of incoming connections to be queued
@return self $this (chainable)
@throws Exception on error
@see self::bind() has to be called first to bind name to socket
@uses socket_listen() | [
"start",
"listen",
"for",
"incoming",
"connections"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Socket.php#L221-L228 |
clue/php-socket-raw | src/Socket.php | Socket.read | public function read($length, $type = PHP_BINARY_READ)
{
$data = @socket_read($this->resource, $length, $type);
if ($data === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $data;
} | php | public function read($length, $type = PHP_BINARY_READ)
{
$data = @socket_read($this->resource, $length, $type);
if ($data === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $data;
} | [
"public",
"function",
"read",
"(",
"$",
"length",
",",
"$",
"type",
"=",
"PHP_BINARY_READ",
")",
"{",
"$",
"data",
"=",
"@",
"socket_read",
"(",
"$",
"this",
"->",
"resource",
",",
"$",
"length",
",",
"$",
"type",
")",
";",
"if",
"(",
"$",
"data",
... | read up to $length bytes from connect()ed / accept()ed socket
The $type parameter specifies if this should use either binary safe reading
(PHP_BINARY_READ, the default) or stop at CR or LF characters (PHP_NORMAL_READ)
@param int $length maximum length to read
@param int $type either of PHP_BINARY_READ (the default) or PHP_NORMAL_READ
@return string
@throws Exception on error
@see self::recv() if you need to pass flags
@uses socket_read() | [
"read",
"up",
"to",
"$length",
"bytes",
"from",
"connect",
"()",
"ed",
"/",
"accept",
"()",
"ed",
"socket"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Socket.php#L243-L250 |
clue/php-socket-raw | src/Socket.php | Socket.recv | public function recv($length, $flags)
{
$ret = @socket_recv($this->resource, $buffer, $length, $flags);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $buffer;
} | php | public function recv($length, $flags)
{
$ret = @socket_recv($this->resource, $buffer, $length, $flags);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $buffer;
} | [
"public",
"function",
"recv",
"(",
"$",
"length",
",",
"$",
"flags",
")",
"{",
"$",
"ret",
"=",
"@",
"socket_recv",
"(",
"$",
"this",
"->",
"resource",
",",
"$",
"buffer",
",",
"$",
"length",
",",
"$",
"flags",
")",
";",
"if",
"(",
"$",
"ret",
... | receive up to $length bytes from connect()ed / accept()ed socket
@param int $length maximum length to read
@param int $flags
@return string
@throws Exception on error
@see self::read() if you do not need to pass $flags
@see self::recvFrom() if your socket is not connect()ed
@uses socket_recv() | [
"receive",
"up",
"to",
"$length",
"bytes",
"from",
"connect",
"()",
"ed",
"/",
"accept",
"()",
"ed",
"socket"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Socket.php#L263-L270 |
clue/php-socket-raw | src/Socket.php | Socket.recvFrom | public function recvFrom($length, $flags, &$remote)
{
$ret = @socket_recvfrom($this->resource, $buffer, $length, $flags, $address, $port);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
$remote = $this->formatAddress($address, $port);
return $buffer;
} | php | public function recvFrom($length, $flags, &$remote)
{
$ret = @socket_recvfrom($this->resource, $buffer, $length, $flags, $address, $port);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
$remote = $this->formatAddress($address, $port);
return $buffer;
} | [
"public",
"function",
"recvFrom",
"(",
"$",
"length",
",",
"$",
"flags",
",",
"&",
"$",
"remote",
")",
"{",
"$",
"ret",
"=",
"@",
"socket_recvfrom",
"(",
"$",
"this",
"->",
"resource",
",",
"$",
"buffer",
",",
"$",
"length",
",",
"$",
"flags",
",",... | receive up to $length bytes from socket
@param int $length maximum length to read
@param int $flags
@param string $remote reference will be filled with remote/peer address/path
@return string
@throws Exception on error
@see self::recv() if your socket is connect()ed
@uses socket_recvfrom() | [
"receive",
"up",
"to",
"$length",
"bytes",
"from",
"socket"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Socket.php#L283-L291 |
clue/php-socket-raw | src/Socket.php | Socket.selectRead | public function selectRead($sec = 0)
{
$usec = $sec === null ? null : (($sec - floor($sec)) * 1000000);
$r = array($this->resource);
$ret = @socket_select($r, $x, $x, $sec, $usec);
if ($ret === false) {
throw Exception::createFromGlobalSocketOperation('Failed to select socket for reading');
}
return !!$ret;
} | php | public function selectRead($sec = 0)
{
$usec = $sec === null ? null : (($sec - floor($sec)) * 1000000);
$r = array($this->resource);
$ret = @socket_select($r, $x, $x, $sec, $usec);
if ($ret === false) {
throw Exception::createFromGlobalSocketOperation('Failed to select socket for reading');
}
return !!$ret;
} | [
"public",
"function",
"selectRead",
"(",
"$",
"sec",
"=",
"0",
")",
"{",
"$",
"usec",
"=",
"$",
"sec",
"===",
"null",
"?",
"null",
":",
"(",
"(",
"$",
"sec",
"-",
"floor",
"(",
"$",
"sec",
")",
")",
"*",
"1000000",
")",
";",
"$",
"r",
"=",
... | check socket to see if a read/recv/revFrom will not block
@param float|NULL $sec maximum time to wait (in seconds), 0 = immediate polling, null = no limit
@return boolean true = socket ready (read will not block), false = timeout expired, socket is not ready
@throws Exception on error
@uses socket_select() | [
"check",
"socket",
"to",
"see",
"if",
"a",
"read",
"/",
"recv",
"/",
"revFrom",
"will",
"not",
"block"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Socket.php#L301-L310 |
clue/php-socket-raw | src/Socket.php | Socket.selectWrite | public function selectWrite($sec = 0)
{
$usec = $sec === null ? null : (($sec - floor($sec)) * 1000000);
$w = array($this->resource);
$ret = @socket_select($x, $w, $x, $sec, $usec);
if ($ret === false) {
throw Exception::createFromGlobalSocketOperation('Failed to select socket for writing');
}
return !!$ret;
} | php | public function selectWrite($sec = 0)
{
$usec = $sec === null ? null : (($sec - floor($sec)) * 1000000);
$w = array($this->resource);
$ret = @socket_select($x, $w, $x, $sec, $usec);
if ($ret === false) {
throw Exception::createFromGlobalSocketOperation('Failed to select socket for writing');
}
return !!$ret;
} | [
"public",
"function",
"selectWrite",
"(",
"$",
"sec",
"=",
"0",
")",
"{",
"$",
"usec",
"=",
"$",
"sec",
"===",
"null",
"?",
"null",
":",
"(",
"(",
"$",
"sec",
"-",
"floor",
"(",
"$",
"sec",
")",
")",
"*",
"1000000",
")",
";",
"$",
"w",
"=",
... | check socket to see if a write/send/sendTo will not block
@param float|NULL $sec maximum time to wait (in seconds), 0 = immediate polling, null = no limit
@return boolean true = socket ready (write will not block), false = timeout expired, socket is not ready
@throws Exception on error
@uses socket_select() | [
"check",
"socket",
"to",
"see",
"if",
"a",
"write",
"/",
"send",
"/",
"sendTo",
"will",
"not",
"block"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Socket.php#L320-L329 |
clue/php-socket-raw | src/Socket.php | Socket.send | public function send($buffer, $flags)
{
$ret = @socket_send($this->resource, $buffer, strlen($buffer), $flags);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $ret;
} | php | public function send($buffer, $flags)
{
$ret = @socket_send($this->resource, $buffer, strlen($buffer), $flags);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $ret;
} | [
"public",
"function",
"send",
"(",
"$",
"buffer",
",",
"$",
"flags",
")",
"{",
"$",
"ret",
"=",
"@",
"socket_send",
"(",
"$",
"this",
"->",
"resource",
",",
"$",
"buffer",
",",
"strlen",
"(",
"$",
"buffer",
")",
",",
"$",
"flags",
")",
";",
"if",... | send given $buffer to connect()ed / accept()ed socket
@param string $buffer
@param int $flags
@return int number of bytes actually written (make sure to check against given buffer length!)
@throws Exception on error
@see self::write() if you do not need to pass $flags
@see self::sendTo() if your socket is not connect()ed
@uses socket_send() | [
"send",
"given",
"$buffer",
"to",
"connect",
"()",
"ed",
"/",
"accept",
"()",
"ed",
"socket"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Socket.php#L342-L349 |
clue/php-socket-raw | src/Socket.php | Socket.sendTo | public function sendTo($buffer, $flags, $remote)
{
$ret = @socket_sendto($this->resource, $buffer, strlen($buffer), $flags, $this->unformatAddress($remote, $port), $port);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $ret;
} | php | public function sendTo($buffer, $flags, $remote)
{
$ret = @socket_sendto($this->resource, $buffer, strlen($buffer), $flags, $this->unformatAddress($remote, $port), $port);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $ret;
} | [
"public",
"function",
"sendTo",
"(",
"$",
"buffer",
",",
"$",
"flags",
",",
"$",
"remote",
")",
"{",
"$",
"ret",
"=",
"@",
"socket_sendto",
"(",
"$",
"this",
"->",
"resource",
",",
"$",
"buffer",
",",
"strlen",
"(",
"$",
"buffer",
")",
",",
"$",
... | send given $buffer to socket
@param string $buffer
@param int $flags
@param string $remote remote/peer address/path
@return int number of bytes actually written
@throws Exception on error
@see self::send() if your socket is connect()ed
@uses socket_sendto() | [
"send",
"given",
"$buffer",
"to",
"socket"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Socket.php#L362-L369 |
clue/php-socket-raw | src/Socket.php | Socket.setBlocking | public function setBlocking($toggle = true)
{
$ret = $toggle ? @socket_set_block($this->resource) : @socket_set_nonblock($this->resource);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $this;
} | php | public function setBlocking($toggle = true)
{
$ret = $toggle ? @socket_set_block($this->resource) : @socket_set_nonblock($this->resource);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $this;
} | [
"public",
"function",
"setBlocking",
"(",
"$",
"toggle",
"=",
"true",
")",
"{",
"$",
"ret",
"=",
"$",
"toggle",
"?",
"@",
"socket_set_block",
"(",
"$",
"this",
"->",
"resource",
")",
":",
"@",
"socket_set_nonblock",
"(",
"$",
"this",
"->",
"resource",
... | enable/disable blocking/nonblocking mode (O_NONBLOCK flag)
@param boolean $toggle
@return self $this (chainable)
@throws Exception on error
@uses socket_set_block()
@uses socket_set_nonblock() | [
"enable",
"/",
"disable",
"blocking",
"/",
"nonblocking",
"mode",
"(",
"O_NONBLOCK",
"flag",
")"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Socket.php#L380-L387 |
clue/php-socket-raw | src/Socket.php | Socket.setOption | public function setOption($level, $optname, $optval)
{
$ret = @socket_set_option($this->resource, $level, $optname, $optval);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $this;
} | php | public function setOption($level, $optname, $optval)
{
$ret = @socket_set_option($this->resource, $level, $optname, $optval);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $this;
} | [
"public",
"function",
"setOption",
"(",
"$",
"level",
",",
"$",
"optname",
",",
"$",
"optval",
")",
"{",
"$",
"ret",
"=",
"@",
"socket_set_option",
"(",
"$",
"this",
"->",
"resource",
",",
"$",
"level",
",",
"$",
"optname",
",",
"$",
"optval",
")",
... | set socket option
@param int $level
@param int $optname
@param mixed $optval
@return self $this (chainable)
@throws Exception on error
@see self::getOption()
@uses socket_set_option() | [
"set",
"socket",
"option"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Socket.php#L400-L407 |
clue/php-socket-raw | src/Socket.php | Socket.shutdown | public function shutdown($how = 2)
{
$ret = @socket_shutdown($this->resource, $how);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $this;
} | php | public function shutdown($how = 2)
{
$ret = @socket_shutdown($this->resource, $how);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $this;
} | [
"public",
"function",
"shutdown",
"(",
"$",
"how",
"=",
"2",
")",
"{",
"$",
"ret",
"=",
"@",
"socket_shutdown",
"(",
"$",
"this",
"->",
"resource",
",",
"$",
"how",
")",
";",
"if",
"(",
"$",
"ret",
"===",
"false",
")",
"{",
"throw",
"Exception",
... | shuts down socket for receiving, sending or both
@param int $how 0 = shutdown reading, 1 = shutdown writing, 2 = shutdown reading and writing
@return self $this (chainable)
@throws Exception on error
@see self::close()
@uses socket_shutdown() | [
"shuts",
"down",
"socket",
"for",
"receiving",
"sending",
"or",
"both"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Socket.php#L418-L425 |
clue/php-socket-raw | src/Socket.php | Socket.write | public function write($buffer)
{
$ret = @socket_write($this->resource, $buffer);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $ret;
} | php | public function write($buffer)
{
$ret = @socket_write($this->resource, $buffer);
if ($ret === false) {
throw Exception::createFromSocketResource($this->resource);
}
return $ret;
} | [
"public",
"function",
"write",
"(",
"$",
"buffer",
")",
"{",
"$",
"ret",
"=",
"@",
"socket_write",
"(",
"$",
"this",
"->",
"resource",
",",
"$",
"buffer",
")",
";",
"if",
"(",
"$",
"ret",
"===",
"false",
")",
"{",
"throw",
"Exception",
"::",
"creat... | write $buffer to connect()ed / accept()ed socket
@param string $buffer
@return int number of bytes actually written
@throws Exception on error
@see self::send() if you need to pass flags
@uses socket_write() | [
"write",
"$buffer",
"to",
"connect",
"()",
"ed",
"/",
"accept",
"()",
"ed",
"socket"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Socket.php#L436-L443 |
clue/php-socket-raw | src/Socket.php | Socket.assertAlive | public function assertAlive()
{
$code = $this->getOption(SOL_SOCKET, SO_ERROR);
if ($code !== 0) {
throw Exception::createFromCode($code, 'Socket error');
}
return $this;
} | php | public function assertAlive()
{
$code = $this->getOption(SOL_SOCKET, SO_ERROR);
if ($code !== 0) {
throw Exception::createFromCode($code, 'Socket error');
}
return $this;
} | [
"public",
"function",
"assertAlive",
"(",
")",
"{",
"$",
"code",
"=",
"$",
"this",
"->",
"getOption",
"(",
"SOL_SOCKET",
",",
"SO_ERROR",
")",
";",
"if",
"(",
"$",
"code",
"!==",
"0",
")",
"{",
"throw",
"Exception",
"::",
"createFromCode",
"(",
"$",
... | assert that this socket is alive and its error code is 0
This will fetch and reset the current socket error code from the
socket and options and will throw an Exception along with error
message and code if the code is not 0, i.e. if it does indicate
an error situation.
Calling this method should not be needed in most cases and is
likely to not throw an Exception. Each socket operation like
connect(), send(), etc. will throw a dedicated Exception in case
of an error anyway.
@return self $this (chainable)
@throws Exception if error code is not 0
@uses self::getOption() to retrieve and clear current error code
@uses self::getErrorMessage() to translate error code to | [
"assert",
"that",
"this",
"socket",
"is",
"alive",
"and",
"its",
"error",
"code",
"is",
"0"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Socket.php#L475-L482 |
clue/php-socket-raw | src/Socket.php | Socket.formatAddress | protected function formatAddress($address, $port)
{
if ($port !== 0) {
if (strpos($address, ':') !== false) {
$address = '[' . $address . ']';
}
$address .= ':' . $port;
}
return $address;
} | php | protected function formatAddress($address, $port)
{
if ($port !== 0) {
if (strpos($address, ':') !== false) {
$address = '[' . $address . ']';
}
$address .= ':' . $port;
}
return $address;
} | [
"protected",
"function",
"formatAddress",
"(",
"$",
"address",
",",
"$",
"port",
")",
"{",
"if",
"(",
"$",
"port",
"!==",
"0",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"address",
",",
"':'",
")",
"!==",
"false",
")",
"{",
"$",
"address",
"=",
"'[... | format given address/host/path and port
@param string $address
@param int $port
@return string | [
"format",
"given",
"address",
"/",
"host",
"/",
"path",
"and",
"port"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Socket.php#L491-L500 |
clue/php-socket-raw | src/Socket.php | Socket.unformatAddress | protected function unformatAddress($address, &$port)
{
// [::1]:2 => ::1 2
// test:2 => test 2
// ::1 => ::1
// test => test
$colon = strrpos($address, ':');
// there is a colon and this is the only colon or there's a closing IPv6 bracket right before it
if ($colon !== false && (strpos($address, ':') === $colon || strpos($address, ']') === ($colon - 1))) {
$port = (int)substr($address, $colon + 1);
$address = substr($address, 0, $colon);
// remove IPv6 square brackets
if (substr($address, 0, 1) === '[') {
$address = substr($address, 1, -1);
}
}
return $address;
} | php | protected function unformatAddress($address, &$port)
{
// [::1]:2 => ::1 2
// test:2 => test 2
// ::1 => ::1
// test => test
$colon = strrpos($address, ':');
// there is a colon and this is the only colon or there's a closing IPv6 bracket right before it
if ($colon !== false && (strpos($address, ':') === $colon || strpos($address, ']') === ($colon - 1))) {
$port = (int)substr($address, $colon + 1);
$address = substr($address, 0, $colon);
// remove IPv6 square brackets
if (substr($address, 0, 1) === '[') {
$address = substr($address, 1, -1);
}
}
return $address;
} | [
"protected",
"function",
"unformatAddress",
"(",
"$",
"address",
",",
"&",
"$",
"port",
")",
"{",
"// [::1]:2 => ::1 2",
"// test:2 => test 2",
"// ::1 => ::1",
"// test => test",
"$",
"colon",
"=",
"strrpos",
"(",
"$",
"address",
",",
"':'",
")",
";",
"// there... | format given address by splitting it into returned address and port set by reference
@param string $address
@param int $port
@return string address with port removed | [
"format",
"given",
"address",
"by",
"splitting",
"it",
"into",
"returned",
"address",
"and",
"port",
"set",
"by",
"reference"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Socket.php#L509-L529 |
clue/php-socket-raw | src/Factory.php | Factory.createClient | public function createClient($address, $timeout = null)
{
$socket = $this->createFromString($address, $scheme);
try {
if ($timeout === null) {
$socket->connect($address);
} else {
// connectTimeout enables non-blocking mode, so turn blocking on again
$socket->connectTimeout($address, $timeout);
$socket->setBlocking(true);
}
} catch (Exception $e) {
$socket->close();
throw $e;
}
return $socket;
} | php | public function createClient($address, $timeout = null)
{
$socket = $this->createFromString($address, $scheme);
try {
if ($timeout === null) {
$socket->connect($address);
} else {
// connectTimeout enables non-blocking mode, so turn blocking on again
$socket->connectTimeout($address, $timeout);
$socket->setBlocking(true);
}
} catch (Exception $e) {
$socket->close();
throw $e;
}
return $socket;
} | [
"public",
"function",
"createClient",
"(",
"$",
"address",
",",
"$",
"timeout",
"=",
"null",
")",
"{",
"$",
"socket",
"=",
"$",
"this",
"->",
"createFromString",
"(",
"$",
"address",
",",
"$",
"scheme",
")",
";",
"try",
"{",
"if",
"(",
"$",
"timeout"... | create client socket connected to given target address
@param string $address target address to connect to
@param null|float $timeout connection timeout (in seconds), default null = no limit
@return \Socket\Raw\Socket
@throws InvalidArgumentException if given address is invalid
@throws Exception on error
@uses self::createFromString()
@uses Socket::connect()
@uses Socket::connectTimeout() | [
"create",
"client",
"socket",
"connected",
"to",
"given",
"target",
"address"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Factory.php#L21-L39 |
clue/php-socket-raw | src/Factory.php | Factory.createServer | public function createServer($address)
{
$socket = $this->createFromString($address, $scheme);
try {
$socket->bind($address);
if ($socket->getType() === SOCK_STREAM) {
$socket->listen();
}
} catch (Exception $e) {
$socket->close();
throw $e;
}
return $socket;
} | php | public function createServer($address)
{
$socket = $this->createFromString($address, $scheme);
try {
$socket->bind($address);
if ($socket->getType() === SOCK_STREAM) {
$socket->listen();
}
} catch (Exception $e) {
$socket->close();
throw $e;
}
return $socket;
} | [
"public",
"function",
"createServer",
"(",
"$",
"address",
")",
"{",
"$",
"socket",
"=",
"$",
"this",
"->",
"createFromString",
"(",
"$",
"address",
",",
"$",
"scheme",
")",
";",
"try",
"{",
"$",
"socket",
"->",
"bind",
"(",
"$",
"address",
")",
";",... | create server socket bound to given address (and start listening for streaming clients to connect to this stream socket)
@param string $address address to bind socket to
@return \Socket\Raw\Socket
@throws Exception on error
@uses self::createFromString()
@uses Socket::bind()
@uses Socket::listen() only for stream sockets (TCP/UNIX) | [
"create",
"server",
"socket",
"bound",
"to",
"given",
"address",
"(",
"and",
"start",
"listening",
"for",
"streaming",
"clients",
"to",
"connect",
"to",
"this",
"stream",
"socket",
")"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Factory.php#L51-L67 |
clue/php-socket-raw | src/Factory.php | Factory.create | public function create($domain, $type, $protocol)
{
$sock = @socket_create($domain, $type, $protocol);
if ($sock === false) {
throw Exception::createFromGlobalSocketOperation('Unable to create socket');
}
return new Socket($sock);
} | php | public function create($domain, $type, $protocol)
{
$sock = @socket_create($domain, $type, $protocol);
if ($sock === false) {
throw Exception::createFromGlobalSocketOperation('Unable to create socket');
}
return new Socket($sock);
} | [
"public",
"function",
"create",
"(",
"$",
"domain",
",",
"$",
"type",
",",
"$",
"protocol",
")",
"{",
"$",
"sock",
"=",
"@",
"socket_create",
"(",
"$",
"domain",
",",
"$",
"type",
",",
"$",
"protocol",
")",
";",
"if",
"(",
"$",
"sock",
"===",
"fa... | create low level socket with given arguments
@param int $domain
@param int $type
@param int $protocol
@return \Socket\Raw\Socket
@throws Exception if creating socket fails
@uses socket_create() | [
"create",
"low",
"level",
"socket",
"with",
"given",
"arguments"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Factory.php#L175-L182 |
clue/php-socket-raw | src/Factory.php | Factory.createPair | public function createPair($domain, $type, $protocol)
{
$ret = @socket_create_pair($domain, $type, $protocol, $pair);
if ($ret === false) {
throw Exception::createFromGlobalSocketOperation('Unable to create pair of sockets');
}
return array(new Socket($pair[0]), new Socket($pair[1]));
} | php | public function createPair($domain, $type, $protocol)
{
$ret = @socket_create_pair($domain, $type, $protocol, $pair);
if ($ret === false) {
throw Exception::createFromGlobalSocketOperation('Unable to create pair of sockets');
}
return array(new Socket($pair[0]), new Socket($pair[1]));
} | [
"public",
"function",
"createPair",
"(",
"$",
"domain",
",",
"$",
"type",
",",
"$",
"protocol",
")",
"{",
"$",
"ret",
"=",
"@",
"socket_create_pair",
"(",
"$",
"domain",
",",
"$",
"type",
",",
"$",
"protocol",
",",
"$",
"pair",
")",
";",
"if",
"(",... | create a pair of indistinguishable sockets (commonly used in IPC)
@param int $domain
@param int $type
@param int $protocol
@return \Socket\Raw\Socket[]
@throws Exception if creating pair of sockets fails
@uses socket_create_pair() | [
"create",
"a",
"pair",
"of",
"indistinguishable",
"sockets",
"(",
"commonly",
"used",
"in",
"IPC",
")"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Factory.php#L194-L201 |
clue/php-socket-raw | src/Factory.php | Factory.createListen | public function createListen($port, $backlog = 128)
{
$sock = @socket_create_listen($port, $backlog);
if ($sock === false) {
throw Exception::createFromGlobalSocketOperation('Unable to create listening socket');
}
return new Socket($sock);
} | php | public function createListen($port, $backlog = 128)
{
$sock = @socket_create_listen($port, $backlog);
if ($sock === false) {
throw Exception::createFromGlobalSocketOperation('Unable to create listening socket');
}
return new Socket($sock);
} | [
"public",
"function",
"createListen",
"(",
"$",
"port",
",",
"$",
"backlog",
"=",
"128",
")",
"{",
"$",
"sock",
"=",
"@",
"socket_create_listen",
"(",
"$",
"port",
",",
"$",
"backlog",
")",
";",
"if",
"(",
"$",
"sock",
"===",
"false",
")",
"{",
"th... | create TCP/IPv4 stream socket and listen for new connections
@param int $port
@param int $backlog
@return \Socket\Raw\Socket
@throws Exception if creating listening socket fails
@uses socket_create_listen()
@see self::createServer() as an alternative to bind to specific IP, IPv6, UDP, UNIX, UGP | [
"create",
"TCP",
"/",
"IPv4",
"stream",
"socket",
"and",
"listen",
"for",
"new",
"connections"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Factory.php#L213-L220 |
clue/php-socket-raw | src/Factory.php | Factory.createFromString | public function createFromString(&$address, &$scheme)
{
if ($scheme === null) {
$scheme = 'tcp';
}
$hasScheme = false;
$pos = strpos($address, '://');
if ($pos !== false) {
$scheme = substr($address, 0, $pos);
$address = substr($address, $pos + 3);
$hasScheme = true;
}
if (strpos($address, ':') !== strrpos($address, ':') && in_array($scheme, array('tcp', 'udp', 'icmp'))) {
// TCP/UDP/ICMP address with several colons => must be IPv6
$scheme .= '6';
}
if ($scheme === 'tcp') {
$socket = $this->createTcp4();
} elseif ($scheme === 'udp') {
$socket = $this->createUdp4();
} elseif ($scheme === 'tcp6') {
$socket = $this->createTcp6();
} elseif ($scheme === 'udp6') {
$socket = $this->createUdp6();
} elseif ($scheme === 'unix') {
$socket = $this->createUnix();
} elseif ($scheme === 'udg') {
$socket = $this->createUdg();
} elseif ($scheme === 'icmp') {
$socket = $this->createIcmp4();
} elseif ($scheme === 'icmp6') {
$socket = $this->createIcmp6();
if ($hasScheme) {
// scheme was stripped from address, resulting IPv6 must not
// have a port (due to ICMP) and thus must not be enclosed in
// square brackets
$address = trim($address, '[]');
}
} else {
throw new InvalidArgumentException('Invalid address scheme given');
}
return $socket;
} | php | public function createFromString(&$address, &$scheme)
{
if ($scheme === null) {
$scheme = 'tcp';
}
$hasScheme = false;
$pos = strpos($address, '://');
if ($pos !== false) {
$scheme = substr($address, 0, $pos);
$address = substr($address, $pos + 3);
$hasScheme = true;
}
if (strpos($address, ':') !== strrpos($address, ':') && in_array($scheme, array('tcp', 'udp', 'icmp'))) {
// TCP/UDP/ICMP address with several colons => must be IPv6
$scheme .= '6';
}
if ($scheme === 'tcp') {
$socket = $this->createTcp4();
} elseif ($scheme === 'udp') {
$socket = $this->createUdp4();
} elseif ($scheme === 'tcp6') {
$socket = $this->createTcp6();
} elseif ($scheme === 'udp6') {
$socket = $this->createUdp6();
} elseif ($scheme === 'unix') {
$socket = $this->createUnix();
} elseif ($scheme === 'udg') {
$socket = $this->createUdg();
} elseif ($scheme === 'icmp') {
$socket = $this->createIcmp4();
} elseif ($scheme === 'icmp6') {
$socket = $this->createIcmp6();
if ($hasScheme) {
// scheme was stripped from address, resulting IPv6 must not
// have a port (due to ICMP) and thus must not be enclosed in
// square brackets
$address = trim($address, '[]');
}
} else {
throw new InvalidArgumentException('Invalid address scheme given');
}
return $socket;
} | [
"public",
"function",
"createFromString",
"(",
"&",
"$",
"address",
",",
"&",
"$",
"scheme",
")",
"{",
"if",
"(",
"$",
"scheme",
"===",
"null",
")",
"{",
"$",
"scheme",
"=",
"'tcp'",
";",
"}",
"$",
"hasScheme",
"=",
"false",
";",
"$",
"pos",
"=",
... | create socket for given address
@param string $address (passed by reference in order to remove scheme, if present)
@param string $scheme default scheme to use, defaults to TCP (passed by reference in order to update with actual scheme used)
@return \Socket\Raw\Socket
@throws InvalidArgumentException if given address is invalid
@throws Exception in case creating socket failed
@uses self::createTcp4() etc. | [
"create",
"socket",
"for",
"given",
"address"
] | train | https://github.com/clue/php-socket-raw/blob/2f6654445233407900c9a804490cecd8e4f2ae86/src/Factory.php#L232-L278 |
nicmart/Tree | src/Node/NodeTrait.php | NodeTrait.addChild | public function addChild(NodeInterface $child)
{
$child->setParent($this);
$this->children[] = $child;
return $this;
} | php | public function addChild(NodeInterface $child)
{
$child->setParent($this);
$this->children[] = $child;
return $this;
} | [
"public",
"function",
"addChild",
"(",
"NodeInterface",
"$",
"child",
")",
"{",
"$",
"child",
"->",
"setParent",
"(",
"$",
"this",
")",
";",
"$",
"this",
"->",
"children",
"[",
"]",
"=",
"$",
"child",
";",
"return",
"$",
"this",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/nicmart/Tree/blob/80a0b205e9556aaaf61664865bfe223465c5b406/src/Node/NodeTrait.php#L68-L74 |
nicmart/Tree | src/Node/NodeTrait.php | NodeTrait.removeChild | public function removeChild(NodeInterface $child)
{
foreach ($this->children as $key => $myChild) {
if ($child == $myChild) {
unset($this->children[$key]);
}
}
$this->children = array_values($this->children);
$child->setParent(null);
return $this;
} | php | public function removeChild(NodeInterface $child)
{
foreach ($this->children as $key => $myChild) {
if ($child == $myChild) {
unset($this->children[$key]);
}
}
$this->children = array_values($this->children);
$child->setParent(null);
return $this;
} | [
"public",
"function",
"removeChild",
"(",
"NodeInterface",
"$",
"child",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"children",
"as",
"$",
"key",
"=>",
"$",
"myChild",
")",
"{",
"if",
"(",
"$",
"child",
"==",
"$",
"myChild",
")",
"{",
"unset",
"(",... | {@inheritdoc} | [
"{"
] | train | https://github.com/nicmart/Tree/blob/80a0b205e9556aaaf61664865bfe223465c5b406/src/Node/NodeTrait.php#L79-L92 |
nicmart/Tree | src/Node/NodeTrait.php | NodeTrait.getAncestors | public function getAncestors()
{
$parents = [];
$node = $this;
while ($parent = $node->getParent()) {
array_unshift($parents, $parent);
$node = $parent;
}
return $parents;
} | php | public function getAncestors()
{
$parents = [];
$node = $this;
while ($parent = $node->getParent()) {
array_unshift($parents, $parent);
$node = $parent;
}
return $parents;
} | [
"public",
"function",
"getAncestors",
"(",
")",
"{",
"$",
"parents",
"=",
"[",
"]",
";",
"$",
"node",
"=",
"$",
"this",
";",
"while",
"(",
"$",
"parent",
"=",
"$",
"node",
"->",
"getParent",
"(",
")",
")",
"{",
"array_unshift",
"(",
"$",
"parents",... | {@inheritdoc} | [
"{"
] | train | https://github.com/nicmart/Tree/blob/80a0b205e9556aaaf61664865bfe223465c5b406/src/Node/NodeTrait.php#L146-L156 |
nicmart/Tree | src/Node/NodeTrait.php | NodeTrait.getNeighbors | public function getNeighbors()
{
$neighbors = $this->getParent()->getChildren();
$current = $this;
// Uses array_values to reset indexes after filter.
return array_values(
array_filter(
$neighbors,
function ($item) use ($current) {
return $item != $current;
}
)
);
} | php | public function getNeighbors()
{
$neighbors = $this->getParent()->getChildren();
$current = $this;
// Uses array_values to reset indexes after filter.
return array_values(
array_filter(
$neighbors,
function ($item) use ($current) {
return $item != $current;
}
)
);
} | [
"public",
"function",
"getNeighbors",
"(",
")",
"{",
"$",
"neighbors",
"=",
"$",
"this",
"->",
"getParent",
"(",
")",
"->",
"getChildren",
"(",
")",
";",
"$",
"current",
"=",
"$",
"this",
";",
"// Uses array_values to reset indexes after filter.",
"return",
"a... | {@inheritdoc} | [
"{"
] | train | https://github.com/nicmart/Tree/blob/80a0b205e9556aaaf61664865bfe223465c5b406/src/Node/NodeTrait.php#L169-L183 |
nicmart/Tree | src/Node/NodeTrait.php | NodeTrait.getHeight | public function getHeight()
{
if ($this->isLeaf()) {
return 0;
}
$heights = [];
foreach ($this->getChildren() as $child) {
$heights[] = $child->getHeight();
}
return max($heights) + 1;
} | php | public function getHeight()
{
if ($this->isLeaf()) {
return 0;
}
$heights = [];
foreach ($this->getChildren() as $child) {
$heights[] = $child->getHeight();
}
return max($heights) + 1;
} | [
"public",
"function",
"getHeight",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isLeaf",
"(",
")",
")",
"{",
"return",
"0",
";",
"}",
"$",
"heights",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getChildren",
"(",
")",
"as",
"$",
"c... | Return the height of the tree whose root is this node
@return int | [
"Return",
"the",
"height",
"of",
"the",
"tree",
"whose",
"root",
"is",
"this",
"node"
] | train | https://github.com/nicmart/Tree/blob/80a0b205e9556aaaf61664865bfe223465c5b406/src/Node/NodeTrait.php#L253-L266 |
nicmart/Tree | src/Node/NodeTrait.php | NodeTrait.getSize | public function getSize()
{
$size = 1;
foreach ($this->getChildren() as $child) {
$size += $child->getSize();
}
return $size;
} | php | public function getSize()
{
$size = 1;
foreach ($this->getChildren() as $child) {
$size += $child->getSize();
}
return $size;
} | [
"public",
"function",
"getSize",
"(",
")",
"{",
"$",
"size",
"=",
"1",
";",
"foreach",
"(",
"$",
"this",
"->",
"getChildren",
"(",
")",
"as",
"$",
"child",
")",
"{",
"$",
"size",
"+=",
"$",
"child",
"->",
"getSize",
"(",
")",
";",
"}",
"return",
... | Return the number of nodes in a tree
@return int | [
"Return",
"the",
"number",
"of",
"nodes",
"in",
"a",
"tree"
] | train | https://github.com/nicmart/Tree/blob/80a0b205e9556aaaf61664865bfe223465c5b406/src/Node/NodeTrait.php#L272-L280 |
nicmart/Tree | src/Builder/NodeBuilder.php | NodeBuilder.leaf | public function leaf($value = null)
{
$this->getNode()->addChild(
$this->nodeInstanceByValue($value)
);
return $this;
} | php | public function leaf($value = null)
{
$this->getNode()->addChild(
$this->nodeInstanceByValue($value)
);
return $this;
} | [
"public",
"function",
"leaf",
"(",
"$",
"value",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"getNode",
"(",
")",
"->",
"addChild",
"(",
"$",
"this",
"->",
"nodeInstanceByValue",
"(",
"$",
"value",
")",
")",
";",
"return",
"$",
"this",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/nicmart/Tree/blob/80a0b205e9556aaaf61664865bfe223465c5b406/src/Builder/NodeBuilder.php#L58-L65 |
nicmart/Tree | src/Builder/NodeBuilder.php | NodeBuilder.tree | public function tree($value = null)
{
$node = $this->nodeInstanceByValue($value);
$this->getNode()->addChild($node);
$this->pushNode($node);
return $this;
} | php | public function tree($value = null)
{
$node = $this->nodeInstanceByValue($value);
$this->getNode()->addChild($node);
$this->pushNode($node);
return $this;
} | [
"public",
"function",
"tree",
"(",
"$",
"value",
"=",
"null",
")",
"{",
"$",
"node",
"=",
"$",
"this",
"->",
"nodeInstanceByValue",
"(",
"$",
"value",
")",
";",
"$",
"this",
"->",
"getNode",
"(",
")",
"->",
"addChild",
"(",
"$",
"node",
")",
";",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/nicmart/Tree/blob/80a0b205e9556aaaf61664865bfe223465c5b406/src/Builder/NodeBuilder.php#L82-L89 |
nicmart/Tree | src/Visitor/YieldVisitor.php | YieldVisitor.visit | public function visit(NodeInterface $node)
{
if ($node->isLeaf()) {
return [$node];
}
$yield = [];
foreach ($node->getChildren() as $child) {
$yield = array_merge($yield, $child->accept($this));
}
return $yield;
} | php | public function visit(NodeInterface $node)
{
if ($node->isLeaf()) {
return [$node];
}
$yield = [];
foreach ($node->getChildren() as $child) {
$yield = array_merge($yield, $child->accept($this));
}
return $yield;
} | [
"public",
"function",
"visit",
"(",
"NodeInterface",
"$",
"node",
")",
"{",
"if",
"(",
"$",
"node",
"->",
"isLeaf",
"(",
")",
")",
"{",
"return",
"[",
"$",
"node",
"]",
";",
"}",
"$",
"yield",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"node",
"-... | {@inheritdoc} | [
"{"
] | train | https://github.com/nicmart/Tree/blob/80a0b205e9556aaaf61664865bfe223465c5b406/src/Visitor/YieldVisitor.php#L26-L39 |
laravel/cashier-braintree | src/Billable.php | Billable.charge | public function charge($amount, array $options = []): Successful
{
$response = BraintreeTransaction::sale(array_merge([
'amount' => number_format($amount * (1 + ($this->taxPercentage() / 100)), 2, '.', ''),
'paymentMethodToken' => $this->paymentMethod()->token,
'options' => [
'submitForSettlement' => true,
],
'recurring' => true,
], $options));
if (! $response->success) {
throw new Exception('Braintree was unable to perform a charge: '.$response->message);
}
return $response;
} | php | public function charge($amount, array $options = []): Successful
{
$response = BraintreeTransaction::sale(array_merge([
'amount' => number_format($amount * (1 + ($this->taxPercentage() / 100)), 2, '.', ''),
'paymentMethodToken' => $this->paymentMethod()->token,
'options' => [
'submitForSettlement' => true,
],
'recurring' => true,
], $options));
if (! $response->success) {
throw new Exception('Braintree was unable to perform a charge: '.$response->message);
}
return $response;
} | [
"public",
"function",
"charge",
"(",
"$",
"amount",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
":",
"Successful",
"{",
"$",
"response",
"=",
"BraintreeTransaction",
"::",
"sale",
"(",
"array_merge",
"(",
"[",
"'amount'",
"=>",
"number_format",
"(",
... | Make a "one off" charge on the customer for the given amount.
@param int $amount
@param array $options
@return \Braintree\Result\Successful
@throws \Exception | [
"Make",
"a",
"one",
"off",
"charge",
"on",
"the",
"customer",
"for",
"the",
"given",
"amount",
"."
] | train | https://github.com/laravel/cashier-braintree/blob/6d315e2715710ad226c9f9433b15bf9a83a53d8c/src/Billable.php#L30-L46 |
laravel/cashier-braintree | src/Billable.php | Billable.tab | public function tab($description, $amount, array $options = []): Successful
{
return $this->charge($amount, array_merge($options, [
'customFields' => [
'description' => $description,
],
]));
} | php | public function tab($description, $amount, array $options = []): Successful
{
return $this->charge($amount, array_merge($options, [
'customFields' => [
'description' => $description,
],
]));
} | [
"public",
"function",
"tab",
"(",
"$",
"description",
",",
"$",
"amount",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
":",
"Successful",
"{",
"return",
"$",
"this",
"->",
"charge",
"(",
"$",
"amount",
",",
"array_merge",
"(",
"$",
"options",
",... | Invoice the customer for the given amount.
@param string $description
@param int $amount
@param array $options
@return \Braintree\Result\Successful
@throws \Exception | [
"Invoice",
"the",
"customer",
"for",
"the",
"given",
"amount",
"."
] | train | https://github.com/laravel/cashier-braintree/blob/6d315e2715710ad226c9f9433b15bf9a83a53d8c/src/Billable.php#L57-L64 |
laravel/cashier-braintree | src/Billable.php | Billable.invoiceFor | public function invoiceFor($description, $amount, array $options = []): Successful
{
return $this->tab($description, $amount, $options);
} | php | public function invoiceFor($description, $amount, array $options = []): Successful
{
return $this->tab($description, $amount, $options);
} | [
"public",
"function",
"invoiceFor",
"(",
"$",
"description",
",",
"$",
"amount",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
":",
"Successful",
"{",
"return",
"$",
"this",
"->",
"tab",
"(",
"$",
"description",
",",
"$",
"amount",
",",
"$",
"opt... | Invoice the customer for the given amount (alias).
@param string $description
@param int $amount
@param array $options
@return \Braintree\Result\Successful
@throws \Exception | [
"Invoice",
"the",
"customer",
"for",
"the",
"given",
"amount",
"(",
"alias",
")",
"."
] | train | https://github.com/laravel/cashier-braintree/blob/6d315e2715710ad226c9f9433b15bf9a83a53d8c/src/Billable.php#L75-L78 |
laravel/cashier-braintree | src/Billable.php | Billable.findInvoice | public function findInvoice($id)
{
try {
$transaction = BraintreeTransaction::find($id);
if ($transaction->customerDetails->id != $this->braintree_id) {
return;
}
return new Invoice($this, $transaction);
} catch (Exception $e) {
//
}
} | php | public function findInvoice($id)
{
try {
$transaction = BraintreeTransaction::find($id);
if ($transaction->customerDetails->id != $this->braintree_id) {
return;
}
return new Invoice($this, $transaction);
} catch (Exception $e) {
//
}
} | [
"public",
"function",
"findInvoice",
"(",
"$",
"id",
")",
"{",
"try",
"{",
"$",
"transaction",
"=",
"BraintreeTransaction",
"::",
"find",
"(",
"$",
"id",
")",
";",
"if",
"(",
"$",
"transaction",
"->",
"customerDetails",
"->",
"id",
"!=",
"$",
"this",
"... | Find an invoice by ID.
@param string $id
@return \Laravel\Cashier\Invoice|null | [
"Find",
"an",
"invoice",
"by",
"ID",
"."
] | train | https://github.com/laravel/cashier-braintree/blob/6d315e2715710ad226c9f9433b15bf9a83a53d8c/src/Billable.php#L179-L192 |
laravel/cashier-braintree | src/Billable.php | Billable.invoices | public function invoices($includePending = false, $parameters = []): Collection
{
$invoices = [];
$customer = $this->asBraintreeCustomer();
$parameters = array_merge([
'id' => TransactionSearch::customerId()->is($customer->id),
'range' => TransactionSearch::createdAt()->between(
Carbon::today()->subYears(2)->format('m/d/Y H:i'),
Carbon::tomorrow()->format('m/d/Y H:i')
),
], $parameters);
$transactions = BraintreeTransaction::search($parameters);
// Here we will loop through the Braintree invoices and create our own custom Invoice
// instance that gets more helper methods and is generally more convenient to work
// work than the plain Braintree objects are. Then, we'll return the full array.
if (! is_null($transactions)) {
foreach ($transactions as $transaction) {
if ($transaction->status == BraintreeTransaction::SETTLED || $includePending) {
$invoices[] = new Invoice($this, $transaction);
}
}
}
return new Collection($invoices);
} | php | public function invoices($includePending = false, $parameters = []): Collection
{
$invoices = [];
$customer = $this->asBraintreeCustomer();
$parameters = array_merge([
'id' => TransactionSearch::customerId()->is($customer->id),
'range' => TransactionSearch::createdAt()->between(
Carbon::today()->subYears(2)->format('m/d/Y H:i'),
Carbon::tomorrow()->format('m/d/Y H:i')
),
], $parameters);
$transactions = BraintreeTransaction::search($parameters);
// Here we will loop through the Braintree invoices and create our own custom Invoice
// instance that gets more helper methods and is generally more convenient to work
// work than the plain Braintree objects are. Then, we'll return the full array.
if (! is_null($transactions)) {
foreach ($transactions as $transaction) {
if ($transaction->status == BraintreeTransaction::SETTLED || $includePending) {
$invoices[] = new Invoice($this, $transaction);
}
}
}
return new Collection($invoices);
} | [
"public",
"function",
"invoices",
"(",
"$",
"includePending",
"=",
"false",
",",
"$",
"parameters",
"=",
"[",
"]",
")",
":",
"Collection",
"{",
"$",
"invoices",
"=",
"[",
"]",
";",
"$",
"customer",
"=",
"$",
"this",
"->",
"asBraintreeCustomer",
"(",
")... | Get a collection of the entity's invoices.
@param bool $includePending
@param array $parameters
@return \Illuminate\Support\Collection
@throws \Braintree\Exception\NotFound | [
"Get",
"a",
"collection",
"of",
"the",
"entity",
"s",
"invoices",
"."
] | train | https://github.com/laravel/cashier-braintree/blob/6d315e2715710ad226c9f9433b15bf9a83a53d8c/src/Billable.php#L232-L260 |
laravel/cashier-braintree | src/Billable.php | Billable.updateCard | public function updateCard($token, array $options = [])
{
$customer = $this->asBraintreeCustomer();
$response = PaymentMethod::create(
array_replace_recursive([
'customerId' => $customer->id,
'paymentMethodNonce' => $token,
'options' => [
'makeDefault' => true,
'verifyCard' => true,
],
], $options)
);
if (! $response->success) {
throw new Exception('Braintree was unable to create a payment method: '.$response->message);
}
$paypalAccount = $response->paymentMethod instanceof PaypalAccount;
$this->forceFill([
'paypal_email' => $paypalAccount ? $response->paymentMethod->email : null,
'card_brand' => $paypalAccount ? null : $response->paymentMethod->cardType,
'card_last_four' => $paypalAccount ? null : $response->paymentMethod->last4,
])->save();
$this->updateSubscriptionsToPaymentMethod(
$response->paymentMethod->token
);
} | php | public function updateCard($token, array $options = [])
{
$customer = $this->asBraintreeCustomer();
$response = PaymentMethod::create(
array_replace_recursive([
'customerId' => $customer->id,
'paymentMethodNonce' => $token,
'options' => [
'makeDefault' => true,
'verifyCard' => true,
],
], $options)
);
if (! $response->success) {
throw new Exception('Braintree was unable to create a payment method: '.$response->message);
}
$paypalAccount = $response->paymentMethod instanceof PaypalAccount;
$this->forceFill([
'paypal_email' => $paypalAccount ? $response->paymentMethod->email : null,
'card_brand' => $paypalAccount ? null : $response->paymentMethod->cardType,
'card_last_four' => $paypalAccount ? null : $response->paymentMethod->last4,
])->save();
$this->updateSubscriptionsToPaymentMethod(
$response->paymentMethod->token
);
} | [
"public",
"function",
"updateCard",
"(",
"$",
"token",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"customer",
"=",
"$",
"this",
"->",
"asBraintreeCustomer",
"(",
")",
";",
"$",
"response",
"=",
"PaymentMethod",
"::",
"create",
"(",
"ar... | Update customer's credit card.
@param string $token
@param array $options
@return void
@throws \Exception | [
"Update",
"customer",
"s",
"credit",
"card",
"."
] | train | https://github.com/laravel/cashier-braintree/blob/6d315e2715710ad226c9f9433b15bf9a83a53d8c/src/Billable.php#L282-L312 |
laravel/cashier-braintree | src/Billable.php | Billable.updateSubscriptionsToPaymentMethod | protected function updateSubscriptionsToPaymentMethod($token)
{
foreach ($this->subscriptions as $subscription) {
if ($subscription->active()) {
BraintreeSubscription::update($subscription->braintree_id, [
'paymentMethodToken' => $token,
]);
}
}
} | php | protected function updateSubscriptionsToPaymentMethod($token)
{
foreach ($this->subscriptions as $subscription) {
if ($subscription->active()) {
BraintreeSubscription::update($subscription->braintree_id, [
'paymentMethodToken' => $token,
]);
}
}
} | [
"protected",
"function",
"updateSubscriptionsToPaymentMethod",
"(",
"$",
"token",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"subscriptions",
"as",
"$",
"subscription",
")",
"{",
"if",
"(",
"$",
"subscription",
"->",
"active",
"(",
")",
")",
"{",
"Braintre... | Update the payment method token for all of the model's subscriptions.
@param string $token
@return void | [
"Update",
"the",
"payment",
"method",
"token",
"for",
"all",
"of",
"the",
"model",
"s",
"subscriptions",
"."
] | train | https://github.com/laravel/cashier-braintree/blob/6d315e2715710ad226c9f9433b15bf9a83a53d8c/src/Billable.php#L320-L329 |
laravel/cashier-braintree | src/Billable.php | Billable.applyCoupon | public function applyCoupon($coupon, $subscription = 'default', $removeOthers = false)
{
$subscription = $this->subscription($subscription);
if (! $subscription) {
throw new InvalidArgumentException('Unable to apply coupon. Subscription does not exist.');
}
$subscription->applyCoupon($coupon, $removeOthers);
} | php | public function applyCoupon($coupon, $subscription = 'default', $removeOthers = false)
{
$subscription = $this->subscription($subscription);
if (! $subscription) {
throw new InvalidArgumentException('Unable to apply coupon. Subscription does not exist.');
}
$subscription->applyCoupon($coupon, $removeOthers);
} | [
"public",
"function",
"applyCoupon",
"(",
"$",
"coupon",
",",
"$",
"subscription",
"=",
"'default'",
",",
"$",
"removeOthers",
"=",
"false",
")",
"{",
"$",
"subscription",
"=",
"$",
"this",
"->",
"subscription",
"(",
"$",
"subscription",
")",
";",
"if",
... | Apply a coupon to the billable entity.
@param string $coupon
@param string $subscription
@param bool $removeOthers
@return void
@throws \InvalidArgumentException | [
"Apply",
"a",
"coupon",
"to",
"the",
"billable",
"entity",
"."
] | train | https://github.com/laravel/cashier-braintree/blob/6d315e2715710ad226c9f9433b15bf9a83a53d8c/src/Billable.php#L340-L349 |
laravel/cashier-braintree | src/Billable.php | Billable.paymentMethod | public function paymentMethod()
{
$customer = $this->asBraintreeCustomer();
foreach ($customer->paymentMethods as $paymentMethod) {
if ($paymentMethod->isDefault()) {
return $paymentMethod;
}
}
} | php | public function paymentMethod()
{
$customer = $this->asBraintreeCustomer();
foreach ($customer->paymentMethods as $paymentMethod) {
if ($paymentMethod->isDefault()) {
return $paymentMethod;
}
}
} | [
"public",
"function",
"paymentMethod",
"(",
")",
"{",
"$",
"customer",
"=",
"$",
"this",
"->",
"asBraintreeCustomer",
"(",
")",
";",
"foreach",
"(",
"$",
"customer",
"->",
"paymentMethods",
"as",
"$",
"paymentMethod",
")",
"{",
"if",
"(",
"$",
"paymentMeth... | Get the default payment method for the customer.
@return array
@throws \Braintree\Exception\NotFound | [
"Get",
"the",
"default",
"payment",
"method",
"for",
"the",
"customer",
"."
] | train | https://github.com/laravel/cashier-braintree/blob/6d315e2715710ad226c9f9433b15bf9a83a53d8c/src/Billable.php#L357-L366 |
laravel/cashier-braintree | src/Billable.php | Billable.subscribedToPlan | public function subscribedToPlan($plans, $subscription = 'default')
{
$subscription = $this->subscription($subscription);
if (! $subscription || ! $subscription->valid()) {
return false;
}
foreach ((array) $plans as $plan) {
if ($subscription->braintree_plan === $plan) {
return true;
}
}
return false;
} | php | public function subscribedToPlan($plans, $subscription = 'default')
{
$subscription = $this->subscription($subscription);
if (! $subscription || ! $subscription->valid()) {
return false;
}
foreach ((array) $plans as $plan) {
if ($subscription->braintree_plan === $plan) {
return true;
}
}
return false;
} | [
"public",
"function",
"subscribedToPlan",
"(",
"$",
"plans",
",",
"$",
"subscription",
"=",
"'default'",
")",
"{",
"$",
"subscription",
"=",
"$",
"this",
"->",
"subscription",
"(",
"$",
"subscription",
")",
";",
"if",
"(",
"!",
"$",
"subscription",
"||",
... | Determine if the model is actively subscribed to one of the given plans.
@param array|string $plans
@param string $subscription
@return bool | [
"Determine",
"if",
"the",
"model",
"is",
"actively",
"subscribed",
"to",
"one",
"of",
"the",
"given",
"plans",
"."
] | train | https://github.com/laravel/cashier-braintree/blob/6d315e2715710ad226c9f9433b15bf9a83a53d8c/src/Billable.php#L375-L390 |
laravel/cashier-braintree | src/Billable.php | Billable.onPlan | public function onPlan($plan)
{
return ! is_null($this->subscriptions->first(function ($value) use ($plan) {
return $value->braintree_plan === $plan;
}));
} | php | public function onPlan($plan)
{
return ! is_null($this->subscriptions->first(function ($value) use ($plan) {
return $value->braintree_plan === $plan;
}));
} | [
"public",
"function",
"onPlan",
"(",
"$",
"plan",
")",
"{",
"return",
"!",
"is_null",
"(",
"$",
"this",
"->",
"subscriptions",
"->",
"first",
"(",
"function",
"(",
"$",
"value",
")",
"use",
"(",
"$",
"plan",
")",
"{",
"return",
"$",
"value",
"->",
... | Determine if the entity is on the given plan.
@param string $plan
@return bool | [
"Determine",
"if",
"the",
"entity",
"is",
"on",
"the",
"given",
"plan",
"."
] | train | https://github.com/laravel/cashier-braintree/blob/6d315e2715710ad226c9f9433b15bf9a83a53d8c/src/Billable.php#L398-L403 |
laravel/cashier-braintree | src/Billable.php | Billable.createAsBraintreeCustomer | public function createAsBraintreeCustomer($token, array $options = []): Customer
{
$response = BraintreeCustomer::create(
array_replace_recursive([
'firstName' => Arr::get(explode(' ', $this->name), 0),
'lastName' => Arr::get(explode(' ', $this->name), 1),
'email' => $this->email,
'paymentMethodNonce' => $token,
'creditCard' => [
'options' => [
'verifyCard' => true,
],
],
], $options)
);
if (! $response->success) {
throw new Exception('Unable to create Braintree customer: '.$response->message);
}
$this->braintree_id = $response->customer->id;
$paymentMethod = $this->paymentMethod();
$paypalAccount = $paymentMethod instanceof PayPalAccount;
$this->forceFill([
'braintree_id' => $response->customer->id,
'paypal_email' => $paypalAccount ? $paymentMethod->email : null,
'card_brand' => ! $paypalAccount ? $paymentMethod->cardType : null,
'card_last_four' => ! $paypalAccount ? $paymentMethod->last4 : null,
])->save();
return $response->customer;
} | php | public function createAsBraintreeCustomer($token, array $options = []): Customer
{
$response = BraintreeCustomer::create(
array_replace_recursive([
'firstName' => Arr::get(explode(' ', $this->name), 0),
'lastName' => Arr::get(explode(' ', $this->name), 1),
'email' => $this->email,
'paymentMethodNonce' => $token,
'creditCard' => [
'options' => [
'verifyCard' => true,
],
],
], $options)
);
if (! $response->success) {
throw new Exception('Unable to create Braintree customer: '.$response->message);
}
$this->braintree_id = $response->customer->id;
$paymentMethod = $this->paymentMethod();
$paypalAccount = $paymentMethod instanceof PayPalAccount;
$this->forceFill([
'braintree_id' => $response->customer->id,
'paypal_email' => $paypalAccount ? $paymentMethod->email : null,
'card_brand' => ! $paypalAccount ? $paymentMethod->cardType : null,
'card_last_four' => ! $paypalAccount ? $paymentMethod->last4 : null,
])->save();
return $response->customer;
} | [
"public",
"function",
"createAsBraintreeCustomer",
"(",
"$",
"token",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
":",
"Customer",
"{",
"$",
"response",
"=",
"BraintreeCustomer",
"::",
"create",
"(",
"array_replace_recursive",
"(",
"[",
"'firstName'",
"=... | Create a Braintree customer for the given model.
@param string $token
@param array $options
@return \Braintree\Customer
@throws \Exception | [
"Create",
"a",
"Braintree",
"customer",
"for",
"the",
"given",
"model",
"."
] | train | https://github.com/laravel/cashier-braintree/blob/6d315e2715710ad226c9f9433b15bf9a83a53d8c/src/Billable.php#L413-L447 |
laravel/cashier-braintree | src/Invoice.php | Invoice.date | public function date($timezone = null): Carbon
{
$carbon = Carbon::instance($this->transaction->createdAt);
return $timezone ? $carbon->setTimezone($timezone) : $carbon;
} | php | public function date($timezone = null): Carbon
{
$carbon = Carbon::instance($this->transaction->createdAt);
return $timezone ? $carbon->setTimezone($timezone) : $carbon;
} | [
"public",
"function",
"date",
"(",
"$",
"timezone",
"=",
"null",
")",
":",
"Carbon",
"{",
"$",
"carbon",
"=",
"Carbon",
"::",
"instance",
"(",
"$",
"this",
"->",
"transaction",
"->",
"createdAt",
")",
";",
"return",
"$",
"timezone",
"?",
"$",
"carbon",... | Get a Carbon date for the invoice.
@param \DateTimeZone|string $timezone
@return \Carbon\Carbon | [
"Get",
"a",
"Carbon",
"date",
"for",
"the",
"invoice",
"."
] | train | https://github.com/laravel/cashier-braintree/blob/6d315e2715710ad226c9f9433b15bf9a83a53d8c/src/Invoice.php#L48-L53 |
laravel/cashier-braintree | src/Invoice.php | Invoice.addOnAmount | public function addOnAmount()
{
$totalAddOn = 0;
foreach ($this->transaction->addOns as $addOn) {
$totalAddOn += $addOn->amount * ($addOn->quantity ?? 1);
}
return (float) $totalAddOn;
} | php | public function addOnAmount()
{
$totalAddOn = 0;
foreach ($this->transaction->addOns as $addOn) {
$totalAddOn += $addOn->amount * ($addOn->quantity ?? 1);
}
return (float) $totalAddOn;
} | [
"public",
"function",
"addOnAmount",
"(",
")",
"{",
"$",
"totalAddOn",
"=",
"0",
";",
"foreach",
"(",
"$",
"this",
"->",
"transaction",
"->",
"addOns",
"as",
"$",
"addOn",
")",
"{",
"$",
"totalAddOn",
"+=",
"$",
"addOn",
"->",
"amount",
"*",
"(",
"$"... | Get the raw add-on amount.
@return float | [
"Get",
"the",
"raw",
"add",
"-",
"on",
"amount",
"."
] | train | https://github.com/laravel/cashier-braintree/blob/6d315e2715710ad226c9f9433b15bf9a83a53d8c/src/Invoice.php#L112-L121 |
laravel/cashier-braintree | src/Invoice.php | Invoice.addOns | public function addOns()
{
$addOns = [];
foreach ($this->transaction->addOns as $addOn) {
$addOns[] = $addOn->id;
}
return $addOns;
} | php | public function addOns()
{
$addOns = [];
foreach ($this->transaction->addOns as $addOn) {
$addOns[] = $addOn->id;
}
return $addOns;
} | [
"public",
"function",
"addOns",
"(",
")",
"{",
"$",
"addOns",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"transaction",
"->",
"addOns",
"as",
"$",
"addOn",
")",
"{",
"$",
"addOns",
"[",
"]",
"=",
"$",
"addOn",
"->",
"id",
";",
"}",
... | Get the add-on codes applied to the invoice.
@return array | [
"Get",
"the",
"add",
"-",
"on",
"codes",
"applied",
"to",
"the",
"invoice",
"."
] | train | https://github.com/laravel/cashier-braintree/blob/6d315e2715710ad226c9f9433b15bf9a83a53d8c/src/Invoice.php#L128-L137 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.