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 |
|---|---|---|---|---|---|---|---|---|---|---|
aidantwoods/SecureHeaders | src/Operations/CompileCSP.php | CompileCSP.mergeCSPList | public static function mergeCSPList(array $cspList)
{
$finalCSP = [];
foreach ($cspList as $csp)
{
foreach ($csp as $directive => $sources)
{
if ( ! isset($finalCSP[$directive]))
{
$finalCSP[$directive] = $sources;
continue;
}
elseif ($finalCSP[$directive] === true)
{
continue;
}
else
{
$finalCSP[$directive] = array_merge(
$finalCSP[$directive],
$sources
);
continue;
}
}
}
return $finalCSP;
} | php | public static function mergeCSPList(array $cspList)
{
$finalCSP = [];
foreach ($cspList as $csp)
{
foreach ($csp as $directive => $sources)
{
if ( ! isset($finalCSP[$directive]))
{
$finalCSP[$directive] = $sources;
continue;
}
elseif ($finalCSP[$directive] === true)
{
continue;
}
else
{
$finalCSP[$directive] = array_merge(
$finalCSP[$directive],
$sources
);
continue;
}
}
}
return $finalCSP;
} | [
"public",
"static",
"function",
"mergeCSPList",
"(",
"array",
"$",
"cspList",
")",
"{",
"$",
"finalCSP",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"cspList",
"as",
"$",
"csp",
")",
"{",
"foreach",
"(",
"$",
"csp",
"as",
"$",
"directive",
"=>",
"$",
"sources",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"finalCSP",
"[",
"$",
"directive",
"]",
")",
")",
"{",
"$",
"finalCSP",
"[",
"$",
"directive",
"]",
"=",
"$",
"sources",
";",
"continue",
";",
"}",
"elseif",
"(",
"$",
"finalCSP",
"[",
"$",
"directive",
"]",
"===",
"true",
")",
"{",
"continue",
";",
"}",
"else",
"{",
"$",
"finalCSP",
"[",
"$",
"directive",
"]",
"=",
"array_merge",
"(",
"$",
"finalCSP",
"[",
"$",
"directive",
"]",
",",
"$",
"sources",
")",
";",
"continue",
";",
"}",
"}",
"}",
"return",
"$",
"finalCSP",
";",
"}"
] | Merge a multiple CSP configs together into a single CSP
@param array $cspList
@return array | [
"Merge",
"a",
"multiple",
"CSP",
"configs",
"together",
"into",
"a",
"single",
"CSP"
] | train | https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Operations/CompileCSP.php#L235-L266 |
aidantwoods/SecureHeaders | src/ValidatorDelegates/CSPRODestination.php | CSPRODestination.validate | public static function validate(Header $header)
{
$errors = [];
if (
! $header->hasAttribute('report-uri')
or ! preg_match(
'/https:\/\/[a-z0-9\-]+[.][a-z]{2,}.*/i',
$header->getAttributeValue('report-uri')
)
) {
$friendlyHeader = $header->getFriendlyName();
$errors[] = new Error(
$friendlyHeader.' header was sent,
but an invalid, unsafe, or no reporting address was given.
This header will not enforce violations, and with no
reporting address specified, the browser can only
report them locally in its console. Consider adding
a reporting address to make full use of this header.'
);
}
return $errors;
} | php | public static function validate(Header $header)
{
$errors = [];
if (
! $header->hasAttribute('report-uri')
or ! preg_match(
'/https:\/\/[a-z0-9\-]+[.][a-z]{2,}.*/i',
$header->getAttributeValue('report-uri')
)
) {
$friendlyHeader = $header->getFriendlyName();
$errors[] = new Error(
$friendlyHeader.' header was sent,
but an invalid, unsafe, or no reporting address was given.
This header will not enforce violations, and with no
reporting address specified, the browser can only
report them locally in its console. Consider adding
a reporting address to make full use of this header.'
);
}
return $errors;
} | [
"public",
"static",
"function",
"validate",
"(",
"Header",
"$",
"header",
")",
"{",
"$",
"errors",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"$",
"header",
"->",
"hasAttribute",
"(",
"'report-uri'",
")",
"or",
"!",
"preg_match",
"(",
"'/https:\\/\\/[a-z0-9\\-]+[.][a-z]{2,}.*/i'",
",",
"$",
"header",
"->",
"getAttributeValue",
"(",
"'report-uri'",
")",
")",
")",
"{",
"$",
"friendlyHeader",
"=",
"$",
"header",
"->",
"getFriendlyName",
"(",
")",
";",
"$",
"errors",
"[",
"]",
"=",
"new",
"Error",
"(",
"$",
"friendlyHeader",
".",
"' header was sent,\n but an invalid, unsafe, or no reporting address was given.\n This header will not enforce violations, and with no\n reporting address specified, the browser can only\n report them locally in its console. Consider adding\n a reporting address to make full use of this header.'",
")",
";",
"}",
"return",
"$",
"errors",
";",
"}"
] | Validate the given header
@param Header $header
@return Error[] | [
"Validate",
"the",
"given",
"header"
] | train | https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/ValidatorDelegates/CSPRODestination.php#L18-L42 |
aidantwoods/SecureHeaders | src/Util/TypeError.php | TypeError.fromBacktrace | public static function fromBacktrace($argumentNum, $expectedType, $actualType, $bcIndex = 0)
{
$backtrace = debug_backtrace();
for ($i = $bcIndex; $i > 0; $i--)
{
if (isset($backtrace[$i]['file']))
{
break;
}
}
$caller = $backtrace[$i];
$typeError = new static(
"Argument $argumentNum passed to "
."${caller['class']}::${caller['function']}() must be of"
." the type $expectedType, $actualType given in "
."${caller['file']} on line ${caller['line']}"
);
throw $typeError;
} | php | public static function fromBacktrace($argumentNum, $expectedType, $actualType, $bcIndex = 0)
{
$backtrace = debug_backtrace();
for ($i = $bcIndex; $i > 0; $i--)
{
if (isset($backtrace[$i]['file']))
{
break;
}
}
$caller = $backtrace[$i];
$typeError = new static(
"Argument $argumentNum passed to "
."${caller['class']}::${caller['function']}() must be of"
." the type $expectedType, $actualType given in "
."${caller['file']} on line ${caller['line']}"
);
throw $typeError;
} | [
"public",
"static",
"function",
"fromBacktrace",
"(",
"$",
"argumentNum",
",",
"$",
"expectedType",
",",
"$",
"actualType",
",",
"$",
"bcIndex",
"=",
"0",
")",
"{",
"$",
"backtrace",
"=",
"debug_backtrace",
"(",
")",
";",
"for",
"(",
"$",
"i",
"=",
"$",
"bcIndex",
";",
"$",
"i",
">",
"0",
";",
"$",
"i",
"--",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"backtrace",
"[",
"$",
"i",
"]",
"[",
"'file'",
"]",
")",
")",
"{",
"break",
";",
"}",
"}",
"$",
"caller",
"=",
"$",
"backtrace",
"[",
"$",
"i",
"]",
";",
"$",
"typeError",
"=",
"new",
"static",
"(",
"\"Argument $argumentNum passed to \"",
".",
"\"${caller['class']}::${caller['function']}() must be of\"",
".",
"\" the type $expectedType, $actualType given in \"",
".",
"\"${caller['file']} on line ${caller['line']}\"",
")",
";",
"throw",
"$",
"typeError",
";",
"}"
] | Generate a TypeError with backtrace string, where $argumentNum
is the argument number in the errored function, $expectedType is the type
that was expected, and $actualType is the recieved type.
@param int $argumentNum
@param string $actualType
@param string $actualType
@param int $bcIndex = 0
@throws TypeError | [
"Generate",
"a",
"TypeError",
"with",
"backtrace",
"string",
"where",
"$argumentNum",
"is",
"the",
"argument",
"number",
"in",
"the",
"errored",
"function",
"$expectedType",
"is",
"the",
"type",
"that",
"was",
"expected",
"and",
"$actualType",
"is",
"the",
"recieved",
"type",
"."
] | train | https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Util/TypeError.php#L20-L41 |
aidantwoods/SecureHeaders | src/HeaderBag.php | HeaderBag.fromHeaderLines | public static function fromHeaderLines(array $lines)
{
$bag = new static;
foreach ($lines as $line)
{
preg_match('/^([^:]++)(?|(?:[:][ ]?+)(.*+)|())/', $line, $matches);
array_shift($matches);
list($name, $value) = $matches;
$bag->add($name, $value);
}
return $bag;
} | php | public static function fromHeaderLines(array $lines)
{
$bag = new static;
foreach ($lines as $line)
{
preg_match('/^([^:]++)(?|(?:[:][ ]?+)(.*+)|())/', $line, $matches);
array_shift($matches);
list($name, $value) = $matches;
$bag->add($name, $value);
}
return $bag;
} | [
"public",
"static",
"function",
"fromHeaderLines",
"(",
"array",
"$",
"lines",
")",
"{",
"$",
"bag",
"=",
"new",
"static",
";",
"foreach",
"(",
"$",
"lines",
"as",
"$",
"line",
")",
"{",
"preg_match",
"(",
"'/^([^:]++)(?|(?:[:][ ]?+)(.*+)|())/'",
",",
"$",
"line",
",",
"$",
"matches",
")",
";",
"array_shift",
"(",
"$",
"matches",
")",
";",
"list",
"(",
"$",
"name",
",",
"$",
"value",
")",
"=",
"$",
"matches",
";",
"$",
"bag",
"->",
"add",
"(",
"$",
"name",
",",
"$",
"value",
")",
";",
"}",
"return",
"$",
"bag",
";",
"}"
] | Create a HeaderBag from an array of header lines, $lines.
@api
@param string[] $lines
@return static | [
"Create",
"a",
"HeaderBag",
"from",
"an",
"array",
"of",
"header",
"lines",
"$lines",
"."
] | train | https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/HeaderBag.php#L36-L51 |
aidantwoods/SecureHeaders | src/HeaderBag.php | HeaderBag.has | public function has($name)
{
Types::assert(['string' => [$name]]);
return array_key_exists(strtolower($name), $this->headers);
} | php | public function has($name)
{
Types::assert(['string' => [$name]]);
return array_key_exists(strtolower($name), $this->headers);
} | [
"public",
"function",
"has",
"(",
"$",
"name",
")",
"{",
"Types",
"::",
"assert",
"(",
"[",
"'string'",
"=>",
"[",
"$",
"name",
"]",
"]",
")",
";",
"return",
"array_key_exists",
"(",
"strtolower",
"(",
"$",
"name",
")",
",",
"$",
"this",
"->",
"headers",
")",
";",
"}"
] | Determine whether the HeaderBag contains a header with $name,
case-insensitively.
@api
@param string $name
@return bool | [
"Determine",
"whether",
"the",
"HeaderBag",
"contains",
"a",
"header",
"with",
"$name",
"case",
"-",
"insensitively",
"."
] | train | https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/HeaderBag.php#L62-L67 |
aidantwoods/SecureHeaders | src/HeaderBag.php | HeaderBag.add | public function add($name, $value = '')
{
Types::assert(['string' => [$name, $value]]);
$key = strtolower($name);
if ( ! array_key_exists($key, $this->headers))
{
$this->headers[$key] = [];
}
$this->headers[$key][] = HeaderFactory::build($name, $value);
} | php | public function add($name, $value = '')
{
Types::assert(['string' => [$name, $value]]);
$key = strtolower($name);
if ( ! array_key_exists($key, $this->headers))
{
$this->headers[$key] = [];
}
$this->headers[$key][] = HeaderFactory::build($name, $value);
} | [
"public",
"function",
"add",
"(",
"$",
"name",
",",
"$",
"value",
"=",
"''",
")",
"{",
"Types",
"::",
"assert",
"(",
"[",
"'string'",
"=>",
"[",
"$",
"name",
",",
"$",
"value",
"]",
"]",
")",
";",
"$",
"key",
"=",
"strtolower",
"(",
"$",
"name",
")",
";",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"this",
"->",
"headers",
")",
")",
"{",
"$",
"this",
"->",
"headers",
"[",
"$",
"key",
"]",
"=",
"[",
"]",
";",
"}",
"$",
"this",
"->",
"headers",
"[",
"$",
"key",
"]",
"[",
"]",
"=",
"HeaderFactory",
"::",
"build",
"(",
"$",
"name",
",",
"$",
"value",
")",
";",
"}"
] | Add a header with $name and value $value
@api
@param string $name
@param string $value
@return void | [
"Add",
"a",
"header",
"with",
"$name",
"and",
"value",
"$value"
] | train | https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/HeaderBag.php#L78-L89 |
aidantwoods/SecureHeaders | src/HeaderBag.php | HeaderBag.replace | public function replace($name, $value = '')
{
Types::assert(['string' => [$name, $value]]);
$header = HeaderFactory::build($name, $value);
$this->headers[strtolower($name)] = [$header];
} | php | public function replace($name, $value = '')
{
Types::assert(['string' => [$name, $value]]);
$header = HeaderFactory::build($name, $value);
$this->headers[strtolower($name)] = [$header];
} | [
"public",
"function",
"replace",
"(",
"$",
"name",
",",
"$",
"value",
"=",
"''",
")",
"{",
"Types",
"::",
"assert",
"(",
"[",
"'string'",
"=>",
"[",
"$",
"name",
",",
"$",
"value",
"]",
"]",
")",
";",
"$",
"header",
"=",
"HeaderFactory",
"::",
"build",
"(",
"$",
"name",
",",
"$",
"value",
")",
";",
"$",
"this",
"->",
"headers",
"[",
"strtolower",
"(",
"$",
"name",
")",
"]",
"=",
"[",
"$",
"header",
"]",
";",
"}"
] | Add (in replace mode) a header with $name and value $value
@api
@param string $name
@param string $value
@return void | [
"Add",
"(",
"in",
"replace",
"mode",
")",
"a",
"header",
"with",
"$name",
"and",
"value",
"$value"
] | train | https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/HeaderBag.php#L100-L106 |
aidantwoods/SecureHeaders | src/HeaderBag.php | HeaderBag.getByName | public function getByName($name)
{
Types::assert(['string' => [$name]]);
$name = strtolower($name);
if ( ! array_key_exists($name, $this->headers))
{
return [];
}
return $this->headers[$name];
} | php | public function getByName($name)
{
Types::assert(['string' => [$name]]);
$name = strtolower($name);
if ( ! array_key_exists($name, $this->headers))
{
return [];
}
return $this->headers[$name];
} | [
"public",
"function",
"getByName",
"(",
"$",
"name",
")",
"{",
"Types",
"::",
"assert",
"(",
"[",
"'string'",
"=>",
"[",
"$",
"name",
"]",
"]",
")",
";",
"$",
"name",
"=",
"strtolower",
"(",
"$",
"name",
")",
";",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"name",
",",
"$",
"this",
"->",
"headers",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"return",
"$",
"this",
"->",
"headers",
"[",
"$",
"name",
"]",
";",
"}"
] | Get Headers from the HeaderBag with name, $name
@api
@param string $name
@return Header[] | [
"Get",
"Headers",
"from",
"the",
"HeaderBag",
"with",
"name",
"$name"
] | train | https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/HeaderBag.php#L162-L174 |
aidantwoods/SecureHeaders | src/HeaderBag.php | HeaderBag.forEachNamed | public function forEachNamed($name, callable $callable)
{
Types::assert(['string' => [$name]]);
$name = strtolower($name);
if (isset($this->headers[$name]))
{
foreach ($this->headers[$name] as $header)
{
$callable($header);
}
}
} | php | public function forEachNamed($name, callable $callable)
{
Types::assert(['string' => [$name]]);
$name = strtolower($name);
if (isset($this->headers[$name]))
{
foreach ($this->headers[$name] as $header)
{
$callable($header);
}
}
} | [
"public",
"function",
"forEachNamed",
"(",
"$",
"name",
",",
"callable",
"$",
"callable",
")",
"{",
"Types",
"::",
"assert",
"(",
"[",
"'string'",
"=>",
"[",
"$",
"name",
"]",
"]",
")",
";",
"$",
"name",
"=",
"strtolower",
"(",
"$",
"name",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"headers",
"[",
"$",
"name",
"]",
")",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"headers",
"[",
"$",
"name",
"]",
"as",
"$",
"header",
")",
"{",
"$",
"callable",
"(",
"$",
"header",
")",
";",
"}",
"}",
"}"
] | Let a header named $name be $header.
Apply $callable($header) to every header named $name.
@api
@param string $name
@param callable $callable
@return void | [
"Let",
"a",
"header",
"named",
"$name",
"be",
"$header",
".",
"Apply",
"$callable",
"(",
"$header",
")",
"to",
"every",
"header",
"named",
"$name",
"."
] | train | https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/HeaderBag.php#L186-L199 |
aidantwoods/SecureHeaders | src/Headers/AbstractHeader.php | AbstractHeader.is | public function is($name)
{
Types::assert(['string' => [$name]]);
return strtolower($name) === strtolower($this->name);
} | php | public function is($name)
{
Types::assert(['string' => [$name]]);
return strtolower($name) === strtolower($this->name);
} | [
"public",
"function",
"is",
"(",
"$",
"name",
")",
"{",
"Types",
"::",
"assert",
"(",
"[",
"'string'",
"=>",
"[",
"$",
"name",
"]",
"]",
")",
";",
"return",
"strtolower",
"(",
"$",
"name",
")",
"===",
"strtolower",
"(",
"$",
"this",
"->",
"name",
")",
";",
"}"
] | {@inheritDoc} | [
"{"
] | train | https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Headers/AbstractHeader.php#L52-L57 |
aidantwoods/SecureHeaders | src/Headers/AbstractHeader.php | AbstractHeader.getAttributeValue | public function getAttributeValue($name)
{
Types::assert(['string' => [$name]]);
if ( ! $this->hasAttribute($name))
{
throw new InvalidArgumentException(
"Attribute '$name' was not found"
);
}
return $this->attributes[strtolower($name)][0]['value'];
} | php | public function getAttributeValue($name)
{
Types::assert(['string' => [$name]]);
if ( ! $this->hasAttribute($name))
{
throw new InvalidArgumentException(
"Attribute '$name' was not found"
);
}
return $this->attributes[strtolower($name)][0]['value'];
} | [
"public",
"function",
"getAttributeValue",
"(",
"$",
"name",
")",
"{",
"Types",
"::",
"assert",
"(",
"[",
"'string'",
"=>",
"[",
"$",
"name",
"]",
"]",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"hasAttribute",
"(",
"$",
"name",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Attribute '$name' was not found\"",
")",
";",
"}",
"return",
"$",
"this",
"->",
"attributes",
"[",
"strtolower",
"(",
"$",
"name",
")",
"]",
"[",
"0",
"]",
"[",
"'value'",
"]",
";",
"}"
] | {@inheritDoc} | [
"{"
] | train | https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Headers/AbstractHeader.php#L90-L102 |
aidantwoods/SecureHeaders | src/Headers/AbstractHeader.php | AbstractHeader.hasAttribute | public function hasAttribute($name)
{
Types::assert(['string' => [$name]]);
$name = strtolower($name);
return array_key_exists($name, $this->attributes);
} | php | public function hasAttribute($name)
{
Types::assert(['string' => [$name]]);
$name = strtolower($name);
return array_key_exists($name, $this->attributes);
} | [
"public",
"function",
"hasAttribute",
"(",
"$",
"name",
")",
"{",
"Types",
"::",
"assert",
"(",
"[",
"'string'",
"=>",
"[",
"$",
"name",
"]",
"]",
")",
";",
"$",
"name",
"=",
"strtolower",
"(",
"$",
"name",
")",
";",
"return",
"array_key_exists",
"(",
"$",
"name",
",",
"$",
"this",
"->",
"attributes",
")",
";",
"}"
] | {@inheritDoc} | [
"{"
] | train | https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Headers/AbstractHeader.php#L107-L114 |
aidantwoods/SecureHeaders | src/Headers/AbstractHeader.php | AbstractHeader.removeAttribute | public function removeAttribute($name)
{
Types::assert(['string' => [$name]]);
$name = strtolower($name);
unset($this->attributes[$name]);
$this->writeAttributesToValue();
} | php | public function removeAttribute($name)
{
Types::assert(['string' => [$name]]);
$name = strtolower($name);
unset($this->attributes[$name]);
$this->writeAttributesToValue();
} | [
"public",
"function",
"removeAttribute",
"(",
"$",
"name",
")",
"{",
"Types",
"::",
"assert",
"(",
"[",
"'string'",
"=>",
"[",
"$",
"name",
"]",
"]",
")",
";",
"$",
"name",
"=",
"strtolower",
"(",
"$",
"name",
")",
";",
"unset",
"(",
"$",
"this",
"->",
"attributes",
"[",
"$",
"name",
"]",
")",
";",
"$",
"this",
"->",
"writeAttributesToValue",
"(",
")",
";",
"}"
] | {@inheritDoc} | [
"{"
] | train | https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Headers/AbstractHeader.php#L119-L127 |
aidantwoods/SecureHeaders | src/Headers/AbstractHeader.php | AbstractHeader.ensureAttributeMaximum | public function ensureAttributeMaximum($name, $maxValue)
{
Types::assert(['string' => [$name], 'int' => [$maxValue]]);
if (isset($this->attributes[$name]))
{
foreach ($this->attributes[$name] as &$attribute)
{
if (intval($attribute['value']) > $maxValue)
{
$attribute['value'] = $maxValue;
}
}
$this->writeAttributesToValue();
}
} | php | public function ensureAttributeMaximum($name, $maxValue)
{
Types::assert(['string' => [$name], 'int' => [$maxValue]]);
if (isset($this->attributes[$name]))
{
foreach ($this->attributes[$name] as &$attribute)
{
if (intval($attribute['value']) > $maxValue)
{
$attribute['value'] = $maxValue;
}
}
$this->writeAttributesToValue();
}
} | [
"public",
"function",
"ensureAttributeMaximum",
"(",
"$",
"name",
",",
"$",
"maxValue",
")",
"{",
"Types",
"::",
"assert",
"(",
"[",
"'string'",
"=>",
"[",
"$",
"name",
"]",
",",
"'int'",
"=>",
"[",
"$",
"maxValue",
"]",
"]",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"attributes",
"[",
"$",
"name",
"]",
")",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"attributes",
"[",
"$",
"name",
"]",
"as",
"&",
"$",
"attribute",
")",
"{",
"if",
"(",
"intval",
"(",
"$",
"attribute",
"[",
"'value'",
"]",
")",
">",
"$",
"maxValue",
")",
"{",
"$",
"attribute",
"[",
"'value'",
"]",
"=",
"$",
"maxValue",
";",
"}",
"}",
"$",
"this",
"->",
"writeAttributesToValue",
"(",
")",
";",
"}",
"}"
] | {@inheritDoc} | [
"{"
] | train | https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Headers/AbstractHeader.php#L132-L148 |
aidantwoods/SecureHeaders | src/Headers/AbstractHeader.php | AbstractHeader.forEachAttribute | public function forEachAttribute(callable $callable)
{
foreach ($this->attributes as $attributes)
{
foreach ($attributes as $attribute)
{
$callable($attribute['name'], $attribute['value']);
}
}
} | php | public function forEachAttribute(callable $callable)
{
foreach ($this->attributes as $attributes)
{
foreach ($attributes as $attribute)
{
$callable($attribute['name'], $attribute['value']);
}
}
} | [
"public",
"function",
"forEachAttribute",
"(",
"callable",
"$",
"callable",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"attributes",
"as",
"$",
"attributes",
")",
"{",
"foreach",
"(",
"$",
"attributes",
"as",
"$",
"attribute",
")",
"{",
"$",
"callable",
"(",
"$",
"attribute",
"[",
"'name'",
"]",
",",
"$",
"attribute",
"[",
"'value'",
"]",
")",
";",
"}",
"}",
"}"
] | {@inheritDoc} | [
"{"
] | train | https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Headers/AbstractHeader.php#L177-L186 |
aidantwoods/SecureHeaders | src/Headers/AbstractHeader.php | AbstractHeader.parseAttributes | protected function parseAttributes()
{
$parts = explode('; ', $this->value);
$this->attributes = [];
foreach ($parts as $part)
{
$attrParts = explode('=', $part, 2);
$type = strtolower($attrParts[0]);
if ( ! isset($this->attributes[$type]))
{
$this->attributes[$type] = [];
}
$this->attributes[$type][] = [
'name' => $attrParts[0],
'value' => isset($attrParts[1]) ? $attrParts[1] : true
];
}
} | php | protected function parseAttributes()
{
$parts = explode('; ', $this->value);
$this->attributes = [];
foreach ($parts as $part)
{
$attrParts = explode('=', $part, 2);
$type = strtolower($attrParts[0]);
if ( ! isset($this->attributes[$type]))
{
$this->attributes[$type] = [];
}
$this->attributes[$type][] = [
'name' => $attrParts[0],
'value' => isset($attrParts[1]) ? $attrParts[1] : true
];
}
} | [
"protected",
"function",
"parseAttributes",
"(",
")",
"{",
"$",
"parts",
"=",
"explode",
"(",
"'; '",
",",
"$",
"this",
"->",
"value",
")",
";",
"$",
"this",
"->",
"attributes",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"parts",
"as",
"$",
"part",
")",
"{",
"$",
"attrParts",
"=",
"explode",
"(",
"'='",
",",
"$",
"part",
",",
"2",
")",
";",
"$",
"type",
"=",
"strtolower",
"(",
"$",
"attrParts",
"[",
"0",
"]",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"attributes",
"[",
"$",
"type",
"]",
")",
")",
"{",
"$",
"this",
"->",
"attributes",
"[",
"$",
"type",
"]",
"=",
"[",
"]",
";",
"}",
"$",
"this",
"->",
"attributes",
"[",
"$",
"type",
"]",
"[",
"]",
"=",
"[",
"'name'",
"=>",
"$",
"attrParts",
"[",
"0",
"]",
",",
"'value'",
"=>",
"isset",
"(",
"$",
"attrParts",
"[",
"1",
"]",
")",
"?",
"$",
"attrParts",
"[",
"1",
"]",
":",
"true",
"]",
";",
"}",
"}"
] | Parse and store attributes from the internal header value
@return void | [
"Parse",
"and",
"store",
"attributes",
"from",
"the",
"internal",
"header",
"value"
] | train | https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Headers/AbstractHeader.php#L201-L223 |
aidantwoods/SecureHeaders | src/Headers/AbstractHeader.php | AbstractHeader.writeAttributesToValue | protected function writeAttributesToValue()
{
$attributeStrings = [];
foreach ($this->attributes as $attributes)
{
foreach ($attributes as $attrInfo)
{
$key = $attrInfo['name'];
$value = $attrInfo['value'];
if ($value === true)
{
$string = $key;
}
elseif ($value === false)
{
continue;
}
else
{
$string = "$key=$value";
}
$attributeStrings[] = $string;
}
}
$this->value = implode('; ', $attributeStrings);
} | php | protected function writeAttributesToValue()
{
$attributeStrings = [];
foreach ($this->attributes as $attributes)
{
foreach ($attributes as $attrInfo)
{
$key = $attrInfo['name'];
$value = $attrInfo['value'];
if ($value === true)
{
$string = $key;
}
elseif ($value === false)
{
continue;
}
else
{
$string = "$key=$value";
}
$attributeStrings[] = $string;
}
}
$this->value = implode('; ', $attributeStrings);
} | [
"protected",
"function",
"writeAttributesToValue",
"(",
")",
"{",
"$",
"attributeStrings",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"attributes",
"as",
"$",
"attributes",
")",
"{",
"foreach",
"(",
"$",
"attributes",
"as",
"$",
"attrInfo",
")",
"{",
"$",
"key",
"=",
"$",
"attrInfo",
"[",
"'name'",
"]",
";",
"$",
"value",
"=",
"$",
"attrInfo",
"[",
"'value'",
"]",
";",
"if",
"(",
"$",
"value",
"===",
"true",
")",
"{",
"$",
"string",
"=",
"$",
"key",
";",
"}",
"elseif",
"(",
"$",
"value",
"===",
"false",
")",
"{",
"continue",
";",
"}",
"else",
"{",
"$",
"string",
"=",
"\"$key=$value\"",
";",
"}",
"$",
"attributeStrings",
"[",
"]",
"=",
"$",
"string",
";",
"}",
"}",
"$",
"this",
"->",
"value",
"=",
"implode",
"(",
"'; '",
",",
"$",
"attributeStrings",
")",
";",
"}"
] | Write internal attributes to the internal header value
@return void | [
"Write",
"internal",
"attributes",
"to",
"the",
"internal",
"header",
"value"
] | train | https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Headers/AbstractHeader.php#L230-L259 |
aidantwoods/SecureHeaders | src/Operations/CompileHSTS.php | CompileHSTS.makeHeaderValue | private function makeHeaderValue()
{
$pieces = ['max-age=' . $this->config['max-age']];
if ($this->config['subdomains'])
{
$pieces[] = 'includeSubDomains';
}
if ($this->config['preload'])
{
$pieces[] = 'preload';
}
return implode('; ', $pieces);
} | php | private function makeHeaderValue()
{
$pieces = ['max-age=' . $this->config['max-age']];
if ($this->config['subdomains'])
{
$pieces[] = 'includeSubDomains';
}
if ($this->config['preload'])
{
$pieces[] = 'preload';
}
return implode('; ', $pieces);
} | [
"private",
"function",
"makeHeaderValue",
"(",
")",
"{",
"$",
"pieces",
"=",
"[",
"'max-age='",
".",
"$",
"this",
"->",
"config",
"[",
"'max-age'",
"]",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"config",
"[",
"'subdomains'",
"]",
")",
"{",
"$",
"pieces",
"[",
"]",
"=",
"'includeSubDomains'",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"config",
"[",
"'preload'",
"]",
")",
"{",
"$",
"pieces",
"[",
"]",
"=",
"'preload'",
";",
"}",
"return",
"implode",
"(",
"'; '",
",",
"$",
"pieces",
")",
";",
"}"
] | Make the HSTS header value
@return string | [
"Make",
"the",
"HSTS",
"header",
"value"
] | train | https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Operations/CompileHSTS.php#L42-L57 |
aidantwoods/SecureHeaders | src/Operations/InjectStrictDynamic.php | InjectStrictDynamic.modify | public function modify(HeaderBag &$HeaderBag)
{
$CSPHeaders = array_merge(
$this->mode & self::ENFORCE ?
$HeaderBag->getByName('content-security-policy') : [],
$this->mode & self::REPORT ?
$HeaderBag->getByName('content-security-policy-report-only') : []
);
foreach ($CSPHeaders as $Header)
{
$directive = $this->canInjectStrictDynamic($Header);
if (is_string($directive))
{
$Header->setAttribute($directive, "'strict-dynamic'");
}
elseif ($directive !== -1)
{
$this->addError(
"<b>Strict-Mode</b> is enabled, but
<b>'strict-dynamic'</b> could not be added to <b>"
. $Header->getFriendlyName()
. '</b> because no hash or nonce was used.',
E_USER_WARNING
);
}
}
} | php | public function modify(HeaderBag &$HeaderBag)
{
$CSPHeaders = array_merge(
$this->mode & self::ENFORCE ?
$HeaderBag->getByName('content-security-policy') : [],
$this->mode & self::REPORT ?
$HeaderBag->getByName('content-security-policy-report-only') : []
);
foreach ($CSPHeaders as $Header)
{
$directive = $this->canInjectStrictDynamic($Header);
if (is_string($directive))
{
$Header->setAttribute($directive, "'strict-dynamic'");
}
elseif ($directive !== -1)
{
$this->addError(
"<b>Strict-Mode</b> is enabled, but
<b>'strict-dynamic'</b> could not be added to <b>"
. $Header->getFriendlyName()
. '</b> because no hash or nonce was used.',
E_USER_WARNING
);
}
}
} | [
"public",
"function",
"modify",
"(",
"HeaderBag",
"&",
"$",
"HeaderBag",
")",
"{",
"$",
"CSPHeaders",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"mode",
"&",
"self",
"::",
"ENFORCE",
"?",
"$",
"HeaderBag",
"->",
"getByName",
"(",
"'content-security-policy'",
")",
":",
"[",
"]",
",",
"$",
"this",
"->",
"mode",
"&",
"self",
"::",
"REPORT",
"?",
"$",
"HeaderBag",
"->",
"getByName",
"(",
"'content-security-policy-report-only'",
")",
":",
"[",
"]",
")",
";",
"foreach",
"(",
"$",
"CSPHeaders",
"as",
"$",
"Header",
")",
"{",
"$",
"directive",
"=",
"$",
"this",
"->",
"canInjectStrictDynamic",
"(",
"$",
"Header",
")",
";",
"if",
"(",
"is_string",
"(",
"$",
"directive",
")",
")",
"{",
"$",
"Header",
"->",
"setAttribute",
"(",
"$",
"directive",
",",
"\"'strict-dynamic'\"",
")",
";",
"}",
"elseif",
"(",
"$",
"directive",
"!==",
"-",
"1",
")",
"{",
"$",
"this",
"->",
"addError",
"(",
"\"<b>Strict-Mode</b> is enabled, but\n <b>'strict-dynamic'</b> could not be added to <b>\"",
".",
"$",
"Header",
"->",
"getFriendlyName",
"(",
")",
".",
"'</b> because no hash or nonce was used.'",
",",
"E_USER_WARNING",
")",
";",
"}",
"}",
"}"
] | Transform the given set of headers
@param HeaderBag $HeaderBag
@return void | [
"Transform",
"the",
"given",
"set",
"of",
"headers"
] | train | https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Operations/InjectStrictDynamic.php#L40-L68 |
aidantwoods/SecureHeaders | src/Operations/InjectStrictDynamic.php | InjectStrictDynamic.canInjectStrictDynamic | private function canInjectStrictDynamic(Header $header)
{
# check if a relevant directive exists
if (
$header->hasAttribute($directive = 'script-src')
or $header->hasAttribute($directive = 'default-src')
) {
if (
preg_match(
"/(?:^|\s)(?:'strict-dynamic'|'none')(?:$|\s)/i",
$header->getAttributeValue($directive)
)
) {
return -1;
}
$nonceOrHashRe = implode(
'|',
array_map(
function ($s)
{
return preg_quote($s, '/');
},
array_merge(
['nonce'],
$this->allowedCSPHashAlgs
)
)
);
# if the directive contains a nonce or hash, return the directive
# that strict-dynamic should be injected into
$containsNonceOrHash = preg_match(
"/(?:^|\s)'(?:$nonceOrHashRe)-/i",
$header->getAttributeValue($directive)
);
if ($containsNonceOrHash)
{
return $directive;
}
}
return false;
} | php | private function canInjectStrictDynamic(Header $header)
{
# check if a relevant directive exists
if (
$header->hasAttribute($directive = 'script-src')
or $header->hasAttribute($directive = 'default-src')
) {
if (
preg_match(
"/(?:^|\s)(?:'strict-dynamic'|'none')(?:$|\s)/i",
$header->getAttributeValue($directive)
)
) {
return -1;
}
$nonceOrHashRe = implode(
'|',
array_map(
function ($s)
{
return preg_quote($s, '/');
},
array_merge(
['nonce'],
$this->allowedCSPHashAlgs
)
)
);
# if the directive contains a nonce or hash, return the directive
# that strict-dynamic should be injected into
$containsNonceOrHash = preg_match(
"/(?:^|\s)'(?:$nonceOrHashRe)-/i",
$header->getAttributeValue($directive)
);
if ($containsNonceOrHash)
{
return $directive;
}
}
return false;
} | [
"private",
"function",
"canInjectStrictDynamic",
"(",
"Header",
"$",
"header",
")",
"{",
"# check if a relevant directive exists",
"if",
"(",
"$",
"header",
"->",
"hasAttribute",
"(",
"$",
"directive",
"=",
"'script-src'",
")",
"or",
"$",
"header",
"->",
"hasAttribute",
"(",
"$",
"directive",
"=",
"'default-src'",
")",
")",
"{",
"if",
"(",
"preg_match",
"(",
"\"/(?:^|\\s)(?:'strict-dynamic'|'none')(?:$|\\s)/i\"",
",",
"$",
"header",
"->",
"getAttributeValue",
"(",
"$",
"directive",
")",
")",
")",
"{",
"return",
"-",
"1",
";",
"}",
"$",
"nonceOrHashRe",
"=",
"implode",
"(",
"'|'",
",",
"array_map",
"(",
"function",
"(",
"$",
"s",
")",
"{",
"return",
"preg_quote",
"(",
"$",
"s",
",",
"'/'",
")",
";",
"}",
",",
"array_merge",
"(",
"[",
"'nonce'",
"]",
",",
"$",
"this",
"->",
"allowedCSPHashAlgs",
")",
")",
")",
";",
"# if the directive contains a nonce or hash, return the directive",
"# that strict-dynamic should be injected into",
"$",
"containsNonceOrHash",
"=",
"preg_match",
"(",
"\"/(?:^|\\s)'(?:$nonceOrHashRe)-/i\"",
",",
"$",
"header",
"->",
"getAttributeValue",
"(",
"$",
"directive",
")",
")",
";",
"if",
"(",
"$",
"containsNonceOrHash",
")",
"{",
"return",
"$",
"directive",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Determine which directive `'strict-dynamic'` may be injected into, if
any.
If Safe-Mode conflicts, `-1` will be returned.
If `'strict-dynamic'` cannot be injected, `false` will be returned.
@return string|int|bool | [
"Determine",
"which",
"directive",
"strict",
"-",
"dynamic",
"may",
"be",
"injected",
"into",
"if",
"any",
".",
"If",
"Safe",
"-",
"Mode",
"conflicts",
"-",
"1",
"will",
"be",
"returned",
".",
"If",
"strict",
"-",
"dynamic",
"cannot",
"be",
"injected",
"false",
"will",
"be",
"returned",
"."
] | train | https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Operations/InjectStrictDynamic.php#L78-L122 |
aidantwoods/SecureHeaders | src/HeaderFactory.php | HeaderFactory.build | public static function build($name, $value = '')
{
Types::assert(['string' => [$name, $value]]);
$namespace = __NAMESPACE__.'\\Headers';
foreach (self::$memberClasses as $class => $headerNames)
{
$class = "$namespace\\$class";
if (in_array(strtolower($name), $headerNames, true))
{
return new $class($name, $value);
}
}
return new RegularHeader($name, $value);
} | php | public static function build($name, $value = '')
{
Types::assert(['string' => [$name, $value]]);
$namespace = __NAMESPACE__.'\\Headers';
foreach (self::$memberClasses as $class => $headerNames)
{
$class = "$namespace\\$class";
if (in_array(strtolower($name), $headerNames, true))
{
return new $class($name, $value);
}
}
return new RegularHeader($name, $value);
} | [
"public",
"static",
"function",
"build",
"(",
"$",
"name",
",",
"$",
"value",
"=",
"''",
")",
"{",
"Types",
"::",
"assert",
"(",
"[",
"'string'",
"=>",
"[",
"$",
"name",
",",
"$",
"value",
"]",
"]",
")",
";",
"$",
"namespace",
"=",
"__NAMESPACE__",
".",
"'\\\\Headers'",
";",
"foreach",
"(",
"self",
"::",
"$",
"memberClasses",
"as",
"$",
"class",
"=>",
"$",
"headerNames",
")",
"{",
"$",
"class",
"=",
"\"$namespace\\\\$class\"",
";",
"if",
"(",
"in_array",
"(",
"strtolower",
"(",
"$",
"name",
")",
",",
"$",
"headerNames",
",",
"true",
")",
")",
"{",
"return",
"new",
"$",
"class",
"(",
"$",
"name",
",",
"$",
"value",
")",
";",
"}",
"}",
"return",
"new",
"RegularHeader",
"(",
"$",
"name",
",",
"$",
"value",
")",
";",
"}"
] | Create a Header with name $name, and value $value
@param string $name
@param string $value | [
"Create",
"a",
"Header",
"with",
"name",
"$name",
"and",
"value",
"$value"
] | train | https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/HeaderFactory.php#L25-L42 |
KnpLabs/ConsoleServiceProvider | Knp/Provider/WebServerServiceProvider.php | WebServerServiceProvider.register | public function register(Container $container)
{
if (!isset($container['console'])) {
throw new \LogicException('You must register the ConsoleServiceProvider to use the WebServerServiceProvider.');
}
$container['web_server.document_root'] = null;
$container['web_server.environment'] = 'dev';
$commands = [
'server:run' => 'web_server.command.server_run',
'server:start' => 'web_server.command.server_start',
'server:stop' => 'web_server.command.server_stop',
'server:status' => 'web_server.command.server_status',
];
$container['web_server.command.server_run'] = function (Container $container) {
if (null === $docRoot = $container['web_server.document_root']) {
throw new \LogicException('You must set the web_server.document_root parameter to use the development web server.');
}
return new ServerRunCommand($docRoot, $container['web_server.environment']);
};
$container['web_server.command.server_start'] = function (Container $container) {
if (null === $docRoot = $container['web_server.document_root']) {
throw new \LogicException('You must set the web_server.document_root parameter to use the development web server.');
}
return new ServerStartCommand($docRoot, $container['web_server.environment']);
};
$container['web_server.command.server_stop'] = function () {
return new ServerStopCommand();
};
$container['web_server.command.server_status'] = function () {
return new ServerStatusCommand();
};
if (class_exists(ConsoleFormatter::class)) {
$container['web_server.command.server_log'] = function () {
return new ServerLogCommand();
};
$commands['server:log'] = 'web_server.command.server_log';
}
$container['console.command.ids'] = array_merge($container['console.command.ids'], $commands);
} | php | public function register(Container $container)
{
if (!isset($container['console'])) {
throw new \LogicException('You must register the ConsoleServiceProvider to use the WebServerServiceProvider.');
}
$container['web_server.document_root'] = null;
$container['web_server.environment'] = 'dev';
$commands = [
'server:run' => 'web_server.command.server_run',
'server:start' => 'web_server.command.server_start',
'server:stop' => 'web_server.command.server_stop',
'server:status' => 'web_server.command.server_status',
];
$container['web_server.command.server_run'] = function (Container $container) {
if (null === $docRoot = $container['web_server.document_root']) {
throw new \LogicException('You must set the web_server.document_root parameter to use the development web server.');
}
return new ServerRunCommand($docRoot, $container['web_server.environment']);
};
$container['web_server.command.server_start'] = function (Container $container) {
if (null === $docRoot = $container['web_server.document_root']) {
throw new \LogicException('You must set the web_server.document_root parameter to use the development web server.');
}
return new ServerStartCommand($docRoot, $container['web_server.environment']);
};
$container['web_server.command.server_stop'] = function () {
return new ServerStopCommand();
};
$container['web_server.command.server_status'] = function () {
return new ServerStatusCommand();
};
if (class_exists(ConsoleFormatter::class)) {
$container['web_server.command.server_log'] = function () {
return new ServerLogCommand();
};
$commands['server:log'] = 'web_server.command.server_log';
}
$container['console.command.ids'] = array_merge($container['console.command.ids'], $commands);
} | [
"public",
"function",
"register",
"(",
"Container",
"$",
"container",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"container",
"[",
"'console'",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"LogicException",
"(",
"'You must register the ConsoleServiceProvider to use the WebServerServiceProvider.'",
")",
";",
"}",
"$",
"container",
"[",
"'web_server.document_root'",
"]",
"=",
"null",
";",
"$",
"container",
"[",
"'web_server.environment'",
"]",
"=",
"'dev'",
";",
"$",
"commands",
"=",
"[",
"'server:run'",
"=>",
"'web_server.command.server_run'",
",",
"'server:start'",
"=>",
"'web_server.command.server_start'",
",",
"'server:stop'",
"=>",
"'web_server.command.server_stop'",
",",
"'server:status'",
"=>",
"'web_server.command.server_status'",
",",
"]",
";",
"$",
"container",
"[",
"'web_server.command.server_run'",
"]",
"=",
"function",
"(",
"Container",
"$",
"container",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"docRoot",
"=",
"$",
"container",
"[",
"'web_server.document_root'",
"]",
")",
"{",
"throw",
"new",
"\\",
"LogicException",
"(",
"'You must set the web_server.document_root parameter to use the development web server.'",
")",
";",
"}",
"return",
"new",
"ServerRunCommand",
"(",
"$",
"docRoot",
",",
"$",
"container",
"[",
"'web_server.environment'",
"]",
")",
";",
"}",
";",
"$",
"container",
"[",
"'web_server.command.server_start'",
"]",
"=",
"function",
"(",
"Container",
"$",
"container",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"docRoot",
"=",
"$",
"container",
"[",
"'web_server.document_root'",
"]",
")",
"{",
"throw",
"new",
"\\",
"LogicException",
"(",
"'You must set the web_server.document_root parameter to use the development web server.'",
")",
";",
"}",
"return",
"new",
"ServerStartCommand",
"(",
"$",
"docRoot",
",",
"$",
"container",
"[",
"'web_server.environment'",
"]",
")",
";",
"}",
";",
"$",
"container",
"[",
"'web_server.command.server_stop'",
"]",
"=",
"function",
"(",
")",
"{",
"return",
"new",
"ServerStopCommand",
"(",
")",
";",
"}",
";",
"$",
"container",
"[",
"'web_server.command.server_status'",
"]",
"=",
"function",
"(",
")",
"{",
"return",
"new",
"ServerStatusCommand",
"(",
")",
";",
"}",
";",
"if",
"(",
"class_exists",
"(",
"ConsoleFormatter",
"::",
"class",
")",
")",
"{",
"$",
"container",
"[",
"'web_server.command.server_log'",
"]",
"=",
"function",
"(",
")",
"{",
"return",
"new",
"ServerLogCommand",
"(",
")",
";",
"}",
";",
"$",
"commands",
"[",
"'server:log'",
"]",
"=",
"'web_server.command.server_log'",
";",
"}",
"$",
"container",
"[",
"'console.command.ids'",
"]",
"=",
"array_merge",
"(",
"$",
"container",
"[",
"'console.command.ids'",
"]",
",",
"$",
"commands",
")",
";",
"}"
] | Registers the web server console commands.
@param Container $container | [
"Registers",
"the",
"web",
"server",
"console",
"commands",
"."
] | train | https://github.com/KnpLabs/ConsoleServiceProvider/blob/3f08c7337513a4027086de9324475056ad9e1416/Knp/Provider/WebServerServiceProvider.php#L24-L72 |
KnpLabs/ConsoleServiceProvider | Knp/Console/Application.php | Application.doRun | public function doRun(InputInterface $input, OutputInterface $output)
{
$this->getSilexApplication()->boot();
return parent::doRun($input, $output);
} | php | public function doRun(InputInterface $input, OutputInterface $output)
{
$this->getSilexApplication()->boot();
return parent::doRun($input, $output);
} | [
"public",
"function",
"doRun",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"this",
"->",
"getSilexApplication",
"(",
")",
"->",
"boot",
"(",
")",
";",
"return",
"parent",
"::",
"doRun",
"(",
"$",
"input",
",",
"$",
"output",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/KnpLabs/ConsoleServiceProvider/blob/3f08c7337513a4027086de9324475056ad9e1416/Knp/Console/Application.php#L62-L67 |
KnpLabs/ConsoleServiceProvider | Knp/Command/Twig/LintCommand.php | LintCommand.getTwigEnvironment | protected function getTwigEnvironment()
{
if (null === $twig = parent::getTwigEnvironment()) {
$this->setTwigEnvironment($twig = $this->container['twig']);
}
return $twig;
} | php | protected function getTwigEnvironment()
{
if (null === $twig = parent::getTwigEnvironment()) {
$this->setTwigEnvironment($twig = $this->container['twig']);
}
return $twig;
} | [
"protected",
"function",
"getTwigEnvironment",
"(",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"twig",
"=",
"parent",
"::",
"getTwigEnvironment",
"(",
")",
")",
"{",
"$",
"this",
"->",
"setTwigEnvironment",
"(",
"$",
"twig",
"=",
"$",
"this",
"->",
"container",
"[",
"'twig'",
"]",
")",
";",
"}",
"return",
"$",
"twig",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/KnpLabs/ConsoleServiceProvider/blob/3f08c7337513a4027086de9324475056ad9e1416/Knp/Command/Twig/LintCommand.php#L33-L40 |
KnpLabs/ConsoleServiceProvider | Knp/Provider/ConsoleServiceProvider.php | ConsoleServiceProvider.register | public function register(Container $app)
{
$app['console.name'] = 'Silex console';
$app['console.version'] = 'UNKNOWN';
// Assume we are in vendor/knplabs/console-service-provider/Knp/Provider
$app['console.project_directory'] = __DIR__.'/../../../../..';
$app['console.class'] = ConsoleApplication::class;
// List of command service ids indexed by command name (i.e: array('my:command' => 'my.command.service.id'))
$app['console.command.ids'] = [];
// Maintain BC with projects that depend on the old behavior (application gets booted from console constructor)
$app['console.boot_in_constructor'] = false;
$app['console'] = function () use ($app) {
/** @var ConsoleApplication $console */
$console = new $app['console.class'](
$app,
$app['console.project_directory'],
$app['console.name'],
$app['console.version']
);
$console->setDispatcher($app['dispatcher']);
foreach ($app['console.command.ids'] as $id) {
$console->add($app[$id]);
}
if ($app['dispatcher']->hasListeners(ConsoleEvents::INIT)) {
@trigger_error('Listening to the Knp\Console\ConsoleEvents::INIT event is deprecated and will be removed in v3 of the service provider. You should extend the console service instead.', E_USER_DEPRECATED);
$app['dispatcher']->dispatch(ConsoleEvents::INIT, new ConsoleEvent($console));
}
return $console;
};
$commands = [];
if (isset($app['twig']) && class_exists(TwigBridgeDebugCommand::class)) {
$app['console.command.twig.debug'] = function (Container $container) {
return new DebugCommand($container);
};
$app['console.command.twig.lint'] = function (Container $container) {
return new LintCommand($container);
};
$commands['debug:twig'] = 'console.command.twig.debug';
$commands['lint:twig'] = 'console.command.twig.lint';
}
if (class_exists(LintYamlCommand::class)) {
$app['console.command.yaml.lint'] = function () {
return new LintYamlCommand();
};
$commands['lint:yaml'] = 'console.command.yaml.lint';
}
$app['console.command.ids'] = $commands;
} | php | public function register(Container $app)
{
$app['console.name'] = 'Silex console';
$app['console.version'] = 'UNKNOWN';
// Assume we are in vendor/knplabs/console-service-provider/Knp/Provider
$app['console.project_directory'] = __DIR__.'/../../../../..';
$app['console.class'] = ConsoleApplication::class;
// List of command service ids indexed by command name (i.e: array('my:command' => 'my.command.service.id'))
$app['console.command.ids'] = [];
// Maintain BC with projects that depend on the old behavior (application gets booted from console constructor)
$app['console.boot_in_constructor'] = false;
$app['console'] = function () use ($app) {
/** @var ConsoleApplication $console */
$console = new $app['console.class'](
$app,
$app['console.project_directory'],
$app['console.name'],
$app['console.version']
);
$console->setDispatcher($app['dispatcher']);
foreach ($app['console.command.ids'] as $id) {
$console->add($app[$id]);
}
if ($app['dispatcher']->hasListeners(ConsoleEvents::INIT)) {
@trigger_error('Listening to the Knp\Console\ConsoleEvents::INIT event is deprecated and will be removed in v3 of the service provider. You should extend the console service instead.', E_USER_DEPRECATED);
$app['dispatcher']->dispatch(ConsoleEvents::INIT, new ConsoleEvent($console));
}
return $console;
};
$commands = [];
if (isset($app['twig']) && class_exists(TwigBridgeDebugCommand::class)) {
$app['console.command.twig.debug'] = function (Container $container) {
return new DebugCommand($container);
};
$app['console.command.twig.lint'] = function (Container $container) {
return new LintCommand($container);
};
$commands['debug:twig'] = 'console.command.twig.debug';
$commands['lint:twig'] = 'console.command.twig.lint';
}
if (class_exists(LintYamlCommand::class)) {
$app['console.command.yaml.lint'] = function () {
return new LintYamlCommand();
};
$commands['lint:yaml'] = 'console.command.yaml.lint';
}
$app['console.command.ids'] = $commands;
} | [
"public",
"function",
"register",
"(",
"Container",
"$",
"app",
")",
"{",
"$",
"app",
"[",
"'console.name'",
"]",
"=",
"'Silex console'",
";",
"$",
"app",
"[",
"'console.version'",
"]",
"=",
"'UNKNOWN'",
";",
"// Assume we are in vendor/knplabs/console-service-provider/Knp/Provider",
"$",
"app",
"[",
"'console.project_directory'",
"]",
"=",
"__DIR__",
".",
"'/../../../../..'",
";",
"$",
"app",
"[",
"'console.class'",
"]",
"=",
"ConsoleApplication",
"::",
"class",
";",
"// List of command service ids indexed by command name (i.e: array('my:command' => 'my.command.service.id'))",
"$",
"app",
"[",
"'console.command.ids'",
"]",
"=",
"[",
"]",
";",
"// Maintain BC with projects that depend on the old behavior (application gets booted from console constructor)",
"$",
"app",
"[",
"'console.boot_in_constructor'",
"]",
"=",
"false",
";",
"$",
"app",
"[",
"'console'",
"]",
"=",
"function",
"(",
")",
"use",
"(",
"$",
"app",
")",
"{",
"/** @var ConsoleApplication $console */",
"$",
"console",
"=",
"new",
"$",
"app",
"[",
"'console.class'",
"]",
"(",
"$",
"app",
",",
"$",
"app",
"[",
"'console.project_directory'",
"]",
",",
"$",
"app",
"[",
"'console.name'",
"]",
",",
"$",
"app",
"[",
"'console.version'",
"]",
")",
";",
"$",
"console",
"->",
"setDispatcher",
"(",
"$",
"app",
"[",
"'dispatcher'",
"]",
")",
";",
"foreach",
"(",
"$",
"app",
"[",
"'console.command.ids'",
"]",
"as",
"$",
"id",
")",
"{",
"$",
"console",
"->",
"add",
"(",
"$",
"app",
"[",
"$",
"id",
"]",
")",
";",
"}",
"if",
"(",
"$",
"app",
"[",
"'dispatcher'",
"]",
"->",
"hasListeners",
"(",
"ConsoleEvents",
"::",
"INIT",
")",
")",
"{",
"@",
"trigger_error",
"(",
"'Listening to the Knp\\Console\\ConsoleEvents::INIT event is deprecated and will be removed in v3 of the service provider. You should extend the console service instead.'",
",",
"E_USER_DEPRECATED",
")",
";",
"$",
"app",
"[",
"'dispatcher'",
"]",
"->",
"dispatch",
"(",
"ConsoleEvents",
"::",
"INIT",
",",
"new",
"ConsoleEvent",
"(",
"$",
"console",
")",
")",
";",
"}",
"return",
"$",
"console",
";",
"}",
";",
"$",
"commands",
"=",
"[",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"app",
"[",
"'twig'",
"]",
")",
"&&",
"class_exists",
"(",
"TwigBridgeDebugCommand",
"::",
"class",
")",
")",
"{",
"$",
"app",
"[",
"'console.command.twig.debug'",
"]",
"=",
"function",
"(",
"Container",
"$",
"container",
")",
"{",
"return",
"new",
"DebugCommand",
"(",
"$",
"container",
")",
";",
"}",
";",
"$",
"app",
"[",
"'console.command.twig.lint'",
"]",
"=",
"function",
"(",
"Container",
"$",
"container",
")",
"{",
"return",
"new",
"LintCommand",
"(",
"$",
"container",
")",
";",
"}",
";",
"$",
"commands",
"[",
"'debug:twig'",
"]",
"=",
"'console.command.twig.debug'",
";",
"$",
"commands",
"[",
"'lint:twig'",
"]",
"=",
"'console.command.twig.lint'",
";",
"}",
"if",
"(",
"class_exists",
"(",
"LintYamlCommand",
"::",
"class",
")",
")",
"{",
"$",
"app",
"[",
"'console.command.yaml.lint'",
"]",
"=",
"function",
"(",
")",
"{",
"return",
"new",
"LintYamlCommand",
"(",
")",
";",
"}",
";",
"$",
"commands",
"[",
"'lint:yaml'",
"]",
"=",
"'console.command.yaml.lint'",
";",
"}",
"$",
"app",
"[",
"'console.command.ids'",
"]",
"=",
"$",
"commands",
";",
"}"
] | Registers the service provider.
@param Container $app The Pimple container | [
"Registers",
"the",
"service",
"provider",
"."
] | train | https://github.com/KnpLabs/ConsoleServiceProvider/blob/3f08c7337513a4027086de9324475056ad9e1416/Knp/Provider/ConsoleServiceProvider.php#L25-L84 |
drewjbartlett/wordpress-eloquent | WPEloquent/Core/Laravel.php | Laravel.connect | public static function connect ($options = []) {
$defaults = [
'global' => true,
'config' => [
'database' => [
'user' => '',
'password' => '',
'name' => '',
'host' => '',
'port' => '3306'
],
'prefix' => 'wp_'
],
'events' => false,
'log' => true
];
$options = array_replace_recursive($defaults, $options);
if(is_null(self::$_capsule)) {
self::$_capsule = new \Illuminate\Database\Capsule\Manager();
self::$_capsule->addConnection([
'driver' => 'mysql',
'host' => $options['config']['database']['host'],
'database' => $options['config']['database']['name'],
'username' => $options['config']['database']['user'],
'password' => $options['config']['database']['password'],
'port' => $options['config']['database']['port'],
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => $options['config']['prefix']
]);
self::$_capsule->bootEloquent();
if($options['events']) self::$_capsule->setEventDispatcher(new \Illuminate\Events\Dispatcher);
if($options['global']) self::$_capsule->setAsGlobal();
if($options['log']) self::$_capsule->getConnection()->enableQueryLog();
}
return self::$_capsule;
} | php | public static function connect ($options = []) {
$defaults = [
'global' => true,
'config' => [
'database' => [
'user' => '',
'password' => '',
'name' => '',
'host' => '',
'port' => '3306'
],
'prefix' => 'wp_'
],
'events' => false,
'log' => true
];
$options = array_replace_recursive($defaults, $options);
if(is_null(self::$_capsule)) {
self::$_capsule = new \Illuminate\Database\Capsule\Manager();
self::$_capsule->addConnection([
'driver' => 'mysql',
'host' => $options['config']['database']['host'],
'database' => $options['config']['database']['name'],
'username' => $options['config']['database']['user'],
'password' => $options['config']['database']['password'],
'port' => $options['config']['database']['port'],
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => $options['config']['prefix']
]);
self::$_capsule->bootEloquent();
if($options['events']) self::$_capsule->setEventDispatcher(new \Illuminate\Events\Dispatcher);
if($options['global']) self::$_capsule->setAsGlobal();
if($options['log']) self::$_capsule->getConnection()->enableQueryLog();
}
return self::$_capsule;
} | [
"public",
"static",
"function",
"connect",
"(",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'global'",
"=>",
"true",
",",
"'config'",
"=>",
"[",
"'database'",
"=>",
"[",
"'user'",
"=>",
"''",
",",
"'password'",
"=>",
"''",
",",
"'name'",
"=>",
"''",
",",
"'host'",
"=>",
"''",
",",
"'port'",
"=>",
"'3306'",
"]",
",",
"'prefix'",
"=>",
"'wp_'",
"]",
",",
"'events'",
"=>",
"false",
",",
"'log'",
"=>",
"true",
"]",
";",
"$",
"options",
"=",
"array_replace_recursive",
"(",
"$",
"defaults",
",",
"$",
"options",
")",
";",
"if",
"(",
"is_null",
"(",
"self",
"::",
"$",
"_capsule",
")",
")",
"{",
"self",
"::",
"$",
"_capsule",
"=",
"new",
"\\",
"Illuminate",
"\\",
"Database",
"\\",
"Capsule",
"\\",
"Manager",
"(",
")",
";",
"self",
"::",
"$",
"_capsule",
"->",
"addConnection",
"(",
"[",
"'driver'",
"=>",
"'mysql'",
",",
"'host'",
"=>",
"$",
"options",
"[",
"'config'",
"]",
"[",
"'database'",
"]",
"[",
"'host'",
"]",
",",
"'database'",
"=>",
"$",
"options",
"[",
"'config'",
"]",
"[",
"'database'",
"]",
"[",
"'name'",
"]",
",",
"'username'",
"=>",
"$",
"options",
"[",
"'config'",
"]",
"[",
"'database'",
"]",
"[",
"'user'",
"]",
",",
"'password'",
"=>",
"$",
"options",
"[",
"'config'",
"]",
"[",
"'database'",
"]",
"[",
"'password'",
"]",
",",
"'port'",
"=>",
"$",
"options",
"[",
"'config'",
"]",
"[",
"'database'",
"]",
"[",
"'port'",
"]",
",",
"'charset'",
"=>",
"'utf8'",
",",
"'collation'",
"=>",
"'utf8_unicode_ci'",
",",
"'prefix'",
"=>",
"$",
"options",
"[",
"'config'",
"]",
"[",
"'prefix'",
"]",
"]",
")",
";",
"self",
"::",
"$",
"_capsule",
"->",
"bootEloquent",
"(",
")",
";",
"if",
"(",
"$",
"options",
"[",
"'events'",
"]",
")",
"self",
"::",
"$",
"_capsule",
"->",
"setEventDispatcher",
"(",
"new",
"\\",
"Illuminate",
"\\",
"Events",
"\\",
"Dispatcher",
")",
";",
"if",
"(",
"$",
"options",
"[",
"'global'",
"]",
")",
"self",
"::",
"$",
"_capsule",
"->",
"setAsGlobal",
"(",
")",
";",
"if",
"(",
"$",
"options",
"[",
"'log'",
"]",
")",
"self",
"::",
"$",
"_capsule",
"->",
"getConnection",
"(",
")",
"->",
"enableQueryLog",
"(",
")",
";",
"}",
"return",
"self",
"::",
"$",
"_capsule",
";",
"}"
] | [capsule description]
@param array $options [description]
@return [type] [description]
@author drewjbartlett | [
"[",
"capsule",
"description",
"]"
] | train | https://github.com/drewjbartlett/wordpress-eloquent/blob/a8950087fed82ee7b0f31f35af2c1228458902dd/WPEloquent/Core/Laravel.php#L16-L67 |
oat-sa/extension-tao-community | scripts/update/Updater.php | Updater.update | public function update($initialVersion)
{
if ($this->isBetween('0.0.0', '1.1.3')) {
throw new \common_exception_NotImplemented('Updates from versions prior to Tao 3.1 are not longer supported, please update to Tao 3.1 first');
}
$this->skip('1.1.3', '1.6.2');
if ($this->isVersion('1.6.2')) {
AclProxy::applyRule(new AccessRule('grant', TaoRoles::ANONYMOUS,
['ext'=>'taoCe', 'mod' => 'Main', 'act' => 'rootEntry']));
$this->setVersion('1.7.0');
}
$this->skip('1.7.0', '1.7.1');
// add guest login
if ($this->isVersion('1.7.1')) {
$entryPointService = $this->getServiceManager()->get(EntryPointService::SERVICE_ID);
$entryPointService->addEntryPoint(new GuestAccess(), EntryPointService::OPTION_PRELOGIN);
$this->getServiceManager()->register(EntryPointService::SERVICE_ID, $entryPointService);
$this->setVersion('1.8.0');
}
$this->skip('1.8.0', '5.6.0');
} | php | public function update($initialVersion)
{
if ($this->isBetween('0.0.0', '1.1.3')) {
throw new \common_exception_NotImplemented('Updates from versions prior to Tao 3.1 are not longer supported, please update to Tao 3.1 first');
}
$this->skip('1.1.3', '1.6.2');
if ($this->isVersion('1.6.2')) {
AclProxy::applyRule(new AccessRule('grant', TaoRoles::ANONYMOUS,
['ext'=>'taoCe', 'mod' => 'Main', 'act' => 'rootEntry']));
$this->setVersion('1.7.0');
}
$this->skip('1.7.0', '1.7.1');
// add guest login
if ($this->isVersion('1.7.1')) {
$entryPointService = $this->getServiceManager()->get(EntryPointService::SERVICE_ID);
$entryPointService->addEntryPoint(new GuestAccess(), EntryPointService::OPTION_PRELOGIN);
$this->getServiceManager()->register(EntryPointService::SERVICE_ID, $entryPointService);
$this->setVersion('1.8.0');
}
$this->skip('1.8.0', '5.6.0');
} | [
"public",
"function",
"update",
"(",
"$",
"initialVersion",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isBetween",
"(",
"'0.0.0'",
",",
"'1.1.3'",
")",
")",
"{",
"throw",
"new",
"\\",
"common_exception_NotImplemented",
"(",
"'Updates from versions prior to Tao 3.1 are not longer supported, please update to Tao 3.1 first'",
")",
";",
"}",
"$",
"this",
"->",
"skip",
"(",
"'1.1.3'",
",",
"'1.6.2'",
")",
";",
"if",
"(",
"$",
"this",
"->",
"isVersion",
"(",
"'1.6.2'",
")",
")",
"{",
"AclProxy",
"::",
"applyRule",
"(",
"new",
"AccessRule",
"(",
"'grant'",
",",
"TaoRoles",
"::",
"ANONYMOUS",
",",
"[",
"'ext'",
"=>",
"'taoCe'",
",",
"'mod'",
"=>",
"'Main'",
",",
"'act'",
"=>",
"'rootEntry'",
"]",
")",
")",
";",
"$",
"this",
"->",
"setVersion",
"(",
"'1.7.0'",
")",
";",
"}",
"$",
"this",
"->",
"skip",
"(",
"'1.7.0'",
",",
"'1.7.1'",
")",
";",
"// add guest login",
"if",
"(",
"$",
"this",
"->",
"isVersion",
"(",
"'1.7.1'",
")",
")",
"{",
"$",
"entryPointService",
"=",
"$",
"this",
"->",
"getServiceManager",
"(",
")",
"->",
"get",
"(",
"EntryPointService",
"::",
"SERVICE_ID",
")",
";",
"$",
"entryPointService",
"->",
"addEntryPoint",
"(",
"new",
"GuestAccess",
"(",
")",
",",
"EntryPointService",
"::",
"OPTION_PRELOGIN",
")",
";",
"$",
"this",
"->",
"getServiceManager",
"(",
")",
"->",
"register",
"(",
"EntryPointService",
"::",
"SERVICE_ID",
",",
"$",
"entryPointService",
")",
";",
"$",
"this",
"->",
"setVersion",
"(",
"'1.8.0'",
")",
";",
"}",
"$",
"this",
"->",
"skip",
"(",
"'1.8.0'",
",",
"'5.6.0'",
")",
";",
"}"
] | Perform update from $currentVersion to $versionUpdatedTo.
@param string $currentVersion
@return string $versionUpdatedTo | [
"Perform",
"update",
"from",
"$currentVersion",
"to",
"$versionUpdatedTo",
"."
] | train | https://github.com/oat-sa/extension-tao-community/blob/b1bb3c9e336e9b2f7163fc8f5bfd6038045bb885/scripts/update/Updater.php#L42-L69 |
oat-sa/extension-tao-community | actions/Main.php | Main.index | public function index()
{
$this->defaultData();
//redirect to the usual tao/Main/index
if($this->hasRequestParameter('ext') || $this->hasRequestParameter('structure')){
//but before update the first time property
$user = $this->getServiceLocator()->get(\tao_models_classes_UserService::SERVICE_ID)->getCurrentUser();
if($this->hasRequestParameter('nosplash')){
TaoCe::becomeVeteran();
}
//@todo use forward on cross-extension forward is supported
$this->redirect(_url('index', 'Main', 'tao', array(
'ext' => $this->getRequestParameter('ext'),
'structure' => $this->getRequestParameter('structure')
)));
} else {
//render the index but with the taoCe URL used by client side routes
parent::index();
}
} | php | public function index()
{
$this->defaultData();
//redirect to the usual tao/Main/index
if($this->hasRequestParameter('ext') || $this->hasRequestParameter('structure')){
//but before update the first time property
$user = $this->getServiceLocator()->get(\tao_models_classes_UserService::SERVICE_ID)->getCurrentUser();
if($this->hasRequestParameter('nosplash')){
TaoCe::becomeVeteran();
}
//@todo use forward on cross-extension forward is supported
$this->redirect(_url('index', 'Main', 'tao', array(
'ext' => $this->getRequestParameter('ext'),
'structure' => $this->getRequestParameter('structure')
)));
} else {
//render the index but with the taoCe URL used by client side routes
parent::index();
}
} | [
"public",
"function",
"index",
"(",
")",
"{",
"$",
"this",
"->",
"defaultData",
"(",
")",
";",
"//redirect to the usual tao/Main/index",
"if",
"(",
"$",
"this",
"->",
"hasRequestParameter",
"(",
"'ext'",
")",
"||",
"$",
"this",
"->",
"hasRequestParameter",
"(",
"'structure'",
")",
")",
"{",
"//but before update the first time property",
"$",
"user",
"=",
"$",
"this",
"->",
"getServiceLocator",
"(",
")",
"->",
"get",
"(",
"\\",
"tao_models_classes_UserService",
"::",
"SERVICE_ID",
")",
"->",
"getCurrentUser",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"hasRequestParameter",
"(",
"'nosplash'",
")",
")",
"{",
"TaoCe",
"::",
"becomeVeteran",
"(",
")",
";",
"}",
"//@todo use forward on cross-extension forward is supported",
"$",
"this",
"->",
"redirect",
"(",
"_url",
"(",
"'index'",
",",
"'Main'",
",",
"'tao'",
",",
"array",
"(",
"'ext'",
"=>",
"$",
"this",
"->",
"getRequestParameter",
"(",
"'ext'",
")",
",",
"'structure'",
"=>",
"$",
"this",
"->",
"getRequestParameter",
"(",
"'structure'",
")",
")",
")",
")",
";",
"}",
"else",
"{",
"//render the index but with the taoCe URL used by client side routes",
"parent",
"::",
"index",
"(",
")",
";",
"}",
"}"
] | Wrapper to the main action: update the first time property and redirect
@return void | [
"Wrapper",
"to",
"the",
"main",
"action",
":",
"update",
"the",
"first",
"time",
"property",
"and",
"redirect"
] | train | https://github.com/oat-sa/extension-tao-community/blob/b1bb3c9e336e9b2f7163fc8f5bfd6038045bb885/actions/Main.php#L42-L65 |
oat-sa/extension-tao-community | actions/Main.php | Main.rootEntry | public function rootEntry()
{
$this->defaultData();
if (\common_session_SessionManager::isAnonymous()) {
/* @var $urlRouteService DefaultUrlService */
$urlRouteService = $this->getServiceLocator()->get(DefaultUrlService::SERVICE_ID);
$this->redirect($urlRouteService->getLoginUrl());
} else {
$this->redirect(_url('entry', 'Main', 'tao'));
}
} | php | public function rootEntry()
{
$this->defaultData();
if (\common_session_SessionManager::isAnonymous()) {
/* @var $urlRouteService DefaultUrlService */
$urlRouteService = $this->getServiceLocator()->get(DefaultUrlService::SERVICE_ID);
$this->redirect($urlRouteService->getLoginUrl());
} else {
$this->redirect(_url('entry', 'Main', 'tao'));
}
} | [
"public",
"function",
"rootEntry",
"(",
")",
"{",
"$",
"this",
"->",
"defaultData",
"(",
")",
";",
"if",
"(",
"\\",
"common_session_SessionManager",
"::",
"isAnonymous",
"(",
")",
")",
"{",
"/* @var $urlRouteService DefaultUrlService */",
"$",
"urlRouteService",
"=",
"$",
"this",
"->",
"getServiceLocator",
"(",
")",
"->",
"get",
"(",
"DefaultUrlService",
"::",
"SERVICE_ID",
")",
";",
"$",
"this",
"->",
"redirect",
"(",
"$",
"urlRouteService",
"->",
"getLoginUrl",
"(",
")",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"redirect",
"(",
"_url",
"(",
"'entry'",
",",
"'Main'",
",",
"'tao'",
")",
")",
";",
"}",
"}"
] | Action used to redirect request made to root of tao. | [
"Action",
"used",
"to",
"redirect",
"request",
"made",
"to",
"root",
"of",
"tao",
"."
] | train | https://github.com/oat-sa/extension-tao-community/blob/b1bb3c9e336e9b2f7163fc8f5bfd6038045bb885/actions/Main.php#L70-L80 |
oat-sa/extension-tao-community | actions/Home.php | Home.splash | public function splash() {
//the list of extensions the splash provides an explanation for.
$defaultExtIds = array('items', 'tests', 'TestTaker', 'groups', 'delivery', 'results');
//check if the user is a noob
$this->setData('firstTime', TaoCe::isFirstTimeInTao());
//load the extension data
$defaultExtensions = array();
$additionalExtensions = array();
foreach (MenuService::getPerspectivesByGroup(Perspective::GROUP_DEFAULT) as $i => $perspective) {
if (in_array((string) $perspective->getId(), $defaultExtIds)) {
$defaultExtensions[strval($perspective->getId())] = array(
'id' => $perspective->getId(),
'name' => $perspective->getName(),
'extension' => $perspective->getExtension(),
'description' => $perspective->getDescription()
);
} else {
$additionalExtensions[$i] = array(
'id' => $perspective->getId(),
'name' => $perspective->getName(),
'extension' => $perspective->getExtension()
);
}
//Test if access
$access = false;
foreach ($perspective->getChildren() as $section) {
if (tao_models_classes_accessControl_AclProxy::hasAccess($section->getAction(), $section->getController(), $section->getExtensionId())) {
$access = true;
break;
}
}
if (in_array((string) $perspective->getId(), $defaultExtIds)) {
$defaultExtensions[strval($perspective->getId())]['enabled'] = $access;
} else {
$additionalExtensions[$i]['enabled'] = $access;
}
}
$this->setData('extensions', array_merge($defaultExtensions, $additionalExtensions));
$this->setData('defaultExtensions', $defaultExtensions);
$this->setData('additionalExtensions', $additionalExtensions);
$this->setView('splash.tpl');
} | php | public function splash() {
//the list of extensions the splash provides an explanation for.
$defaultExtIds = array('items', 'tests', 'TestTaker', 'groups', 'delivery', 'results');
//check if the user is a noob
$this->setData('firstTime', TaoCe::isFirstTimeInTao());
//load the extension data
$defaultExtensions = array();
$additionalExtensions = array();
foreach (MenuService::getPerspectivesByGroup(Perspective::GROUP_DEFAULT) as $i => $perspective) {
if (in_array((string) $perspective->getId(), $defaultExtIds)) {
$defaultExtensions[strval($perspective->getId())] = array(
'id' => $perspective->getId(),
'name' => $perspective->getName(),
'extension' => $perspective->getExtension(),
'description' => $perspective->getDescription()
);
} else {
$additionalExtensions[$i] = array(
'id' => $perspective->getId(),
'name' => $perspective->getName(),
'extension' => $perspective->getExtension()
);
}
//Test if access
$access = false;
foreach ($perspective->getChildren() as $section) {
if (tao_models_classes_accessControl_AclProxy::hasAccess($section->getAction(), $section->getController(), $section->getExtensionId())) {
$access = true;
break;
}
}
if (in_array((string) $perspective->getId(), $defaultExtIds)) {
$defaultExtensions[strval($perspective->getId())]['enabled'] = $access;
} else {
$additionalExtensions[$i]['enabled'] = $access;
}
}
$this->setData('extensions', array_merge($defaultExtensions, $additionalExtensions));
$this->setData('defaultExtensions', $defaultExtensions);
$this->setData('additionalExtensions', $additionalExtensions);
$this->setView('splash.tpl');
} | [
"public",
"function",
"splash",
"(",
")",
"{",
"//the list of extensions the splash provides an explanation for.",
"$",
"defaultExtIds",
"=",
"array",
"(",
"'items'",
",",
"'tests'",
",",
"'TestTaker'",
",",
"'groups'",
",",
"'delivery'",
",",
"'results'",
")",
";",
"//check if the user is a noob",
"$",
"this",
"->",
"setData",
"(",
"'firstTime'",
",",
"TaoCe",
"::",
"isFirstTimeInTao",
"(",
")",
")",
";",
"//load the extension data",
"$",
"defaultExtensions",
"=",
"array",
"(",
")",
";",
"$",
"additionalExtensions",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"MenuService",
"::",
"getPerspectivesByGroup",
"(",
"Perspective",
"::",
"GROUP_DEFAULT",
")",
"as",
"$",
"i",
"=>",
"$",
"perspective",
")",
"{",
"if",
"(",
"in_array",
"(",
"(",
"string",
")",
"$",
"perspective",
"->",
"getId",
"(",
")",
",",
"$",
"defaultExtIds",
")",
")",
"{",
"$",
"defaultExtensions",
"[",
"strval",
"(",
"$",
"perspective",
"->",
"getId",
"(",
")",
")",
"]",
"=",
"array",
"(",
"'id'",
"=>",
"$",
"perspective",
"->",
"getId",
"(",
")",
",",
"'name'",
"=>",
"$",
"perspective",
"->",
"getName",
"(",
")",
",",
"'extension'",
"=>",
"$",
"perspective",
"->",
"getExtension",
"(",
")",
",",
"'description'",
"=>",
"$",
"perspective",
"->",
"getDescription",
"(",
")",
")",
";",
"}",
"else",
"{",
"$",
"additionalExtensions",
"[",
"$",
"i",
"]",
"=",
"array",
"(",
"'id'",
"=>",
"$",
"perspective",
"->",
"getId",
"(",
")",
",",
"'name'",
"=>",
"$",
"perspective",
"->",
"getName",
"(",
")",
",",
"'extension'",
"=>",
"$",
"perspective",
"->",
"getExtension",
"(",
")",
")",
";",
"}",
"//Test if access",
"$",
"access",
"=",
"false",
";",
"foreach",
"(",
"$",
"perspective",
"->",
"getChildren",
"(",
")",
"as",
"$",
"section",
")",
"{",
"if",
"(",
"tao_models_classes_accessControl_AclProxy",
"::",
"hasAccess",
"(",
"$",
"section",
"->",
"getAction",
"(",
")",
",",
"$",
"section",
"->",
"getController",
"(",
")",
",",
"$",
"section",
"->",
"getExtensionId",
"(",
")",
")",
")",
"{",
"$",
"access",
"=",
"true",
";",
"break",
";",
"}",
"}",
"if",
"(",
"in_array",
"(",
"(",
"string",
")",
"$",
"perspective",
"->",
"getId",
"(",
")",
",",
"$",
"defaultExtIds",
")",
")",
"{",
"$",
"defaultExtensions",
"[",
"strval",
"(",
"$",
"perspective",
"->",
"getId",
"(",
")",
")",
"]",
"[",
"'enabled'",
"]",
"=",
"$",
"access",
";",
"}",
"else",
"{",
"$",
"additionalExtensions",
"[",
"$",
"i",
"]",
"[",
"'enabled'",
"]",
"=",
"$",
"access",
";",
"}",
"}",
"$",
"this",
"->",
"setData",
"(",
"'extensions'",
",",
"array_merge",
"(",
"$",
"defaultExtensions",
",",
"$",
"additionalExtensions",
")",
")",
";",
"$",
"this",
"->",
"setData",
"(",
"'defaultExtensions'",
",",
"$",
"defaultExtensions",
")",
";",
"$",
"this",
"->",
"setData",
"(",
"'additionalExtensions'",
",",
"$",
"additionalExtensions",
")",
";",
"$",
"this",
"->",
"setView",
"(",
"'splash.tpl'",
")",
";",
"}"
] | This action renders the template used by the splash screen popup | [
"This",
"action",
"renders",
"the",
"template",
"used",
"by",
"the",
"splash",
"screen",
"popup"
] | train | https://github.com/oat-sa/extension-tao-community/blob/b1bb3c9e336e9b2f7163fc8f5bfd6038045bb885/actions/Home.php#L43-L90 |
webfactory/slimdump | src/Webfactory/Slimdump/Config/FakerReplacer.php | FakerReplacer.generateReplacement | public function generateReplacement($replacementId)
{
$replacementMethodName = str_replace(self::PREFIX, '', $replacementId);
if (strpos($replacementMethodName,'->') !== false) {
$modifierAndMethod = explode('->',$replacementMethodName);
$modifierName = $modifierAndMethod[0];
$replacementMethodName = $modifierAndMethod[1];
$this->validateReplacementConfiguredModifier($modifierName, $replacementMethodName);
return (string)$this->faker->$modifierName->$replacementMethodName;
} else {
$this->validateReplacementConfigured($replacementMethodName);
return (string)$this->faker->$replacementMethodName;
}
} | php | public function generateReplacement($replacementId)
{
$replacementMethodName = str_replace(self::PREFIX, '', $replacementId);
if (strpos($replacementMethodName,'->') !== false) {
$modifierAndMethod = explode('->',$replacementMethodName);
$modifierName = $modifierAndMethod[0];
$replacementMethodName = $modifierAndMethod[1];
$this->validateReplacementConfiguredModifier($modifierName, $replacementMethodName);
return (string)$this->faker->$modifierName->$replacementMethodName;
} else {
$this->validateReplacementConfigured($replacementMethodName);
return (string)$this->faker->$replacementMethodName;
}
} | [
"public",
"function",
"generateReplacement",
"(",
"$",
"replacementId",
")",
"{",
"$",
"replacementMethodName",
"=",
"str_replace",
"(",
"self",
"::",
"PREFIX",
",",
"''",
",",
"$",
"replacementId",
")",
";",
"if",
"(",
"strpos",
"(",
"$",
"replacementMethodName",
",",
"'->'",
")",
"!==",
"false",
")",
"{",
"$",
"modifierAndMethod",
"=",
"explode",
"(",
"'->'",
",",
"$",
"replacementMethodName",
")",
";",
"$",
"modifierName",
"=",
"$",
"modifierAndMethod",
"[",
"0",
"]",
";",
"$",
"replacementMethodName",
"=",
"$",
"modifierAndMethod",
"[",
"1",
"]",
";",
"$",
"this",
"->",
"validateReplacementConfiguredModifier",
"(",
"$",
"modifierName",
",",
"$",
"replacementMethodName",
")",
";",
"return",
"(",
"string",
")",
"$",
"this",
"->",
"faker",
"->",
"$",
"modifierName",
"->",
"$",
"replacementMethodName",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"validateReplacementConfigured",
"(",
"$",
"replacementMethodName",
")",
";",
"return",
"(",
"string",
")",
"$",
"this",
"->",
"faker",
"->",
"$",
"replacementMethodName",
";",
"}",
"}"
] | wrapper method which removes the prefix calls the defined faker method
@param string $replacementId
@return string | [
"wrapper",
"method",
"which",
"removes",
"the",
"prefix",
"calls",
"the",
"defined",
"faker",
"method"
] | train | https://github.com/webfactory/slimdump/blob/43a73b9b1a63f5058e506707efa07fac14be35c0/src/Webfactory/Slimdump/Config/FakerReplacer.php#L52-L69 |
webfactory/slimdump | src/Webfactory/Slimdump/Config/FakerReplacer.php | FakerReplacer.validateReplacementConfigured | private function validateReplacementConfigured($replacementName)
{
try {
$this->faker->__get($replacementName);
} catch (\InvalidArgumentException $exception) {
throw new InvalidReplacementOptionException($replacementName . ' is no valid faker replacement');
}
} | php | private function validateReplacementConfigured($replacementName)
{
try {
$this->faker->__get($replacementName);
} catch (\InvalidArgumentException $exception) {
throw new InvalidReplacementOptionException($replacementName . ' is no valid faker replacement');
}
} | [
"private",
"function",
"validateReplacementConfigured",
"(",
"$",
"replacementName",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"faker",
"->",
"__get",
"(",
"$",
"replacementName",
")",
";",
"}",
"catch",
"(",
"\\",
"InvalidArgumentException",
"$",
"exception",
")",
"{",
"throw",
"new",
"InvalidReplacementOptionException",
"(",
"$",
"replacementName",
".",
"' is no valid faker replacement'",
")",
";",
"}",
"}"
] | validates if this type of replacement was configured
@param string $replacementName
@throws \Webfactory\Slimdump\Exception\InvalidReplacementOptionException if not a faker method | [
"validates",
"if",
"this",
"type",
"of",
"replacement",
"was",
"configured"
] | train | https://github.com/webfactory/slimdump/blob/43a73b9b1a63f5058e506707efa07fac14be35c0/src/Webfactory/Slimdump/Config/FakerReplacer.php#L77-L84 |
webfactory/slimdump | src/Webfactory/Slimdump/Config/Table.php | Table.getStringForInsertStatement | public function getStringForInsertStatement($columnName, $value, $isBlobColumn, Connection $db)
{
if ($value === null) {
return 'NULL';
} else if ($value === '') {
return '""';
} else {
if ($column = $this->findColumn($columnName)) {
return $db->quote($column->processRowValue($value));
}
if ($isBlobColumn) {
return $value;
}
return $db->quote($value);
}
} | php | public function getStringForInsertStatement($columnName, $value, $isBlobColumn, Connection $db)
{
if ($value === null) {
return 'NULL';
} else if ($value === '') {
return '""';
} else {
if ($column = $this->findColumn($columnName)) {
return $db->quote($column->processRowValue($value));
}
if ($isBlobColumn) {
return $value;
}
return $db->quote($value);
}
} | [
"public",
"function",
"getStringForInsertStatement",
"(",
"$",
"columnName",
",",
"$",
"value",
",",
"$",
"isBlobColumn",
",",
"Connection",
"$",
"db",
")",
"{",
"if",
"(",
"$",
"value",
"===",
"null",
")",
"{",
"return",
"'NULL'",
";",
"}",
"else",
"if",
"(",
"$",
"value",
"===",
"''",
")",
"{",
"return",
"'\"\"'",
";",
"}",
"else",
"{",
"if",
"(",
"$",
"column",
"=",
"$",
"this",
"->",
"findColumn",
"(",
"$",
"columnName",
")",
")",
"{",
"return",
"$",
"db",
"->",
"quote",
"(",
"$",
"column",
"->",
"processRowValue",
"(",
"$",
"value",
")",
")",
";",
"}",
"if",
"(",
"$",
"isBlobColumn",
")",
"{",
"return",
"$",
"value",
";",
"}",
"return",
"$",
"db",
"->",
"quote",
"(",
"$",
"value",
")",
";",
"}",
"}"
] | @param string $columnName
@param string|null $value
@param boolean $isBlobColumn
@param Connection $db
@return string | [
"@param",
"string",
"$columnName",
"@param",
"string|null",
"$value",
"@param",
"boolean",
"$isBlobColumn",
"@param",
"Connection",
"$db"
] | train | https://github.com/webfactory/slimdump/blob/43a73b9b1a63f5058e506707efa07fac14be35c0/src/Webfactory/Slimdump/Config/Table.php#L175-L192 |
webfactory/slimdump | src/Webfactory/Slimdump/Database/Dumper.php | Dumper.dumpData | public function dumpData($table, Table $tableConfig, Connection $db)
{
$this->keepalive($db);
$cols = $this->cols($table, $db);
$s = "SELECT ";
$first = true;
foreach (array_keys($cols) as $name) {
$isBlobColumn = $this->isBlob($name, $cols);
if (!$first) {
$s .= ', ';
}
$s .= $tableConfig->getSelectExpression($name, $isBlobColumn);
$s .= " AS `$name`";
$first = false;
}
$s .= " FROM `$table`";
$s .= $tableConfig->getCondition();
$this->output->writeln("-- BEGIN DATA $table", OutputInterface::OUTPUT_RAW);
$bufferSize = 0;
$max = $this->bufferSize;
$numRows = $db->fetchColumn("SELECT COUNT(*) FROM `$table`".$tableConfig->getCondition());
if ($numRows == 0) {
// Fail fast: No data to dump.
return;
}
$progress = new ProgressBar($this->output, $numRows);
$progress->setFormat("Dumping data <fg=cyan>$table</>: <fg=yellow>%percent:3s%%</> %remaining%/%estimated%");
$progress->setOverwrite(true);
$progress->setRedrawFrequency(max($numRows / 100, 1));
$progress->start();
/** @var PDOConnection $wrappedConnection */
$wrappedConnection = $db->getWrappedConnection();
$wrappedConnection->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
foreach ($db->query($s) as $row) {
$b = $this->rowLengthEstimate($row);
// Start a new statement to ensure that the line does not get too long.
if ($bufferSize && $bufferSize + $b > $max) {
$this->output->writeln(";", OutputInterface::OUTPUT_RAW);
$bufferSize = 0;
}
if ($bufferSize == 0) {
$this->output->write($this->insertValuesStatement($table, $cols), false, OutputInterface::OUTPUT_RAW);
} else {
$this->output->write(",", false, OutputInterface::OUTPUT_RAW);
}
$firstCol = true;
$this->output->write("\n(", false, OutputInterface::OUTPUT_RAW);
foreach ($row as $name => $value) {
$isBlobColumn = $this->isBlob($name, $cols);
if (!$firstCol) {
$this->output->write(", ", false, OutputInterface::OUTPUT_RAW);
}
$this->output->write($tableConfig->getStringForInsertStatement($name, $value, $isBlobColumn, $db), false, OutputInterface::OUTPUT_RAW);
$firstCol = false;
}
$this->output->write(")", false, OutputInterface::OUTPUT_RAW);
$bufferSize += $b;
$progress->advance();
}
$progress->setFormat("Dumping data <fg=green>$table</>: <fg=green>%percent:3s%%</> Took: %elapsed%");
$progress->finish();
if ($this->output instanceof \Symfony\Component\Console\Output\ConsoleOutput) {
$this->output->getErrorOutput()->write("\n"); // write a newline after the progressbar.
}
$wrappedConnection->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
if ($bufferSize) {
$this->output->writeln(";", OutputInterface::OUTPUT_RAW);
}
$this->output->writeln('', OutputInterface::OUTPUT_RAW);
} | php | public function dumpData($table, Table $tableConfig, Connection $db)
{
$this->keepalive($db);
$cols = $this->cols($table, $db);
$s = "SELECT ";
$first = true;
foreach (array_keys($cols) as $name) {
$isBlobColumn = $this->isBlob($name, $cols);
if (!$first) {
$s .= ', ';
}
$s .= $tableConfig->getSelectExpression($name, $isBlobColumn);
$s .= " AS `$name`";
$first = false;
}
$s .= " FROM `$table`";
$s .= $tableConfig->getCondition();
$this->output->writeln("-- BEGIN DATA $table", OutputInterface::OUTPUT_RAW);
$bufferSize = 0;
$max = $this->bufferSize;
$numRows = $db->fetchColumn("SELECT COUNT(*) FROM `$table`".$tableConfig->getCondition());
if ($numRows == 0) {
// Fail fast: No data to dump.
return;
}
$progress = new ProgressBar($this->output, $numRows);
$progress->setFormat("Dumping data <fg=cyan>$table</>: <fg=yellow>%percent:3s%%</> %remaining%/%estimated%");
$progress->setOverwrite(true);
$progress->setRedrawFrequency(max($numRows / 100, 1));
$progress->start();
/** @var PDOConnection $wrappedConnection */
$wrappedConnection = $db->getWrappedConnection();
$wrappedConnection->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
foreach ($db->query($s) as $row) {
$b = $this->rowLengthEstimate($row);
// Start a new statement to ensure that the line does not get too long.
if ($bufferSize && $bufferSize + $b > $max) {
$this->output->writeln(";", OutputInterface::OUTPUT_RAW);
$bufferSize = 0;
}
if ($bufferSize == 0) {
$this->output->write($this->insertValuesStatement($table, $cols), false, OutputInterface::OUTPUT_RAW);
} else {
$this->output->write(",", false, OutputInterface::OUTPUT_RAW);
}
$firstCol = true;
$this->output->write("\n(", false, OutputInterface::OUTPUT_RAW);
foreach ($row as $name => $value) {
$isBlobColumn = $this->isBlob($name, $cols);
if (!$firstCol) {
$this->output->write(", ", false, OutputInterface::OUTPUT_RAW);
}
$this->output->write($tableConfig->getStringForInsertStatement($name, $value, $isBlobColumn, $db), false, OutputInterface::OUTPUT_RAW);
$firstCol = false;
}
$this->output->write(")", false, OutputInterface::OUTPUT_RAW);
$bufferSize += $b;
$progress->advance();
}
$progress->setFormat("Dumping data <fg=green>$table</>: <fg=green>%percent:3s%%</> Took: %elapsed%");
$progress->finish();
if ($this->output instanceof \Symfony\Component\Console\Output\ConsoleOutput) {
$this->output->getErrorOutput()->write("\n"); // write a newline after the progressbar.
}
$wrappedConnection->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
if ($bufferSize) {
$this->output->writeln(";", OutputInterface::OUTPUT_RAW);
}
$this->output->writeln('', OutputInterface::OUTPUT_RAW);
} | [
"public",
"function",
"dumpData",
"(",
"$",
"table",
",",
"Table",
"$",
"tableConfig",
",",
"Connection",
"$",
"db",
")",
"{",
"$",
"this",
"->",
"keepalive",
"(",
"$",
"db",
")",
";",
"$",
"cols",
"=",
"$",
"this",
"->",
"cols",
"(",
"$",
"table",
",",
"$",
"db",
")",
";",
"$",
"s",
"=",
"\"SELECT \"",
";",
"$",
"first",
"=",
"true",
";",
"foreach",
"(",
"array_keys",
"(",
"$",
"cols",
")",
"as",
"$",
"name",
")",
"{",
"$",
"isBlobColumn",
"=",
"$",
"this",
"->",
"isBlob",
"(",
"$",
"name",
",",
"$",
"cols",
")",
";",
"if",
"(",
"!",
"$",
"first",
")",
"{",
"$",
"s",
".=",
"', '",
";",
"}",
"$",
"s",
".=",
"$",
"tableConfig",
"->",
"getSelectExpression",
"(",
"$",
"name",
",",
"$",
"isBlobColumn",
")",
";",
"$",
"s",
".=",
"\" AS `$name`\"",
";",
"$",
"first",
"=",
"false",
";",
"}",
"$",
"s",
".=",
"\" FROM `$table`\"",
";",
"$",
"s",
".=",
"$",
"tableConfig",
"->",
"getCondition",
"(",
")",
";",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"\"-- BEGIN DATA $table\"",
",",
"OutputInterface",
"::",
"OUTPUT_RAW",
")",
";",
"$",
"bufferSize",
"=",
"0",
";",
"$",
"max",
"=",
"$",
"this",
"->",
"bufferSize",
";",
"$",
"numRows",
"=",
"$",
"db",
"->",
"fetchColumn",
"(",
"\"SELECT COUNT(*) FROM `$table`\"",
".",
"$",
"tableConfig",
"->",
"getCondition",
"(",
")",
")",
";",
"if",
"(",
"$",
"numRows",
"==",
"0",
")",
"{",
"// Fail fast: No data to dump.",
"return",
";",
"}",
"$",
"progress",
"=",
"new",
"ProgressBar",
"(",
"$",
"this",
"->",
"output",
",",
"$",
"numRows",
")",
";",
"$",
"progress",
"->",
"setFormat",
"(",
"\"Dumping data <fg=cyan>$table</>: <fg=yellow>%percent:3s%%</> %remaining%/%estimated%\"",
")",
";",
"$",
"progress",
"->",
"setOverwrite",
"(",
"true",
")",
";",
"$",
"progress",
"->",
"setRedrawFrequency",
"(",
"max",
"(",
"$",
"numRows",
"/",
"100",
",",
"1",
")",
")",
";",
"$",
"progress",
"->",
"start",
"(",
")",
";",
"/** @var PDOConnection $wrappedConnection */",
"$",
"wrappedConnection",
"=",
"$",
"db",
"->",
"getWrappedConnection",
"(",
")",
";",
"$",
"wrappedConnection",
"->",
"setAttribute",
"(",
"\\",
"PDO",
"::",
"MYSQL_ATTR_USE_BUFFERED_QUERY",
",",
"false",
")",
";",
"foreach",
"(",
"$",
"db",
"->",
"query",
"(",
"$",
"s",
")",
"as",
"$",
"row",
")",
"{",
"$",
"b",
"=",
"$",
"this",
"->",
"rowLengthEstimate",
"(",
"$",
"row",
")",
";",
"// Start a new statement to ensure that the line does not get too long.",
"if",
"(",
"$",
"bufferSize",
"&&",
"$",
"bufferSize",
"+",
"$",
"b",
">",
"$",
"max",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"\";\"",
",",
"OutputInterface",
"::",
"OUTPUT_RAW",
")",
";",
"$",
"bufferSize",
"=",
"0",
";",
"}",
"if",
"(",
"$",
"bufferSize",
"==",
"0",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"write",
"(",
"$",
"this",
"->",
"insertValuesStatement",
"(",
"$",
"table",
",",
"$",
"cols",
")",
",",
"false",
",",
"OutputInterface",
"::",
"OUTPUT_RAW",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"output",
"->",
"write",
"(",
"\",\"",
",",
"false",
",",
"OutputInterface",
"::",
"OUTPUT_RAW",
")",
";",
"}",
"$",
"firstCol",
"=",
"true",
";",
"$",
"this",
"->",
"output",
"->",
"write",
"(",
"\"\\n(\"",
",",
"false",
",",
"OutputInterface",
"::",
"OUTPUT_RAW",
")",
";",
"foreach",
"(",
"$",
"row",
"as",
"$",
"name",
"=>",
"$",
"value",
")",
"{",
"$",
"isBlobColumn",
"=",
"$",
"this",
"->",
"isBlob",
"(",
"$",
"name",
",",
"$",
"cols",
")",
";",
"if",
"(",
"!",
"$",
"firstCol",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"write",
"(",
"\", \"",
",",
"false",
",",
"OutputInterface",
"::",
"OUTPUT_RAW",
")",
";",
"}",
"$",
"this",
"->",
"output",
"->",
"write",
"(",
"$",
"tableConfig",
"->",
"getStringForInsertStatement",
"(",
"$",
"name",
",",
"$",
"value",
",",
"$",
"isBlobColumn",
",",
"$",
"db",
")",
",",
"false",
",",
"OutputInterface",
"::",
"OUTPUT_RAW",
")",
";",
"$",
"firstCol",
"=",
"false",
";",
"}",
"$",
"this",
"->",
"output",
"->",
"write",
"(",
"\")\"",
",",
"false",
",",
"OutputInterface",
"::",
"OUTPUT_RAW",
")",
";",
"$",
"bufferSize",
"+=",
"$",
"b",
";",
"$",
"progress",
"->",
"advance",
"(",
")",
";",
"}",
"$",
"progress",
"->",
"setFormat",
"(",
"\"Dumping data <fg=green>$table</>: <fg=green>%percent:3s%%</> Took: %elapsed%\"",
")",
";",
"$",
"progress",
"->",
"finish",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"output",
"instanceof",
"\\",
"Symfony",
"\\",
"Component",
"\\",
"Console",
"\\",
"Output",
"\\",
"ConsoleOutput",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"getErrorOutput",
"(",
")",
"->",
"write",
"(",
"\"\\n\"",
")",
";",
"// write a newline after the progressbar.",
"}",
"$",
"wrappedConnection",
"->",
"setAttribute",
"(",
"\\",
"PDO",
"::",
"MYSQL_ATTR_USE_BUFFERED_QUERY",
",",
"true",
")",
";",
"if",
"(",
"$",
"bufferSize",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"\";\"",
",",
"OutputInterface",
"::",
"OUTPUT_RAW",
")",
";",
"}",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"''",
",",
"OutputInterface",
"::",
"OUTPUT_RAW",
")",
";",
"}"
] | @param $table
@param Table $tableConfig
@param Connection $db
@throws \Doctrine\DBAL\DBALException | [
"@param",
"$table",
"@param",
"Table",
"$tableConfig",
"@param",
"Connection",
"$db"
] | train | https://github.com/webfactory/slimdump/blob/43a73b9b1a63f5058e506707efa07fac14be35c0/src/Webfactory/Slimdump/Database/Dumper.php#L112-L202 |
webfactory/slimdump | src/Webfactory/Slimdump/Database/Dumper.php | Dumper.cols | protected function cols($table, Connection $db)
{
$c = array();
foreach ($db->fetchAll("SHOW COLUMNS FROM `$table`") as $row) {
$c[$row['Field']] = $row['Type'];
}
return $c;
} | php | protected function cols($table, Connection $db)
{
$c = array();
foreach ($db->fetchAll("SHOW COLUMNS FROM `$table`") as $row) {
$c[$row['Field']] = $row['Type'];
}
return $c;
} | [
"protected",
"function",
"cols",
"(",
"$",
"table",
",",
"Connection",
"$",
"db",
")",
"{",
"$",
"c",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"db",
"->",
"fetchAll",
"(",
"\"SHOW COLUMNS FROM `$table`\"",
")",
"as",
"$",
"row",
")",
"{",
"$",
"c",
"[",
"$",
"row",
"[",
"'Field'",
"]",
"]",
"=",
"$",
"row",
"[",
"'Type'",
"]",
";",
"}",
"return",
"$",
"c",
";",
"}"
] | @param string $table
@param Connection $db
@return array | [
"@param",
"string",
"$table",
"@param",
"Connection",
"$db"
] | train | https://github.com/webfactory/slimdump/blob/43a73b9b1a63f5058e506707efa07fac14be35c0/src/Webfactory/Slimdump/Database/Dumper.php#L210-L217 |
webfactory/slimdump | src/Webfactory/Slimdump/Config/Config.php | Config.merge | public function merge(Config $other)
{
$this->tables = array_merge($this->tables, $other->getTables());
} | php | public function merge(Config $other)
{
$this->tables = array_merge($this->tables, $other->getTables());
} | [
"public",
"function",
"merge",
"(",
"Config",
"$",
"other",
")",
"{",
"$",
"this",
"->",
"tables",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"tables",
",",
"$",
"other",
"->",
"getTables",
"(",
")",
")",
";",
"}"
] | Merge two configurations together.
If two configurations specify the same table,
the last one wins.
@param Config $other | [
"Merge",
"two",
"configurations",
"together",
".",
"If",
"two",
"configurations",
"specify",
"the",
"same",
"table",
"the",
"last",
"one",
"wins",
"."
] | train | https://github.com/webfactory/slimdump/blob/43a73b9b1a63f5058e506707efa07fac14be35c0/src/Webfactory/Slimdump/Config/Config.php#L45-L48 |
rollerworks/PasswordStrengthBundle | src/DependencyInjection/RollerworksPasswordStrengthExtension.php | RollerworksPasswordStrengthExtension.prepend | public function prepend(ContainerBuilder $container)
{
$container->prependExtensionConfig('framework', [
'translator' => [
'paths' => [
dirname(dirname((new \ReflectionClass(LazyChainProvider::class))->getFileName())).'/Resources/translations',
],
],
]);
} | php | public function prepend(ContainerBuilder $container)
{
$container->prependExtensionConfig('framework', [
'translator' => [
'paths' => [
dirname(dirname((new \ReflectionClass(LazyChainProvider::class))->getFileName())).'/Resources/translations',
],
],
]);
} | [
"public",
"function",
"prepend",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"container",
"->",
"prependExtensionConfig",
"(",
"'framework'",
",",
"[",
"'translator'",
"=>",
"[",
"'paths'",
"=>",
"[",
"dirname",
"(",
"dirname",
"(",
"(",
"new",
"\\",
"ReflectionClass",
"(",
"LazyChainProvider",
"::",
"class",
")",
")",
"->",
"getFileName",
"(",
")",
")",
")",
".",
"'/Resources/translations'",
",",
"]",
",",
"]",
",",
"]",
")",
";",
"}"
] | Allow an extension to prepend the extension configurations.
@param ContainerBuilder $container | [
"Allow",
"an",
"extension",
"to",
"prepend",
"the",
"extension",
"configurations",
"."
] | train | https://github.com/rollerworks/PasswordStrengthBundle/blob/b37eebff9488d82e528a2b80910e9dc8e987d90a/src/DependencyInjection/RollerworksPasswordStrengthExtension.php#L55-L64 |
mpclarkson/freshdesk-php-sdk | src/Resources/Contact.php | Contact.makeAgent | public function makeAgent($id, array $query = null)
{
$end = $id . '/make_agent';
return $this->api()->request('GET', $this->endpoint($end), null, $query);
} | php | public function makeAgent($id, array $query = null)
{
$end = $id . '/make_agent';
return $this->api()->request('GET', $this->endpoint($end), null, $query);
} | [
"public",
"function",
"makeAgent",
"(",
"$",
"id",
",",
"array",
"$",
"query",
"=",
"null",
")",
"{",
"$",
"end",
"=",
"$",
"id",
".",
"'/make_agent'",
";",
"return",
"$",
"this",
"->",
"api",
"(",
")",
"->",
"request",
"(",
"'GET'",
",",
"$",
"this",
"->",
"endpoint",
"(",
"$",
"end",
")",
",",
"null",
",",
"$",
"query",
")",
";",
"}"
] | Convert a contact into an agent
Note:
1. The contact must have an email address in order to be converted into an agent.
2. If your account has already reached the maximum number of agents, the API request will fail with HTTP error code 403
3. The agent whose credentials (API key, username and password) were used to make this API call should be authorised to convert a contact into an agent
@param int $id The agent id
@param array|null $query
@return array|null
@throws \Freshdesk\Exceptions\AccessDeniedException
@throws \Freshdesk\Exceptions\ApiException
@throws \Freshdesk\Exceptions\AuthenticationException
@throws \Freshdesk\Exceptions\ConflictingStateException
@throws \Freshdesk\Exceptions\NotFoundException
@throws \Freshdesk\Exceptions\RateLimitExceededException
@throws \Freshdesk\Exceptions\UnsupportedContentTypeException
@throws \Freshdesk\Exceptions\MethodNotAllowedException
@throws \Freshdesk\Exceptions\UnsupportedAcceptHeaderException
@throws \Freshdesk\Exceptions\ValidationException | [
"Convert",
"a",
"contact",
"into",
"an",
"agent"
] | train | https://github.com/mpclarkson/freshdesk-php-sdk/blob/9247ef457f7df414b470359f5bc268c489b6289a/src/Resources/Contact.php#L84-L89 |
mpclarkson/freshdesk-php-sdk | src/Api.php | Api.performRequest | private function performRequest($method, $url, $options) {
try {
switch ($method) {
case 'GET':
return json_decode($this->client->get($url, $options)->getBody(), true);
case 'POST':
return json_decode($this->client->post($url, $options)->getBody(), true);
case 'PUT':
return json_decode($this->client->put($url, $options)->getBody(), true);
case 'DELETE':
return json_decode($this->client->delete($url, $options)->getBody(), true);
default:
return null;
}
} catch (RequestException $e) {
throw ApiException::create($e);
}
} | php | private function performRequest($method, $url, $options) {
try {
switch ($method) {
case 'GET':
return json_decode($this->client->get($url, $options)->getBody(), true);
case 'POST':
return json_decode($this->client->post($url, $options)->getBody(), true);
case 'PUT':
return json_decode($this->client->put($url, $options)->getBody(), true);
case 'DELETE':
return json_decode($this->client->delete($url, $options)->getBody(), true);
default:
return null;
}
} catch (RequestException $e) {
throw ApiException::create($e);
}
} | [
"private",
"function",
"performRequest",
"(",
"$",
"method",
",",
"$",
"url",
",",
"$",
"options",
")",
"{",
"try",
"{",
"switch",
"(",
"$",
"method",
")",
"{",
"case",
"'GET'",
":",
"return",
"json_decode",
"(",
"$",
"this",
"->",
"client",
"->",
"get",
"(",
"$",
"url",
",",
"$",
"options",
")",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"case",
"'POST'",
":",
"return",
"json_decode",
"(",
"$",
"this",
"->",
"client",
"->",
"post",
"(",
"$",
"url",
",",
"$",
"options",
")",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"case",
"'PUT'",
":",
"return",
"json_decode",
"(",
"$",
"this",
"->",
"client",
"->",
"put",
"(",
"$",
"url",
",",
"$",
"options",
")",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"case",
"'DELETE'",
":",
"return",
"json_decode",
"(",
"$",
"this",
"->",
"client",
"->",
"delete",
"(",
"$",
"url",
",",
"$",
"options",
")",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"default",
":",
"return",
"null",
";",
"}",
"}",
"catch",
"(",
"RequestException",
"$",
"e",
")",
"{",
"throw",
"ApiException",
"::",
"create",
"(",
"$",
"e",
")",
";",
"}",
"}"
] | Performs the request
@internal
@param $method
@param $url
@param $options
@return mixed|null
@throws AccessDeniedException
@throws ApiException
@throws AuthenticationException
@throws ConflictingStateException | [
"Performs",
"the",
"request"
] | train | https://github.com/mpclarkson/freshdesk-php-sdk/blob/9247ef457f7df414b470359f5bc268c489b6289a/src/Api.php#L244-L262 |
mpclarkson/freshdesk-php-sdk | src/Api.php | Api.validateConstructorArgs | private function validateConstructorArgs($apiKey, $domain)
{
if (!isset($apiKey)) {
throw new Exceptions\InvalidConfigurationException("API key is empty.");
}
if (!isset($domain)) {
throw new Exceptions\InvalidConfigurationException("Domain is empty.");
}
} | php | private function validateConstructorArgs($apiKey, $domain)
{
if (!isset($apiKey)) {
throw new Exceptions\InvalidConfigurationException("API key is empty.");
}
if (!isset($domain)) {
throw new Exceptions\InvalidConfigurationException("Domain is empty.");
}
} | [
"private",
"function",
"validateConstructorArgs",
"(",
"$",
"apiKey",
",",
"$",
"domain",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"apiKey",
")",
")",
"{",
"throw",
"new",
"Exceptions",
"\\",
"InvalidConfigurationException",
"(",
"\"API key is empty.\"",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"domain",
")",
")",
"{",
"throw",
"new",
"Exceptions",
"\\",
"InvalidConfigurationException",
"(",
"\"Domain is empty.\"",
")",
";",
"}",
"}"
] | @param $apiKey
@param $domain
@throws Exceptions\InvalidConfigurationException
@internal | [
"@param",
"$apiKey",
"@param",
"$domain",
"@throws",
"Exceptions",
"\\",
"InvalidConfigurationException",
"@internal"
] | train | https://github.com/mpclarkson/freshdesk-php-sdk/blob/9247ef457f7df414b470359f5bc268c489b6289a/src/Api.php#L272-L281 |
mpclarkson/freshdesk-php-sdk | src/Resources/Traits/ViewTrait.php | ViewTrait.view | public function view($id, array $query = null)
{
return $this->api()->request('GET', $this->endpoint($id), null, $query);
} | php | public function view($id, array $query = null)
{
return $this->api()->request('GET', $this->endpoint($id), null, $query);
} | [
"public",
"function",
"view",
"(",
"$",
"id",
",",
"array",
"$",
"query",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"api",
"(",
")",
"->",
"request",
"(",
"'GET'",
",",
"$",
"this",
"->",
"endpoint",
"(",
"$",
"id",
")",
",",
"null",
",",
"$",
"query",
")",
";",
"}"
] | View a resource
Use 'include' to embed additional details in the response. Each include will consume an additional credit.
For example if you embed the requester and company information you will be charged a total of 3 API credits for the call.
See Freshdesk's documentation for details.
@api
@param int $id The resource id
@param array|null $query
@return array|null
@throws \Freshdesk\Exceptions\AccessDeniedException
@throws \Freshdesk\Exceptions\ApiException
@throws \Freshdesk\Exceptions\AuthenticationException
@throws \Freshdesk\Exceptions\ConflictingStateException
@throws \Freshdesk\Exceptions\NotFoundException
@throws \Freshdesk\Exceptions\RateLimitExceededException
@throws \Freshdesk\Exceptions\UnsupportedContentTypeException
@throws \Freshdesk\Exceptions\MethodNotAllowedException
@throws \Freshdesk\Exceptions\UnsupportedAcceptHeaderException
@throws \Freshdesk\Exceptions\ValidationException | [
"View",
"a",
"resource"
] | train | https://github.com/mpclarkson/freshdesk-php-sdk/blob/9247ef457f7df414b470359f5bc268c489b6289a/src/Resources/Traits/ViewTrait.php#L54-L57 |
mpclarkson/freshdesk-php-sdk | src/Resources/Traits/AllTrait.php | AllTrait.all | public function all(array $query = null)
{
return $this->api()->request('GET', $this->endpoint(), null, $query);
} | php | public function all(array $query = null)
{
return $this->api()->request('GET', $this->endpoint(), null, $query);
} | [
"public",
"function",
"all",
"(",
"array",
"$",
"query",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"api",
"(",
")",
"->",
"request",
"(",
"'GET'",
",",
"$",
"this",
"->",
"endpoint",
"(",
")",
",",
"null",
",",
"$",
"query",
")",
";",
"}"
] | Get a list of all agents.
Use filters ($query) to view only specific resources (those which match the criteria that you choose).
@api
@param array|null $query
@return array|null
@throws \Freshdesk\Exceptions\AccessDeniedException
@throws \Freshdesk\Exceptions\ApiException
@throws \Freshdesk\Exceptions\AuthenticationException
@throws \Freshdesk\Exceptions\ConflictingStateException
@throws \Freshdesk\Exceptions\NotFoundException
@throws \Freshdesk\Exceptions\RateLimitExceededException
@throws \Freshdesk\Exceptions\UnsupportedContentTypeException
@throws \Freshdesk\Exceptions\MethodNotAllowedException
@throws \Freshdesk\Exceptions\UnsupportedAcceptHeaderException
@throws \Freshdesk\Exceptions\ValidationException | [
"Get",
"a",
"list",
"of",
"all",
"agents",
"."
] | train | https://github.com/mpclarkson/freshdesk-php-sdk/blob/9247ef457f7df414b470359f5bc268c489b6289a/src/Resources/Traits/AllTrait.php#L51-L54 |
mpclarkson/freshdesk-php-sdk | src/Resources/TimeEntry.php | TimeEntry.ticketsEndpoint | protected function ticketsEndpoint($id = null)
{
return $id === null ? $this->ticketsEndpoint : $this->ticketsEndpoint . '/' . $id;
} | php | protected function ticketsEndpoint($id = null)
{
return $id === null ? $this->ticketsEndpoint : $this->ticketsEndpoint . '/' . $id;
} | [
"protected",
"function",
"ticketsEndpoint",
"(",
"$",
"id",
"=",
"null",
")",
"{",
"return",
"$",
"id",
"===",
"null",
"?",
"$",
"this",
"->",
"ticketsEndpoint",
":",
"$",
"this",
"->",
"ticketsEndpoint",
".",
"'/'",
".",
"$",
"id",
";",
"}"
] | Creates the forums endpoint
@param string $id
@return string
@internal | [
"Creates",
"the",
"forums",
"endpoint"
] | train | https://github.com/mpclarkson/freshdesk-php-sdk/blob/9247ef457f7df414b470359f5bc268c489b6289a/src/Resources/TimeEntry.php#L50-L53 |
mpclarkson/freshdesk-php-sdk | src/Resources/Traits/UpdateTrait.php | UpdateTrait.update | public function update($id, array $data)
{
return $this->api()->request('PUT', $this->endpoint($id), $data);
} | php | public function update($id, array $data)
{
return $this->api()->request('PUT', $this->endpoint($id), $data);
} | [
"public",
"function",
"update",
"(",
"$",
"id",
",",
"array",
"$",
"data",
")",
"{",
"return",
"$",
"this",
"->",
"api",
"(",
")",
"->",
"request",
"(",
"'PUT'",
",",
"$",
"this",
"->",
"endpoint",
"(",
"$",
"id",
")",
",",
"$",
"data",
")",
";",
"}"
] | Update a resource
Updates the resources for the given $id with the supplied data/.
@api
@param int $id The resource id
@param array $data The data
@return array|null
@throws \Freshdesk\Exceptions\AccessDeniedException
@throws \Freshdesk\Exceptions\ApiException
@throws \Freshdesk\Exceptions\AuthenticationException
@throws \Freshdesk\Exceptions\ConflictingStateException
@throws \Freshdesk\Exceptions\NotFoundException
@throws \Freshdesk\Exceptions\RateLimitExceededException
@throws \Freshdesk\Exceptions\UnsupportedContentTypeException
@throws \Freshdesk\Exceptions\MethodNotAllowedException
@throws \Freshdesk\Exceptions\UnsupportedAcceptHeaderException
@throws \Freshdesk\Exceptions\ValidationException | [
"Update",
"a",
"resource"
] | train | https://github.com/mpclarkson/freshdesk-php-sdk/blob/9247ef457f7df414b470359f5bc268c489b6289a/src/Resources/Traits/UpdateTrait.php#L53-L56 |
mpclarkson/freshdesk-php-sdk | src/Resources/Forum.php | Forum.categoryEndpoint | private function categoryEndpoint($id = null)
{
return $id === null ? $this->categoryEndpoint : $this->categoryEndpoint . '/' . $id;
} | php | private function categoryEndpoint($id = null)
{
return $id === null ? $this->categoryEndpoint : $this->categoryEndpoint . '/' . $id;
} | [
"private",
"function",
"categoryEndpoint",
"(",
"$",
"id",
"=",
"null",
")",
"{",
"return",
"$",
"id",
"===",
"null",
"?",
"$",
"this",
"->",
"categoryEndpoint",
":",
"$",
"this",
"->",
"categoryEndpoint",
".",
"'/'",
".",
"$",
"id",
";",
"}"
] | Creates the category endpoint (for creating forums)
@param integer $id
@return string
@internal | [
"Creates",
"the",
"category",
"endpoint",
"(",
"for",
"creating",
"forums",
")"
] | train | https://github.com/mpclarkson/freshdesk-php-sdk/blob/9247ef457f7df414b470359f5bc268c489b6289a/src/Resources/Forum.php#L53-L56 |
mpclarkson/freshdesk-php-sdk | src/Resources/Ticket.php | Ticket.restore | public function restore($id)
{
$end = $id . '/restore';
return $this->api()->request('PUT', $this->endpoint($end));
} | php | public function restore($id)
{
$end = $id . '/restore';
return $this->api()->request('PUT', $this->endpoint($end));
} | [
"public",
"function",
"restore",
"(",
"$",
"id",
")",
"{",
"$",
"end",
"=",
"$",
"id",
".",
"'/restore'",
";",
"return",
"$",
"this",
"->",
"api",
"(",
")",
"->",
"request",
"(",
"'PUT'",
",",
"$",
"this",
"->",
"endpoint",
"(",
"$",
"end",
")",
")",
";",
"}"
] | Restore a ticket
Restores a previously deleted ticket
@api
@param $id
@return mixed|null
@throws \Freshdesk\Exceptions\AccessDeniedException
@throws \Freshdesk\Exceptions\ApiException
@throws \Freshdesk\Exceptions\AuthenticationException
@throws \Freshdesk\Exceptions\ConflictingStateException
@throws \Freshdesk\Exceptions\NotFoundException
@throws \Freshdesk\Exceptions\RateLimitExceededException
@throws \Freshdesk\Exceptions\UnsupportedContentTypeException
@throws \Freshdesk\Exceptions\MethodNotAllowedException
@throws \Freshdesk\Exceptions\UnsupportedAcceptHeaderException
@throws \Freshdesk\Exceptions\ValidationException | [
"Restore",
"a",
"ticket"
] | train | https://github.com/mpclarkson/freshdesk-php-sdk/blob/9247ef457f7df414b470359f5bc268c489b6289a/src/Resources/Ticket.php#L55-L60 |
mpclarkson/freshdesk-php-sdk | src/Resources/Ticket.php | Ticket.search | public function search(string $filtersQuery)
{
$end = '/search'.$this->endpoint();
$query = [
'query' => '"'.$filtersQuery.'"',
];
return $this->api()->request('GET', $end, null, $query);
} | php | public function search(string $filtersQuery)
{
$end = '/search'.$this->endpoint();
$query = [
'query' => '"'.$filtersQuery.'"',
];
return $this->api()->request('GET', $end, null, $query);
} | [
"public",
"function",
"search",
"(",
"string",
"$",
"filtersQuery",
")",
"{",
"$",
"end",
"=",
"'/search'",
".",
"$",
"this",
"->",
"endpoint",
"(",
")",
";",
"$",
"query",
"=",
"[",
"'query'",
"=>",
"'\"'",
".",
"$",
"filtersQuery",
".",
"'\"'",
",",
"]",
";",
"return",
"$",
"this",
"->",
"api",
"(",
")",
"->",
"request",
"(",
"'GET'",
",",
"$",
"end",
",",
"null",
",",
"$",
"query",
")",
";",
"}"
] | Filters by ticket fields
Make sure to pass a valid $filtersQuery string example: "type:question"
@api
@param string $filtersQuery
@return array|null
@throws \Freshdesk\Exceptions\AccessDeniedException
@throws \Freshdesk\Exceptions\ApiException
@throws \Freshdesk\Exceptions\AuthenticationException
@throws \Freshdesk\Exceptions\ConflictingStateException
@throws \Freshdesk\Exceptions\NotFoundException
@throws \Freshdesk\Exceptions\RateLimitExceededException
@throws \Freshdesk\Exceptions\UnsupportedContentTypeException
@throws \Freshdesk\Exceptions\MethodNotAllowedException
@throws \Freshdesk\Exceptions\UnsupportedAcceptHeaderException
@throws \Freshdesk\Exceptions\ValidationException | [
"Filters",
"by",
"ticket",
"fields"
] | train | https://github.com/mpclarkson/freshdesk-php-sdk/blob/9247ef457f7df414b470359f5bc268c489b6289a/src/Resources/Ticket.php#L153-L160 |
mpclarkson/freshdesk-php-sdk | src/Resources/Traits/MonitorTrait.php | MonitorTrait.monitor | public function monitor($id, $userId)
{
$data = [
'user_id' => $userId
];
return $this->api()->request('POST', $this->endpoint($id . '/follow'), $data);
} | php | public function monitor($id, $userId)
{
$data = [
'user_id' => $userId
];
return $this->api()->request('POST', $this->endpoint($id . '/follow'), $data);
} | [
"public",
"function",
"monitor",
"(",
"$",
"id",
",",
"$",
"userId",
")",
"{",
"$",
"data",
"=",
"[",
"'user_id'",
"=>",
"$",
"userId",
"]",
";",
"return",
"$",
"this",
"->",
"api",
"(",
")",
"->",
"request",
"(",
"'POST'",
",",
"$",
"this",
"->",
"endpoint",
"(",
"$",
"id",
".",
"'/follow'",
")",
",",
"$",
"data",
")",
";",
"}"
] | Monitor a resource
Monitor a resource for the given user
@api
@param $id The id of the resource
@param $userId The id of the user
@return array|null
@throws \Freshdesk\Exceptions\AccessDeniedException
@throws \Freshdesk\Exceptions\ApiException
@throws \Freshdesk\Exceptions\AuthenticationException
@throws \Freshdesk\Exceptions\ConflictingStateException
@throws \Freshdesk\Exceptions\NotFoundException
@throws \Freshdesk\Exceptions\RateLimitExceededException
@throws \Freshdesk\Exceptions\UnsupportedContentTypeException
@throws \Freshdesk\Exceptions\MethodNotAllowedException
@throws \Freshdesk\Exceptions\UnsupportedAcceptHeaderException
@throws \Freshdesk\Exceptions\ValidationException | [
"Monitor",
"a",
"resource"
] | train | https://github.com/mpclarkson/freshdesk-php-sdk/blob/9247ef457f7df414b470359f5bc268c489b6289a/src/Resources/Traits/MonitorTrait.php#L52-L59 |
mpclarkson/freshdesk-php-sdk | src/Resources/Traits/MonitorTrait.php | MonitorTrait.monitorStatus | public function monitorStatus($id, $userId)
{
$query = [
'user_id' => $userId
];
return $this->api()->request('GET', $this->endpoint($id . '/follow'), null, $query);
} | php | public function monitorStatus($id, $userId)
{
$query = [
'user_id' => $userId
];
return $this->api()->request('GET', $this->endpoint($id . '/follow'), null, $query);
} | [
"public",
"function",
"monitorStatus",
"(",
"$",
"id",
",",
"$",
"userId",
")",
"{",
"$",
"query",
"=",
"[",
"'user_id'",
"=>",
"$",
"userId",
"]",
";",
"return",
"$",
"this",
"->",
"api",
"(",
")",
"->",
"request",
"(",
"'GET'",
",",
"$",
"this",
"->",
"endpoint",
"(",
"$",
"id",
".",
"'/follow'",
")",
",",
"null",
",",
"$",
"query",
")",
";",
"}"
] | Monitor status
Get the monitoring status of the topic for the user
@api
@param $id The id of the resource
@param $userId The id of the user
@return array|null
@throws \Freshdesk\Exceptions\AccessDeniedException
@throws \Freshdesk\Exceptions\ApiException
@throws \Freshdesk\Exceptions\AuthenticationException
@throws \Freshdesk\Exceptions\ConflictingStateException
@throws \Freshdesk\Exceptions\NotFoundException
@throws \Freshdesk\Exceptions\RateLimitExceededException
@throws \Freshdesk\Exceptions\UnsupportedContentTypeException
@throws \Freshdesk\Exceptions\MethodNotAllowedException
@throws \Freshdesk\Exceptions\UnsupportedAcceptHeaderException
@throws \Freshdesk\Exceptions\ValidationException | [
"Monitor",
"status"
] | train | https://github.com/mpclarkson/freshdesk-php-sdk/blob/9247ef457f7df414b470359f5bc268c489b6289a/src/Resources/Traits/MonitorTrait.php#L110-L117 |
mpclarkson/freshdesk-php-sdk | src/Resources/AbstractResource.php | AbstractResource.endpoint | protected function endpoint($id = null)
{
return $id === null ? $this->endpoint : $this->endpoint . '/' . $id;
} | php | protected function endpoint($id = null)
{
return $id === null ? $this->endpoint : $this->endpoint . '/' . $id;
} | [
"protected",
"function",
"endpoint",
"(",
"$",
"id",
"=",
"null",
")",
"{",
"return",
"$",
"id",
"===",
"null",
"?",
"$",
"this",
"->",
"endpoint",
":",
"$",
"this",
"->",
"endpoint",
".",
"'/'",
".",
"$",
"id",
";",
"}"
] | Creates the endpoint
@param null $id The endpoint terminator
@return string
@internal | [
"Creates",
"the",
"endpoint"
] | train | https://github.com/mpclarkson/freshdesk-php-sdk/blob/9247ef457f7df414b470359f5bc268c489b6289a/src/Resources/AbstractResource.php#L58-L61 |
mpclarkson/freshdesk-php-sdk | src/Resources/Comment.php | Comment.topicsEndpoint | protected function topicsEndpoint($id = null)
{
return $id === null ? $this->topicsEndpoint : $this->topicsEndpoint . '/' . $id;
} | php | protected function topicsEndpoint($id = null)
{
return $id === null ? $this->topicsEndpoint : $this->topicsEndpoint . '/' . $id;
} | [
"protected",
"function",
"topicsEndpoint",
"(",
"$",
"id",
"=",
"null",
")",
"{",
"return",
"$",
"id",
"===",
"null",
"?",
"$",
"this",
"->",
"topicsEndpoint",
":",
"$",
"this",
"->",
"topicsEndpoint",
".",
"'/'",
".",
"$",
"id",
";",
"}"
] | Creates the forums endpoint
@param string $id
@return string
@internal | [
"Creates",
"the",
"forums",
"endpoint"
] | train | https://github.com/mpclarkson/freshdesk-php-sdk/blob/9247ef457f7df414b470359f5bc268c489b6289a/src/Resources/Comment.php#L50-L53 |
mpclarkson/freshdesk-php-sdk | src/Resources/Topic.php | Topic.forumsEndpoint | protected function forumsEndpoint($id = null)
{
return $id === null ? $this->forumsEndpoint : $this->forumsEndpoint . '/' . $id;
} | php | protected function forumsEndpoint($id = null)
{
return $id === null ? $this->forumsEndpoint : $this->forumsEndpoint . '/' . $id;
} | [
"protected",
"function",
"forumsEndpoint",
"(",
"$",
"id",
"=",
"null",
")",
"{",
"return",
"$",
"id",
"===",
"null",
"?",
"$",
"this",
"->",
"forumsEndpoint",
":",
"$",
"this",
"->",
"forumsEndpoint",
".",
"'/'",
".",
"$",
"id",
";",
"}"
] | Creates the forums endpoint
@param string $id
@return string
@internal | [
"Creates",
"the",
"forums",
"endpoint"
] | train | https://github.com/mpclarkson/freshdesk-php-sdk/blob/9247ef457f7df414b470359f5bc268c489b6289a/src/Resources/Topic.php#L50-L53 |
Limenius/Liform | src/Limenius/Liform/Transformer/ArrayTransformer.php | ArrayTransformer.transform | public function transform(FormInterface $form, array $extensions = [], $widget = null)
{
$children = [];
foreach ($form->all() as $name => $field) {
$transformerData = $this->resolver->resolve($field);
$transformedChild = $transformerData['transformer']->transform($field, $extensions, $transformerData['widget']);
$children[] = $transformedChild;
if ($transformerData['transformer']->isRequired($field)) {
$required[] = $field->getName();
}
}
if (empty($children)) {
$entryType = $form->getConfig()->getAttribute('prototype');
if (!$entryType) {
throw new TransformerException('Liform cannot infer the json-schema representation of a an empty Collection or array-like type without the option "allow_add" (to check the proptotype). Evaluating "'.$form->getName().'"');
}
$transformerData = $this->resolver->resolve($entryType);
$children[] = $transformerData['transformer']->transform($entryType, $extensions, $transformerData['widget']);
$children[0]['title'] = 'prototype';
}
$schema = [
'type' => 'array',
'title' => $form->getConfig()->getOption('label'),
'items' => $children[0],
];
$schema = $this->addCommonSpecs($form, $schema, $extensions, $widget);
return $schema;
} | php | public function transform(FormInterface $form, array $extensions = [], $widget = null)
{
$children = [];
foreach ($form->all() as $name => $field) {
$transformerData = $this->resolver->resolve($field);
$transformedChild = $transformerData['transformer']->transform($field, $extensions, $transformerData['widget']);
$children[] = $transformedChild;
if ($transformerData['transformer']->isRequired($field)) {
$required[] = $field->getName();
}
}
if (empty($children)) {
$entryType = $form->getConfig()->getAttribute('prototype');
if (!$entryType) {
throw new TransformerException('Liform cannot infer the json-schema representation of a an empty Collection or array-like type without the option "allow_add" (to check the proptotype). Evaluating "'.$form->getName().'"');
}
$transformerData = $this->resolver->resolve($entryType);
$children[] = $transformerData['transformer']->transform($entryType, $extensions, $transformerData['widget']);
$children[0]['title'] = 'prototype';
}
$schema = [
'type' => 'array',
'title' => $form->getConfig()->getOption('label'),
'items' => $children[0],
];
$schema = $this->addCommonSpecs($form, $schema, $extensions, $widget);
return $schema;
} | [
"public",
"function",
"transform",
"(",
"FormInterface",
"$",
"form",
",",
"array",
"$",
"extensions",
"=",
"[",
"]",
",",
"$",
"widget",
"=",
"null",
")",
"{",
"$",
"children",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"form",
"->",
"all",
"(",
")",
"as",
"$",
"name",
"=>",
"$",
"field",
")",
"{",
"$",
"transformerData",
"=",
"$",
"this",
"->",
"resolver",
"->",
"resolve",
"(",
"$",
"field",
")",
";",
"$",
"transformedChild",
"=",
"$",
"transformerData",
"[",
"'transformer'",
"]",
"->",
"transform",
"(",
"$",
"field",
",",
"$",
"extensions",
",",
"$",
"transformerData",
"[",
"'widget'",
"]",
")",
";",
"$",
"children",
"[",
"]",
"=",
"$",
"transformedChild",
";",
"if",
"(",
"$",
"transformerData",
"[",
"'transformer'",
"]",
"->",
"isRequired",
"(",
"$",
"field",
")",
")",
"{",
"$",
"required",
"[",
"]",
"=",
"$",
"field",
"->",
"getName",
"(",
")",
";",
"}",
"}",
"if",
"(",
"empty",
"(",
"$",
"children",
")",
")",
"{",
"$",
"entryType",
"=",
"$",
"form",
"->",
"getConfig",
"(",
")",
"->",
"getAttribute",
"(",
"'prototype'",
")",
";",
"if",
"(",
"!",
"$",
"entryType",
")",
"{",
"throw",
"new",
"TransformerException",
"(",
"'Liform cannot infer the json-schema representation of a an empty Collection or array-like type without the option \"allow_add\" (to check the proptotype). Evaluating \"'",
".",
"$",
"form",
"->",
"getName",
"(",
")",
".",
"'\"'",
")",
";",
"}",
"$",
"transformerData",
"=",
"$",
"this",
"->",
"resolver",
"->",
"resolve",
"(",
"$",
"entryType",
")",
";",
"$",
"children",
"[",
"]",
"=",
"$",
"transformerData",
"[",
"'transformer'",
"]",
"->",
"transform",
"(",
"$",
"entryType",
",",
"$",
"extensions",
",",
"$",
"transformerData",
"[",
"'widget'",
"]",
")",
";",
"$",
"children",
"[",
"0",
"]",
"[",
"'title'",
"]",
"=",
"'prototype'",
";",
"}",
"$",
"schema",
"=",
"[",
"'type'",
"=>",
"'array'",
",",
"'title'",
"=>",
"$",
"form",
"->",
"getConfig",
"(",
")",
"->",
"getOption",
"(",
"'label'",
")",
",",
"'items'",
"=>",
"$",
"children",
"[",
"0",
"]",
",",
"]",
";",
"$",
"schema",
"=",
"$",
"this",
"->",
"addCommonSpecs",
"(",
"$",
"form",
",",
"$",
"schema",
",",
"$",
"extensions",
",",
"$",
"widget",
")",
";",
"return",
"$",
"schema",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/Limenius/Liform/blob/b46ba76cc7703b9d9989ff9f8ca4437cfc8f6c6c/src/Limenius/Liform/Transformer/ArrayTransformer.php#L47-L82 |
Limenius/Liform | src/Limenius/Liform/FormUtil.php | FormUtil.typeAncestryForType | public static function typeAncestryForType(ResolvedFormTypeInterface $formType = null, array &$types)
{
if (!($formType instanceof ResolvedFormTypeInterface)) {
return;
}
$types[] = $formType->getBlockPrefix();
self::typeAncestryForType($formType->getParent(), $types);
} | php | public static function typeAncestryForType(ResolvedFormTypeInterface $formType = null, array &$types)
{
if (!($formType instanceof ResolvedFormTypeInterface)) {
return;
}
$types[] = $formType->getBlockPrefix();
self::typeAncestryForType($formType->getParent(), $types);
} | [
"public",
"static",
"function",
"typeAncestryForType",
"(",
"ResolvedFormTypeInterface",
"$",
"formType",
"=",
"null",
",",
"array",
"&",
"$",
"types",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"formType",
"instanceof",
"ResolvedFormTypeInterface",
")",
")",
"{",
"return",
";",
"}",
"$",
"types",
"[",
"]",
"=",
"$",
"formType",
"->",
"getBlockPrefix",
"(",
")",
";",
"self",
"::",
"typeAncestryForType",
"(",
"$",
"formType",
"->",
"getParent",
"(",
")",
",",
"$",
"types",
")",
";",
"}"
] | @param ResolvedFormTypeInterface $formType
@param array $types
@return void | [
"@param",
"ResolvedFormTypeInterface",
"$formType",
"@param",
"array",
"$types"
] | train | https://github.com/Limenius/Liform/blob/b46ba76cc7703b9d9989ff9f8ca4437cfc8f6c6c/src/Limenius/Liform/FormUtil.php#L41-L50 |
Limenius/Liform | src/Limenius/Liform/FormUtil.php | FormUtil.findDataClass | public static function findDataClass($formType)
{
if ($dataClass = $formType->getConfig()->getDataClass()) {
return $dataClass;
} else {
if ($parent = $formType->getParent()) {
return self::findDataClass($parent);
} else {
return null;
}
}
} | php | public static function findDataClass($formType)
{
if ($dataClass = $formType->getConfig()->getDataClass()) {
return $dataClass;
} else {
if ($parent = $formType->getParent()) {
return self::findDataClass($parent);
} else {
return null;
}
}
} | [
"public",
"static",
"function",
"findDataClass",
"(",
"$",
"formType",
")",
"{",
"if",
"(",
"$",
"dataClass",
"=",
"$",
"formType",
"->",
"getConfig",
"(",
")",
"->",
"getDataClass",
"(",
")",
")",
"{",
"return",
"$",
"dataClass",
";",
"}",
"else",
"{",
"if",
"(",
"$",
"parent",
"=",
"$",
"formType",
"->",
"getParent",
"(",
")",
")",
"{",
"return",
"self",
"::",
"findDataClass",
"(",
"$",
"parent",
")",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}",
"}"
] | Returns the dataClass of the form or its parents, if any
@param mixed $formType
@return string|null the dataClass | [
"Returns",
"the",
"dataClass",
"of",
"the",
"form",
"or",
"its",
"parents",
"if",
"any"
] | train | https://github.com/Limenius/Liform/blob/b46ba76cc7703b9d9989ff9f8ca4437cfc8f6c6c/src/Limenius/Liform/FormUtil.php#L59-L70 |
Limenius/Liform | src/Limenius/Liform/Serializer/Normalizer/FormErrorNormalizer.php | FormErrorNormalizer.convertFormToArray | private function convertFormToArray(FormInterface $data)
{
$form = $errors = [];
foreach ($data->getErrors() as $error) {
$errors[] = $this->getErrorMessage($error);
}
if ($errors) {
$form['errors'] = $errors;
}
$children = [];
foreach ($data->all() as $child) {
if ($child instanceof FormInterface) {
$children[$child->getName()] = $this->convertFormToArray($child);
}
}
if ($children) {
$form['children'] = $children;
}
return $form;
} | php | private function convertFormToArray(FormInterface $data)
{
$form = $errors = [];
foreach ($data->getErrors() as $error) {
$errors[] = $this->getErrorMessage($error);
}
if ($errors) {
$form['errors'] = $errors;
}
$children = [];
foreach ($data->all() as $child) {
if ($child instanceof FormInterface) {
$children[$child->getName()] = $this->convertFormToArray($child);
}
}
if ($children) {
$form['children'] = $children;
}
return $form;
} | [
"private",
"function",
"convertFormToArray",
"(",
"FormInterface",
"$",
"data",
")",
"{",
"$",
"form",
"=",
"$",
"errors",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"data",
"->",
"getErrors",
"(",
")",
"as",
"$",
"error",
")",
"{",
"$",
"errors",
"[",
"]",
"=",
"$",
"this",
"->",
"getErrorMessage",
"(",
"$",
"error",
")",
";",
"}",
"if",
"(",
"$",
"errors",
")",
"{",
"$",
"form",
"[",
"'errors'",
"]",
"=",
"$",
"errors",
";",
"}",
"$",
"children",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"data",
"->",
"all",
"(",
")",
"as",
"$",
"child",
")",
"{",
"if",
"(",
"$",
"child",
"instanceof",
"FormInterface",
")",
"{",
"$",
"children",
"[",
"$",
"child",
"->",
"getName",
"(",
")",
"]",
"=",
"$",
"this",
"->",
"convertFormToArray",
"(",
"$",
"child",
")",
";",
"}",
"}",
"if",
"(",
"$",
"children",
")",
"{",
"$",
"form",
"[",
"'children'",
"]",
"=",
"$",
"children",
";",
"}",
"return",
"$",
"form",
";",
"}"
] | This code has been taken from JMSSerializer.
@param FormInterface $data
@return array | [
"This",
"code",
"has",
"been",
"taken",
"from",
"JMSSerializer",
"."
] | train | https://github.com/Limenius/Liform/blob/b46ba76cc7703b9d9989ff9f8ca4437cfc8f6c6c/src/Limenius/Liform/Serializer/Normalizer/FormErrorNormalizer.php#L66-L89 |
Limenius/Liform | src/Limenius/Liform/Serializer/Normalizer/FormErrorNormalizer.php | FormErrorNormalizer.getErrorMessage | private function getErrorMessage(FormError $error)
{
if (null !== $error->getMessagePluralization()) {
return $this->translator->transChoice($error->getMessageTemplate(), $error->getMessagePluralization(), $error->getMessageParameters(), 'validators');
}
return $this->translator->trans($error->getMessageTemplate(), $error->getMessageParameters(), 'validators');
} | php | private function getErrorMessage(FormError $error)
{
if (null !== $error->getMessagePluralization()) {
return $this->translator->transChoice($error->getMessageTemplate(), $error->getMessagePluralization(), $error->getMessageParameters(), 'validators');
}
return $this->translator->trans($error->getMessageTemplate(), $error->getMessageParameters(), 'validators');
} | [
"private",
"function",
"getErrorMessage",
"(",
"FormError",
"$",
"error",
")",
"{",
"if",
"(",
"null",
"!==",
"$",
"error",
"->",
"getMessagePluralization",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"translator",
"->",
"transChoice",
"(",
"$",
"error",
"->",
"getMessageTemplate",
"(",
")",
",",
"$",
"error",
"->",
"getMessagePluralization",
"(",
")",
",",
"$",
"error",
"->",
"getMessageParameters",
"(",
")",
",",
"'validators'",
")",
";",
"}",
"return",
"$",
"this",
"->",
"translator",
"->",
"trans",
"(",
"$",
"error",
"->",
"getMessageTemplate",
"(",
")",
",",
"$",
"error",
"->",
"getMessageParameters",
"(",
")",
",",
"'validators'",
")",
";",
"}"
] | @param FormError $error
@return string | [
"@param",
"FormError",
"$error"
] | train | https://github.com/Limenius/Liform/blob/b46ba76cc7703b9d9989ff9f8ca4437cfc8f6c6c/src/Limenius/Liform/Serializer/Normalizer/FormErrorNormalizer.php#L96-L103 |
Limenius/Liform | src/Limenius/Liform/Transformer/IntegerTransformer.php | IntegerTransformer.transform | public function transform(FormInterface $form, array $extensions = [], $widget = null)
{
$schema = ['type' => 'integer'];
$schema = $this->addCommonSpecs($form, $schema, $extensions, $widget);
return $schema;
} | php | public function transform(FormInterface $form, array $extensions = [], $widget = null)
{
$schema = ['type' => 'integer'];
$schema = $this->addCommonSpecs($form, $schema, $extensions, $widget);
return $schema;
} | [
"public",
"function",
"transform",
"(",
"FormInterface",
"$",
"form",
",",
"array",
"$",
"extensions",
"=",
"[",
"]",
",",
"$",
"widget",
"=",
"null",
")",
"{",
"$",
"schema",
"=",
"[",
"'type'",
"=>",
"'integer'",
"]",
";",
"$",
"schema",
"=",
"$",
"this",
"->",
"addCommonSpecs",
"(",
"$",
"form",
",",
"$",
"schema",
",",
"$",
"extensions",
",",
"$",
"widget",
")",
";",
"return",
"$",
"schema",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/Limenius/Liform/blob/b46ba76cc7703b9d9989ff9f8ca4437cfc8f6c6c/src/Limenius/Liform/Transformer/IntegerTransformer.php#L24-L30 |
Limenius/Liform | src/Limenius/Liform/Guesser/ValidatorGuesser.php | ValidatorGuesser.guessMinLength | public function guessMinLength($class, $property)
{
return $this->guess($class, $property, function (Constraint $constraint) {
return $this->guessMinLengthForConstraint($constraint);
});
} | php | public function guessMinLength($class, $property)
{
return $this->guess($class, $property, function (Constraint $constraint) {
return $this->guessMinLengthForConstraint($constraint);
});
} | [
"public",
"function",
"guessMinLength",
"(",
"$",
"class",
",",
"$",
"property",
")",
"{",
"return",
"$",
"this",
"->",
"guess",
"(",
"$",
"class",
",",
"$",
"property",
",",
"function",
"(",
"Constraint",
"$",
"constraint",
")",
"{",
"return",
"$",
"this",
"->",
"guessMinLengthForConstraint",
"(",
"$",
"constraint",
")",
";",
"}",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/Limenius/Liform/blob/b46ba76cc7703b9d9989ff9f8ca4437cfc8f6c6c/src/Limenius/Liform/Guesser/ValidatorGuesser.php#L27-L32 |
Limenius/Liform | src/Limenius/Liform/Guesser/ValidatorGuesser.php | ValidatorGuesser.guessMinLengthForConstraint | public function guessMinLengthForConstraint(Constraint $constraint)
{
switch (get_class($constraint)) {
case 'Symfony\Component\Validator\Constraints\Length':
if (is_numeric($constraint->min)) {
return new ValueGuess($constraint->min, Guess::HIGH_CONFIDENCE);
}
break;
case 'Symfony\Component\Validator\Constraints\Type':
if (in_array($constraint->type, array('double', 'float', 'numeric', 'real'))) {
return new ValueGuess(null, Guess::MEDIUM_CONFIDENCE);
}
break;
case 'Symfony\Component\Validator\Constraints\Range':
if (is_numeric($constraint->min)) {
return new ValueGuess(strlen((string) $constraint->min), Guess::LOW_CONFIDENCE);
}
break;
}
} | php | public function guessMinLengthForConstraint(Constraint $constraint)
{
switch (get_class($constraint)) {
case 'Symfony\Component\Validator\Constraints\Length':
if (is_numeric($constraint->min)) {
return new ValueGuess($constraint->min, Guess::HIGH_CONFIDENCE);
}
break;
case 'Symfony\Component\Validator\Constraints\Type':
if (in_array($constraint->type, array('double', 'float', 'numeric', 'real'))) {
return new ValueGuess(null, Guess::MEDIUM_CONFIDENCE);
}
break;
case 'Symfony\Component\Validator\Constraints\Range':
if (is_numeric($constraint->min)) {
return new ValueGuess(strlen((string) $constraint->min), Guess::LOW_CONFIDENCE);
}
break;
}
} | [
"public",
"function",
"guessMinLengthForConstraint",
"(",
"Constraint",
"$",
"constraint",
")",
"{",
"switch",
"(",
"get_class",
"(",
"$",
"constraint",
")",
")",
"{",
"case",
"'Symfony\\Component\\Validator\\Constraints\\Length'",
":",
"if",
"(",
"is_numeric",
"(",
"$",
"constraint",
"->",
"min",
")",
")",
"{",
"return",
"new",
"ValueGuess",
"(",
"$",
"constraint",
"->",
"min",
",",
"Guess",
"::",
"HIGH_CONFIDENCE",
")",
";",
"}",
"break",
";",
"case",
"'Symfony\\Component\\Validator\\Constraints\\Type'",
":",
"if",
"(",
"in_array",
"(",
"$",
"constraint",
"->",
"type",
",",
"array",
"(",
"'double'",
",",
"'float'",
",",
"'numeric'",
",",
"'real'",
")",
")",
")",
"{",
"return",
"new",
"ValueGuess",
"(",
"null",
",",
"Guess",
"::",
"MEDIUM_CONFIDENCE",
")",
";",
"}",
"break",
";",
"case",
"'Symfony\\Component\\Validator\\Constraints\\Range'",
":",
"if",
"(",
"is_numeric",
"(",
"$",
"constraint",
"->",
"min",
")",
")",
"{",
"return",
"new",
"ValueGuess",
"(",
"strlen",
"(",
"(",
"string",
")",
"$",
"constraint",
"->",
"min",
")",
",",
"Guess",
"::",
"LOW_CONFIDENCE",
")",
";",
"}",
"break",
";",
"}",
"}"
] | Guesses a field's minimum length based on the given constraint.
@param Constraint $constraint The constraint to guess for
@return ValueGuess|null The guess for the minimum length | [
"Guesses",
"a",
"field",
"s",
"minimum",
"length",
"based",
"on",
"the",
"given",
"constraint",
"."
] | train | https://github.com/Limenius/Liform/blob/b46ba76cc7703b9d9989ff9f8ca4437cfc8f6c6c/src/Limenius/Liform/Guesser/ValidatorGuesser.php#L41-L60 |
Limenius/Liform | src/Limenius/Liform/Transformer/StringTransformer.php | StringTransformer.transform | public function transform(FormInterface $form, array $extensions = [], $widget = null)
{
$schema = ['type' => 'string'];
$schema = $this->addCommonSpecs($form, $schema, $extensions, $widget);
$schema = $this->addMaxLength($form, $schema);
$schema = $this->addMinLength($form, $schema);
return $schema;
} | php | public function transform(FormInterface $form, array $extensions = [], $widget = null)
{
$schema = ['type' => 'string'];
$schema = $this->addCommonSpecs($form, $schema, $extensions, $widget);
$schema = $this->addMaxLength($form, $schema);
$schema = $this->addMinLength($form, $schema);
return $schema;
} | [
"public",
"function",
"transform",
"(",
"FormInterface",
"$",
"form",
",",
"array",
"$",
"extensions",
"=",
"[",
"]",
",",
"$",
"widget",
"=",
"null",
")",
"{",
"$",
"schema",
"=",
"[",
"'type'",
"=>",
"'string'",
"]",
";",
"$",
"schema",
"=",
"$",
"this",
"->",
"addCommonSpecs",
"(",
"$",
"form",
",",
"$",
"schema",
",",
"$",
"extensions",
",",
"$",
"widget",
")",
";",
"$",
"schema",
"=",
"$",
"this",
"->",
"addMaxLength",
"(",
"$",
"form",
",",
"$",
"schema",
")",
";",
"$",
"schema",
"=",
"$",
"this",
"->",
"addMinLength",
"(",
"$",
"form",
",",
"$",
"schema",
")",
";",
"return",
"$",
"schema",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/Limenius/Liform/blob/b46ba76cc7703b9d9989ff9f8ca4437cfc8f6c6c/src/Limenius/Liform/Transformer/StringTransformer.php#L26-L34 |
Limenius/Liform | src/Limenius/Liform/Transformer/StringTransformer.php | StringTransformer.addMaxLength | protected function addMaxLength(FormInterface $form, array $schema)
{
if ($attr = $form->getConfig()->getOption('attr')) {
if (isset($attr['maxlength'])) {
$schema['maxLength'] = $attr['maxlength'];
}
}
return $schema;
} | php | protected function addMaxLength(FormInterface $form, array $schema)
{
if ($attr = $form->getConfig()->getOption('attr')) {
if (isset($attr['maxlength'])) {
$schema['maxLength'] = $attr['maxlength'];
}
}
return $schema;
} | [
"protected",
"function",
"addMaxLength",
"(",
"FormInterface",
"$",
"form",
",",
"array",
"$",
"schema",
")",
"{",
"if",
"(",
"$",
"attr",
"=",
"$",
"form",
"->",
"getConfig",
"(",
")",
"->",
"getOption",
"(",
"'attr'",
")",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"attr",
"[",
"'maxlength'",
"]",
")",
")",
"{",
"$",
"schema",
"[",
"'maxLength'",
"]",
"=",
"$",
"attr",
"[",
"'maxlength'",
"]",
";",
"}",
"}",
"return",
"$",
"schema",
";",
"}"
] | @param FormInterface $form
@param array $schema
@return array | [
"@param",
"FormInterface",
"$form",
"@param",
"array",
"$schema"
] | train | https://github.com/Limenius/Liform/blob/b46ba76cc7703b9d9989ff9f8ca4437cfc8f6c6c/src/Limenius/Liform/Transformer/StringTransformer.php#L42-L51 |
Limenius/Liform | src/Limenius/Liform/Transformer/StringTransformer.php | StringTransformer.addMinLength | protected function addMinLength(FormInterface $form, array $schema)
{
if ($attr = $form->getConfig()->getOption('attr')) {
if (isset($attr['minlength'])) {
$schema['minLength'] = $attr['minlength'];
return $schema;
}
}
if (null === $this->validatorGuesser) {
return $schema;
}
$class = FormUtil::findDataClass($form);
if (null === $class) {
return $schema;
}
$minLengthGuess = $this->validatorGuesser->guessMinLength($class, $form->getName());
$minLength = $minLengthGuess ? $minLengthGuess->getValue() : null;
if ($minLength) {
$schema['minLength'] = $minLength;
}
return $schema;
} | php | protected function addMinLength(FormInterface $form, array $schema)
{
if ($attr = $form->getConfig()->getOption('attr')) {
if (isset($attr['minlength'])) {
$schema['minLength'] = $attr['minlength'];
return $schema;
}
}
if (null === $this->validatorGuesser) {
return $schema;
}
$class = FormUtil::findDataClass($form);
if (null === $class) {
return $schema;
}
$minLengthGuess = $this->validatorGuesser->guessMinLength($class, $form->getName());
$minLength = $minLengthGuess ? $minLengthGuess->getValue() : null;
if ($minLength) {
$schema['minLength'] = $minLength;
}
return $schema;
} | [
"protected",
"function",
"addMinLength",
"(",
"FormInterface",
"$",
"form",
",",
"array",
"$",
"schema",
")",
"{",
"if",
"(",
"$",
"attr",
"=",
"$",
"form",
"->",
"getConfig",
"(",
")",
"->",
"getOption",
"(",
"'attr'",
")",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"attr",
"[",
"'minlength'",
"]",
")",
")",
"{",
"$",
"schema",
"[",
"'minLength'",
"]",
"=",
"$",
"attr",
"[",
"'minlength'",
"]",
";",
"return",
"$",
"schema",
";",
"}",
"}",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"validatorGuesser",
")",
"{",
"return",
"$",
"schema",
";",
"}",
"$",
"class",
"=",
"FormUtil",
"::",
"findDataClass",
"(",
"$",
"form",
")",
";",
"if",
"(",
"null",
"===",
"$",
"class",
")",
"{",
"return",
"$",
"schema",
";",
"}",
"$",
"minLengthGuess",
"=",
"$",
"this",
"->",
"validatorGuesser",
"->",
"guessMinLength",
"(",
"$",
"class",
",",
"$",
"form",
"->",
"getName",
"(",
")",
")",
";",
"$",
"minLength",
"=",
"$",
"minLengthGuess",
"?",
"$",
"minLengthGuess",
"->",
"getValue",
"(",
")",
":",
"null",
";",
"if",
"(",
"$",
"minLength",
")",
"{",
"$",
"schema",
"[",
"'minLength'",
"]",
"=",
"$",
"minLength",
";",
"}",
"return",
"$",
"schema",
";",
"}"
] | @param FormInterface $form
@param array $schema
@return array | [
"@param",
"FormInterface",
"$form",
"@param",
"array",
"$schema"
] | train | https://github.com/Limenius/Liform/blob/b46ba76cc7703b9d9989ff9f8ca4437cfc8f6c6c/src/Limenius/Liform/Transformer/StringTransformer.php#L59-L87 |
Limenius/Liform | src/Limenius/Liform/Transformer/ChoiceTransformer.php | ChoiceTransformer.transform | public function transform(FormInterface $form, array $extensions = [], $widget = null)
{
$formView = $form->createView();
$choices = [];
$titles = [];
foreach ($formView->vars['choices'] as $choiceView) {
if ($choiceView instanceof ChoiceGroupView) {
foreach ($choiceView->choices as $choiceItem) {
$choices[] = $choiceItem->value;
$titles[] = $this->translator->trans($choiceItem->label);
}
} else {
$choices[] = $choiceView->value;
$titles[] = $this->translator->trans($choiceView->label);
}
}
if ($formView->vars['multiple']) {
$schema = $this->transformMultiple($form, $choices, $titles);
} else {
$schema = $this->transformSingle($form, $choices, $titles);
}
$schema = $this->addCommonSpecs($form, $schema, $extensions, $widget);
return $schema;
} | php | public function transform(FormInterface $form, array $extensions = [], $widget = null)
{
$formView = $form->createView();
$choices = [];
$titles = [];
foreach ($formView->vars['choices'] as $choiceView) {
if ($choiceView instanceof ChoiceGroupView) {
foreach ($choiceView->choices as $choiceItem) {
$choices[] = $choiceItem->value;
$titles[] = $this->translator->trans($choiceItem->label);
}
} else {
$choices[] = $choiceView->value;
$titles[] = $this->translator->trans($choiceView->label);
}
}
if ($formView->vars['multiple']) {
$schema = $this->transformMultiple($form, $choices, $titles);
} else {
$schema = $this->transformSingle($form, $choices, $titles);
}
$schema = $this->addCommonSpecs($form, $schema, $extensions, $widget);
return $schema;
} | [
"public",
"function",
"transform",
"(",
"FormInterface",
"$",
"form",
",",
"array",
"$",
"extensions",
"=",
"[",
"]",
",",
"$",
"widget",
"=",
"null",
")",
"{",
"$",
"formView",
"=",
"$",
"form",
"->",
"createView",
"(",
")",
";",
"$",
"choices",
"=",
"[",
"]",
";",
"$",
"titles",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"formView",
"->",
"vars",
"[",
"'choices'",
"]",
"as",
"$",
"choiceView",
")",
"{",
"if",
"(",
"$",
"choiceView",
"instanceof",
"ChoiceGroupView",
")",
"{",
"foreach",
"(",
"$",
"choiceView",
"->",
"choices",
"as",
"$",
"choiceItem",
")",
"{",
"$",
"choices",
"[",
"]",
"=",
"$",
"choiceItem",
"->",
"value",
";",
"$",
"titles",
"[",
"]",
"=",
"$",
"this",
"->",
"translator",
"->",
"trans",
"(",
"$",
"choiceItem",
"->",
"label",
")",
";",
"}",
"}",
"else",
"{",
"$",
"choices",
"[",
"]",
"=",
"$",
"choiceView",
"->",
"value",
";",
"$",
"titles",
"[",
"]",
"=",
"$",
"this",
"->",
"translator",
"->",
"trans",
"(",
"$",
"choiceView",
"->",
"label",
")",
";",
"}",
"}",
"if",
"(",
"$",
"formView",
"->",
"vars",
"[",
"'multiple'",
"]",
")",
"{",
"$",
"schema",
"=",
"$",
"this",
"->",
"transformMultiple",
"(",
"$",
"form",
",",
"$",
"choices",
",",
"$",
"titles",
")",
";",
"}",
"else",
"{",
"$",
"schema",
"=",
"$",
"this",
"->",
"transformSingle",
"(",
"$",
"form",
",",
"$",
"choices",
",",
"$",
"titles",
")",
";",
"}",
"$",
"schema",
"=",
"$",
"this",
"->",
"addCommonSpecs",
"(",
"$",
"form",
",",
"$",
"schema",
",",
"$",
"extensions",
",",
"$",
"widget",
")",
";",
"return",
"$",
"schema",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/Limenius/Liform/blob/b46ba76cc7703b9d9989ff9f8ca4437cfc8f6c6c/src/Limenius/Liform/Transformer/ChoiceTransformer.php#L25-L52 |
Limenius/Liform | src/Limenius/Liform/Transformer/CompoundTransformer.php | CompoundTransformer.transform | public function transform(FormInterface $form, array $extensions = [], $widget = null)
{
$data = [];
$order = 1;
$required = [];
foreach ($form->all() as $name => $field) {
$transformerData = $this->resolver->resolve($field);
$transformedChild = $transformerData['transformer']->transform($field, $extensions, $transformerData['widget']);
$transformedChild['propertyOrder'] = $order;
$data[$name] = $transformedChild;
$order ++;
if ($transformerData['transformer']->isRequired($field)) {
$required[] = $field->getName();
}
}
$schema = [
'title' => $form->getConfig()->getOption('label'),
'type' => 'object',
'properties' => $data,
];
if (!empty($required)) {
$schema['required'] = $required;
}
$innerType = $form->getConfig()->getType()->getInnerType();
$schema = $this->addCommonSpecs($form, $schema, $extensions, $widget);
if (method_exists($innerType, 'buildLiform')) {
$schema = $innerType->buildLiform($form, $schema);
}
return $schema;
} | php | public function transform(FormInterface $form, array $extensions = [], $widget = null)
{
$data = [];
$order = 1;
$required = [];
foreach ($form->all() as $name => $field) {
$transformerData = $this->resolver->resolve($field);
$transformedChild = $transformerData['transformer']->transform($field, $extensions, $transformerData['widget']);
$transformedChild['propertyOrder'] = $order;
$data[$name] = $transformedChild;
$order ++;
if ($transformerData['transformer']->isRequired($field)) {
$required[] = $field->getName();
}
}
$schema = [
'title' => $form->getConfig()->getOption('label'),
'type' => 'object',
'properties' => $data,
];
if (!empty($required)) {
$schema['required'] = $required;
}
$innerType = $form->getConfig()->getType()->getInnerType();
$schema = $this->addCommonSpecs($form, $schema, $extensions, $widget);
if (method_exists($innerType, 'buildLiform')) {
$schema = $innerType->buildLiform($form, $schema);
}
return $schema;
} | [
"public",
"function",
"transform",
"(",
"FormInterface",
"$",
"form",
",",
"array",
"$",
"extensions",
"=",
"[",
"]",
",",
"$",
"widget",
"=",
"null",
")",
"{",
"$",
"data",
"=",
"[",
"]",
";",
"$",
"order",
"=",
"1",
";",
"$",
"required",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"form",
"->",
"all",
"(",
")",
"as",
"$",
"name",
"=>",
"$",
"field",
")",
"{",
"$",
"transformerData",
"=",
"$",
"this",
"->",
"resolver",
"->",
"resolve",
"(",
"$",
"field",
")",
";",
"$",
"transformedChild",
"=",
"$",
"transformerData",
"[",
"'transformer'",
"]",
"->",
"transform",
"(",
"$",
"field",
",",
"$",
"extensions",
",",
"$",
"transformerData",
"[",
"'widget'",
"]",
")",
";",
"$",
"transformedChild",
"[",
"'propertyOrder'",
"]",
"=",
"$",
"order",
";",
"$",
"data",
"[",
"$",
"name",
"]",
"=",
"$",
"transformedChild",
";",
"$",
"order",
"++",
";",
"if",
"(",
"$",
"transformerData",
"[",
"'transformer'",
"]",
"->",
"isRequired",
"(",
"$",
"field",
")",
")",
"{",
"$",
"required",
"[",
"]",
"=",
"$",
"field",
"->",
"getName",
"(",
")",
";",
"}",
"}",
"$",
"schema",
"=",
"[",
"'title'",
"=>",
"$",
"form",
"->",
"getConfig",
"(",
")",
"->",
"getOption",
"(",
"'label'",
")",
",",
"'type'",
"=>",
"'object'",
",",
"'properties'",
"=>",
"$",
"data",
",",
"]",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"required",
")",
")",
"{",
"$",
"schema",
"[",
"'required'",
"]",
"=",
"$",
"required",
";",
"}",
"$",
"innerType",
"=",
"$",
"form",
"->",
"getConfig",
"(",
")",
"->",
"getType",
"(",
")",
"->",
"getInnerType",
"(",
")",
";",
"$",
"schema",
"=",
"$",
"this",
"->",
"addCommonSpecs",
"(",
"$",
"form",
",",
"$",
"schema",
",",
"$",
"extensions",
",",
"$",
"widget",
")",
";",
"if",
"(",
"method_exists",
"(",
"$",
"innerType",
",",
"'buildLiform'",
")",
")",
"{",
"$",
"schema",
"=",
"$",
"innerType",
"->",
"buildLiform",
"(",
"$",
"form",
",",
"$",
"schema",
")",
";",
"}",
"return",
"$",
"schema",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/Limenius/Liform/blob/b46ba76cc7703b9d9989ff9f8ca4437cfc8f6c6c/src/Limenius/Liform/Transformer/CompoundTransformer.php#L47-L84 |
Limenius/Liform | src/Limenius/Liform/Resolver.php | Resolver.resolve | public function resolve(FormInterface $form)
{
$types = FormUtil::typeAncestry($form);
foreach ($types as $type) {
if (isset($this->transformers[$type])) {
return $this->transformers[$type];
}
}
// Perhaps a compound we don't have a specific transformer for
if (FormUtil::isCompound($form)) {
return [
'transformer' => $this->transformers['compound']['transformer'],
'widget' => null,
];
}
throw new TransformerException(
sprintf(
'Could not find a transformer for any of these types (%s)',
implode(', ', $types)
)
);
} | php | public function resolve(FormInterface $form)
{
$types = FormUtil::typeAncestry($form);
foreach ($types as $type) {
if (isset($this->transformers[$type])) {
return $this->transformers[$type];
}
}
// Perhaps a compound we don't have a specific transformer for
if (FormUtil::isCompound($form)) {
return [
'transformer' => $this->transformers['compound']['transformer'],
'widget' => null,
];
}
throw new TransformerException(
sprintf(
'Could not find a transformer for any of these types (%s)',
implode(', ', $types)
)
);
} | [
"public",
"function",
"resolve",
"(",
"FormInterface",
"$",
"form",
")",
"{",
"$",
"types",
"=",
"FormUtil",
"::",
"typeAncestry",
"(",
"$",
"form",
")",
";",
"foreach",
"(",
"$",
"types",
"as",
"$",
"type",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"transformers",
"[",
"$",
"type",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"transformers",
"[",
"$",
"type",
"]",
";",
"}",
"}",
"// Perhaps a compound we don't have a specific transformer for",
"if",
"(",
"FormUtil",
"::",
"isCompound",
"(",
"$",
"form",
")",
")",
"{",
"return",
"[",
"'transformer'",
"=>",
"$",
"this",
"->",
"transformers",
"[",
"'compound'",
"]",
"[",
"'transformer'",
"]",
",",
"'widget'",
"=>",
"null",
",",
"]",
";",
"}",
"throw",
"new",
"TransformerException",
"(",
"sprintf",
"(",
"'Could not find a transformer for any of these types (%s)'",
",",
"implode",
"(",
"', '",
",",
"$",
"types",
")",
")",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/Limenius/Liform/blob/b46ba76cc7703b9d9989ff9f8ca4437cfc8f6c6c/src/Limenius/Liform/Resolver.php#L44-L68 |
Limenius/Liform | src/Limenius/Liform/Liform.php | Liform.transform | public function transform(FormInterface $form)
{
$transformerData = $this->resolver->resolve($form);
return $transformerData['transformer']->transform($form, $this->extensions, $transformerData['widget']);
} | php | public function transform(FormInterface $form)
{
$transformerData = $this->resolver->resolve($form);
return $transformerData['transformer']->transform($form, $this->extensions, $transformerData['widget']);
} | [
"public",
"function",
"transform",
"(",
"FormInterface",
"$",
"form",
")",
"{",
"$",
"transformerData",
"=",
"$",
"this",
"->",
"resolver",
"->",
"resolve",
"(",
"$",
"form",
")",
";",
"return",
"$",
"transformerData",
"[",
"'transformer'",
"]",
"->",
"transform",
"(",
"$",
"form",
",",
"$",
"this",
"->",
"extensions",
",",
"$",
"transformerData",
"[",
"'widget'",
"]",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/Limenius/Liform/blob/b46ba76cc7703b9d9989ff9f8ca4437cfc8f6c6c/src/Limenius/Liform/Liform.php#L43-L48 |
Limenius/Liform | src/Limenius/Liform/Transformer/AbstractTransformer.php | AbstractTransformer.applyExtensions | protected function applyExtensions(array $extensions, FormInterface $form, array $schema)
{
$newSchema = $schema;
foreach ($extensions as $extension) {
$newSchema = $extension->apply($form, $newSchema);
}
return $newSchema;
} | php | protected function applyExtensions(array $extensions, FormInterface $form, array $schema)
{
$newSchema = $schema;
foreach ($extensions as $extension) {
$newSchema = $extension->apply($form, $newSchema);
}
return $newSchema;
} | [
"protected",
"function",
"applyExtensions",
"(",
"array",
"$",
"extensions",
",",
"FormInterface",
"$",
"form",
",",
"array",
"$",
"schema",
")",
"{",
"$",
"newSchema",
"=",
"$",
"schema",
";",
"foreach",
"(",
"$",
"extensions",
"as",
"$",
"extension",
")",
"{",
"$",
"newSchema",
"=",
"$",
"extension",
"->",
"apply",
"(",
"$",
"form",
",",
"$",
"newSchema",
")",
";",
"}",
"return",
"$",
"newSchema",
";",
"}"
] | @param ExtensionInterface[] $extensions
@param FormInterface $form
@param array $schema
@return array | [
"@param",
"ExtensionInterface",
"[]",
"$extensions",
"@param",
"FormInterface",
"$form",
"@param",
"array",
"$schema"
] | train | https://github.com/Limenius/Liform/blob/b46ba76cc7703b9d9989ff9f8ca4437cfc8f6c6c/src/Limenius/Liform/Transformer/AbstractTransformer.php#L50-L58 |
Limenius/Liform | src/Limenius/Liform/Transformer/AbstractTransformer.php | AbstractTransformer.addCommonSpecs | protected function addCommonSpecs(FormInterface $form, array $schema, $extensions = [], $widget)
{
$schema = $this->addLabel($form, $schema);
$schema = $this->addAttr($form, $schema);
$schema = $this->addPattern($form, $schema);
$schema = $this->addDescription($form, $schema);
$schema = $this->addWidget($form, $schema, $widget);
$schema = $this->applyExtensions($extensions, $form, $schema);
return $schema;
} | php | protected function addCommonSpecs(FormInterface $form, array $schema, $extensions = [], $widget)
{
$schema = $this->addLabel($form, $schema);
$schema = $this->addAttr($form, $schema);
$schema = $this->addPattern($form, $schema);
$schema = $this->addDescription($form, $schema);
$schema = $this->addWidget($form, $schema, $widget);
$schema = $this->applyExtensions($extensions, $form, $schema);
return $schema;
} | [
"protected",
"function",
"addCommonSpecs",
"(",
"FormInterface",
"$",
"form",
",",
"array",
"$",
"schema",
",",
"$",
"extensions",
"=",
"[",
"]",
",",
"$",
"widget",
")",
"{",
"$",
"schema",
"=",
"$",
"this",
"->",
"addLabel",
"(",
"$",
"form",
",",
"$",
"schema",
")",
";",
"$",
"schema",
"=",
"$",
"this",
"->",
"addAttr",
"(",
"$",
"form",
",",
"$",
"schema",
")",
";",
"$",
"schema",
"=",
"$",
"this",
"->",
"addPattern",
"(",
"$",
"form",
",",
"$",
"schema",
")",
";",
"$",
"schema",
"=",
"$",
"this",
"->",
"addDescription",
"(",
"$",
"form",
",",
"$",
"schema",
")",
";",
"$",
"schema",
"=",
"$",
"this",
"->",
"addWidget",
"(",
"$",
"form",
",",
"$",
"schema",
",",
"$",
"widget",
")",
";",
"$",
"schema",
"=",
"$",
"this",
"->",
"applyExtensions",
"(",
"$",
"extensions",
",",
"$",
"form",
",",
"$",
"schema",
")",
";",
"return",
"$",
"schema",
";",
"}"
] | @param FormInterface $form
@param array $schema
@param ExtensionInterface[] $extensions
@param string $widget
@return array | [
"@param",
"FormInterface",
"$form",
"@param",
"array",
"$schema",
"@param",
"ExtensionInterface",
"[]",
"$extensions",
"@param",
"string",
"$widget"
] | train | https://github.com/Limenius/Liform/blob/b46ba76cc7703b9d9989ff9f8ca4437cfc8f6c6c/src/Limenius/Liform/Transformer/AbstractTransformer.php#L68-L78 |
Limenius/Liform | src/Limenius/Liform/Transformer/AbstractTransformer.php | AbstractTransformer.addPattern | protected function addPattern(FormInterface $form, array $schema)
{
if ($attr = $form->getConfig()->getOption('attr')) {
if (isset($attr['pattern'])) {
$schema['pattern'] = $attr['pattern'];
}
}
return $schema;
} | php | protected function addPattern(FormInterface $form, array $schema)
{
if ($attr = $form->getConfig()->getOption('attr')) {
if (isset($attr['pattern'])) {
$schema['pattern'] = $attr['pattern'];
}
}
return $schema;
} | [
"protected",
"function",
"addPattern",
"(",
"FormInterface",
"$",
"form",
",",
"array",
"$",
"schema",
")",
"{",
"if",
"(",
"$",
"attr",
"=",
"$",
"form",
"->",
"getConfig",
"(",
")",
"->",
"getOption",
"(",
"'attr'",
")",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"attr",
"[",
"'pattern'",
"]",
")",
")",
"{",
"$",
"schema",
"[",
"'pattern'",
"]",
"=",
"$",
"attr",
"[",
"'pattern'",
"]",
";",
"}",
"}",
"return",
"$",
"schema",
";",
"}"
] | @param FormInterface $form
@param array $schema
@return array | [
"@param",
"FormInterface",
"$form",
"@param",
"array",
"$schema"
] | train | https://github.com/Limenius/Liform/blob/b46ba76cc7703b9d9989ff9f8ca4437cfc8f6c6c/src/Limenius/Liform/Transformer/AbstractTransformer.php#L87-L96 |
Limenius/Liform | src/Limenius/Liform/Transformer/AbstractTransformer.php | AbstractTransformer.addLabel | protected function addLabel(FormInterface $form, array $schema)
{
$translationDomain = $form->getConfig()->getOption('translation_domain');
if ($label = $form->getConfig()->getOption('label')) {
$schema['title'] = $this->translator->trans($label, [], $translationDomain);
} else {
$schema['title'] = $this->translator->trans($form->getName(), [], $translationDomain);
}
return $schema;
} | php | protected function addLabel(FormInterface $form, array $schema)
{
$translationDomain = $form->getConfig()->getOption('translation_domain');
if ($label = $form->getConfig()->getOption('label')) {
$schema['title'] = $this->translator->trans($label, [], $translationDomain);
} else {
$schema['title'] = $this->translator->trans($form->getName(), [], $translationDomain);
}
return $schema;
} | [
"protected",
"function",
"addLabel",
"(",
"FormInterface",
"$",
"form",
",",
"array",
"$",
"schema",
")",
"{",
"$",
"translationDomain",
"=",
"$",
"form",
"->",
"getConfig",
"(",
")",
"->",
"getOption",
"(",
"'translation_domain'",
")",
";",
"if",
"(",
"$",
"label",
"=",
"$",
"form",
"->",
"getConfig",
"(",
")",
"->",
"getOption",
"(",
"'label'",
")",
")",
"{",
"$",
"schema",
"[",
"'title'",
"]",
"=",
"$",
"this",
"->",
"translator",
"->",
"trans",
"(",
"$",
"label",
",",
"[",
"]",
",",
"$",
"translationDomain",
")",
";",
"}",
"else",
"{",
"$",
"schema",
"[",
"'title'",
"]",
"=",
"$",
"this",
"->",
"translator",
"->",
"trans",
"(",
"$",
"form",
"->",
"getName",
"(",
")",
",",
"[",
"]",
",",
"$",
"translationDomain",
")",
";",
"}",
"return",
"$",
"schema",
";",
"}"
] | @param FormInterface $form
@param array $schema
@return array | [
"@param",
"FormInterface",
"$form",
"@param",
"array",
"$schema"
] | train | https://github.com/Limenius/Liform/blob/b46ba76cc7703b9d9989ff9f8ca4437cfc8f6c6c/src/Limenius/Liform/Transformer/AbstractTransformer.php#L104-L114 |
Limenius/Liform | src/Limenius/Liform/Transformer/AbstractTransformer.php | AbstractTransformer.addAttr | protected function addAttr(FormInterface $form, array $schema)
{
if ($attr = $form->getConfig()->getOption('attr')) {
$schema['attr'] = $attr;
}
return $schema;
} | php | protected function addAttr(FormInterface $form, array $schema)
{
if ($attr = $form->getConfig()->getOption('attr')) {
$schema['attr'] = $attr;
}
return $schema;
} | [
"protected",
"function",
"addAttr",
"(",
"FormInterface",
"$",
"form",
",",
"array",
"$",
"schema",
")",
"{",
"if",
"(",
"$",
"attr",
"=",
"$",
"form",
"->",
"getConfig",
"(",
")",
"->",
"getOption",
"(",
"'attr'",
")",
")",
"{",
"$",
"schema",
"[",
"'attr'",
"]",
"=",
"$",
"attr",
";",
"}",
"return",
"$",
"schema",
";",
"}"
] | @param FormInterface $form
@param array $schema
@return array | [
"@param",
"FormInterface",
"$form",
"@param",
"array",
"$schema"
] | train | https://github.com/Limenius/Liform/blob/b46ba76cc7703b9d9989ff9f8ca4437cfc8f6c6c/src/Limenius/Liform/Transformer/AbstractTransformer.php#L122-L129 |
Limenius/Liform | src/Limenius/Liform/Transformer/AbstractTransformer.php | AbstractTransformer.addDescription | protected function addDescription(FormInterface $form, array $schema)
{
if ($liform = $form->getConfig()->getOption('liform')) {
if (isset($liform['description']) && $description = $liform['description']) {
$schema['description'] = $this->translator->trans($description);
}
}
return $schema;
} | php | protected function addDescription(FormInterface $form, array $schema)
{
if ($liform = $form->getConfig()->getOption('liform')) {
if (isset($liform['description']) && $description = $liform['description']) {
$schema['description'] = $this->translator->trans($description);
}
}
return $schema;
} | [
"protected",
"function",
"addDescription",
"(",
"FormInterface",
"$",
"form",
",",
"array",
"$",
"schema",
")",
"{",
"if",
"(",
"$",
"liform",
"=",
"$",
"form",
"->",
"getConfig",
"(",
")",
"->",
"getOption",
"(",
"'liform'",
")",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"liform",
"[",
"'description'",
"]",
")",
"&&",
"$",
"description",
"=",
"$",
"liform",
"[",
"'description'",
"]",
")",
"{",
"$",
"schema",
"[",
"'description'",
"]",
"=",
"$",
"this",
"->",
"translator",
"->",
"trans",
"(",
"$",
"description",
")",
";",
"}",
"}",
"return",
"$",
"schema",
";",
"}"
] | @param FormInterface $form
@param array $schema
@return array | [
"@param",
"FormInterface",
"$form",
"@param",
"array",
"$schema"
] | train | https://github.com/Limenius/Liform/blob/b46ba76cc7703b9d9989ff9f8ca4437cfc8f6c6c/src/Limenius/Liform/Transformer/AbstractTransformer.php#L137-L146 |
Limenius/Liform | src/Limenius/Liform/Transformer/AbstractTransformer.php | AbstractTransformer.addWidget | protected function addWidget(FormInterface $form, array $schema, $configWidget)
{
if ($liform = $form->getConfig()->getOption('liform')) {
if (isset($liform['widget']) && $widget = $liform['widget']) {
$schema['widget'] = $widget;
}
} elseif ($configWidget) {
$schema['widget'] = $configWidget;
}
return $schema;
} | php | protected function addWidget(FormInterface $form, array $schema, $configWidget)
{
if ($liform = $form->getConfig()->getOption('liform')) {
if (isset($liform['widget']) && $widget = $liform['widget']) {
$schema['widget'] = $widget;
}
} elseif ($configWidget) {
$schema['widget'] = $configWidget;
}
return $schema;
} | [
"protected",
"function",
"addWidget",
"(",
"FormInterface",
"$",
"form",
",",
"array",
"$",
"schema",
",",
"$",
"configWidget",
")",
"{",
"if",
"(",
"$",
"liform",
"=",
"$",
"form",
"->",
"getConfig",
"(",
")",
"->",
"getOption",
"(",
"'liform'",
")",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"liform",
"[",
"'widget'",
"]",
")",
"&&",
"$",
"widget",
"=",
"$",
"liform",
"[",
"'widget'",
"]",
")",
"{",
"$",
"schema",
"[",
"'widget'",
"]",
"=",
"$",
"widget",
";",
"}",
"}",
"elseif",
"(",
"$",
"configWidget",
")",
"{",
"$",
"schema",
"[",
"'widget'",
"]",
"=",
"$",
"configWidget",
";",
"}",
"return",
"$",
"schema",
";",
"}"
] | @param FormInterface $form
@param array $schema
@param mixed $configWidget
@return array | [
"@param",
"FormInterface",
"$form",
"@param",
"array",
"$schema",
"@param",
"mixed",
"$configWidget"
] | train | https://github.com/Limenius/Liform/blob/b46ba76cc7703b9d9989ff9f8ca4437cfc8f6c6c/src/Limenius/Liform/Transformer/AbstractTransformer.php#L155-L166 |
Limenius/Liform | src/Limenius/Liform/Serializer/Normalizer/InitialValuesNormalizer.php | InitialValuesNormalizer.normalize | public function normalize($form, $format = null, array $context = [])
{
$formView = $form->createView();
return $this->getValues($form, $formView);
} | php | public function normalize($form, $format = null, array $context = [])
{
$formView = $form->createView();
return $this->getValues($form, $formView);
} | [
"public",
"function",
"normalize",
"(",
"$",
"form",
",",
"$",
"format",
"=",
"null",
",",
"array",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"$",
"formView",
"=",
"$",
"form",
"->",
"createView",
"(",
")",
";",
"return",
"$",
"this",
"->",
"getValues",
"(",
"$",
"form",
",",
"$",
"formView",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/Limenius/Liform/blob/b46ba76cc7703b9d9989ff9f8ca4437cfc8f6c6c/src/Limenius/Liform/Serializer/Normalizer/InitialValuesNormalizer.php#L29-L34 |
tddwizard/magento2-fixtures | src/Checkout/CartBuilder.php | CartBuilder.withProductRequest | public function withProductRequest($sku, $qty = 1, $request = []) : CartBuilder
{
$result = clone $this;
$requestInfo = array_merge(['qty'=> $qty], $request);
$result->addToCartRequests[$sku][] = new DataObject($requestInfo);
return $result;
} | php | public function withProductRequest($sku, $qty = 1, $request = []) : CartBuilder
{
$result = clone $this;
$requestInfo = array_merge(['qty'=> $qty], $request);
$result->addToCartRequests[$sku][] = new DataObject($requestInfo);
return $result;
} | [
"public",
"function",
"withProductRequest",
"(",
"$",
"sku",
",",
"$",
"qty",
"=",
"1",
",",
"$",
"request",
"=",
"[",
"]",
")",
":",
"CartBuilder",
"{",
"$",
"result",
"=",
"clone",
"$",
"this",
";",
"$",
"requestInfo",
"=",
"array_merge",
"(",
"[",
"'qty'",
"=>",
"$",
"qty",
"]",
",",
"$",
"request",
")",
";",
"$",
"result",
"->",
"addToCartRequests",
"[",
"$",
"sku",
"]",
"[",
"]",
"=",
"new",
"DataObject",
"(",
"$",
"requestInfo",
")",
";",
"return",
"$",
"result",
";",
"}"
] | Lower-level API to support arbitary products
@param $sku
@param int $qty
@param $request
@return CartBuilder | [
"Lower",
"-",
"level",
"API",
"to",
"support",
"arbitary",
"products"
] | train | https://github.com/tddwizard/magento2-fixtures/blob/2eb6962211bc06593ed083df423b6e7590a89cc0/src/Checkout/CartBuilder.php#L69-L75 |
asgrim/ofxparser | lib/OfxParser/Ofx.php | Ofx.createDateTimeFromStr | private function createDateTimeFromStr($dateString, $ignoreErrors = false)
{
if((!isset($dateString) || trim($dateString) === '')) return null;
$regex = '/'
. "(\d{4})(\d{2})(\d{2})?" // YYYYMMDD 1,2,3
. "(?:(\d{2})(\d{2})(\d{2}))?" // HHMMSS - optional 4,5,6
. "(?:\.(\d{3}))?" // .XXX - optional 7
. "(?:\[(-?\d+)\:(\w{3}\]))?" // [-n:TZ] - optional 8,9
. '/';
if (preg_match($regex, $dateString, $matches)) {
$year = (int)$matches[1];
$month = (int)$matches[2];
$day = (int)$matches[3];
$hour = isset($matches[4]) ? $matches[4] : 0;
$min = isset($matches[5]) ? $matches[5] : 0;
$sec = isset($matches[6]) ? $matches[6] : 0;
$format = $year . '-' . $month . '-' . $day . ' ' . $hour . ':' . $min . ':' . $sec;
try {
return new \DateTime($format);
} catch (\Exception $e) {
if ($ignoreErrors) {
return null;
}
throw $e;
}
}
throw new \RuntimeException('Failed to initialize DateTime for string: ' . $dateString);
} | php | private function createDateTimeFromStr($dateString, $ignoreErrors = false)
{
if((!isset($dateString) || trim($dateString) === '')) return null;
$regex = '/'
. "(\d{4})(\d{2})(\d{2})?" // YYYYMMDD 1,2,3
. "(?:(\d{2})(\d{2})(\d{2}))?" // HHMMSS - optional 4,5,6
. "(?:\.(\d{3}))?" // .XXX - optional 7
. "(?:\[(-?\d+)\:(\w{3}\]))?" // [-n:TZ] - optional 8,9
. '/';
if (preg_match($regex, $dateString, $matches)) {
$year = (int)$matches[1];
$month = (int)$matches[2];
$day = (int)$matches[3];
$hour = isset($matches[4]) ? $matches[4] : 0;
$min = isset($matches[5]) ? $matches[5] : 0;
$sec = isset($matches[6]) ? $matches[6] : 0;
$format = $year . '-' . $month . '-' . $day . ' ' . $hour . ':' . $min . ':' . $sec;
try {
return new \DateTime($format);
} catch (\Exception $e) {
if ($ignoreErrors) {
return null;
}
throw $e;
}
}
throw new \RuntimeException('Failed to initialize DateTime for string: ' . $dateString);
} | [
"private",
"function",
"createDateTimeFromStr",
"(",
"$",
"dateString",
",",
"$",
"ignoreErrors",
"=",
"false",
")",
"{",
"if",
"(",
"(",
"!",
"isset",
"(",
"$",
"dateString",
")",
"||",
"trim",
"(",
"$",
"dateString",
")",
"===",
"''",
")",
")",
"return",
"null",
";",
"$",
"regex",
"=",
"'/'",
".",
"\"(\\d{4})(\\d{2})(\\d{2})?\"",
"// YYYYMMDD 1,2,3",
".",
"\"(?:(\\d{2})(\\d{2})(\\d{2}))?\"",
"// HHMMSS - optional 4,5,6",
".",
"\"(?:\\.(\\d{3}))?\"",
"// .XXX - optional 7",
".",
"\"(?:\\[(-?\\d+)\\:(\\w{3}\\]))?\"",
"// [-n:TZ] - optional 8,9",
".",
"'/'",
";",
"if",
"(",
"preg_match",
"(",
"$",
"regex",
",",
"$",
"dateString",
",",
"$",
"matches",
")",
")",
"{",
"$",
"year",
"=",
"(",
"int",
")",
"$",
"matches",
"[",
"1",
"]",
";",
"$",
"month",
"=",
"(",
"int",
")",
"$",
"matches",
"[",
"2",
"]",
";",
"$",
"day",
"=",
"(",
"int",
")",
"$",
"matches",
"[",
"3",
"]",
";",
"$",
"hour",
"=",
"isset",
"(",
"$",
"matches",
"[",
"4",
"]",
")",
"?",
"$",
"matches",
"[",
"4",
"]",
":",
"0",
";",
"$",
"min",
"=",
"isset",
"(",
"$",
"matches",
"[",
"5",
"]",
")",
"?",
"$",
"matches",
"[",
"5",
"]",
":",
"0",
";",
"$",
"sec",
"=",
"isset",
"(",
"$",
"matches",
"[",
"6",
"]",
")",
"?",
"$",
"matches",
"[",
"6",
"]",
":",
"0",
";",
"$",
"format",
"=",
"$",
"year",
".",
"'-'",
".",
"$",
"month",
".",
"'-'",
".",
"$",
"day",
".",
"' '",
".",
"$",
"hour",
".",
"':'",
".",
"$",
"min",
".",
"':'",
".",
"$",
"sec",
";",
"try",
"{",
"return",
"new",
"\\",
"DateTime",
"(",
"$",
"format",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"if",
"(",
"$",
"ignoreErrors",
")",
"{",
"return",
"null",
";",
"}",
"throw",
"$",
"e",
";",
"}",
"}",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'Failed to initialize DateTime for string: '",
".",
"$",
"dateString",
")",
";",
"}"
] | Create a DateTime object from a valid OFX date format
Supports:
YYYYMMDDHHMMSS.XXX[gmt offset:tz name]
YYYYMMDDHHMMSS.XXX
YYYYMMDDHHMMSS
YYYYMMDD
@param string $dateString
@param boolean $ignoreErrors
@return \DateTime $dateString
@throws \Exception | [
"Create",
"a",
"DateTime",
"object",
"from",
"a",
"valid",
"OFX",
"date",
"format"
] | train | https://github.com/asgrim/ofxparser/blob/cdb2a9a573a6f44ac965ae76e1b784f04b3e8c67/lib/OfxParser/Ofx.php#L296-L329 |
asgrim/ofxparser | lib/OfxParser/Ofx.php | Ofx.createAmountFromStr | private function createAmountFromStr($amountString)
{
// Decimal mark style (UK/US): 000.00 or 0,000.00
if (preg_match('/^(-|\+)?([\d,]+)(\.?)([\d]{2})$/', $amountString) === 1) {
return (float)preg_replace(
['/([,]+)/', '/\.?([\d]{2})$/'],
['', '.$1'],
$amountString
);
}
// European style: 000,00 or 0.000,00
if (preg_match('/^(-|\+)?([\d\.]+,?[\d]{2})$/', $amountString) === 1) {
return (float)preg_replace(
['/([\.]+)/', '/,?([\d]{2})$/'],
['', '.$1'],
$amountString
);
}
return (float)$amountString;
} | php | private function createAmountFromStr($amountString)
{
// Decimal mark style (UK/US): 000.00 or 0,000.00
if (preg_match('/^(-|\+)?([\d,]+)(\.?)([\d]{2})$/', $amountString) === 1) {
return (float)preg_replace(
['/([,]+)/', '/\.?([\d]{2})$/'],
['', '.$1'],
$amountString
);
}
// European style: 000,00 or 0.000,00
if (preg_match('/^(-|\+)?([\d\.]+,?[\d]{2})$/', $amountString) === 1) {
return (float)preg_replace(
['/([\.]+)/', '/,?([\d]{2})$/'],
['', '.$1'],
$amountString
);
}
return (float)$amountString;
} | [
"private",
"function",
"createAmountFromStr",
"(",
"$",
"amountString",
")",
"{",
"// Decimal mark style (UK/US): 000.00 or 0,000.00",
"if",
"(",
"preg_match",
"(",
"'/^(-|\\+)?([\\d,]+)(\\.?)([\\d]{2})$/'",
",",
"$",
"amountString",
")",
"===",
"1",
")",
"{",
"return",
"(",
"float",
")",
"preg_replace",
"(",
"[",
"'/([,]+)/'",
",",
"'/\\.?([\\d]{2})$/'",
"]",
",",
"[",
"''",
",",
"'.$1'",
"]",
",",
"$",
"amountString",
")",
";",
"}",
"// European style: 000,00 or 0.000,00",
"if",
"(",
"preg_match",
"(",
"'/^(-|\\+)?([\\d\\.]+,?[\\d]{2})$/'",
",",
"$",
"amountString",
")",
"===",
"1",
")",
"{",
"return",
"(",
"float",
")",
"preg_replace",
"(",
"[",
"'/([\\.]+)/'",
",",
"'/,?([\\d]{2})$/'",
"]",
",",
"[",
"''",
",",
"'.$1'",
"]",
",",
"$",
"amountString",
")",
";",
"}",
"return",
"(",
"float",
")",
"$",
"amountString",
";",
"}"
] | Create a formatted number in Float according to different locale options
Supports:
000,00 and -000,00
0.000,00 and -0.000,00
0,000.00 and -0,000.00
000.00 and 000.00
@param string $amountString
@return float | [
"Create",
"a",
"formatted",
"number",
"in",
"Float",
"according",
"to",
"different",
"locale",
"options"
] | train | https://github.com/asgrim/ofxparser/blob/cdb2a9a573a6f44ac965ae76e1b784f04b3e8c67/lib/OfxParser/Ofx.php#L343-L364 |
asgrim/ofxparser | lib/OfxParser/Entities/Transaction.php | Transaction.typeDesc | public function typeDesc()
{
// Cast SimpleXMLObject to string
$type = (string)$this->type;
return array_key_exists($type, self::$types) ? self::$types[$type] : '';
} | php | public function typeDesc()
{
// Cast SimpleXMLObject to string
$type = (string)$this->type;
return array_key_exists($type, self::$types) ? self::$types[$type] : '';
} | [
"public",
"function",
"typeDesc",
"(",
")",
"{",
"// Cast SimpleXMLObject to string",
"$",
"type",
"=",
"(",
"string",
")",
"$",
"this",
"->",
"type",
";",
"return",
"array_key_exists",
"(",
"$",
"type",
",",
"self",
"::",
"$",
"types",
")",
"?",
"self",
"::",
"$",
"types",
"[",
"$",
"type",
"]",
":",
"''",
";",
"}"
] | Get the associated type description
@return string | [
"Get",
"the",
"associated",
"type",
"description"
] | train | https://github.com/asgrim/ofxparser/blob/cdb2a9a573a6f44ac965ae76e1b784f04b3e8c67/lib/OfxParser/Entities/Transaction.php#L79-L84 |
asgrim/ofxparser | lib/OfxParser/Entities/Status.php | Status.codeDesc | public function codeDesc()
{
// Cast code to string from SimpleXMLObject
$code = (string)$this->code;
return array_key_exists($code, self::$codes) ? self::$codes[$code] : '';
} | php | public function codeDesc()
{
// Cast code to string from SimpleXMLObject
$code = (string)$this->code;
return array_key_exists($code, self::$codes) ? self::$codes[$code] : '';
} | [
"public",
"function",
"codeDesc",
"(",
")",
"{",
"// Cast code to string from SimpleXMLObject",
"$",
"code",
"=",
"(",
"string",
")",
"$",
"this",
"->",
"code",
";",
"return",
"array_key_exists",
"(",
"$",
"code",
",",
"self",
"::",
"$",
"codes",
")",
"?",
"self",
"::",
"$",
"codes",
"[",
"$",
"code",
"]",
":",
"''",
";",
"}"
] | Get the associated code description
@return string | [
"Get",
"the",
"associated",
"code",
"description"
] | train | https://github.com/asgrim/ofxparser/blob/cdb2a9a573a6f44ac965ae76e1b784f04b3e8c67/lib/OfxParser/Entities/Status.php#L39-L44 |
asgrim/ofxparser | lib/OfxParser/Parser.php | Parser.loadFromString | public function loadFromString($ofxContent)
{
$ofxContent = str_replace(["\r\n", "\r"], "\n", $ofxContent);
$ofxContent = utf8_encode($ofxContent);
$ofxContent = $this->conditionallyAddNewlines($ofxContent);
$sgmlStart = stripos($ofxContent, '<OFX>');
$ofxHeader = trim(substr($ofxContent, 0, $sgmlStart-1));
$header = $this->parseHeader($ofxHeader);
$ofxSgml = trim(substr($ofxContent, $sgmlStart));
$ofxXml = $this->convertSgmlToXml($ofxSgml);
$xml = $this->xmlLoadString($ofxXml);
$ofx = new Ofx($xml);
$ofx->buildHeader($header);
return $ofx;
} | php | public function loadFromString($ofxContent)
{
$ofxContent = str_replace(["\r\n", "\r"], "\n", $ofxContent);
$ofxContent = utf8_encode($ofxContent);
$ofxContent = $this->conditionallyAddNewlines($ofxContent);
$sgmlStart = stripos($ofxContent, '<OFX>');
$ofxHeader = trim(substr($ofxContent, 0, $sgmlStart-1));
$header = $this->parseHeader($ofxHeader);
$ofxSgml = trim(substr($ofxContent, $sgmlStart));
$ofxXml = $this->convertSgmlToXml($ofxSgml);
$xml = $this->xmlLoadString($ofxXml);
$ofx = new Ofx($xml);
$ofx->buildHeader($header);
return $ofx;
} | [
"public",
"function",
"loadFromString",
"(",
"$",
"ofxContent",
")",
"{",
"$",
"ofxContent",
"=",
"str_replace",
"(",
"[",
"\"\\r\\n\"",
",",
"\"\\r\"",
"]",
",",
"\"\\n\"",
",",
"$",
"ofxContent",
")",
";",
"$",
"ofxContent",
"=",
"utf8_encode",
"(",
"$",
"ofxContent",
")",
";",
"$",
"ofxContent",
"=",
"$",
"this",
"->",
"conditionallyAddNewlines",
"(",
"$",
"ofxContent",
")",
";",
"$",
"sgmlStart",
"=",
"stripos",
"(",
"$",
"ofxContent",
",",
"'<OFX>'",
")",
";",
"$",
"ofxHeader",
"=",
"trim",
"(",
"substr",
"(",
"$",
"ofxContent",
",",
"0",
",",
"$",
"sgmlStart",
"-",
"1",
")",
")",
";",
"$",
"header",
"=",
"$",
"this",
"->",
"parseHeader",
"(",
"$",
"ofxHeader",
")",
";",
"$",
"ofxSgml",
"=",
"trim",
"(",
"substr",
"(",
"$",
"ofxContent",
",",
"$",
"sgmlStart",
")",
")",
";",
"$",
"ofxXml",
"=",
"$",
"this",
"->",
"convertSgmlToXml",
"(",
"$",
"ofxSgml",
")",
";",
"$",
"xml",
"=",
"$",
"this",
"->",
"xmlLoadString",
"(",
"$",
"ofxXml",
")",
";",
"$",
"ofx",
"=",
"new",
"Ofx",
"(",
"$",
"xml",
")",
";",
"$",
"ofx",
"->",
"buildHeader",
"(",
"$",
"header",
")",
";",
"return",
"$",
"ofx",
";",
"}"
] | Load an OFX by directly using the text content
@param string $ofxContent
@return Ofx
@throws \Exception | [
"Load",
"an",
"OFX",
"by",
"directly",
"using",
"the",
"text",
"content"
] | train | https://github.com/asgrim/ofxparser/blob/cdb2a9a573a6f44ac965ae76e1b784f04b3e8c67/lib/OfxParser/Parser.php#L39-L61 |
asgrim/ofxparser | lib/OfxParser/Parser.php | Parser.xmlLoadString | private function xmlLoadString($xmlString)
{
libxml_clear_errors();
libxml_use_internal_errors(true);
$xml = simplexml_load_string($xmlString);
if ($errors = libxml_get_errors()) {
throw new \RuntimeException('Failed to parse OFX: ' . var_export($errors, true));
}
return $xml;
} | php | private function xmlLoadString($xmlString)
{
libxml_clear_errors();
libxml_use_internal_errors(true);
$xml = simplexml_load_string($xmlString);
if ($errors = libxml_get_errors()) {
throw new \RuntimeException('Failed to parse OFX: ' . var_export($errors, true));
}
return $xml;
} | [
"private",
"function",
"xmlLoadString",
"(",
"$",
"xmlString",
")",
"{",
"libxml_clear_errors",
"(",
")",
";",
"libxml_use_internal_errors",
"(",
"true",
")",
";",
"$",
"xml",
"=",
"simplexml_load_string",
"(",
"$",
"xmlString",
")",
";",
"if",
"(",
"$",
"errors",
"=",
"libxml_get_errors",
"(",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'Failed to parse OFX: '",
".",
"var_export",
"(",
"$",
"errors",
",",
"true",
")",
")",
";",
"}",
"return",
"$",
"xml",
";",
"}"
] | Load an XML string without PHP errors - throws exception instead
@param string $xmlString
@throws \Exception
@return \SimpleXMLElement | [
"Load",
"an",
"XML",
"string",
"without",
"PHP",
"errors",
"-",
"throws",
"exception",
"instead"
] | train | https://github.com/asgrim/ofxparser/blob/cdb2a9a573a6f44ac965ae76e1b784f04b3e8c67/lib/OfxParser/Parser.php#L85-L96 |
asgrim/ofxparser | lib/OfxParser/Parser.php | Parser.parseHeader | private function parseHeader($ofxHeader)
{
$header = [];
$ofxHeader = trim($ofxHeader);
// Remove empty new lines.
$ofxHeader = preg_replace('/^\n+/m', '', $ofxHeader);
$ofxHeaderLines = explode("\n", $ofxHeader);
// Check if it's an XML file (OFXv2)
if(preg_match('/^<\?xml/', $ofxHeader) === 1) {
$ofxHeaderLines = preg_replace(['/"/', '/\?>$/m', '/^(<\?)(XML|OFX)/mi'], '', $ofxHeaderLines);
// Only parse OFX headers and not XML headers.
$ofxHeaderLine = explode(' ', trim($ofxHeaderLines[1]));
foreach ($ofxHeaderLine as $value) {
$tag = explode('=', $value);
$header[$tag[0]] = $tag[1];
}
return $header;
}
foreach ($ofxHeaderLines as $value) {
$tag = explode(':', $value);
$header[$tag[0]] = $tag[1];
}
return $header;
} | php | private function parseHeader($ofxHeader)
{
$header = [];
$ofxHeader = trim($ofxHeader);
// Remove empty new lines.
$ofxHeader = preg_replace('/^\n+/m', '', $ofxHeader);
$ofxHeaderLines = explode("\n", $ofxHeader);
// Check if it's an XML file (OFXv2)
if(preg_match('/^<\?xml/', $ofxHeader) === 1) {
$ofxHeaderLines = preg_replace(['/"/', '/\?>$/m', '/^(<\?)(XML|OFX)/mi'], '', $ofxHeaderLines);
// Only parse OFX headers and not XML headers.
$ofxHeaderLine = explode(' ', trim($ofxHeaderLines[1]));
foreach ($ofxHeaderLine as $value) {
$tag = explode('=', $value);
$header[$tag[0]] = $tag[1];
}
return $header;
}
foreach ($ofxHeaderLines as $value) {
$tag = explode(':', $value);
$header[$tag[0]] = $tag[1];
}
return $header;
} | [
"private",
"function",
"parseHeader",
"(",
"$",
"ofxHeader",
")",
"{",
"$",
"header",
"=",
"[",
"]",
";",
"$",
"ofxHeader",
"=",
"trim",
"(",
"$",
"ofxHeader",
")",
";",
"// Remove empty new lines.",
"$",
"ofxHeader",
"=",
"preg_replace",
"(",
"'/^\\n+/m'",
",",
"''",
",",
"$",
"ofxHeader",
")",
";",
"$",
"ofxHeaderLines",
"=",
"explode",
"(",
"\"\\n\"",
",",
"$",
"ofxHeader",
")",
";",
"// Check if it's an XML file (OFXv2)",
"if",
"(",
"preg_match",
"(",
"'/^<\\?xml/'",
",",
"$",
"ofxHeader",
")",
"===",
"1",
")",
"{",
"$",
"ofxHeaderLines",
"=",
"preg_replace",
"(",
"[",
"'/\"/'",
",",
"'/\\?>$/m'",
",",
"'/^(<\\?)(XML|OFX)/mi'",
"]",
",",
"''",
",",
"$",
"ofxHeaderLines",
")",
";",
"// Only parse OFX headers and not XML headers.",
"$",
"ofxHeaderLine",
"=",
"explode",
"(",
"' '",
",",
"trim",
"(",
"$",
"ofxHeaderLines",
"[",
"1",
"]",
")",
")",
";",
"foreach",
"(",
"$",
"ofxHeaderLine",
"as",
"$",
"value",
")",
"{",
"$",
"tag",
"=",
"explode",
"(",
"'='",
",",
"$",
"value",
")",
";",
"$",
"header",
"[",
"$",
"tag",
"[",
"0",
"]",
"]",
"=",
"$",
"tag",
"[",
"1",
"]",
";",
"}",
"return",
"$",
"header",
";",
"}",
"foreach",
"(",
"$",
"ofxHeaderLines",
"as",
"$",
"value",
")",
"{",
"$",
"tag",
"=",
"explode",
"(",
"':'",
",",
"$",
"value",
")",
";",
"$",
"header",
"[",
"$",
"tag",
"[",
"0",
"]",
"]",
"=",
"$",
"tag",
"[",
"1",
"]",
";",
"}",
"return",
"$",
"header",
";",
"}"
] | Parse the SGML Header to an Array
@param string $ofxHeader
@param int $sgmlStart
@return array | [
"Parse",
"the",
"SGML",
"Header",
"to",
"an",
"Array"
] | train | https://github.com/asgrim/ofxparser/blob/cdb2a9a573a6f44ac965ae76e1b784f04b3e8c67/lib/OfxParser/Parser.php#L126-L156 |
asgrim/ofxparser | lib/OfxParser/Parser.php | Parser.convertSgmlToXml | private function convertSgmlToXml($sgml)
{
$sgml = preg_replace('/&(?!#?[a-z0-9]+;)/', '&', $sgml);
$lines = explode("\n", $sgml);
$xml = '';
foreach ($lines as $line) {
$xml .= trim($this->closeUnclosedXmlTags($line)) . "\n";
}
return trim($xml);
} | php | private function convertSgmlToXml($sgml)
{
$sgml = preg_replace('/&(?!#?[a-z0-9]+;)/', '&', $sgml);
$lines = explode("\n", $sgml);
$xml = '';
foreach ($lines as $line) {
$xml .= trim($this->closeUnclosedXmlTags($line)) . "\n";
}
return trim($xml);
} | [
"private",
"function",
"convertSgmlToXml",
"(",
"$",
"sgml",
")",
"{",
"$",
"sgml",
"=",
"preg_replace",
"(",
"'/&(?!#?[a-z0-9]+;)/'",
",",
"'&'",
",",
"$",
"sgml",
")",
";",
"$",
"lines",
"=",
"explode",
"(",
"\"\\n\"",
",",
"$",
"sgml",
")",
";",
"$",
"xml",
"=",
"''",
";",
"foreach",
"(",
"$",
"lines",
"as",
"$",
"line",
")",
"{",
"$",
"xml",
".=",
"trim",
"(",
"$",
"this",
"->",
"closeUnclosedXmlTags",
"(",
"$",
"line",
")",
")",
".",
"\"\\n\"",
";",
"}",
"return",
"trim",
"(",
"$",
"xml",
")",
";",
"}"
] | Convert an SGML to an XML string
@param string $sgml
@return string | [
"Convert",
"an",
"SGML",
"to",
"an",
"XML",
"string"
] | train | https://github.com/asgrim/ofxparser/blob/cdb2a9a573a6f44ac965ae76e1b784f04b3e8c67/lib/OfxParser/Parser.php#L164-L176 |
CSharpRU/vault-php | src/BaseObject.php | BaseObject.toArray | public function toArray($recursive = true)
{
$data = [];
foreach ($this->getFields() as $field => $definition) {
$data[$field] = is_string($definition) ? $this->$definition : $definition($this, $field);
}
return $recursive ? ArrayHelper::toArray($data, $recursive) : $data;
} | php | public function toArray($recursive = true)
{
$data = [];
foreach ($this->getFields() as $field => $definition) {
$data[$field] = is_string($definition) ? $this->$definition : $definition($this, $field);
}
return $recursive ? ArrayHelper::toArray($data, $recursive) : $data;
} | [
"public",
"function",
"toArray",
"(",
"$",
"recursive",
"=",
"true",
")",
"{",
"$",
"data",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getFields",
"(",
")",
"as",
"$",
"field",
"=>",
"$",
"definition",
")",
"{",
"$",
"data",
"[",
"$",
"field",
"]",
"=",
"is_string",
"(",
"$",
"definition",
")",
"?",
"$",
"this",
"->",
"$",
"definition",
":",
"$",
"definition",
"(",
"$",
"this",
",",
"$",
"field",
")",
";",
"}",
"return",
"$",
"recursive",
"?",
"ArrayHelper",
"::",
"toArray",
"(",
"$",
"data",
",",
"$",
"recursive",
")",
":",
"$",
"data",
";",
"}"
] | @param bool $recursive
@return array | [
"@param",
"bool",
"$recursive"
] | train | https://github.com/CSharpRU/vault-php/blob/c6f959e118b4f29e4802d017f952d774379df70c/src/BaseObject.php#L164-L173 |
CSharpRU/vault-php | src/Builders/ResponseBuilder.php | ResponseBuilder.build | public function build(ResponseInterface $response)
{
$rawData = json_decode((string)$response->getBody(), true) ?: [];
$data = ModelHelper::camelize($rawData);
$data['data'] = ArrayHelper::getValue($rawData, 'data', []);
if ($auth = ArrayHelper::getValue($data, 'auth')) {
$data['auth'] = new Auth($auth);
}
return new Response($data);
} | php | public function build(ResponseInterface $response)
{
$rawData = json_decode((string)$response->getBody(), true) ?: [];
$data = ModelHelper::camelize($rawData);
$data['data'] = ArrayHelper::getValue($rawData, 'data', []);
if ($auth = ArrayHelper::getValue($data, 'auth')) {
$data['auth'] = new Auth($auth);
}
return new Response($data);
} | [
"public",
"function",
"build",
"(",
"ResponseInterface",
"$",
"response",
")",
"{",
"$",
"rawData",
"=",
"json_decode",
"(",
"(",
"string",
")",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"true",
")",
"?",
":",
"[",
"]",
";",
"$",
"data",
"=",
"ModelHelper",
"::",
"camelize",
"(",
"$",
"rawData",
")",
";",
"$",
"data",
"[",
"'data'",
"]",
"=",
"ArrayHelper",
"::",
"getValue",
"(",
"$",
"rawData",
",",
"'data'",
",",
"[",
"]",
")",
";",
"if",
"(",
"$",
"auth",
"=",
"ArrayHelper",
"::",
"getValue",
"(",
"$",
"data",
",",
"'auth'",
")",
")",
"{",
"$",
"data",
"[",
"'auth'",
"]",
"=",
"new",
"Auth",
"(",
"$",
"auth",
")",
";",
"}",
"return",
"new",
"Response",
"(",
"$",
"data",
")",
";",
"}"
] | @param ResponseInterface $response
@return Response | [
"@param",
"ResponseInterface",
"$response"
] | train | https://github.com/CSharpRU/vault-php/blob/c6f959e118b4f29e4802d017f952d774379df70c/src/Builders/ResponseBuilder.php#L23-L34 |
CSharpRU/vault-php | src/BaseClient.php | BaseClient.send | public function send(RequestInterface $request, array $options = [])
{
$request = $request->withHeader('User-Agent', 'VaultPHP/1.0.0');
$request = $request->withHeader('Content-Type', 'application/json');
if ($this->token) {
$request = $request->withHeader('X-Vault-Token', $this->token->getAuth()->getClientToken());
}
$this->logger->debug('Request.', [
'method' => $request->getMethod(),
'uri' => $request->getUri(),
'headers' => $request->getHeaders(),
'body' => $request->getBody()->getContents(),
]);
try {
$response = $this->transport->send($request, $options);
} catch (TransferException $e) {
$this->logger->error('Something went wrong when calling Vault.', [
'code' => $e->getCode(),
'message' => $e->getMessage(),
]);
$this->logger->debug('Trace.', ['exception' => $e]);
throw new ServerException(sprintf('Something went wrong when calling Vault (%s).', $e->getMessage()));
}
$this->logger->debug('Response.', [
'statusCode' => $response->getStatusCode(),
'reasonPhrase' => $response->getReasonPhrase(),
'headers ' => $response->getHeaders(),
'body' => $response->getBody()->getContents(),
]);
return $response;
} | php | public function send(RequestInterface $request, array $options = [])
{
$request = $request->withHeader('User-Agent', 'VaultPHP/1.0.0');
$request = $request->withHeader('Content-Type', 'application/json');
if ($this->token) {
$request = $request->withHeader('X-Vault-Token', $this->token->getAuth()->getClientToken());
}
$this->logger->debug('Request.', [
'method' => $request->getMethod(),
'uri' => $request->getUri(),
'headers' => $request->getHeaders(),
'body' => $request->getBody()->getContents(),
]);
try {
$response = $this->transport->send($request, $options);
} catch (TransferException $e) {
$this->logger->error('Something went wrong when calling Vault.', [
'code' => $e->getCode(),
'message' => $e->getMessage(),
]);
$this->logger->debug('Trace.', ['exception' => $e]);
throw new ServerException(sprintf('Something went wrong when calling Vault (%s).', $e->getMessage()));
}
$this->logger->debug('Response.', [
'statusCode' => $response->getStatusCode(),
'reasonPhrase' => $response->getReasonPhrase(),
'headers ' => $response->getHeaders(),
'body' => $response->getBody()->getContents(),
]);
return $response;
} | [
"public",
"function",
"send",
"(",
"RequestInterface",
"$",
"request",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"request",
"=",
"$",
"request",
"->",
"withHeader",
"(",
"'User-Agent'",
",",
"'VaultPHP/1.0.0'",
")",
";",
"$",
"request",
"=",
"$",
"request",
"->",
"withHeader",
"(",
"'Content-Type'",
",",
"'application/json'",
")",
";",
"if",
"(",
"$",
"this",
"->",
"token",
")",
"{",
"$",
"request",
"=",
"$",
"request",
"->",
"withHeader",
"(",
"'X-Vault-Token'",
",",
"$",
"this",
"->",
"token",
"->",
"getAuth",
"(",
")",
"->",
"getClientToken",
"(",
")",
")",
";",
"}",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'Request.'",
",",
"[",
"'method'",
"=>",
"$",
"request",
"->",
"getMethod",
"(",
")",
",",
"'uri'",
"=>",
"$",
"request",
"->",
"getUri",
"(",
")",
",",
"'headers'",
"=>",
"$",
"request",
"->",
"getHeaders",
"(",
")",
",",
"'body'",
"=>",
"$",
"request",
"->",
"getBody",
"(",
")",
"->",
"getContents",
"(",
")",
",",
"]",
")",
";",
"try",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"transport",
"->",
"send",
"(",
"$",
"request",
",",
"$",
"options",
")",
";",
"}",
"catch",
"(",
"TransferException",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"error",
"(",
"'Something went wrong when calling Vault.'",
",",
"[",
"'code'",
"=>",
"$",
"e",
"->",
"getCode",
"(",
")",
",",
"'message'",
"=>",
"$",
"e",
"->",
"getMessage",
"(",
")",
",",
"]",
")",
";",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'Trace.'",
",",
"[",
"'exception'",
"=>",
"$",
"e",
"]",
")",
";",
"throw",
"new",
"ServerException",
"(",
"sprintf",
"(",
"'Something went wrong when calling Vault (%s).'",
",",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
")",
";",
"}",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'Response.'",
",",
"[",
"'statusCode'",
"=>",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
",",
"'reasonPhrase'",
"=>",
"$",
"response",
"->",
"getReasonPhrase",
"(",
")",
",",
"'headers '",
"=>",
"$",
"response",
"->",
"getHeaders",
"(",
")",
",",
"'body'",
"=>",
"$",
"response",
"->",
"getBody",
"(",
")",
"->",
"getContents",
"(",
")",
",",
"]",
")",
";",
"return",
"$",
"response",
";",
"}"
] | @param RequestInterface $request
@param array $options
@return ResponseInterface
@throws \Vault\Exceptions\TransportException
@throws \Vault\Exceptions\ClientException
@throws \Vault\Exceptions\ServerException
@throws \RuntimeException
@throws \InvalidArgumentException | [
"@param",
"RequestInterface",
"$request",
"@param",
"array",
"$options"
] | train | https://github.com/CSharpRU/vault-php/blob/c6f959e118b4f29e4802d017f952d774379df70c/src/BaseClient.php#L92-L129 |
CSharpRU/vault-php | src/BaseClient.php | BaseClient.get | public function get($url = null, array $options = [])
{
return $this->responseBuilder->build($this->send(new Request('GET', $url), $options));
} | php | public function get($url = null, array $options = [])
{
return $this->responseBuilder->build($this->send(new Request('GET', $url), $options));
} | [
"public",
"function",
"get",
"(",
"$",
"url",
"=",
"null",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"responseBuilder",
"->",
"build",
"(",
"$",
"this",
"->",
"send",
"(",
"new",
"Request",
"(",
"'GET'",
",",
"$",
"url",
")",
",",
"$",
"options",
")",
")",
";",
"}"
] | @param string $url
@param array $options
@return Response
@throws \Vault\Exceptions\TransportException
@throws \Vault\Exceptions\ServerException
@throws \Vault\Exceptions\ClientException
@throws \RuntimeException
@throws \InvalidArgumentException | [
"@param",
"string",
"$url",
"@param",
"array",
"$options"
] | train | https://github.com/CSharpRU/vault-php/blob/c6f959e118b4f29e4802d017f952d774379df70c/src/BaseClient.php#L143-L146 |
CSharpRU/vault-php | src/BaseClient.php | BaseClient.post | public function post($url, array $options = [])
{
return $this->responseBuilder->build($this->send(new Request('POST', $url), $options));
} | php | public function post($url, array $options = [])
{
return $this->responseBuilder->build($this->send(new Request('POST', $url), $options));
} | [
"public",
"function",
"post",
"(",
"$",
"url",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"responseBuilder",
"->",
"build",
"(",
"$",
"this",
"->",
"send",
"(",
"new",
"Request",
"(",
"'POST'",
",",
"$",
"url",
")",
",",
"$",
"options",
")",
")",
";",
"}"
] | @param string $url
@param array $options
@return Response
@throws \Vault\Exceptions\TransportException
@throws \Vault\Exceptions\ServerException
@throws \Vault\Exceptions\ClientException
@throws \RuntimeException
@throws \InvalidArgumentException | [
"@param",
"string",
"$url",
"@param",
"array",
"$options"
] | train | https://github.com/CSharpRU/vault-php/blob/c6f959e118b4f29e4802d017f952d774379df70c/src/BaseClient.php#L211-L214 |
CSharpRU/vault-php | src/CachedClient.php | CachedClient.read | public function read($path)
{
if (!$this->readCacheEnabled) {
return parent::read($path);
}
if (!$this->cache) {
$this->logger->warning('Cache is enabled, but cache pool is not set.');
return parent::read($path);
}
$key = self::READ_CACHE_KEY . str_replace(['{', '}', '(', ')', '/', '\\', '@', '-'], '_', $path);
if ($this->cache->hasItem($key)) {
$this->logger->debug('Has read response in cache.', ['path' => $path]);
return $this->cache->getItem($key)->get();
}
$response = parent::read($path);
$item = (new CacheItem($key))->set($response)->expiresAfter($this->readCacheTtl);
$this->logger->debug('Saving read response in cache.', ['path' => $path, 'item' => $item]);
if (!$this->cache->save($item)) {
$this->logger->warning('Cannot save read response into cache.', ['path' => $path]);
}
return $response;
} | php | public function read($path)
{
if (!$this->readCacheEnabled) {
return parent::read($path);
}
if (!$this->cache) {
$this->logger->warning('Cache is enabled, but cache pool is not set.');
return parent::read($path);
}
$key = self::READ_CACHE_KEY . str_replace(['{', '}', '(', ')', '/', '\\', '@', '-'], '_', $path);
if ($this->cache->hasItem($key)) {
$this->logger->debug('Has read response in cache.', ['path' => $path]);
return $this->cache->getItem($key)->get();
}
$response = parent::read($path);
$item = (new CacheItem($key))->set($response)->expiresAfter($this->readCacheTtl);
$this->logger->debug('Saving read response in cache.', ['path' => $path, 'item' => $item]);
if (!$this->cache->save($item)) {
$this->logger->warning('Cannot save read response into cache.', ['path' => $path]);
}
return $response;
} | [
"public",
"function",
"read",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"readCacheEnabled",
")",
"{",
"return",
"parent",
"::",
"read",
"(",
"$",
"path",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"cache",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"warning",
"(",
"'Cache is enabled, but cache pool is not set.'",
")",
";",
"return",
"parent",
"::",
"read",
"(",
"$",
"path",
")",
";",
"}",
"$",
"key",
"=",
"self",
"::",
"READ_CACHE_KEY",
".",
"str_replace",
"(",
"[",
"'{'",
",",
"'}'",
",",
"'('",
",",
"')'",
",",
"'/'",
",",
"'\\\\'",
",",
"'@'",
",",
"'-'",
"]",
",",
"'_'",
",",
"$",
"path",
")",
";",
"if",
"(",
"$",
"this",
"->",
"cache",
"->",
"hasItem",
"(",
"$",
"key",
")",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'Has read response in cache.'",
",",
"[",
"'path'",
"=>",
"$",
"path",
"]",
")",
";",
"return",
"$",
"this",
"->",
"cache",
"->",
"getItem",
"(",
"$",
"key",
")",
"->",
"get",
"(",
")",
";",
"}",
"$",
"response",
"=",
"parent",
"::",
"read",
"(",
"$",
"path",
")",
";",
"$",
"item",
"=",
"(",
"new",
"CacheItem",
"(",
"$",
"key",
")",
")",
"->",
"set",
"(",
"$",
"response",
")",
"->",
"expiresAfter",
"(",
"$",
"this",
"->",
"readCacheTtl",
")",
";",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'Saving read response in cache.'",
",",
"[",
"'path'",
"=>",
"$",
"path",
",",
"'item'",
"=>",
"$",
"item",
"]",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"cache",
"->",
"save",
"(",
"$",
"item",
")",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"warning",
"(",
"'Cannot save read response into cache.'",
",",
"[",
"'path'",
"=>",
"$",
"path",
"]",
")",
";",
"}",
"return",
"$",
"response",
";",
"}"
] | @inheritdoc
@throws \Psr\Cache\InvalidArgumentException | [
"@inheritdoc"
] | train | https://github.com/CSharpRU/vault-php/blob/c6f959e118b4f29e4802d017f952d774379df70c/src/CachedClient.php#L27-L58 |
CSharpRU/vault-php | src/AuthenticationStrategies/UserPassAuthenticationStrategy.php | UserPassAuthenticationStrategy.authenticate | public function authenticate()
{
$response = $this->client->write(
sprintf('/auth/userpass/login/%s', $this->username),
['password' => $this->password]
);
return $response->getAuth();
} | php | public function authenticate()
{
$response = $this->client->write(
sprintf('/auth/userpass/login/%s', $this->username),
['password' => $this->password]
);
return $response->getAuth();
} | [
"public",
"function",
"authenticate",
"(",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"write",
"(",
"sprintf",
"(",
"'/auth/userpass/login/%s'",
",",
"$",
"this",
"->",
"username",
")",
",",
"[",
"'password'",
"=>",
"$",
"this",
"->",
"password",
"]",
")",
";",
"return",
"$",
"response",
"->",
"getAuth",
"(",
")",
";",
"}"
] | Returns auth for further interactions with Vault.
@return Auth
@throws \Vault\Exceptions\TransportException
@throws \Vault\Exceptions\ServerException
@throws \Vault\Exceptions\ClientException
@throws \RuntimeException
@throws \InvalidArgumentException | [
"Returns",
"auth",
"for",
"further",
"interactions",
"with",
"Vault",
"."
] | train | https://github.com/CSharpRU/vault-php/blob/c6f959e118b4f29e4802d017f952d774379df70c/src/AuthenticationStrategies/UserPassAuthenticationStrategy.php#L47-L55 |
CSharpRU/vault-php | src/Helpers/ModelHelper.php | ModelHelper.camelize | public static function camelize(array $data, $recursive = true)
{
$return = [];
foreach ($data as $key => $value) {
if (is_array($value) && $recursive) {
$value = self::camelize($value, $recursive);
}
$return[Inflector::camelize($key)] = $value;
}
return $return;
} | php | public static function camelize(array $data, $recursive = true)
{
$return = [];
foreach ($data as $key => $value) {
if (is_array($value) && $recursive) {
$value = self::camelize($value, $recursive);
}
$return[Inflector::camelize($key)] = $value;
}
return $return;
} | [
"public",
"static",
"function",
"camelize",
"(",
"array",
"$",
"data",
",",
"$",
"recursive",
"=",
"true",
")",
"{",
"$",
"return",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"data",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"value",
")",
"&&",
"$",
"recursive",
")",
"{",
"$",
"value",
"=",
"self",
"::",
"camelize",
"(",
"$",
"value",
",",
"$",
"recursive",
")",
";",
"}",
"$",
"return",
"[",
"Inflector",
"::",
"camelize",
"(",
"$",
"key",
")",
"]",
"=",
"$",
"value",
";",
"}",
"return",
"$",
"return",
";",
"}"
] | @param array $data
@param bool $recursive
@return array | [
"@param",
"array",
"$data",
"@param",
"bool",
"$recursive"
] | train | https://github.com/CSharpRU/vault-php/blob/c6f959e118b4f29e4802d017f952d774379df70c/src/Helpers/ModelHelper.php#L20-L33 |
CSharpRU/vault-php | src/Client.php | Client.buildPath | public function buildPath($path)
{
if (!$this->version) {
$this->logger->warning('API version is not set!');
return $path;
}
return sprintf('/%s%s', $this->version, $path);
} | php | public function buildPath($path)
{
if (!$this->version) {
$this->logger->warning('API version is not set!');
return $path;
}
return sprintf('/%s%s', $this->version, $path);
} | [
"public",
"function",
"buildPath",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"version",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"warning",
"(",
"'API version is not set!'",
")",
";",
"return",
"$",
"path",
";",
"}",
"return",
"sprintf",
"(",
"'/%s%s'",
",",
"$",
"this",
"->",
"version",
",",
"$",
"path",
")",
";",
"}"
] | @param string $path
@return string | [
"@param",
"string",
"$path"
] | train | https://github.com/CSharpRU/vault-php/blob/c6f959e118b4f29e4802d017f952d774379df70c/src/Client.php#L60-L69 |
CSharpRU/vault-php | src/Client.php | Client.write | public function write($path, array $data = [])
{
return $this->post($this->buildPath($path), ['body' => json_encode($data)]);
} | php | public function write($path, array $data = [])
{
return $this->post($this->buildPath($path), ['body' => json_encode($data)]);
} | [
"public",
"function",
"write",
"(",
"$",
"path",
",",
"array",
"$",
"data",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"post",
"(",
"$",
"this",
"->",
"buildPath",
"(",
"$",
"path",
")",
",",
"[",
"'body'",
"=>",
"json_encode",
"(",
"$",
"data",
")",
"]",
")",
";",
"}"
] | @param string $path
@param array $data
@return Response
@throws \Vault\Exceptions\TransportException
@throws \Vault\Exceptions\ServerException
@throws \Vault\Exceptions\ClientException
@throws \RuntimeException
@throws \InvalidArgumentException | [
"@param",
"string",
"$path",
"@param",
"array",
"$data"
] | train | https://github.com/CSharpRU/vault-php/blob/c6f959e118b4f29e4802d017f952d774379df70c/src/Client.php#L83-L86 |
CSharpRU/vault-php | src/Client.php | Client.setAuthenticationStrategy | public function setAuthenticationStrategy(AuthenticationStrategy $authenticationStrategy)
{
$authenticationStrategy->setClient($this);
$this->authenticationStrategy = $authenticationStrategy;
return $this;
} | php | public function setAuthenticationStrategy(AuthenticationStrategy $authenticationStrategy)
{
$authenticationStrategy->setClient($this);
$this->authenticationStrategy = $authenticationStrategy;
return $this;
} | [
"public",
"function",
"setAuthenticationStrategy",
"(",
"AuthenticationStrategy",
"$",
"authenticationStrategy",
")",
"{",
"$",
"authenticationStrategy",
"->",
"setClient",
"(",
"$",
"this",
")",
";",
"$",
"this",
"->",
"authenticationStrategy",
"=",
"$",
"authenticationStrategy",
";",
"return",
"$",
"this",
";",
"}"
] | @param AuthenticationStrategy $authenticationStrategy
@return $this | [
"@param",
"AuthenticationStrategy",
"$authenticationStrategy"
] | train | https://github.com/CSharpRU/vault-php/blob/c6f959e118b4f29e4802d017f952d774379df70c/src/Client.php#L137-L144 |
CSharpRU/vault-php | src/Client.php | Client.send | public function send(RequestInterface $request, array $options = [])
{
$response = parent::send($request, $options);
// re-authenticate if 403 and token is expired
if (
$this->token &&
$response->getStatusCode() === 403 &&
$this->isTokenExpired($this->token) &&
!$this->authenticate()
) {
throw new ClientException('Cannot re-authenticate.');
}
$this->checkResponse($response);
return $response;
} | php | public function send(RequestInterface $request, array $options = [])
{
$response = parent::send($request, $options);
// re-authenticate if 403 and token is expired
if (
$this->token &&
$response->getStatusCode() === 403 &&
$this->isTokenExpired($this->token) &&
!$this->authenticate()
) {
throw new ClientException('Cannot re-authenticate.');
}
$this->checkResponse($response);
return $response;
} | [
"public",
"function",
"send",
"(",
"RequestInterface",
"$",
"request",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"response",
"=",
"parent",
"::",
"send",
"(",
"$",
"request",
",",
"$",
"options",
")",
";",
"// re-authenticate if 403 and token is expired",
"if",
"(",
"$",
"this",
"->",
"token",
"&&",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"===",
"403",
"&&",
"$",
"this",
"->",
"isTokenExpired",
"(",
"$",
"this",
"->",
"token",
")",
"&&",
"!",
"$",
"this",
"->",
"authenticate",
"(",
")",
")",
"{",
"throw",
"new",
"ClientException",
"(",
"'Cannot re-authenticate.'",
")",
";",
"}",
"$",
"this",
"->",
"checkResponse",
"(",
"$",
"response",
")",
";",
"return",
"$",
"response",
";",
"}"
] | @inheritdoc
@throws \Psr\Cache\InvalidArgumentException
@throws \Vault\Exceptions\DependencyException | [
"@inheritdoc"
] | train | https://github.com/CSharpRU/vault-php/blob/c6f959e118b4f29e4802d017f952d774379df70c/src/Client.php#L152-L169 |
CSharpRU/vault-php | src/Client.php | Client.isTokenExpired | protected function isTokenExpired($token)
{
return !$token ||
(
$token->getCreationTtl() > 0 &&
time() > $token->getCreationTime() + $token->getCreationTtl()
);
} | php | protected function isTokenExpired($token)
{
return !$token ||
(
$token->getCreationTtl() > 0 &&
time() > $token->getCreationTime() + $token->getCreationTtl()
);
} | [
"protected",
"function",
"isTokenExpired",
"(",
"$",
"token",
")",
"{",
"return",
"!",
"$",
"token",
"||",
"(",
"$",
"token",
"->",
"getCreationTtl",
"(",
")",
">",
"0",
"&&",
"time",
"(",
")",
">",
"$",
"token",
"->",
"getCreationTime",
"(",
")",
"+",
"$",
"token",
"->",
"getCreationTtl",
"(",
")",
")",
";",
"}"
] | @param Token $token
@return bool | [
"@param",
"Token",
"$token"
] | train | https://github.com/CSharpRU/vault-php/blob/c6f959e118b4f29e4802d017f952d774379df70c/src/Client.php#L176-L183 |
CSharpRU/vault-php | src/Client.php | Client.authenticate | public function authenticate()
{
if ($this->token = $this->getTokenFromCache()) {
$this->logger->debug('Using token from cache.');
$this->writeTokenInfoToDebugLog();
return (bool)$this->token;
}
if (!$this->authenticationStrategy) {
$this->logger->critical('Trying to authenticate without strategy.');
throw new DependencyException(sprintf(
'Specify authentication strategy before calling this method (%s).',
__METHOD__
));
}
$this->logger->debug('Trying to authenticate.');
if ($auth = $this->authenticationStrategy->authenticate()) {
$this->logger->debug('Authentication was successful.', ['clientToken' => $auth->getClientToken()]);
// temporary
$this->token = new Token(['auth' => $auth]);
// get info about self
$response = $this->get('/v1/auth/token/lookup-self');
$this->token = new Token(array_merge(ModelHelper::camelize($response->getData()), ['auth' => $auth]));
$this->writeTokenInfoToDebugLog();
$this->putTokenIntoCache();
return true;
}
return false;
} | php | public function authenticate()
{
if ($this->token = $this->getTokenFromCache()) {
$this->logger->debug('Using token from cache.');
$this->writeTokenInfoToDebugLog();
return (bool)$this->token;
}
if (!$this->authenticationStrategy) {
$this->logger->critical('Trying to authenticate without strategy.');
throw new DependencyException(sprintf(
'Specify authentication strategy before calling this method (%s).',
__METHOD__
));
}
$this->logger->debug('Trying to authenticate.');
if ($auth = $this->authenticationStrategy->authenticate()) {
$this->logger->debug('Authentication was successful.', ['clientToken' => $auth->getClientToken()]);
// temporary
$this->token = new Token(['auth' => $auth]);
// get info about self
$response = $this->get('/v1/auth/token/lookup-self');
$this->token = new Token(array_merge(ModelHelper::camelize($response->getData()), ['auth' => $auth]));
$this->writeTokenInfoToDebugLog();
$this->putTokenIntoCache();
return true;
}
return false;
} | [
"public",
"function",
"authenticate",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"token",
"=",
"$",
"this",
"->",
"getTokenFromCache",
"(",
")",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'Using token from cache.'",
")",
";",
"$",
"this",
"->",
"writeTokenInfoToDebugLog",
"(",
")",
";",
"return",
"(",
"bool",
")",
"$",
"this",
"->",
"token",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"authenticationStrategy",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"critical",
"(",
"'Trying to authenticate without strategy.'",
")",
";",
"throw",
"new",
"DependencyException",
"(",
"sprintf",
"(",
"'Specify authentication strategy before calling this method (%s).'",
",",
"__METHOD__",
")",
")",
";",
"}",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'Trying to authenticate.'",
")",
";",
"if",
"(",
"$",
"auth",
"=",
"$",
"this",
"->",
"authenticationStrategy",
"->",
"authenticate",
"(",
")",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'Authentication was successful.'",
",",
"[",
"'clientToken'",
"=>",
"$",
"auth",
"->",
"getClientToken",
"(",
")",
"]",
")",
";",
"// temporary",
"$",
"this",
"->",
"token",
"=",
"new",
"Token",
"(",
"[",
"'auth'",
"=>",
"$",
"auth",
"]",
")",
";",
"// get info about self",
"$",
"response",
"=",
"$",
"this",
"->",
"get",
"(",
"'/v1/auth/token/lookup-self'",
")",
";",
"$",
"this",
"->",
"token",
"=",
"new",
"Token",
"(",
"array_merge",
"(",
"ModelHelper",
"::",
"camelize",
"(",
"$",
"response",
"->",
"getData",
"(",
")",
")",
",",
"[",
"'auth'",
"=>",
"$",
"auth",
"]",
")",
")",
";",
"$",
"this",
"->",
"writeTokenInfoToDebugLog",
"(",
")",
";",
"$",
"this",
"->",
"putTokenIntoCache",
"(",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | @return bool
@throws \Vault\Exceptions\TransportException
@throws \Vault\Exceptions\DependencyException
@throws \Psr\Cache\InvalidArgumentException
@throws \Vault\Exceptions\ServerException
@throws \Vault\Exceptions\ClientException
@throws \RuntimeException
@throws \InvalidArgumentException | [
"@return",
"bool"
] | train | https://github.com/CSharpRU/vault-php/blob/c6f959e118b4f29e4802d017f952d774379df70c/src/Client.php#L196-L235 |
CSharpRU/vault-php | src/Client.php | Client.getTokenFromCache | protected function getTokenFromCache()
{
if (!$this->cache || !$this->cache->hasItem(self::TOKEN_CACHE_KEY)) {
return null;
}
/** @var Token $token */
$token = $this->cache->getItem(self::TOKEN_CACHE_KEY)->get();
if (!$token || !$token->getAuth()) {
$this->logger->debug('No token in cache or auth is empty, returning null.');
return null;
}
// invalidate token
if ($this->isTokenExpired($token)) {
$this->logger->debug('Token is expired.');
$this->writeTokenInfoToDebugLog();
return null;
}
return $token;
} | php | protected function getTokenFromCache()
{
if (!$this->cache || !$this->cache->hasItem(self::TOKEN_CACHE_KEY)) {
return null;
}
/** @var Token $token */
$token = $this->cache->getItem(self::TOKEN_CACHE_KEY)->get();
if (!$token || !$token->getAuth()) {
$this->logger->debug('No token in cache or auth is empty, returning null.');
return null;
}
// invalidate token
if ($this->isTokenExpired($token)) {
$this->logger->debug('Token is expired.');
$this->writeTokenInfoToDebugLog();
return null;
}
return $token;
} | [
"protected",
"function",
"getTokenFromCache",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"cache",
"||",
"!",
"$",
"this",
"->",
"cache",
"->",
"hasItem",
"(",
"self",
"::",
"TOKEN_CACHE_KEY",
")",
")",
"{",
"return",
"null",
";",
"}",
"/** @var Token $token */",
"$",
"token",
"=",
"$",
"this",
"->",
"cache",
"->",
"getItem",
"(",
"self",
"::",
"TOKEN_CACHE_KEY",
")",
"->",
"get",
"(",
")",
";",
"if",
"(",
"!",
"$",
"token",
"||",
"!",
"$",
"token",
"->",
"getAuth",
"(",
")",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'No token in cache or auth is empty, returning null.'",
")",
";",
"return",
"null",
";",
"}",
"// invalidate token",
"if",
"(",
"$",
"this",
"->",
"isTokenExpired",
"(",
"$",
"token",
")",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'Token is expired.'",
")",
";",
"$",
"this",
"->",
"writeTokenInfoToDebugLog",
"(",
")",
";",
"return",
"null",
";",
"}",
"return",
"$",
"token",
";",
"}"
] | @TODO: move to separated class
@return Token|null
@throws \Psr\Cache\InvalidArgumentException | [
"@TODO",
":",
"move",
"to",
"separated",
"class"
] | train | https://github.com/CSharpRU/vault-php/blob/c6f959e118b4f29e4802d017f952d774379df70c/src/Client.php#L244-L269 |
CSharpRU/vault-php | src/Client.php | Client.putTokenIntoCache | protected function putTokenIntoCache()
{
if (!$this->cache) {
return true; // just ignore
}
if ($this->isTokenExpired($this->token)) {
throw new ClientException('Cannot save expired token into cache!');
}
$authItem = (new CacheItem(self::TOKEN_CACHE_KEY))
->set($this->token)
->expiresAfter($this->token->getAuth()->getLeaseDuration());
$this->logger->debug('Token is saved into cache.');
return $this->cache->save($authItem);
} | php | protected function putTokenIntoCache()
{
if (!$this->cache) {
return true; // just ignore
}
if ($this->isTokenExpired($this->token)) {
throw new ClientException('Cannot save expired token into cache!');
}
$authItem = (new CacheItem(self::TOKEN_CACHE_KEY))
->set($this->token)
->expiresAfter($this->token->getAuth()->getLeaseDuration());
$this->logger->debug('Token is saved into cache.');
return $this->cache->save($authItem);
} | [
"protected",
"function",
"putTokenIntoCache",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"cache",
")",
"{",
"return",
"true",
";",
"// just ignore",
"}",
"if",
"(",
"$",
"this",
"->",
"isTokenExpired",
"(",
"$",
"this",
"->",
"token",
")",
")",
"{",
"throw",
"new",
"ClientException",
"(",
"'Cannot save expired token into cache!'",
")",
";",
"}",
"$",
"authItem",
"=",
"(",
"new",
"CacheItem",
"(",
"self",
"::",
"TOKEN_CACHE_KEY",
")",
")",
"->",
"set",
"(",
"$",
"this",
"->",
"token",
")",
"->",
"expiresAfter",
"(",
"$",
"this",
"->",
"token",
"->",
"getAuth",
"(",
")",
"->",
"getLeaseDuration",
"(",
")",
")",
";",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'Token is saved into cache.'",
")",
";",
"return",
"$",
"this",
"->",
"cache",
"->",
"save",
"(",
"$",
"authItem",
")",
";",
"}"
] | @TODO: move to separated class
@return bool
@throws \Vault\Exceptions\ClientException | [
"@TODO",
":",
"move",
"to",
"separated",
"class"
] | train | https://github.com/CSharpRU/vault-php/blob/c6f959e118b4f29e4802d017f952d774379df70c/src/Client.php#L293-L310 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.