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
sequencelengths 15
672k
| func_documentation_string
stringlengths 1
47.2k
| func_documentation_tokens
sequencelengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|---|---|---|
brunschgi/TerrificComposerBundle | Form/SkinType.php | SkinType.buildForm | public function buildForm(FormBuilderInterface $builder, array $options)
{
global $kernel;
// get all modules
$modules = array();
$dir = $kernel->getRootDir().'/../src/Terrific/Module/';
$finder = new Finder();
$finder->directories()->in($dir)->depth('== 0');
foreach ($finder as $file) {
$filename = $file->getFilename();
$module = str_replace('Bundle', '', $filename);
$modules[$module] = $module;
}
$builder->add('module', 'choice', array(
'choices' => $modules,
'multiple' => false,
'label' => 'Skin for Module'
));
$builder->add('name', 'text');
$builder->add('style', 'choice', array(
'choices' => array('css' => 'CSS', 'less' => 'LESS'),
'multiple' => false,
'expanded' => true
));
} | php | public function buildForm(FormBuilderInterface $builder, array $options)
{
global $kernel;
// get all modules
$modules = array();
$dir = $kernel->getRootDir().'/../src/Terrific/Module/';
$finder = new Finder();
$finder->directories()->in($dir)->depth('== 0');
foreach ($finder as $file) {
$filename = $file->getFilename();
$module = str_replace('Bundle', '', $filename);
$modules[$module] = $module;
}
$builder->add('module', 'choice', array(
'choices' => $modules,
'multiple' => false,
'label' => 'Skin for Module'
));
$builder->add('name', 'text');
$builder->add('style', 'choice', array(
'choices' => array('css' => 'CSS', 'less' => 'LESS'),
'multiple' => false,
'expanded' => true
));
} | [
"public",
"function",
"buildForm",
"(",
"FormBuilderInterface",
"$",
"builder",
",",
"array",
"$",
"options",
")",
"{",
"global",
"$",
"kernel",
";",
"// get all modules",
"$",
"modules",
"=",
"array",
"(",
")",
";",
"$",
"dir",
"=",
"$",
"kernel",
"->",
"getRootDir",
"(",
")",
".",
"'/../src/Terrific/Module/'",
";",
"$",
"finder",
"=",
"new",
"Finder",
"(",
")",
";",
"$",
"finder",
"->",
"directories",
"(",
")",
"->",
"in",
"(",
"$",
"dir",
")",
"->",
"depth",
"(",
"'== 0'",
")",
";",
"foreach",
"(",
"$",
"finder",
"as",
"$",
"file",
")",
"{",
"$",
"filename",
"=",
"$",
"file",
"->",
"getFilename",
"(",
")",
";",
"$",
"module",
"=",
"str_replace",
"(",
"'Bundle'",
",",
"''",
",",
"$",
"filename",
")",
";",
"$",
"modules",
"[",
"$",
"module",
"]",
"=",
"$",
"module",
";",
"}",
"$",
"builder",
"->",
"add",
"(",
"'module'",
",",
"'choice'",
",",
"array",
"(",
"'choices'",
"=>",
"$",
"modules",
",",
"'multiple'",
"=>",
"false",
",",
"'label'",
"=>",
"'Skin for Module'",
")",
")",
";",
"$",
"builder",
"->",
"add",
"(",
"'name'",
",",
"'text'",
")",
";",
"$",
"builder",
"->",
"add",
"(",
"'style'",
",",
"'choice'",
",",
"array",
"(",
"'choices'",
"=>",
"array",
"(",
"'css'",
"=>",
"'CSS'",
",",
"'less'",
"=>",
"'LESS'",
")",
",",
"'multiple'",
"=>",
"false",
",",
"'expanded'",
"=>",
"true",
")",
")",
";",
"}"
] | Builds the Skin form.
@param \Symfony\Component\Form\FormBuilder $builder
@param array $options | [
"Builds",
"the",
"Skin",
"form",
"."
] | train | https://github.com/brunschgi/TerrificComposerBundle/blob/6eef4ace887c19ef166ab6654de385bc1ffbf5f1/Form/SkinType.php#L29-L58 |
Attibee/Bumble-Shell | src/Arg.php | Arg.addOption | public function addOption( $opt, $type ) {
if( $type !== self::OPT_PARAM || $type !== self::OPT_SWITCH ) {
return;
}
$this->options[(string)$opt] = $type;
} | php | public function addOption( $opt, $type ) {
if( $type !== self::OPT_PARAM || $type !== self::OPT_SWITCH ) {
return;
}
$this->options[(string)$opt] = $type;
} | [
"public",
"function",
"addOption",
"(",
"$",
"opt",
",",
"$",
"type",
")",
"{",
"if",
"(",
"$",
"type",
"!==",
"self",
"::",
"OPT_PARAM",
"||",
"$",
"type",
"!==",
"self",
"::",
"OPT_SWITCH",
")",
"{",
"return",
";",
"}",
"$",
"this",
"->",
"options",
"[",
"(",
"string",
")",
"$",
"opt",
"]",
"=",
"$",
"type",
";",
"}"
] | Adds an option to the argument parser.
@param string $opt The name of the option.
@param string $type Args::SWITCH or Args::PARAM | [
"Adds",
"an",
"option",
"to",
"the",
"argument",
"parser",
"."
] | train | https://github.com/Attibee/Bumble-Shell/blob/c42da09654c0f3f5d0c81815ab69b930e1052c55/src/Arg.php#L87-L93 |
Attibee/Bumble-Shell | src/Arg.php | Arg.parse | public function parse() {
global $argv;
$options = array();
$parameters = array();
$argc = count( $argv );
$paramCount = count( $this->parameters );
//get parameters
if( $argc - 1 < $paramCount ) {
throw new \Exception("The command requires $paramCount parameters.");
}
//last items are the params
for( $i = $paramCount - 1; $i >= 0; $i-- ) {
$this->abstractParameters[$this->parameters[$i]] = $argv[$argc - $i - 1];
}
//go through each arg
for( $i = 1; $i < $argc - $paramCount; $i++ ) {
$arg = $argv[$i];
//cannot start without a switch
if( !$this->isOption( $arg ) ) {
throw new \Exception("Invalid argument \"$arg\".");
}
//check if it's a valid option
$option = $arg[1];
if( $this->isParam( $option ) ) {
//the arg stands on its own, such as -f, not -ffile.txt
//set next as its value, move $i ahead
if( $this->isSolitary( $arg ) ) {
//last item
if( $i == $argc - $paramCount - 1 ) {
throw new \Exception("Parameter does not follow the option \"$option\".");
}
$this->abstractOptions[$option] = $argv[$i+1];
$i++;
} else {
$this->abstractOptions[$option] = substr( $arg, 2 );
}
} else if( $this->isSwitch( $option ) ) {
//loop through all switches in the param
for( $i = 1; $i < strlen( $param ) - 1; $i++ ) {
$s = $arg[$i];
//not a switch
if( !$this->isSwitch( $arg[$i] ) ) {
throw new \Exception("An invalid switch \"$s\" was provided.");
}
$this->abstractOptions[$s] = true;
}
}
}
} | php | public function parse() {
global $argv;
$options = array();
$parameters = array();
$argc = count( $argv );
$paramCount = count( $this->parameters );
//get parameters
if( $argc - 1 < $paramCount ) {
throw new \Exception("The command requires $paramCount parameters.");
}
//last items are the params
for( $i = $paramCount - 1; $i >= 0; $i-- ) {
$this->abstractParameters[$this->parameters[$i]] = $argv[$argc - $i - 1];
}
//go through each arg
for( $i = 1; $i < $argc - $paramCount; $i++ ) {
$arg = $argv[$i];
//cannot start without a switch
if( !$this->isOption( $arg ) ) {
throw new \Exception("Invalid argument \"$arg\".");
}
//check if it's a valid option
$option = $arg[1];
if( $this->isParam( $option ) ) {
//the arg stands on its own, such as -f, not -ffile.txt
//set next as its value, move $i ahead
if( $this->isSolitary( $arg ) ) {
//last item
if( $i == $argc - $paramCount - 1 ) {
throw new \Exception("Parameter does not follow the option \"$option\".");
}
$this->abstractOptions[$option] = $argv[$i+1];
$i++;
} else {
$this->abstractOptions[$option] = substr( $arg, 2 );
}
} else if( $this->isSwitch( $option ) ) {
//loop through all switches in the param
for( $i = 1; $i < strlen( $param ) - 1; $i++ ) {
$s = $arg[$i];
//not a switch
if( !$this->isSwitch( $arg[$i] ) ) {
throw new \Exception("An invalid switch \"$s\" was provided.");
}
$this->abstractOptions[$s] = true;
}
}
}
} | [
"public",
"function",
"parse",
"(",
")",
"{",
"global",
"$",
"argv",
";",
"$",
"options",
"=",
"array",
"(",
")",
";",
"$",
"parameters",
"=",
"array",
"(",
")",
";",
"$",
"argc",
"=",
"count",
"(",
"$",
"argv",
")",
";",
"$",
"paramCount",
"=",
"count",
"(",
"$",
"this",
"->",
"parameters",
")",
";",
"//get parameters",
"if",
"(",
"$",
"argc",
"-",
"1",
"<",
"$",
"paramCount",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"\"The command requires $paramCount parameters.\"",
")",
";",
"}",
"//last items are the params",
"for",
"(",
"$",
"i",
"=",
"$",
"paramCount",
"-",
"1",
";",
"$",
"i",
">=",
"0",
";",
"$",
"i",
"--",
")",
"{",
"$",
"this",
"->",
"abstractParameters",
"[",
"$",
"this",
"->",
"parameters",
"[",
"$",
"i",
"]",
"]",
"=",
"$",
"argv",
"[",
"$",
"argc",
"-",
"$",
"i",
"-",
"1",
"]",
";",
"}",
"//go through each arg",
"for",
"(",
"$",
"i",
"=",
"1",
";",
"$",
"i",
"<",
"$",
"argc",
"-",
"$",
"paramCount",
";",
"$",
"i",
"++",
")",
"{",
"$",
"arg",
"=",
"$",
"argv",
"[",
"$",
"i",
"]",
";",
"//cannot start without a switch",
"if",
"(",
"!",
"$",
"this",
"->",
"isOption",
"(",
"$",
"arg",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"\"Invalid argument \\\"$arg\\\".\"",
")",
";",
"}",
"//check if it's a valid option",
"$",
"option",
"=",
"$",
"arg",
"[",
"1",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"isParam",
"(",
"$",
"option",
")",
")",
"{",
"//the arg stands on its own, such as -f, not -ffile.txt",
"//set next as its value, move $i ahead",
"if",
"(",
"$",
"this",
"->",
"isSolitary",
"(",
"$",
"arg",
")",
")",
"{",
"//last item",
"if",
"(",
"$",
"i",
"==",
"$",
"argc",
"-",
"$",
"paramCount",
"-",
"1",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"\"Parameter does not follow the option \\\"$option\\\".\"",
")",
";",
"}",
"$",
"this",
"->",
"abstractOptions",
"[",
"$",
"option",
"]",
"=",
"$",
"argv",
"[",
"$",
"i",
"+",
"1",
"]",
";",
"$",
"i",
"++",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"abstractOptions",
"[",
"$",
"option",
"]",
"=",
"substr",
"(",
"$",
"arg",
",",
"2",
")",
";",
"}",
"}",
"else",
"if",
"(",
"$",
"this",
"->",
"isSwitch",
"(",
"$",
"option",
")",
")",
"{",
"//loop through all switches in the param",
"for",
"(",
"$",
"i",
"=",
"1",
";",
"$",
"i",
"<",
"strlen",
"(",
"$",
"param",
")",
"-",
"1",
";",
"$",
"i",
"++",
")",
"{",
"$",
"s",
"=",
"$",
"arg",
"[",
"$",
"i",
"]",
";",
"//not a switch",
"if",
"(",
"!",
"$",
"this",
"->",
"isSwitch",
"(",
"$",
"arg",
"[",
"$",
"i",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"\"An invalid switch \\\"$s\\\" was provided.\"",
")",
";",
"}",
"$",
"this",
"->",
"abstractOptions",
"[",
"$",
"s",
"]",
"=",
"true",
";",
"}",
"}",
"}",
"}"
] | Parses the parameters and throws an error if the user supplied an invalid format. | [
"Parses",
"the",
"parameters",
"and",
"throws",
"an",
"error",
"if",
"the",
"user",
"supplied",
"an",
"invalid",
"format",
"."
] | train | https://github.com/Attibee/Bumble-Shell/blob/c42da09654c0f3f5d0c81815ab69b930e1052c55/src/Arg.php#L118-L176 |
kaiohken1982/Neobazaar | src/Neobazaar/Entity/MappedSuperclassBase.php | MappedSuperclassBase.exchangeArray | public function exchangeArray($data)
{
foreach($data as $prop => $value) {
$methodName = 'set' . ucfirst($prop);
if(method_exists ($this, $methodName)) {
call_user_func(array($this, $methodName), $value);
}
}
} | php | public function exchangeArray($data)
{
foreach($data as $prop => $value) {
$methodName = 'set' . ucfirst($prop);
if(method_exists ($this, $methodName)) {
call_user_func(array($this, $methodName), $value);
}
}
} | [
"public",
"function",
"exchangeArray",
"(",
"$",
"data",
")",
"{",
"foreach",
"(",
"$",
"data",
"as",
"$",
"prop",
"=>",
"$",
"value",
")",
"{",
"$",
"methodName",
"=",
"'set'",
".",
"ucfirst",
"(",
"$",
"prop",
")",
";",
"if",
"(",
"method_exists",
"(",
"$",
"this",
",",
"$",
"methodName",
")",
")",
"{",
"call_user_func",
"(",
"array",
"(",
"$",
"this",
",",
"$",
"methodName",
")",
",",
"$",
"value",
")",
";",
"}",
"}",
"}"
] | Exchange array - used in ZF2 form
@param array $data An array of data | [
"Exchange",
"array",
"-",
"used",
"in",
"ZF2",
"form"
] | train | https://github.com/kaiohken1982/Neobazaar/blob/288c972dea981d715c4e136edb5dba0318c9e6cb/src/Neobazaar/Entity/MappedSuperclassBase.php#L30-L38 |
kaiohken1982/Neobazaar | src/Neobazaar/Entity/MappedSuperclassBase.php | MappedSuperclassBase.getArrayCopy | public function getArrayCopy()
{
$vars = get_object_vars($this);
foreach($vars as $k => $var) {
if($var instanceof Datetime) {
$vars[$k . '_f'] = $var->format(Datetime::ISO8601);
}
}
return $vars;
} | php | public function getArrayCopy()
{
$vars = get_object_vars($this);
foreach($vars as $k => $var) {
if($var instanceof Datetime) {
$vars[$k . '_f'] = $var->format(Datetime::ISO8601);
}
}
return $vars;
} | [
"public",
"function",
"getArrayCopy",
"(",
")",
"{",
"$",
"vars",
"=",
"get_object_vars",
"(",
"$",
"this",
")",
";",
"foreach",
"(",
"$",
"vars",
"as",
"$",
"k",
"=>",
"$",
"var",
")",
"{",
"if",
"(",
"$",
"var",
"instanceof",
"Datetime",
")",
"{",
"$",
"vars",
"[",
"$",
"k",
".",
"'_f'",
"]",
"=",
"$",
"var",
"->",
"format",
"(",
"Datetime",
"::",
"ISO8601",
")",
";",
"}",
"}",
"return",
"$",
"vars",
";",
"}"
] | Restituisce le proprietà dell'oggetto allo scopo di popolare i form
NOTA BENE: questo metodo restituisce i valori
per le proprieta con access modifier protected.
Le proprietà private non saranno esposte, QUINDI
se non si desidera che siano restituiti i valori di certe proprietà
( es. password ) basterà dichiararle come private.
Se questo metodo non restituisce nulla per una entità probabilmente
le proprietà sono tutte private (il generatore le genera private)
@return multitype: | [
"Restituisce",
"le",
"proprietà",
"dell",
"oggetto",
"allo",
"scopo",
"di",
"popolare",
"i",
"form",
"NOTA",
"BENE",
":",
"questo",
"metodo",
"restituisce",
"i",
"valori",
"per",
"le",
"proprieta",
"con",
"access",
"modifier",
"protected",
"."
] | train | https://github.com/kaiohken1982/Neobazaar/blob/288c972dea981d715c4e136edb5dba0318c9e6cb/src/Neobazaar/Entity/MappedSuperclassBase.php#L54-L63 |
rancoud/Session | src/DatabaseEncryption.php | DatabaseEncryption.read | public function read($sessionId): string
{
$encryptedData = parent::read($sessionId);
return $this->decrypt($encryptedData);
} | php | public function read($sessionId): string
{
$encryptedData = parent::read($sessionId);
return $this->decrypt($encryptedData);
} | [
"public",
"function",
"read",
"(",
"$",
"sessionId",
")",
":",
"string",
"{",
"$",
"encryptedData",
"=",
"parent",
"::",
"read",
"(",
"$",
"sessionId",
")",
";",
"return",
"$",
"this",
"->",
"decrypt",
"(",
"$",
"encryptedData",
")",
";",
"}"
] | @param string $sessionId
@throws SessionException
@throws DatabaseException
@return string | [
"@param",
"string",
"$sessionId"
] | train | https://github.com/rancoud/Session/blob/8c79fae900a0804b3c0637e51bf52d8bb9b9cfb3/src/DatabaseEncryption.php#L24-L29 |
rancoud/Session | src/DatabaseEncryption.php | DatabaseEncryption.write | public function write($sessionId, $data): bool
{
$cryptedData = $this->encrypt($data);
return parent::write($sessionId, $cryptedData);
} | php | public function write($sessionId, $data): bool
{
$cryptedData = $this->encrypt($data);
return parent::write($sessionId, $cryptedData);
} | [
"public",
"function",
"write",
"(",
"$",
"sessionId",
",",
"$",
"data",
")",
":",
"bool",
"{",
"$",
"cryptedData",
"=",
"$",
"this",
"->",
"encrypt",
"(",
"$",
"data",
")",
";",
"return",
"parent",
"::",
"write",
"(",
"$",
"sessionId",
",",
"$",
"cryptedData",
")",
";",
"}"
] | @param string $sessionId
@param string $data
@throws DatabaseException
@throws SessionException
@return bool | [
"@param",
"string",
"$sessionId",
"@param",
"string",
"$data"
] | train | https://github.com/rancoud/Session/blob/8c79fae900a0804b3c0637e51bf52d8bb9b9cfb3/src/DatabaseEncryption.php#L40-L45 |
zodream/helpers | src/Tree.php | Tree.getTreeChild | public static function getTreeChild($data, $parent_id, $key = 'parent_id', $id_key = 'id') {
$result = [];
$args = [$parent_id];
do {
$kids = [];
$flag = false;
foreach ($args as $fid) {
for ($i = count($data) - 1; $i >=0 ; $i --) {
$node = $data[$i];
if ($node[$key] == $fid) {
array_splice($data, $i , 1);
$result[] = $node[$id_key];
$kids[] = $node[$id_key];
$flag = true;
}
}
}
$args = $kids;
} while($flag === true);
return $result;
} | php | public static function getTreeChild($data, $parent_id, $key = 'parent_id', $id_key = 'id') {
$result = [];
$args = [$parent_id];
do {
$kids = [];
$flag = false;
foreach ($args as $fid) {
for ($i = count($data) - 1; $i >=0 ; $i --) {
$node = $data[$i];
if ($node[$key] == $fid) {
array_splice($data, $i , 1);
$result[] = $node[$id_key];
$kids[] = $node[$id_key];
$flag = true;
}
}
}
$args = $kids;
} while($flag === true);
return $result;
} | [
"public",
"static",
"function",
"getTreeChild",
"(",
"$",
"data",
",",
"$",
"parent_id",
",",
"$",
"key",
"=",
"'parent_id'",
",",
"$",
"id_key",
"=",
"'id'",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"$",
"args",
"=",
"[",
"$",
"parent_id",
"]",
";",
"do",
"{",
"$",
"kids",
"=",
"[",
"]",
";",
"$",
"flag",
"=",
"false",
";",
"foreach",
"(",
"$",
"args",
"as",
"$",
"fid",
")",
"{",
"for",
"(",
"$",
"i",
"=",
"count",
"(",
"$",
"data",
")",
"-",
"1",
";",
"$",
"i",
">=",
"0",
";",
"$",
"i",
"--",
")",
"{",
"$",
"node",
"=",
"$",
"data",
"[",
"$",
"i",
"]",
";",
"if",
"(",
"$",
"node",
"[",
"$",
"key",
"]",
"==",
"$",
"fid",
")",
"{",
"array_splice",
"(",
"$",
"data",
",",
"$",
"i",
",",
"1",
")",
";",
"$",
"result",
"[",
"]",
"=",
"$",
"node",
"[",
"$",
"id_key",
"]",
";",
"$",
"kids",
"[",
"]",
"=",
"$",
"node",
"[",
"$",
"id_key",
"]",
";",
"$",
"flag",
"=",
"true",
";",
"}",
"}",
"}",
"$",
"args",
"=",
"$",
"kids",
";",
"}",
"while",
"(",
"$",
"flag",
"===",
"true",
")",
";",
"return",
"$",
"result",
";",
"}"
] | 获取子孙id
@param $data
@param $parent_id
@param string $key
@param string $id_key
@return array | [
"获取子孙id"
] | train | https://github.com/zodream/helpers/blob/98c533a0a50547bd8e3c97ab750d2d15f8e58b49/src/Tree.php#L18-L38 |
zodream/helpers | src/Tree.php | Tree.getTreeParent | public static function getTreeParent($data, $id, $key = 'parent_id', $id_key = 'id') {
$result = [];
$obj = [];
foreach ($data as $node) {
$obj[$node[$id_key]] = $node[$key];
}
while ($id) {
if (isset($obj[$id])) {
break;
}
if (in_array($obj[$id], $result)) {
// 数组有问题,陷入死循环,提前退出
break;
}
$result[] = $obj[$id];
$id = $obj[$id];
}
unset($obj);
return array_reverse($result);
} | php | public static function getTreeParent($data, $id, $key = 'parent_id', $id_key = 'id') {
$result = [];
$obj = [];
foreach ($data as $node) {
$obj[$node[$id_key]] = $node[$key];
}
while ($id) {
if (isset($obj[$id])) {
break;
}
if (in_array($obj[$id], $result)) {
// 数组有问题,陷入死循环,提前退出
break;
}
$result[] = $obj[$id];
$id = $obj[$id];
}
unset($obj);
return array_reverse($result);
} | [
"public",
"static",
"function",
"getTreeParent",
"(",
"$",
"data",
",",
"$",
"id",
",",
"$",
"key",
"=",
"'parent_id'",
",",
"$",
"id_key",
"=",
"'id'",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"$",
"obj",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"data",
"as",
"$",
"node",
")",
"{",
"$",
"obj",
"[",
"$",
"node",
"[",
"$",
"id_key",
"]",
"]",
"=",
"$",
"node",
"[",
"$",
"key",
"]",
";",
"}",
"while",
"(",
"$",
"id",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"obj",
"[",
"$",
"id",
"]",
")",
")",
"{",
"break",
";",
"}",
"if",
"(",
"in_array",
"(",
"$",
"obj",
"[",
"$",
"id",
"]",
",",
"$",
"result",
")",
")",
"{",
"// 数组有问题,陷入死循环,提前退出",
"break",
";",
"}",
"$",
"result",
"[",
"]",
"=",
"$",
"obj",
"[",
"$",
"id",
"]",
";",
"$",
"id",
"=",
"$",
"obj",
"[",
"$",
"id",
"]",
";",
"}",
"unset",
"(",
"$",
"obj",
")",
";",
"return",
"array_reverse",
"(",
"$",
"result",
")",
";",
"}"
] | 获取父级id
@param $data
@param $id
@param string $key
@param string $id_key
@return array | [
"获取父级id"
] | train | https://github.com/zodream/helpers/blob/98c533a0a50547bd8e3c97ab750d2d15f8e58b49/src/Tree.php#L48-L67 |
zodream/helpers | src/Tree.php | Tree.getTree | public function getTree($items) {
$tree = array(); //格式化好的树
$newItems = array();
foreach ($items as $value) {
$newItems[$value['id']] = $value;
}
foreach ($newItems as $key => $item) {
if (isset($newItems[$item['pid']])) {
$newItems[$item['pid']]['son'][] = &$newItems[$key];
} else {
$tree[] = &$newItems[$key];
}
}
return $tree;
} | php | public function getTree($items) {
$tree = array(); //格式化好的树
$newItems = array();
foreach ($items as $value) {
$newItems[$value['id']] = $value;
}
foreach ($newItems as $key => $item) {
if (isset($newItems[$item['pid']])) {
$newItems[$item['pid']]['son'][] = &$newItems[$key];
} else {
$tree[] = &$newItems[$key];
}
}
return $tree;
} | [
"public",
"function",
"getTree",
"(",
"$",
"items",
")",
"{",
"$",
"tree",
"=",
"array",
"(",
")",
";",
"//格式化好的树",
"$",
"newItems",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"items",
"as",
"$",
"value",
")",
"{",
"$",
"newItems",
"[",
"$",
"value",
"[",
"'id'",
"]",
"]",
"=",
"$",
"value",
";",
"}",
"foreach",
"(",
"$",
"newItems",
"as",
"$",
"key",
"=>",
"$",
"item",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"newItems",
"[",
"$",
"item",
"[",
"'pid'",
"]",
"]",
")",
")",
"{",
"$",
"newItems",
"[",
"$",
"item",
"[",
"'pid'",
"]",
"]",
"[",
"'son'",
"]",
"[",
"]",
"=",
"&",
"$",
"newItems",
"[",
"$",
"key",
"]",
";",
"}",
"else",
"{",
"$",
"tree",
"[",
"]",
"=",
"&",
"$",
"newItems",
"[",
"$",
"key",
"]",
";",
"}",
"}",
"return",
"$",
"tree",
";",
"}"
] | 将数据格式化成树形结构
@author Xuefen.Tong
@param array $items
@return array | [
"将数据格式化成树形结构"
] | train | https://github.com/zodream/helpers/blob/98c533a0a50547bd8e3c97ab750d2d15f8e58b49/src/Tree.php#L206-L220 |
kaiohken1982/NeobazaarDocumentModule | src/Document/Service/Image.php | Image.save | public function save(array $data)
{
// All the services we need
$main = $this->getServiceLocator()->get('neobazaar.service.main');
$em = $main->getEntityManager();
$documentRepository = $main->getDocumentEntityRepository();
$userRepository = $main->getUserEntityRepository();
$cache = $this->getServiceLocator()->get('ClassifiedCache');
$form = $this->getServiceLocator()->get('document.form.classifiedimageadd');
$classifiedId = !empty($data['classifiedid']) ? $data['classifiedid'] : null;
$classified = null !== $classifiedId ?
$documentRepository->findByEncryptedId($classifiedId, 'documentId') : null;
// remove parent cache
$cache = $this->getServiceLocator()->get('ClassifiedCache');
if (!empty($classifiedId) && $cache->hasItem($classifiedId)) {
$cache->removeItem($classifiedId);
}
$userId = !empty($data['userid']) ? $data['userid'] : null;
$user = null !== $userId ?
$userRepository->findByEncryptedId($userId, 'userId') : null;
$entity = new Document();
$form->setData($data);
if (!$form->isValid()) {
throw new \Exception(serialize($form->getMessages('files')));
}
$data = $form->getData();
// @todo Better recover this in a smarter way
$files = isset($data['files']) ? $data['files'] : array();
$firstFile = reset($files);
if(empty($firstFile)) {
throw new \Exception(serialize(array('Empty file')));
}
$title = is_array($firstFile) && isset($firstFile['name']) ?
$firstFile['name'] : '';
$entity->setDocumentType(Document::DOCUMENT_TYPE_IMAGE);
$entity->setTitle($title);
$entity->setParent($classified);
$entity->setUser($user);
$entity->setState(Document::DOCUMENT_STATE_ACTIVE);
$em->persist($entity);
$em->flush();
// trigger saveClassified event with the saved entity
$this->getEventManager()->trigger('imageSaved', null, $entity);
return $entity;
} | php | public function save(array $data)
{
// All the services we need
$main = $this->getServiceLocator()->get('neobazaar.service.main');
$em = $main->getEntityManager();
$documentRepository = $main->getDocumentEntityRepository();
$userRepository = $main->getUserEntityRepository();
$cache = $this->getServiceLocator()->get('ClassifiedCache');
$form = $this->getServiceLocator()->get('document.form.classifiedimageadd');
$classifiedId = !empty($data['classifiedid']) ? $data['classifiedid'] : null;
$classified = null !== $classifiedId ?
$documentRepository->findByEncryptedId($classifiedId, 'documentId') : null;
// remove parent cache
$cache = $this->getServiceLocator()->get('ClassifiedCache');
if (!empty($classifiedId) && $cache->hasItem($classifiedId)) {
$cache->removeItem($classifiedId);
}
$userId = !empty($data['userid']) ? $data['userid'] : null;
$user = null !== $userId ?
$userRepository->findByEncryptedId($userId, 'userId') : null;
$entity = new Document();
$form->setData($data);
if (!$form->isValid()) {
throw new \Exception(serialize($form->getMessages('files')));
}
$data = $form->getData();
// @todo Better recover this in a smarter way
$files = isset($data['files']) ? $data['files'] : array();
$firstFile = reset($files);
if(empty($firstFile)) {
throw new \Exception(serialize(array('Empty file')));
}
$title = is_array($firstFile) && isset($firstFile['name']) ?
$firstFile['name'] : '';
$entity->setDocumentType(Document::DOCUMENT_TYPE_IMAGE);
$entity->setTitle($title);
$entity->setParent($classified);
$entity->setUser($user);
$entity->setState(Document::DOCUMENT_STATE_ACTIVE);
$em->persist($entity);
$em->flush();
// trigger saveClassified event with the saved entity
$this->getEventManager()->trigger('imageSaved', null, $entity);
return $entity;
} | [
"public",
"function",
"save",
"(",
"array",
"$",
"data",
")",
"{",
"// All the services we need",
"$",
"main",
"=",
"$",
"this",
"->",
"getServiceLocator",
"(",
")",
"->",
"get",
"(",
"'neobazaar.service.main'",
")",
";",
"$",
"em",
"=",
"$",
"main",
"->",
"getEntityManager",
"(",
")",
";",
"$",
"documentRepository",
"=",
"$",
"main",
"->",
"getDocumentEntityRepository",
"(",
")",
";",
"$",
"userRepository",
"=",
"$",
"main",
"->",
"getUserEntityRepository",
"(",
")",
";",
"$",
"cache",
"=",
"$",
"this",
"->",
"getServiceLocator",
"(",
")",
"->",
"get",
"(",
"'ClassifiedCache'",
")",
";",
"$",
"form",
"=",
"$",
"this",
"->",
"getServiceLocator",
"(",
")",
"->",
"get",
"(",
"'document.form.classifiedimageadd'",
")",
";",
"$",
"classifiedId",
"=",
"!",
"empty",
"(",
"$",
"data",
"[",
"'classifiedid'",
"]",
")",
"?",
"$",
"data",
"[",
"'classifiedid'",
"]",
":",
"null",
";",
"$",
"classified",
"=",
"null",
"!==",
"$",
"classifiedId",
"?",
"$",
"documentRepository",
"->",
"findByEncryptedId",
"(",
"$",
"classifiedId",
",",
"'documentId'",
")",
":",
"null",
";",
"// remove parent cache",
"$",
"cache",
"=",
"$",
"this",
"->",
"getServiceLocator",
"(",
")",
"->",
"get",
"(",
"'ClassifiedCache'",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"classifiedId",
")",
"&&",
"$",
"cache",
"->",
"hasItem",
"(",
"$",
"classifiedId",
")",
")",
"{",
"$",
"cache",
"->",
"removeItem",
"(",
"$",
"classifiedId",
")",
";",
"}",
"$",
"userId",
"=",
"!",
"empty",
"(",
"$",
"data",
"[",
"'userid'",
"]",
")",
"?",
"$",
"data",
"[",
"'userid'",
"]",
":",
"null",
";",
"$",
"user",
"=",
"null",
"!==",
"$",
"userId",
"?",
"$",
"userRepository",
"->",
"findByEncryptedId",
"(",
"$",
"userId",
",",
"'userId'",
")",
":",
"null",
";",
"$",
"entity",
"=",
"new",
"Document",
"(",
")",
";",
"$",
"form",
"->",
"setData",
"(",
"$",
"data",
")",
";",
"if",
"(",
"!",
"$",
"form",
"->",
"isValid",
"(",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"serialize",
"(",
"$",
"form",
"->",
"getMessages",
"(",
"'files'",
")",
")",
")",
";",
"}",
"$",
"data",
"=",
"$",
"form",
"->",
"getData",
"(",
")",
";",
"// @todo Better recover this in a smarter way",
"$",
"files",
"=",
"isset",
"(",
"$",
"data",
"[",
"'files'",
"]",
")",
"?",
"$",
"data",
"[",
"'files'",
"]",
":",
"array",
"(",
")",
";",
"$",
"firstFile",
"=",
"reset",
"(",
"$",
"files",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"firstFile",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"serialize",
"(",
"array",
"(",
"'Empty file'",
")",
")",
")",
";",
"}",
"$",
"title",
"=",
"is_array",
"(",
"$",
"firstFile",
")",
"&&",
"isset",
"(",
"$",
"firstFile",
"[",
"'name'",
"]",
")",
"?",
"$",
"firstFile",
"[",
"'name'",
"]",
":",
"''",
";",
"$",
"entity",
"->",
"setDocumentType",
"(",
"Document",
"::",
"DOCUMENT_TYPE_IMAGE",
")",
";",
"$",
"entity",
"->",
"setTitle",
"(",
"$",
"title",
")",
";",
"$",
"entity",
"->",
"setParent",
"(",
"$",
"classified",
")",
";",
"$",
"entity",
"->",
"setUser",
"(",
"$",
"user",
")",
";",
"$",
"entity",
"->",
"setState",
"(",
"Document",
"::",
"DOCUMENT_STATE_ACTIVE",
")",
";",
"$",
"em",
"->",
"persist",
"(",
"$",
"entity",
")",
";",
"$",
"em",
"->",
"flush",
"(",
")",
";",
"// trigger saveClassified event with the saved entity",
"$",
"this",
"->",
"getEventManager",
"(",
")",
"->",
"trigger",
"(",
"'imageSaved'",
",",
"null",
",",
"$",
"entity",
")",
";",
"return",
"$",
"entity",
";",
"}"
] | Save a document
@param array $data
@throws \Exception
@return \Neobazaar\Entity\Document | [
"Save",
"a",
"document"
] | train | https://github.com/kaiohken1982/NeobazaarDocumentModule/blob/edb0223878fe02e791d2a0266c5a7c0f2029e3fe/src/Document/Service/Image.php#L80-L137 |
kaiohken1982/NeobazaarDocumentModule | src/Document/Service/Image.php | Image.delete | public function delete($idOrDocument)
{
$cache = $this->getServiceLocator()->get('ClassifiedCache');
$main = $this->getServiceLocator()->get('neobazaar.service.main');
$classifiedService = $this->getServiceLocator()->get('document.service.classified');
$entityManager = $main->getEntityManager();
$documentRepository = $main->getDocumentEntityRepository();
$entity = $documentRepository->getEntity($idOrDocument);
// It can NOT exists when add a NEW classified (parent still doesn't exists)
$parent = $entity->getParent();
// checking for permission, only if we are in edit mode
if(null !== $parent && !$classifiedService->checkIfOwnerOrAdmin($parent)) {
throw new \Exception('Non possiedi i permessi per agire su questo documento');
}
$cacheKey = $parent ? $documentRepository->getEncryptedId($parent->getDocumentId()) : 'noCache';
$imageModel = new ImageModel($entity, $this->getServiceLocator());
// 1) Delete the image
$phisical = $imageModel->deleteImages();
// 3) Remove the document
$entityManager->remove($entity);
$entityManager->flush();
// 4) Remove parent classified cache
if($cache->hasItem($cacheKey)) {
$cache->removeItem($cacheKey);
}
return $phisical;
} | php | public function delete($idOrDocument)
{
$cache = $this->getServiceLocator()->get('ClassifiedCache');
$main = $this->getServiceLocator()->get('neobazaar.service.main');
$classifiedService = $this->getServiceLocator()->get('document.service.classified');
$entityManager = $main->getEntityManager();
$documentRepository = $main->getDocumentEntityRepository();
$entity = $documentRepository->getEntity($idOrDocument);
// It can NOT exists when add a NEW classified (parent still doesn't exists)
$parent = $entity->getParent();
// checking for permission, only if we are in edit mode
if(null !== $parent && !$classifiedService->checkIfOwnerOrAdmin($parent)) {
throw new \Exception('Non possiedi i permessi per agire su questo documento');
}
$cacheKey = $parent ? $documentRepository->getEncryptedId($parent->getDocumentId()) : 'noCache';
$imageModel = new ImageModel($entity, $this->getServiceLocator());
// 1) Delete the image
$phisical = $imageModel->deleteImages();
// 3) Remove the document
$entityManager->remove($entity);
$entityManager->flush();
// 4) Remove parent classified cache
if($cache->hasItem($cacheKey)) {
$cache->removeItem($cacheKey);
}
return $phisical;
} | [
"public",
"function",
"delete",
"(",
"$",
"idOrDocument",
")",
"{",
"$",
"cache",
"=",
"$",
"this",
"->",
"getServiceLocator",
"(",
")",
"->",
"get",
"(",
"'ClassifiedCache'",
")",
";",
"$",
"main",
"=",
"$",
"this",
"->",
"getServiceLocator",
"(",
")",
"->",
"get",
"(",
"'neobazaar.service.main'",
")",
";",
"$",
"classifiedService",
"=",
"$",
"this",
"->",
"getServiceLocator",
"(",
")",
"->",
"get",
"(",
"'document.service.classified'",
")",
";",
"$",
"entityManager",
"=",
"$",
"main",
"->",
"getEntityManager",
"(",
")",
";",
"$",
"documentRepository",
"=",
"$",
"main",
"->",
"getDocumentEntityRepository",
"(",
")",
";",
"$",
"entity",
"=",
"$",
"documentRepository",
"->",
"getEntity",
"(",
"$",
"idOrDocument",
")",
";",
"// It can NOT exists when add a NEW classified (parent still doesn't exists)",
"$",
"parent",
"=",
"$",
"entity",
"->",
"getParent",
"(",
")",
";",
"// checking for permission, only if we are in edit mode",
"if",
"(",
"null",
"!==",
"$",
"parent",
"&&",
"!",
"$",
"classifiedService",
"->",
"checkIfOwnerOrAdmin",
"(",
"$",
"parent",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'Non possiedi i permessi per agire su questo documento'",
")",
";",
"}",
"$",
"cacheKey",
"=",
"$",
"parent",
"?",
"$",
"documentRepository",
"->",
"getEncryptedId",
"(",
"$",
"parent",
"->",
"getDocumentId",
"(",
")",
")",
":",
"'noCache'",
";",
"$",
"imageModel",
"=",
"new",
"ImageModel",
"(",
"$",
"entity",
",",
"$",
"this",
"->",
"getServiceLocator",
"(",
")",
")",
";",
"// 1) Delete the image",
"$",
"phisical",
"=",
"$",
"imageModel",
"->",
"deleteImages",
"(",
")",
";",
"// 3) Remove the document",
"$",
"entityManager",
"->",
"remove",
"(",
"$",
"entity",
")",
";",
"$",
"entityManager",
"->",
"flush",
"(",
")",
";",
"// 4) Remove parent classified cache",
"if",
"(",
"$",
"cache",
"->",
"hasItem",
"(",
"$",
"cacheKey",
")",
")",
"{",
"$",
"cache",
"->",
"removeItem",
"(",
"$",
"cacheKey",
")",
";",
"}",
"return",
"$",
"phisical",
";",
"}"
] | Delete an image document and related images.
If there is a parent delete its cache.
@param unknown $idOrDocument
@throws \Exception
@return boolean | [
"Delete",
"an",
"image",
"document",
"and",
"related",
"images",
".",
"If",
"there",
"is",
"a",
"parent",
"delete",
"its",
"cache",
"."
] | train | https://github.com/kaiohken1982/NeobazaarDocumentModule/blob/edb0223878fe02e791d2a0266c5a7c0f2029e3fe/src/Document/Service/Image.php#L147-L179 |
kaiohken1982/NeobazaarDocumentModule | src/Document/Service/Image.php | Image.getEntity | public function getEntity($idOrDocument)
{
// All the services we need
$main = $this->getServiceLocator()->get('neobazaar.service.main');
$documentRepository = $main->getDocumentEntityRepository();
if(!$idOrDocument instanceof Document) {
if(is_numeric($idOrDocument)) {
$document = $documentRepository->find($idOrDocument);
} else {
$document = $documentRepository->findByEncryptedId($idOrDocument, 'documentId');
}
} else {
$document = $idOrDocument;
}
if(!$document instanceof Document) {
throw new \Exception('Errore di sistema, riprovare più tardi');
}
return $document;
} | php | public function getEntity($idOrDocument)
{
// All the services we need
$main = $this->getServiceLocator()->get('neobazaar.service.main');
$documentRepository = $main->getDocumentEntityRepository();
if(!$idOrDocument instanceof Document) {
if(is_numeric($idOrDocument)) {
$document = $documentRepository->find($idOrDocument);
} else {
$document = $documentRepository->findByEncryptedId($idOrDocument, 'documentId');
}
} else {
$document = $idOrDocument;
}
if(!$document instanceof Document) {
throw new \Exception('Errore di sistema, riprovare più tardi');
}
return $document;
} | [
"public",
"function",
"getEntity",
"(",
"$",
"idOrDocument",
")",
"{",
"// All the services we need",
"$",
"main",
"=",
"$",
"this",
"->",
"getServiceLocator",
"(",
")",
"->",
"get",
"(",
"'neobazaar.service.main'",
")",
";",
"$",
"documentRepository",
"=",
"$",
"main",
"->",
"getDocumentEntityRepository",
"(",
")",
";",
"if",
"(",
"!",
"$",
"idOrDocument",
"instanceof",
"Document",
")",
"{",
"if",
"(",
"is_numeric",
"(",
"$",
"idOrDocument",
")",
")",
"{",
"$",
"document",
"=",
"$",
"documentRepository",
"->",
"find",
"(",
"$",
"idOrDocument",
")",
";",
"}",
"else",
"{",
"$",
"document",
"=",
"$",
"documentRepository",
"->",
"findByEncryptedId",
"(",
"$",
"idOrDocument",
",",
"'documentId'",
")",
";",
"}",
"}",
"else",
"{",
"$",
"document",
"=",
"$",
"idOrDocument",
";",
"}",
"if",
"(",
"!",
"$",
"document",
"instanceof",
"Document",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'Errore di sistema, riprovare più tardi')",
";",
"",
"}",
"return",
"$",
"document",
";",
"}"
] | Return the document entity
@deprecated
@param unknown $idOrDocument
@throws \Exception
@return \Neobazaar\Entity\Document | [
"Return",
"the",
"document",
"entity"
] | train | https://github.com/kaiohken1982/NeobazaarDocumentModule/blob/edb0223878fe02e791d2a0266c5a7c0f2029e3fe/src/Document/Service/Image.php#L189-L210 |
DarvinStudio/databaser | src/Darvin/Databaser/Manager/LocalManager.php | LocalManager.importDump | public function importDump($pathname)
{
$tmp = tempnam(sys_get_temp_dir(), 'db_');
if (false === $tmp) {
throw new \RuntimeException('Unable to create temporary file.');
}
$this->filesToRemove[] = $tmp;
(new GzipArchiver())->extract($pathname, $tmp);
if (!$resource = fopen($tmp, 'r')) {
throw new \RuntimeException(sprintf('Unable to read database dump file "%s".', $tmp));
}
$pdo = $this->getPdo();
$pdo->query('SET FOREIGN_KEY_CHECKS = 0');
$pdo->beginTransaction();
$query = '';
while ($line = fgets($resource)) {
if (0 === strpos($line, '/*') || 0 === strpos($line, '--')) {
continue;
}
$line = trim($line);
$query .= $line;
if (preg_match('/;$/', $line)) {
$pdo->query($query);
$query = '';
}
}
$pdo->commit();
$pdo->query('SET FOREIGN_KEY_CHECKS = 1');
return $this;
} | php | public function importDump($pathname)
{
$tmp = tempnam(sys_get_temp_dir(), 'db_');
if (false === $tmp) {
throw new \RuntimeException('Unable to create temporary file.');
}
$this->filesToRemove[] = $tmp;
(new GzipArchiver())->extract($pathname, $tmp);
if (!$resource = fopen($tmp, 'r')) {
throw new \RuntimeException(sprintf('Unable to read database dump file "%s".', $tmp));
}
$pdo = $this->getPdo();
$pdo->query('SET FOREIGN_KEY_CHECKS = 0');
$pdo->beginTransaction();
$query = '';
while ($line = fgets($resource)) {
if (0 === strpos($line, '/*') || 0 === strpos($line, '--')) {
continue;
}
$line = trim($line);
$query .= $line;
if (preg_match('/;$/', $line)) {
$pdo->query($query);
$query = '';
}
}
$pdo->commit();
$pdo->query('SET FOREIGN_KEY_CHECKS = 1');
return $this;
} | [
"public",
"function",
"importDump",
"(",
"$",
"pathname",
")",
"{",
"$",
"tmp",
"=",
"tempnam",
"(",
"sys_get_temp_dir",
"(",
")",
",",
"'db_'",
")",
";",
"if",
"(",
"false",
"===",
"$",
"tmp",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'Unable to create temporary file.'",
")",
";",
"}",
"$",
"this",
"->",
"filesToRemove",
"[",
"]",
"=",
"$",
"tmp",
";",
"(",
"new",
"GzipArchiver",
"(",
")",
")",
"->",
"extract",
"(",
"$",
"pathname",
",",
"$",
"tmp",
")",
";",
"if",
"(",
"!",
"$",
"resource",
"=",
"fopen",
"(",
"$",
"tmp",
",",
"'r'",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"sprintf",
"(",
"'Unable to read database dump file \"%s\".'",
",",
"$",
"tmp",
")",
")",
";",
"}",
"$",
"pdo",
"=",
"$",
"this",
"->",
"getPdo",
"(",
")",
";",
"$",
"pdo",
"->",
"query",
"(",
"'SET FOREIGN_KEY_CHECKS = 0'",
")",
";",
"$",
"pdo",
"->",
"beginTransaction",
"(",
")",
";",
"$",
"query",
"=",
"''",
";",
"while",
"(",
"$",
"line",
"=",
"fgets",
"(",
"$",
"resource",
")",
")",
"{",
"if",
"(",
"0",
"===",
"strpos",
"(",
"$",
"line",
",",
"'/*'",
")",
"||",
"0",
"===",
"strpos",
"(",
"$",
"line",
",",
"'--'",
")",
")",
"{",
"continue",
";",
"}",
"$",
"line",
"=",
"trim",
"(",
"$",
"line",
")",
";",
"$",
"query",
".=",
"$",
"line",
";",
"if",
"(",
"preg_match",
"(",
"'/;$/'",
",",
"$",
"line",
")",
")",
"{",
"$",
"pdo",
"->",
"query",
"(",
"$",
"query",
")",
";",
"$",
"query",
"=",
"''",
";",
"}",
"}",
"$",
"pdo",
"->",
"commit",
"(",
")",
";",
"$",
"pdo",
"->",
"query",
"(",
"'SET FOREIGN_KEY_CHECKS = 1'",
")",
";",
"return",
"$",
"this",
";",
"}"
] | @param string $pathname Database dump pathname
@return LocalManager
@throws \RuntimeException | [
"@param",
"string",
"$pathname",
"Database",
"dump",
"pathname"
] | train | https://github.com/DarvinStudio/databaser/blob/3ecc56d873358908daaf2a1bbd347f4ec29d4e73/src/Darvin/Databaser/Manager/LocalManager.php#L106-L149 |
DarvinStudio/databaser | src/Darvin/Databaser/Manager/LocalManager.php | LocalManager.getMySqlCredentials | protected function getMySqlCredentials()
{
if (empty($this->mySqlCredentials)) {
$pathname = $this->projectPath.'app/config/parameters.yml';
$content = @file_get_contents($pathname);
if (false === $content) {
throw new \RuntimeException(sprintf('Unable to get content of Symfony parameters file "%s".', $pathname));
}
$this->mySqlCredentials = MySqlCredentials::fromSymfonyParamsFile($content);
}
return $this->mySqlCredentials;
} | php | protected function getMySqlCredentials()
{
if (empty($this->mySqlCredentials)) {
$pathname = $this->projectPath.'app/config/parameters.yml';
$content = @file_get_contents($pathname);
if (false === $content) {
throw new \RuntimeException(sprintf('Unable to get content of Symfony parameters file "%s".', $pathname));
}
$this->mySqlCredentials = MySqlCredentials::fromSymfonyParamsFile($content);
}
return $this->mySqlCredentials;
} | [
"protected",
"function",
"getMySqlCredentials",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"mySqlCredentials",
")",
")",
"{",
"$",
"pathname",
"=",
"$",
"this",
"->",
"projectPath",
".",
"'app/config/parameters.yml'",
";",
"$",
"content",
"=",
"@",
"file_get_contents",
"(",
"$",
"pathname",
")",
";",
"if",
"(",
"false",
"===",
"$",
"content",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"sprintf",
"(",
"'Unable to get content of Symfony parameters file \"%s\".'",
",",
"$",
"pathname",
")",
")",
";",
"}",
"$",
"this",
"->",
"mySqlCredentials",
"=",
"MySqlCredentials",
"::",
"fromSymfonyParamsFile",
"(",
"$",
"content",
")",
";",
"}",
"return",
"$",
"this",
"->",
"mySqlCredentials",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/DarvinStudio/databaser/blob/3ecc56d873358908daaf2a1bbd347f4ec29d4e73/src/Darvin/Databaser/Manager/LocalManager.php#L154-L169 |
gingerwfms/ginger-core | src/GingerCore/Controller/AbstractRestfulController.php | AbstractRestfulController.onDispatch | public function onDispatch(MvcEvent $e)
{
try {
parent::onDispatch($e);
} catch (\Exception $e) {
return $this->getResponse()->setStatusCode(500)->setContent($e->__toString());
}
} | php | public function onDispatch(MvcEvent $e)
{
try {
parent::onDispatch($e);
} catch (\Exception $e) {
return $this->getResponse()->setStatusCode(500)->setContent($e->__toString());
}
} | [
"public",
"function",
"onDispatch",
"(",
"MvcEvent",
"$",
"e",
")",
"{",
"try",
"{",
"parent",
"::",
"onDispatch",
"(",
"$",
"e",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"return",
"$",
"this",
"->",
"getResponse",
"(",
")",
"->",
"setStatusCode",
"(",
"500",
")",
"->",
"setContent",
"(",
"$",
"e",
"->",
"__toString",
"(",
")",
")",
";",
"}",
"}"
] | Handle the request
@param MvcEvent $e
@return mixed | [
"Handle",
"the",
"request"
] | train | https://github.com/gingerwfms/ginger-core/blob/178e699dd1a912ec7b8b4e21f7de51edd2a1c1e8/src/GingerCore/Controller/AbstractRestfulController.php#L26-L33 |
MindyPHP/FormBundle | DependencyInjection/Configuration.php | Configuration.getConfigTreeBuilder | public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$root = $treeBuilder->root('form');
$root
->children()
->arrayNode('themes')
->fixXmlConfig('themes')
->addDefaultChildrenIfNoneSet()
->prototype('scalar')->defaultValue('default')->end()
->validate()
->ifTrue(function ($v) {
return !in_array('default', $v);
})
->then(function ($v) {
return array_merge(['default'], $v);
})
->end()
->end()
->end();
return $treeBuilder;
} | php | public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$root = $treeBuilder->root('form');
$root
->children()
->arrayNode('themes')
->fixXmlConfig('themes')
->addDefaultChildrenIfNoneSet()
->prototype('scalar')->defaultValue('default')->end()
->validate()
->ifTrue(function ($v) {
return !in_array('default', $v);
})
->then(function ($v) {
return array_merge(['default'], $v);
})
->end()
->end()
->end();
return $treeBuilder;
} | [
"public",
"function",
"getConfigTreeBuilder",
"(",
")",
"{",
"$",
"treeBuilder",
"=",
"new",
"TreeBuilder",
"(",
")",
";",
"$",
"root",
"=",
"$",
"treeBuilder",
"->",
"root",
"(",
"'form'",
")",
";",
"$",
"root",
"->",
"children",
"(",
")",
"->",
"arrayNode",
"(",
"'themes'",
")",
"->",
"fixXmlConfig",
"(",
"'themes'",
")",
"->",
"addDefaultChildrenIfNoneSet",
"(",
")",
"->",
"prototype",
"(",
"'scalar'",
")",
"->",
"defaultValue",
"(",
"'default'",
")",
"->",
"end",
"(",
")",
"->",
"validate",
"(",
")",
"->",
"ifTrue",
"(",
"function",
"(",
"$",
"v",
")",
"{",
"return",
"!",
"in_array",
"(",
"'default'",
",",
"$",
"v",
")",
";",
"}",
")",
"->",
"then",
"(",
"function",
"(",
"$",
"v",
")",
"{",
"return",
"array_merge",
"(",
"[",
"'default'",
"]",
",",
"$",
"v",
")",
";",
"}",
")",
"->",
"end",
"(",
")",
"->",
"end",
"(",
")",
"->",
"end",
"(",
")",
";",
"return",
"$",
"treeBuilder",
";",
"}"
] | Generates the configuration tree builder.
@return \Symfony\Component\Config\Definition\Builder\TreeBuilder The tree builder | [
"Generates",
"the",
"configuration",
"tree",
"builder",
"."
] | train | https://github.com/MindyPHP/FormBundle/blob/566cc965cc4e44c6ee491059c050346c7fa9c76d/DependencyInjection/Configuration.php#L25-L48 |
SimplyCodedSoftware/integration-messaging-cqrs | src/LoadAggregateService.php | LoadAggregateService.load | public function load(Message $message) : Message
{
$commandReflection = new \ReflectionClass($message->getPayload());
$aggregateIdentifiers = [];
$expectedVersion = null;
foreach ($commandReflection->getProperties() as $property) {
if (preg_match("*AggregateIdAnnotation*", $property->getDocComment())) {
$property->setAccessible(true);
$value = (string)$property->getValue($message->getPayload());
if ($value) {
$aggregateIdentifiers[$property->getName()] = $value;
}
}
if (preg_match("*AggregateExpectedVersionAnnotation*", $property->getDocComment())) {
$property->setAccessible(true);
$expectedVersion = $property->getValue($message->getPayload());
}
}
$aggregate = null;
if (!$this->isFactoryMethod) {
if (!$aggregateIdentifiers) {
throw AggregateNotFoundException::create("There is no aggregate id to search for found. Are you sure you defined AggregateId Annotation or are not aggregateIdentifiers null?");
}
$aggregate = is_null($expectedVersion)
? $this->aggregateRepository->findBy($aggregateIdentifiers)
: $this->aggregateRepository->findWithLockingBy($aggregateIdentifiers, $expectedVersion);
}
$messageBuilder = MessageBuilder::fromMessage($message);
if ($aggregate) {
$messageBuilder = $messageBuilder->setHeader(CqrsMessagingModule::INTEGRATION_MESSAGING_CQRS_AGGREGATE_HEADER, $aggregate);
}
if ($expectedVersion) {
$messageBuilder = $messageBuilder->setHeader(CqrsMessagingModule::INTEGRATION_MESSAGING_CQRS_AGGREGATE_EXPECTED_VERSION_HEADER, $expectedVersion);
}
return $messageBuilder
->setHeader(CqrsMessagingModule::INTEGRATION_MESSAGING_CQRS_AGGREGATE_CLASS_NAME_HEADER, $this->aggregateClassName)
->setHeader(CqrsMessagingModule::INTEGRATION_MESSAGING_CQRS_AGGREGATE_METHOD_HEADER, $this->aggregateMethod)
->setHeader(CqrsMessagingModule::INTEGRATION_MESSAGING_CQRS_AGGREGATE_REPOSITORY_HEADER, $this->aggregateRepository)
->setHeader(CqrsMessagingModule::INTEGRATION_MESSAGING_CQRS_AGGREGATE_ID_HEADER, $aggregateIdentifiers)
->setHeader(CqrsMessagingModule::INTEGRATION_MESSAGING_CQRS_AGGREGATE_IS_FACTORY_METHOD_HEADER, $this->isFactoryMethod)
->setHeader(CqrsMessagingModule::INTEGRATION_MESSAGING_CQRS_AGGREGATE_MESSAGE_HEADER, $message->getPayload())
->build();
} | php | public function load(Message $message) : Message
{
$commandReflection = new \ReflectionClass($message->getPayload());
$aggregateIdentifiers = [];
$expectedVersion = null;
foreach ($commandReflection->getProperties() as $property) {
if (preg_match("*AggregateIdAnnotation*", $property->getDocComment())) {
$property->setAccessible(true);
$value = (string)$property->getValue($message->getPayload());
if ($value) {
$aggregateIdentifiers[$property->getName()] = $value;
}
}
if (preg_match("*AggregateExpectedVersionAnnotation*", $property->getDocComment())) {
$property->setAccessible(true);
$expectedVersion = $property->getValue($message->getPayload());
}
}
$aggregate = null;
if (!$this->isFactoryMethod) {
if (!$aggregateIdentifiers) {
throw AggregateNotFoundException::create("There is no aggregate id to search for found. Are you sure you defined AggregateId Annotation or are not aggregateIdentifiers null?");
}
$aggregate = is_null($expectedVersion)
? $this->aggregateRepository->findBy($aggregateIdentifiers)
: $this->aggregateRepository->findWithLockingBy($aggregateIdentifiers, $expectedVersion);
}
$messageBuilder = MessageBuilder::fromMessage($message);
if ($aggregate) {
$messageBuilder = $messageBuilder->setHeader(CqrsMessagingModule::INTEGRATION_MESSAGING_CQRS_AGGREGATE_HEADER, $aggregate);
}
if ($expectedVersion) {
$messageBuilder = $messageBuilder->setHeader(CqrsMessagingModule::INTEGRATION_MESSAGING_CQRS_AGGREGATE_EXPECTED_VERSION_HEADER, $expectedVersion);
}
return $messageBuilder
->setHeader(CqrsMessagingModule::INTEGRATION_MESSAGING_CQRS_AGGREGATE_CLASS_NAME_HEADER, $this->aggregateClassName)
->setHeader(CqrsMessagingModule::INTEGRATION_MESSAGING_CQRS_AGGREGATE_METHOD_HEADER, $this->aggregateMethod)
->setHeader(CqrsMessagingModule::INTEGRATION_MESSAGING_CQRS_AGGREGATE_REPOSITORY_HEADER, $this->aggregateRepository)
->setHeader(CqrsMessagingModule::INTEGRATION_MESSAGING_CQRS_AGGREGATE_ID_HEADER, $aggregateIdentifiers)
->setHeader(CqrsMessagingModule::INTEGRATION_MESSAGING_CQRS_AGGREGATE_IS_FACTORY_METHOD_HEADER, $this->isFactoryMethod)
->setHeader(CqrsMessagingModule::INTEGRATION_MESSAGING_CQRS_AGGREGATE_MESSAGE_HEADER, $message->getPayload())
->build();
} | [
"public",
"function",
"load",
"(",
"Message",
"$",
"message",
")",
":",
"Message",
"{",
"$",
"commandReflection",
"=",
"new",
"\\",
"ReflectionClass",
"(",
"$",
"message",
"->",
"getPayload",
"(",
")",
")",
";",
"$",
"aggregateIdentifiers",
"=",
"[",
"]",
";",
"$",
"expectedVersion",
"=",
"null",
";",
"foreach",
"(",
"$",
"commandReflection",
"->",
"getProperties",
"(",
")",
"as",
"$",
"property",
")",
"{",
"if",
"(",
"preg_match",
"(",
"\"*AggregateIdAnnotation*\"",
",",
"$",
"property",
"->",
"getDocComment",
"(",
")",
")",
")",
"{",
"$",
"property",
"->",
"setAccessible",
"(",
"true",
")",
";",
"$",
"value",
"=",
"(",
"string",
")",
"$",
"property",
"->",
"getValue",
"(",
"$",
"message",
"->",
"getPayload",
"(",
")",
")",
";",
"if",
"(",
"$",
"value",
")",
"{",
"$",
"aggregateIdentifiers",
"[",
"$",
"property",
"->",
"getName",
"(",
")",
"]",
"=",
"$",
"value",
";",
"}",
"}",
"if",
"(",
"preg_match",
"(",
"\"*AggregateExpectedVersionAnnotation*\"",
",",
"$",
"property",
"->",
"getDocComment",
"(",
")",
")",
")",
"{",
"$",
"property",
"->",
"setAccessible",
"(",
"true",
")",
";",
"$",
"expectedVersion",
"=",
"$",
"property",
"->",
"getValue",
"(",
"$",
"message",
"->",
"getPayload",
"(",
")",
")",
";",
"}",
"}",
"$",
"aggregate",
"=",
"null",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"isFactoryMethod",
")",
"{",
"if",
"(",
"!",
"$",
"aggregateIdentifiers",
")",
"{",
"throw",
"AggregateNotFoundException",
"::",
"create",
"(",
"\"There is no aggregate id to search for found. Are you sure you defined AggregateId Annotation or are not aggregateIdentifiers null?\"",
")",
";",
"}",
"$",
"aggregate",
"=",
"is_null",
"(",
"$",
"expectedVersion",
")",
"?",
"$",
"this",
"->",
"aggregateRepository",
"->",
"findBy",
"(",
"$",
"aggregateIdentifiers",
")",
":",
"$",
"this",
"->",
"aggregateRepository",
"->",
"findWithLockingBy",
"(",
"$",
"aggregateIdentifiers",
",",
"$",
"expectedVersion",
")",
";",
"}",
"$",
"messageBuilder",
"=",
"MessageBuilder",
"::",
"fromMessage",
"(",
"$",
"message",
")",
";",
"if",
"(",
"$",
"aggregate",
")",
"{",
"$",
"messageBuilder",
"=",
"$",
"messageBuilder",
"->",
"setHeader",
"(",
"CqrsMessagingModule",
"::",
"INTEGRATION_MESSAGING_CQRS_AGGREGATE_HEADER",
",",
"$",
"aggregate",
")",
";",
"}",
"if",
"(",
"$",
"expectedVersion",
")",
"{",
"$",
"messageBuilder",
"=",
"$",
"messageBuilder",
"->",
"setHeader",
"(",
"CqrsMessagingModule",
"::",
"INTEGRATION_MESSAGING_CQRS_AGGREGATE_EXPECTED_VERSION_HEADER",
",",
"$",
"expectedVersion",
")",
";",
"}",
"return",
"$",
"messageBuilder",
"->",
"setHeader",
"(",
"CqrsMessagingModule",
"::",
"INTEGRATION_MESSAGING_CQRS_AGGREGATE_CLASS_NAME_HEADER",
",",
"$",
"this",
"->",
"aggregateClassName",
")",
"->",
"setHeader",
"(",
"CqrsMessagingModule",
"::",
"INTEGRATION_MESSAGING_CQRS_AGGREGATE_METHOD_HEADER",
",",
"$",
"this",
"->",
"aggregateMethod",
")",
"->",
"setHeader",
"(",
"CqrsMessagingModule",
"::",
"INTEGRATION_MESSAGING_CQRS_AGGREGATE_REPOSITORY_HEADER",
",",
"$",
"this",
"->",
"aggregateRepository",
")",
"->",
"setHeader",
"(",
"CqrsMessagingModule",
"::",
"INTEGRATION_MESSAGING_CQRS_AGGREGATE_ID_HEADER",
",",
"$",
"aggregateIdentifiers",
")",
"->",
"setHeader",
"(",
"CqrsMessagingModule",
"::",
"INTEGRATION_MESSAGING_CQRS_AGGREGATE_IS_FACTORY_METHOD_HEADER",
",",
"$",
"this",
"->",
"isFactoryMethod",
")",
"->",
"setHeader",
"(",
"CqrsMessagingModule",
"::",
"INTEGRATION_MESSAGING_CQRS_AGGREGATE_MESSAGE_HEADER",
",",
"$",
"message",
"->",
"getPayload",
"(",
")",
")",
"->",
"build",
"(",
")",
";",
"}"
] | @param Message $message
@return Message
@throws AggregateNotFoundException
@throws \ReflectionException
@throws \SimplyCodedSoftware\IntegrationMessaging\MessagingException | [
"@param",
"Message",
"$message"
] | train | https://github.com/SimplyCodedSoftware/integration-messaging-cqrs/blob/c59407d61ffbb29a1fdf5b363ca654d541482a2c/src/LoadAggregateService.php#L58-L104 |
AnonymPHP/Anonym-Session | FileSessionHandler.php | FileSessionHandler.read | public function read($session_id)
{
if ($this->driver->has($path = $this->path.$session_id)) {
return $this->driver->read($path);
}
return '';
} | php | public function read($session_id)
{
if ($this->driver->has($path = $this->path.$session_id)) {
return $this->driver->read($path);
}
return '';
} | [
"public",
"function",
"read",
"(",
"$",
"session_id",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"driver",
"->",
"has",
"(",
"$",
"path",
"=",
"$",
"this",
"->",
"path",
".",
"$",
"session_id",
")",
")",
"{",
"return",
"$",
"this",
"->",
"driver",
"->",
"read",
"(",
"$",
"path",
")",
";",
"}",
"return",
"''",
";",
"}"
] | Read session data
@link http://php.net/manual/en/sessionhandlerinterface.read.php
@param string $session_id The session id to read data for.
@return string <p>
Returns an encoded string of the read data.
If nothing was read, it must return an empty string.
Note this value is returned internally to PHP for processing.
</p>
@since 5.4.0 | [
"Read",
"session",
"data"
] | train | https://github.com/AnonymPHP/Anonym-Session/blob/e13458c8d0f5df346cb86fca45c16f062098046d/FileSessionHandler.php#L131-L138 |
AnonymPHP/Anonym-Session | FileSessionHandler.php | FileSessionHandler.write | public function write($session_id, $session_data)
{
if(!$this->driver->has($path = $this->path.$session_id)){
$this->driver->create($path);
}
return $this->driver->put($path, $session_data);
} | php | public function write($session_id, $session_data)
{
if(!$this->driver->has($path = $this->path.$session_id)){
$this->driver->create($path);
}
return $this->driver->put($path, $session_data);
} | [
"public",
"function",
"write",
"(",
"$",
"session_id",
",",
"$",
"session_data",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"driver",
"->",
"has",
"(",
"$",
"path",
"=",
"$",
"this",
"->",
"path",
".",
"$",
"session_id",
")",
")",
"{",
"$",
"this",
"->",
"driver",
"->",
"create",
"(",
"$",
"path",
")",
";",
"}",
"return",
"$",
"this",
"->",
"driver",
"->",
"put",
"(",
"$",
"path",
",",
"$",
"session_data",
")",
";",
"}"
] | Write session data
@link http://php.net/manual/en/sessionhandlerinterface.write.php
@param string $session_id The session id.
@param string $session_data <p>
The encoded session data. This data is the
result of the PHP internally encoding
the $_SESSION superglobal to a serialized
string and passing it as this parameter.
Please note sessions use an alternative serialization method.
</p>
@return bool <p>
The return value (usually TRUE on success, FALSE on failure).
Note this value is returned internally to PHP for processing.
</p>
@since 5.4.0 | [
"Write",
"session",
"data"
] | train | https://github.com/AnonymPHP/Anonym-Session/blob/e13458c8d0f5df346cb86fca45c16f062098046d/FileSessionHandler.php#L157-L164 |
stubbles/stubbles-dbal | src/main/php/pdo/PdoDatabaseConnection.php | PdoDatabaseConnection.connect | public function connect(): DatabaseConnection
{
if (null !== $this->pdo) {
return $this;
}
try {
$pdoCreator = $this->getPdoCreator();
$this->pdo = $pdoCreator($this->configuration);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
if ($this->configuration->hasInitialQuery()) {
$this->pdo->query($this->configuration->getInitialQuery());
}
} catch (PDOException $pdoe) {
throw new DatabaseException($pdoe->getMessage(), $pdoe);
}
return $this;
} | php | public function connect(): DatabaseConnection
{
if (null !== $this->pdo) {
return $this;
}
try {
$pdoCreator = $this->getPdoCreator();
$this->pdo = $pdoCreator($this->configuration);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
if ($this->configuration->hasInitialQuery()) {
$this->pdo->query($this->configuration->getInitialQuery());
}
} catch (PDOException $pdoe) {
throw new DatabaseException($pdoe->getMessage(), $pdoe);
}
return $this;
} | [
"public",
"function",
"connect",
"(",
")",
":",
"DatabaseConnection",
"{",
"if",
"(",
"null",
"!==",
"$",
"this",
"->",
"pdo",
")",
"{",
"return",
"$",
"this",
";",
"}",
"try",
"{",
"$",
"pdoCreator",
"=",
"$",
"this",
"->",
"getPdoCreator",
"(",
")",
";",
"$",
"this",
"->",
"pdo",
"=",
"$",
"pdoCreator",
"(",
"$",
"this",
"->",
"configuration",
")",
";",
"$",
"this",
"->",
"pdo",
"->",
"setAttribute",
"(",
"PDO",
"::",
"ATTR_ERRMODE",
",",
"PDO",
"::",
"ERRMODE_EXCEPTION",
")",
";",
"$",
"this",
"->",
"pdo",
"->",
"setAttribute",
"(",
"PDO",
"::",
"ATTR_DEFAULT_FETCH_MODE",
",",
"PDO",
"::",
"FETCH_ASSOC",
")",
";",
"if",
"(",
"$",
"this",
"->",
"configuration",
"->",
"hasInitialQuery",
"(",
")",
")",
"{",
"$",
"this",
"->",
"pdo",
"->",
"query",
"(",
"$",
"this",
"->",
"configuration",
"->",
"getInitialQuery",
"(",
")",
")",
";",
"}",
"}",
"catch",
"(",
"PDOException",
"$",
"pdoe",
")",
"{",
"throw",
"new",
"DatabaseException",
"(",
"$",
"pdoe",
"->",
"getMessage",
"(",
")",
",",
"$",
"pdoe",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | establishes the connection
@return \stubbles\db\pdo\PdoDatabaseConnection
@throws \stubbles\db\DatabaseException | [
"establishes",
"the",
"connection"
] | train | https://github.com/stubbles/stubbles-dbal/blob/b42a589025a9e511b40a2798ac84df94d6451c36/src/main/php/pdo/PdoDatabaseConnection.php#L105-L124 |
stubbles/stubbles-dbal | src/main/php/pdo/PdoDatabaseConnection.php | PdoDatabaseConnection.prepare | public function prepare(string $statement, array $driverOptions = []): Statement
{
if (null === $this->pdo) {
$this->connect();
}
try {
return new PdoStatement(
$this->pdo->prepare($statement, $driverOptions)
);
} catch (PDOException $pdoe) {
throw new DatabaseException($pdoe->getMessage(), $pdoe);
}
} | php | public function prepare(string $statement, array $driverOptions = []): Statement
{
if (null === $this->pdo) {
$this->connect();
}
try {
return new PdoStatement(
$this->pdo->prepare($statement, $driverOptions)
);
} catch (PDOException $pdoe) {
throw new DatabaseException($pdoe->getMessage(), $pdoe);
}
} | [
"public",
"function",
"prepare",
"(",
"string",
"$",
"statement",
",",
"array",
"$",
"driverOptions",
"=",
"[",
"]",
")",
":",
"Statement",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"pdo",
")",
"{",
"$",
"this",
"->",
"connect",
"(",
")",
";",
"}",
"try",
"{",
"return",
"new",
"PdoStatement",
"(",
"$",
"this",
"->",
"pdo",
"->",
"prepare",
"(",
"$",
"statement",
",",
"$",
"driverOptions",
")",
")",
";",
"}",
"catch",
"(",
"PDOException",
"$",
"pdoe",
")",
"{",
"throw",
"new",
"DatabaseException",
"(",
"$",
"pdoe",
"->",
"getMessage",
"(",
")",
",",
"$",
"pdoe",
")",
";",
"}",
"}"
] | creates a prepared statement
@param string $statement SQL statement
@param array $driverOptions optional one or more key=>value pairs to set attribute values for the Statement object
@return \stubbles\db\pdo\PdoStatement
@throws \stubbles\db\DatabaseException
@see http://php.net/pdo-prepare | [
"creates",
"a",
"prepared",
"statement"
] | train | https://github.com/stubbles/stubbles-dbal/blob/b42a589025a9e511b40a2798ac84df94d6451c36/src/main/php/pdo/PdoDatabaseConnection.php#L230-L243 |
stubbles/stubbles-dbal | src/main/php/pdo/PdoDatabaseConnection.php | PdoDatabaseConnection.query | public function query(string $sql, array $driverOptions = []): QueryResult
{
if (null === $this->pdo) {
$this->connect();
}
try {
if (!isset($driverOptions['fetchMode'])) {
return new PdoQueryResult($this->pdo->query($sql));
}
switch ($driverOptions['fetchMode']) {
case PDO::FETCH_COLUMN:
if (!isset($driverOptions['colNo'])) {
throw new \InvalidArgumentException(
'Fetch mode COLUMN requires driver option colNo.'
);
}
$pdoStatement = $this->pdo->query(
$sql,
$driverOptions['fetchMode'],
$driverOptions['colNo']
);
break;
case PDO::FETCH_INTO:
if (!isset($driverOptions['object'])) {
throw new \InvalidArgumentException(
'Fetch mode INTO requires driver option object.'
);
}
$pdoStatement = $this->pdo->query(
$sql,
$driverOptions['fetchMode'],
$driverOptions['object']
);
break;
case PDO::FETCH_CLASS:
if (!isset($driverOptions['classname'])) {
throw new \InvalidArgumentException(
'Fetch mode CLASS requires driver option classname.'
);
}
$pdoStatement = $this->pdo->query(
$sql,
$driverOptions['fetchMode'],
$driverOptions['classname'],
$driverOptions['ctorargs'] ?? []
);
break;
default:
$pdoStatement = $this->pdo->query(
$sql,
$driverOptions['fetchMode']
);
}
return new PdoQueryResult($pdoStatement);
} catch (PDOException $pdoe) {
throw new DatabaseException($pdoe->getMessage(), $pdoe);
}
} | php | public function query(string $sql, array $driverOptions = []): QueryResult
{
if (null === $this->pdo) {
$this->connect();
}
try {
if (!isset($driverOptions['fetchMode'])) {
return new PdoQueryResult($this->pdo->query($sql));
}
switch ($driverOptions['fetchMode']) {
case PDO::FETCH_COLUMN:
if (!isset($driverOptions['colNo'])) {
throw new \InvalidArgumentException(
'Fetch mode COLUMN requires driver option colNo.'
);
}
$pdoStatement = $this->pdo->query(
$sql,
$driverOptions['fetchMode'],
$driverOptions['colNo']
);
break;
case PDO::FETCH_INTO:
if (!isset($driverOptions['object'])) {
throw new \InvalidArgumentException(
'Fetch mode INTO requires driver option object.'
);
}
$pdoStatement = $this->pdo->query(
$sql,
$driverOptions['fetchMode'],
$driverOptions['object']
);
break;
case PDO::FETCH_CLASS:
if (!isset($driverOptions['classname'])) {
throw new \InvalidArgumentException(
'Fetch mode CLASS requires driver option classname.'
);
}
$pdoStatement = $this->pdo->query(
$sql,
$driverOptions['fetchMode'],
$driverOptions['classname'],
$driverOptions['ctorargs'] ?? []
);
break;
default:
$pdoStatement = $this->pdo->query(
$sql,
$driverOptions['fetchMode']
);
}
return new PdoQueryResult($pdoStatement);
} catch (PDOException $pdoe) {
throw new DatabaseException($pdoe->getMessage(), $pdoe);
}
} | [
"public",
"function",
"query",
"(",
"string",
"$",
"sql",
",",
"array",
"$",
"driverOptions",
"=",
"[",
"]",
")",
":",
"QueryResult",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"pdo",
")",
"{",
"$",
"this",
"->",
"connect",
"(",
")",
";",
"}",
"try",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"driverOptions",
"[",
"'fetchMode'",
"]",
")",
")",
"{",
"return",
"new",
"PdoQueryResult",
"(",
"$",
"this",
"->",
"pdo",
"->",
"query",
"(",
"$",
"sql",
")",
")",
";",
"}",
"switch",
"(",
"$",
"driverOptions",
"[",
"'fetchMode'",
"]",
")",
"{",
"case",
"PDO",
"::",
"FETCH_COLUMN",
":",
"if",
"(",
"!",
"isset",
"(",
"$",
"driverOptions",
"[",
"'colNo'",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Fetch mode COLUMN requires driver option colNo.'",
")",
";",
"}",
"$",
"pdoStatement",
"=",
"$",
"this",
"->",
"pdo",
"->",
"query",
"(",
"$",
"sql",
",",
"$",
"driverOptions",
"[",
"'fetchMode'",
"]",
",",
"$",
"driverOptions",
"[",
"'colNo'",
"]",
")",
";",
"break",
";",
"case",
"PDO",
"::",
"FETCH_INTO",
":",
"if",
"(",
"!",
"isset",
"(",
"$",
"driverOptions",
"[",
"'object'",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Fetch mode INTO requires driver option object.'",
")",
";",
"}",
"$",
"pdoStatement",
"=",
"$",
"this",
"->",
"pdo",
"->",
"query",
"(",
"$",
"sql",
",",
"$",
"driverOptions",
"[",
"'fetchMode'",
"]",
",",
"$",
"driverOptions",
"[",
"'object'",
"]",
")",
";",
"break",
";",
"case",
"PDO",
"::",
"FETCH_CLASS",
":",
"if",
"(",
"!",
"isset",
"(",
"$",
"driverOptions",
"[",
"'classname'",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Fetch mode CLASS requires driver option classname.'",
")",
";",
"}",
"$",
"pdoStatement",
"=",
"$",
"this",
"->",
"pdo",
"->",
"query",
"(",
"$",
"sql",
",",
"$",
"driverOptions",
"[",
"'fetchMode'",
"]",
",",
"$",
"driverOptions",
"[",
"'classname'",
"]",
",",
"$",
"driverOptions",
"[",
"'ctorargs'",
"]",
"??",
"[",
"]",
")",
";",
"break",
";",
"default",
":",
"$",
"pdoStatement",
"=",
"$",
"this",
"->",
"pdo",
"->",
"query",
"(",
"$",
"sql",
",",
"$",
"driverOptions",
"[",
"'fetchMode'",
"]",
")",
";",
"}",
"return",
"new",
"PdoQueryResult",
"(",
"$",
"pdoStatement",
")",
";",
"}",
"catch",
"(",
"PDOException",
"$",
"pdoe",
")",
"{",
"throw",
"new",
"DatabaseException",
"(",
"$",
"pdoe",
"->",
"getMessage",
"(",
")",
",",
"$",
"pdoe",
")",
";",
"}",
"}"
] | executes a SQL statement
The driver options can be:
<code>
fetchMode => one of the PDO::FETCH_* constants
colNo => if fetchMode == PDO::FETCH_COLUMN this denotes the column number to fetch
object => if fetchMode == PDO::FETCH_INTO this denotes the object to fetch the data into
classname => if fetchMode == PDO::FETCH_CLASS this denotes the class to create and fetch the data into
ctorargs => (optional) if fetchMode == PDO::FETCH_CLASS this denotes the list of arguments for the constructor of the class to create and fetch the data into
</code>
@param string $sql the sql query to use
@param array $driverOptions optional how to fetch the data
@return \stubbles\db\pdo\PdoQueryResult
@throws \stubbles\db\DatabaseException
@throws \InvalidArgumentException
@see http://php.net/pdo-query
@see http://php.net/pdostatement-setfetchmode for the details on the fetch mode options | [
"executes",
"a",
"SQL",
"statement"
] | train | https://github.com/stubbles/stubbles-dbal/blob/b42a589025a9e511b40a2798ac84df94d6451c36/src/main/php/pdo/PdoDatabaseConnection.php#L265-L331 |
stubbles/stubbles-dbal | src/main/php/pdo/PdoDatabaseConnection.php | PdoDatabaseConnection.exec | public function exec(string $statement): int
{
if (null === $this->pdo) {
$this->connect();
}
try {
return $this->pdo->exec($statement);
} catch (PDOException $pdoe) {
throw new DatabaseException($pdoe->getMessage(), $pdoe);
}
} | php | public function exec(string $statement): int
{
if (null === $this->pdo) {
$this->connect();
}
try {
return $this->pdo->exec($statement);
} catch (PDOException $pdoe) {
throw new DatabaseException($pdoe->getMessage(), $pdoe);
}
} | [
"public",
"function",
"exec",
"(",
"string",
"$",
"statement",
")",
":",
"int",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"pdo",
")",
"{",
"$",
"this",
"->",
"connect",
"(",
")",
";",
"}",
"try",
"{",
"return",
"$",
"this",
"->",
"pdo",
"->",
"exec",
"(",
"$",
"statement",
")",
";",
"}",
"catch",
"(",
"PDOException",
"$",
"pdoe",
")",
"{",
"throw",
"new",
"DatabaseException",
"(",
"$",
"pdoe",
"->",
"getMessage",
"(",
")",
",",
"$",
"pdoe",
")",
";",
"}",
"}"
] | execute an SQL statement and return the number of affected rows
@param string $statement the sql statement to execute d
@return int number of effected rows
@throws \stubbles\db\DatabaseException | [
"execute",
"an",
"SQL",
"statement",
"and",
"return",
"the",
"number",
"of",
"affected",
"rows"
] | train | https://github.com/stubbles/stubbles-dbal/blob/b42a589025a9e511b40a2798ac84df94d6451c36/src/main/php/pdo/PdoDatabaseConnection.php#L340-L351 |
stubbles/stubbles-dbal | src/main/php/pdo/PdoDatabaseConnection.php | PdoDatabaseConnection.getLastInsertId | public function getLastInsertId(string $name = null)
{
if (null === $this->pdo) {
throw new DatabaseException('Not connected: can not retrieve last insert id');
}
try {
return $this->pdo->lastInsertId($name);
} catch (PDOException $pdoe) {
throw new DatabaseException($pdoe->getMessage(), $pdoe);
}
} | php | public function getLastInsertId(string $name = null)
{
if (null === $this->pdo) {
throw new DatabaseException('Not connected: can not retrieve last insert id');
}
try {
return $this->pdo->lastInsertId($name);
} catch (PDOException $pdoe) {
throw new DatabaseException($pdoe->getMessage(), $pdoe);
}
} | [
"public",
"function",
"getLastInsertId",
"(",
"string",
"$",
"name",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"pdo",
")",
"{",
"throw",
"new",
"DatabaseException",
"(",
"'Not connected: can not retrieve last insert id'",
")",
";",
"}",
"try",
"{",
"return",
"$",
"this",
"->",
"pdo",
"->",
"lastInsertId",
"(",
"$",
"name",
")",
";",
"}",
"catch",
"(",
"PDOException",
"$",
"pdoe",
")",
"{",
"throw",
"new",
"DatabaseException",
"(",
"$",
"pdoe",
"->",
"getMessage",
"(",
")",
",",
"$",
"pdoe",
")",
";",
"}",
"}"
] | returns the last insert id
@param string $name name of the sequence object from which the ID should be returned.
@return int
@throws \stubbles\db\DatabaseException | [
"returns",
"the",
"last",
"insert",
"id"
] | train | https://github.com/stubbles/stubbles-dbal/blob/b42a589025a9e511b40a2798ac84df94d6451c36/src/main/php/pdo/PdoDatabaseConnection.php#L360-L371 |
lightwerk/SurfTasks | Classes/Lightwerk/SurfTasks/Task/Git/TagNodeDeploymentTask.php | TagNodeDeploymentTask.execute | public function execute(Node $node, Application $application, Deployment $deployment, array $options = [])
{
if (!empty($options['disableDeploymentTag'])) {
return;
}
if (isset($options['useApplicationWorkspace']) && $options['useApplicationWorkspace'] === true) {
$gitRootPath = $deployment->getWorkspacePath($application);
} else {
$gitRootPath = $deployment->getApplicationReleasePath($application);
}
$tagPrefix = isset($options['deploymentTagPrefix']) ? $options['deploymentTagPrefix'] : 'server-';
$tagName = preg_replace('/[^a-zA-Z0-9-_\.]*/', '', $tagPrefix.$node->getName());
$quietFlag = (isset($options['verbose']) && $options['verbose']) ? '' : '-q';
if (!empty($options['nodeName'])) {
$node = $deployment->getNode($options['nodeName']);
if ($node === null) {
throw new InvalidConfigurationException(
sprintf('Node "%s" not found', $options['nodeName']),
1408441582
);
}
}
$commands = [
'cd '.escapeshellarg($gitRootPath),
'git tag --force -- '.escapeshellarg($tagName),
'git push origin --force '.$quietFlag.' -- '.escapeshellarg($tagName),
];
$this->shell->executeOrSimulate($commands, $node, $deployment);
} | php | public function execute(Node $node, Application $application, Deployment $deployment, array $options = [])
{
if (!empty($options['disableDeploymentTag'])) {
return;
}
if (isset($options['useApplicationWorkspace']) && $options['useApplicationWorkspace'] === true) {
$gitRootPath = $deployment->getWorkspacePath($application);
} else {
$gitRootPath = $deployment->getApplicationReleasePath($application);
}
$tagPrefix = isset($options['deploymentTagPrefix']) ? $options['deploymentTagPrefix'] : 'server-';
$tagName = preg_replace('/[^a-zA-Z0-9-_\.]*/', '', $tagPrefix.$node->getName());
$quietFlag = (isset($options['verbose']) && $options['verbose']) ? '' : '-q';
if (!empty($options['nodeName'])) {
$node = $deployment->getNode($options['nodeName']);
if ($node === null) {
throw new InvalidConfigurationException(
sprintf('Node "%s" not found', $options['nodeName']),
1408441582
);
}
}
$commands = [
'cd '.escapeshellarg($gitRootPath),
'git tag --force -- '.escapeshellarg($tagName),
'git push origin --force '.$quietFlag.' -- '.escapeshellarg($tagName),
];
$this->shell->executeOrSimulate($commands, $node, $deployment);
} | [
"public",
"function",
"execute",
"(",
"Node",
"$",
"node",
",",
"Application",
"$",
"application",
",",
"Deployment",
"$",
"deployment",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"options",
"[",
"'disableDeploymentTag'",
"]",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"'useApplicationWorkspace'",
"]",
")",
"&&",
"$",
"options",
"[",
"'useApplicationWorkspace'",
"]",
"===",
"true",
")",
"{",
"$",
"gitRootPath",
"=",
"$",
"deployment",
"->",
"getWorkspacePath",
"(",
"$",
"application",
")",
";",
"}",
"else",
"{",
"$",
"gitRootPath",
"=",
"$",
"deployment",
"->",
"getApplicationReleasePath",
"(",
"$",
"application",
")",
";",
"}",
"$",
"tagPrefix",
"=",
"isset",
"(",
"$",
"options",
"[",
"'deploymentTagPrefix'",
"]",
")",
"?",
"$",
"options",
"[",
"'deploymentTagPrefix'",
"]",
":",
"'server-'",
";",
"$",
"tagName",
"=",
"preg_replace",
"(",
"'/[^a-zA-Z0-9-_\\.]*/'",
",",
"''",
",",
"$",
"tagPrefix",
".",
"$",
"node",
"->",
"getName",
"(",
")",
")",
";",
"$",
"quietFlag",
"=",
"(",
"isset",
"(",
"$",
"options",
"[",
"'verbose'",
"]",
")",
"&&",
"$",
"options",
"[",
"'verbose'",
"]",
")",
"?",
"''",
":",
"'-q'",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"options",
"[",
"'nodeName'",
"]",
")",
")",
"{",
"$",
"node",
"=",
"$",
"deployment",
"->",
"getNode",
"(",
"$",
"options",
"[",
"'nodeName'",
"]",
")",
";",
"if",
"(",
"$",
"node",
"===",
"null",
")",
"{",
"throw",
"new",
"InvalidConfigurationException",
"(",
"sprintf",
"(",
"'Node \"%s\" not found'",
",",
"$",
"options",
"[",
"'nodeName'",
"]",
")",
",",
"1408441582",
")",
";",
"}",
"}",
"$",
"commands",
"=",
"[",
"'cd '",
".",
"escapeshellarg",
"(",
"$",
"gitRootPath",
")",
",",
"'git tag --force -- '",
".",
"escapeshellarg",
"(",
"$",
"tagName",
")",
",",
"'git push origin --force '",
".",
"$",
"quietFlag",
".",
"' -- '",
".",
"escapeshellarg",
"(",
"$",
"tagName",
")",
",",
"]",
";",
"$",
"this",
"->",
"shell",
"->",
"executeOrSimulate",
"(",
"$",
"commands",
",",
"$",
"node",
",",
"$",
"deployment",
")",
";",
"}"
] | Executes this task.
@param Node $node
@param Application $application
@param Deployment $deployment
@param array $options
@throws InvalidConfigurationException
@throws TaskExecutionException | [
"Executes",
"this",
"task",
"."
] | train | https://github.com/lightwerk/SurfTasks/blob/8a6e4c85e42c762ad6515778c3fc7e19052cd9d1/Classes/Lightwerk/SurfTasks/Task/Git/TagNodeDeploymentTask.php#L60-L92 |
Nicklas766/Comment | src/Comment/HTMLForm/User/UserResetForm.php | UserResetForm.callbackSubmit | public function callbackSubmit()
{
// Get values from the submitted form
$name = $this->form->value("user");
$answer = $this->form->value("answer");
$user = new User();
$user->setDb($this->di->get("db"));
$res = $user->verifyQuestion($name, $answer);
if ($res) {
$this->form->rememberValues();
$random = substr(md5(mt_rand()), 0, 7);
$this->form->addOutput("Rätt! Ditt lösenord har ändrats till <b>'{$random}'</b>.
Ange det när du loggar in och byt sedan till valfritt i din profilsida.");
$user->setPassword($random);
$user->save();
return true;
}
$this->form->rememberValues();
$this->form->addOutput("Du hade fel, kontrollera så du inte skriver med stora bokstäver");
return false;
} | php | public function callbackSubmit()
{
// Get values from the submitted form
$name = $this->form->value("user");
$answer = $this->form->value("answer");
$user = new User();
$user->setDb($this->di->get("db"));
$res = $user->verifyQuestion($name, $answer);
if ($res) {
$this->form->rememberValues();
$random = substr(md5(mt_rand()), 0, 7);
$this->form->addOutput("Rätt! Ditt lösenord har ändrats till <b>'{$random}'</b>.
Ange det när du loggar in och byt sedan till valfritt i din profilsida.");
$user->setPassword($random);
$user->save();
return true;
}
$this->form->rememberValues();
$this->form->addOutput("Du hade fel, kontrollera så du inte skriver med stora bokstäver");
return false;
} | [
"public",
"function",
"callbackSubmit",
"(",
")",
"{",
"// Get values from the submitted form",
"$",
"name",
"=",
"$",
"this",
"->",
"form",
"->",
"value",
"(",
"\"user\"",
")",
";",
"$",
"answer",
"=",
"$",
"this",
"->",
"form",
"->",
"value",
"(",
"\"answer\"",
")",
";",
"$",
"user",
"=",
"new",
"User",
"(",
")",
";",
"$",
"user",
"->",
"setDb",
"(",
"$",
"this",
"->",
"di",
"->",
"get",
"(",
"\"db\"",
")",
")",
";",
"$",
"res",
"=",
"$",
"user",
"->",
"verifyQuestion",
"(",
"$",
"name",
",",
"$",
"answer",
")",
";",
"if",
"(",
"$",
"res",
")",
"{",
"$",
"this",
"->",
"form",
"->",
"rememberValues",
"(",
")",
";",
"$",
"random",
"=",
"substr",
"(",
"md5",
"(",
"mt_rand",
"(",
")",
")",
",",
"0",
",",
"7",
")",
";",
"$",
"this",
"->",
"form",
"->",
"addOutput",
"(",
"\"Rätt! Ditt lösenord har ändrats till <b>'{$random}'</b>.\n Ange det när du loggar in och byt sedan till valfritt i din profilsida.\")",
";",
"",
"$",
"user",
"->",
"setPassword",
"(",
"$",
"random",
")",
";",
"$",
"user",
"->",
"save",
"(",
")",
";",
"return",
"true",
";",
"}",
"$",
"this",
"->",
"form",
"->",
"rememberValues",
"(",
")",
";",
"$",
"this",
"->",
"form",
"->",
"addOutput",
"(",
"\"Du hade fel, kontrollera så du inte skriver med stora bokstäver\");",
"",
"",
"return",
"false",
";",
"}"
] | Callback for submit-button which should return true if it could
carry out its work and false if something failed.
@return boolean true if okey, false if something went wrong. | [
"Callback",
"for",
"submit",
"-",
"button",
"which",
"should",
"return",
"true",
"if",
"it",
"could",
"carry",
"out",
"its",
"work",
"and",
"false",
"if",
"something",
"failed",
"."
] | train | https://github.com/Nicklas766/Comment/blob/1483eaf1ebb120b8bd6c2a1552c084b3a288ff25/src/Comment/HTMLForm/User/UserResetForm.php#L57-L77 |
AnonymPHP/Anonym-HttpFoundation | Server.php | Server.get | public function get($name = 'HTTP_HOST')
{
$name = isset($this->references[$name]) ? $this->references[$name]: $this->resolveCase($name);
return $this->has($name) ? $_SERVER[$name] : false;
} | php | public function get($name = 'HTTP_HOST')
{
$name = isset($this->references[$name]) ? $this->references[$name]: $this->resolveCase($name);
return $this->has($name) ? $_SERVER[$name] : false;
} | [
"public",
"function",
"get",
"(",
"$",
"name",
"=",
"'HTTP_HOST'",
")",
"{",
"$",
"name",
"=",
"isset",
"(",
"$",
"this",
"->",
"references",
"[",
"$",
"name",
"]",
")",
"?",
"$",
"this",
"->",
"references",
"[",
"$",
"name",
"]",
":",
"$",
"this",
"->",
"resolveCase",
"(",
"$",
"name",
")",
";",
"return",
"$",
"this",
"->",
"has",
"(",
"$",
"name",
")",
"?",
"$",
"_SERVER",
"[",
"$",
"name",
"]",
":",
"false",
";",
"}"
] | get the variable in server
@param string $name
@return string | [
"get",
"the",
"variable",
"in",
"server"
] | train | https://github.com/AnonymPHP/Anonym-HttpFoundation/blob/943e5f40f45bc2e11a4b9e1d22c6583c31dc4317/Server.php#L46-L51 |
Wedeto/IO | src/Path.php | Path.mkdir | public static function mkdir(string $path)
{
if (!is_dir($path))
{
mkdir($path, self::$dir_mode, true);
}
} | php | public static function mkdir(string $path)
{
if (!is_dir($path))
{
mkdir($path, self::$dir_mode, true);
}
} | [
"public",
"static",
"function",
"mkdir",
"(",
"string",
"$",
"path",
")",
"{",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"path",
")",
")",
"{",
"mkdir",
"(",
"$",
"path",
",",
"self",
"::",
"$",
"dir_mode",
",",
"true",
")",
";",
"}",
"}"
] | Make a directory and its parents. When all directories already exist, nothing happens.
Newly created directories are chmod'ded to 0770: RWX for owner and group.
@param $path string The path to create | [
"Make",
"a",
"directory",
"and",
"its",
"parents",
".",
"When",
"all",
"directories",
"already",
"exist",
"nothing",
"happens",
".",
"Newly",
"created",
"directories",
"are",
"chmod",
"ded",
"to",
"0770",
":",
"RWX",
"for",
"owner",
"and",
"group",
"."
] | train | https://github.com/Wedeto/IO/blob/4cfeaedd1bd9bda3097d18cb12233a4afecb2e85/src/Path.php#L137-L143 |
Wedeto/IO | src/Path.php | Path.rmtree | public static function rmtree(string $path)
{
$path = self::realpath($path);
if (empty($path)) // File/dir does not exist
return true;
if (empty(self::$required_prefix))
throw new \RuntimeException("Safety measure: required prefix needs to be set before running rmtree");
if (strpos($path, self::$required_prefix) !== 0)
throw new \RuntimeException("Refusing to remove directory outside " . self::$required_prefix);
self::checkWrite($path);
if (!is_dir($path))
return unlink($path) ? 1 : 0;
$cnt = 0;
$d = \dir($path);
while (($entry = $d->read()) !== false)
{
if ($entry === "." || $entry === "..")
continue;
$entry = $path . '/' . $entry;
self::checkWrite($entry);
if (is_dir($entry))
$cnt += self::rmtree($entry);
else
$cnt += (unlink($entry) ? 1 : 0);
}
rmdir($path);
return $cnt + 1;
} | php | public static function rmtree(string $path)
{
$path = self::realpath($path);
if (empty($path)) // File/dir does not exist
return true;
if (empty(self::$required_prefix))
throw new \RuntimeException("Safety measure: required prefix needs to be set before running rmtree");
if (strpos($path, self::$required_prefix) !== 0)
throw new \RuntimeException("Refusing to remove directory outside " . self::$required_prefix);
self::checkWrite($path);
if (!is_dir($path))
return unlink($path) ? 1 : 0;
$cnt = 0;
$d = \dir($path);
while (($entry = $d->read()) !== false)
{
if ($entry === "." || $entry === "..")
continue;
$entry = $path . '/' . $entry;
self::checkWrite($entry);
if (is_dir($entry))
$cnt += self::rmtree($entry);
else
$cnt += (unlink($entry) ? 1 : 0);
}
rmdir($path);
return $cnt + 1;
} | [
"public",
"static",
"function",
"rmtree",
"(",
"string",
"$",
"path",
")",
"{",
"$",
"path",
"=",
"self",
"::",
"realpath",
"(",
"$",
"path",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"path",
")",
")",
"// File/dir does not exist",
"return",
"true",
";",
"if",
"(",
"empty",
"(",
"self",
"::",
"$",
"required_prefix",
")",
")",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"\"Safety measure: required prefix needs to be set before running rmtree\"",
")",
";",
"if",
"(",
"strpos",
"(",
"$",
"path",
",",
"self",
"::",
"$",
"required_prefix",
")",
"!==",
"0",
")",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"\"Refusing to remove directory outside \"",
".",
"self",
"::",
"$",
"required_prefix",
")",
";",
"self",
"::",
"checkWrite",
"(",
"$",
"path",
")",
";",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"path",
")",
")",
"return",
"unlink",
"(",
"$",
"path",
")",
"?",
"1",
":",
"0",
";",
"$",
"cnt",
"=",
"0",
";",
"$",
"d",
"=",
"\\",
"dir",
"(",
"$",
"path",
")",
";",
"while",
"(",
"(",
"$",
"entry",
"=",
"$",
"d",
"->",
"read",
"(",
")",
")",
"!==",
"false",
")",
"{",
"if",
"(",
"$",
"entry",
"===",
"\".\"",
"||",
"$",
"entry",
"===",
"\"..\"",
")",
"continue",
";",
"$",
"entry",
"=",
"$",
"path",
".",
"'/'",
".",
"$",
"entry",
";",
"self",
"::",
"checkWrite",
"(",
"$",
"entry",
")",
";",
"if",
"(",
"is_dir",
"(",
"$",
"entry",
")",
")",
"$",
"cnt",
"+=",
"self",
"::",
"rmtree",
"(",
"$",
"entry",
")",
";",
"else",
"$",
"cnt",
"+=",
"(",
"unlink",
"(",
"$",
"entry",
")",
"?",
"1",
":",
"0",
")",
";",
"}",
"rmdir",
"(",
"$",
"path",
")",
";",
"return",
"$",
"cnt",
"+",
"1",
";",
"}"
] | Delete a directory and its contents. The provided path must be inside the configured prefix.
@param $path string The path to remove
@return int Amount of files and directories that have been deleted | [
"Delete",
"a",
"directory",
"and",
"its",
"contents",
".",
"The",
"provided",
"path",
"must",
"be",
"inside",
"the",
"configured",
"prefix",
"."
] | train | https://github.com/Wedeto/IO/blob/4cfeaedd1bd9bda3097d18cb12233a4afecb2e85/src/Path.php#L159-L194 |
Wedeto/IO | src/Path.php | Path.makeWritable | public static function makeWritable(string $path)
{
// If it is already writable, there's nothing to do
if (is_writable($path))
return;
$perms = self::getPermissions($path);
$current_user = posix_getpwuid(posix_geteuid());
$owner = posix_getpwuid(fileowner($path));
$group = posix_getgrgid(filegroup($path));
$is_owner = $current_user['uid'] === $owner['uid'];
if (!$is_owner)
{
// @codeCoverageIgnoreStart
// The file is really unwritable, and we cannot change the permissions. This
// is not reliably testable without root permissions.
throw new PermissionError($path, "Cannot change permissions - not the owner");
// @codeCoverageIgnoreEnd
}
// We own the file, so we should be able to fix it
$set_gid = false;
if (self::$file_group !== null)
{
if (self::$file_group !== $group['name'] && !chgrp($path, self::$file_group))
{
// @codeCoverageIgnoreStart
// This is not testable - a read only file system would be needed
throw new PermissionError($path, "Cannot change group");
// @codeCoverageIgnoreEnd
}
$set_gid = true;
}
// Owner and group are all right now, we should be able to modify the permissions
$new_mode = $perms['mode'] | self::OWNER_WRITE | ($set_gid ? self::GROUP_WRITE : 0);
if (is_dir($path))
$new_mode |= self::OWNER_EXECUTE | ($set_gid ? self::GROUP_EXECUTE : 0);
$what = is_dir($path) ? "directory" : "file";
self::getLogger()->notice(
"Changing permissions of {0} {1} to {2} (was: {3})",
[$what, $path, $new_mode, $perms['mode']]
);
try
{
@chmod($path, $new_mode);
}
// @codeCoverageIgnoreStart
// Basically untestable - we need a read-only file system for this
catch (Throwable $e)
{
throw new PermissionError($path, "Could not set permissions");
}
// @codeCoverageIgnoreEnd
} | php | public static function makeWritable(string $path)
{
// If it is already writable, there's nothing to do
if (is_writable($path))
return;
$perms = self::getPermissions($path);
$current_user = posix_getpwuid(posix_geteuid());
$owner = posix_getpwuid(fileowner($path));
$group = posix_getgrgid(filegroup($path));
$is_owner = $current_user['uid'] === $owner['uid'];
if (!$is_owner)
{
// @codeCoverageIgnoreStart
// The file is really unwritable, and we cannot change the permissions. This
// is not reliably testable without root permissions.
throw new PermissionError($path, "Cannot change permissions - not the owner");
// @codeCoverageIgnoreEnd
}
// We own the file, so we should be able to fix it
$set_gid = false;
if (self::$file_group !== null)
{
if (self::$file_group !== $group['name'] && !chgrp($path, self::$file_group))
{
// @codeCoverageIgnoreStart
// This is not testable - a read only file system would be needed
throw new PermissionError($path, "Cannot change group");
// @codeCoverageIgnoreEnd
}
$set_gid = true;
}
// Owner and group are all right now, we should be able to modify the permissions
$new_mode = $perms['mode'] | self::OWNER_WRITE | ($set_gid ? self::GROUP_WRITE : 0);
if (is_dir($path))
$new_mode |= self::OWNER_EXECUTE | ($set_gid ? self::GROUP_EXECUTE : 0);
$what = is_dir($path) ? "directory" : "file";
self::getLogger()->notice(
"Changing permissions of {0} {1} to {2} (was: {3})",
[$what, $path, $new_mode, $perms['mode']]
);
try
{
@chmod($path, $new_mode);
}
// @codeCoverageIgnoreStart
// Basically untestable - we need a read-only file system for this
catch (Throwable $e)
{
throw new PermissionError($path, "Could not set permissions");
}
// @codeCoverageIgnoreEnd
} | [
"public",
"static",
"function",
"makeWritable",
"(",
"string",
"$",
"path",
")",
"{",
"// If it is already writable, there's nothing to do",
"if",
"(",
"is_writable",
"(",
"$",
"path",
")",
")",
"return",
";",
"$",
"perms",
"=",
"self",
"::",
"getPermissions",
"(",
"$",
"path",
")",
";",
"$",
"current_user",
"=",
"posix_getpwuid",
"(",
"posix_geteuid",
"(",
")",
")",
";",
"$",
"owner",
"=",
"posix_getpwuid",
"(",
"fileowner",
"(",
"$",
"path",
")",
")",
";",
"$",
"group",
"=",
"posix_getgrgid",
"(",
"filegroup",
"(",
"$",
"path",
")",
")",
";",
"$",
"is_owner",
"=",
"$",
"current_user",
"[",
"'uid'",
"]",
"===",
"$",
"owner",
"[",
"'uid'",
"]",
";",
"if",
"(",
"!",
"$",
"is_owner",
")",
"{",
"// @codeCoverageIgnoreStart",
"// The file is really unwritable, and we cannot change the permissions. This",
"// is not reliably testable without root permissions.",
"throw",
"new",
"PermissionError",
"(",
"$",
"path",
",",
"\"Cannot change permissions - not the owner\"",
")",
";",
"// @codeCoverageIgnoreEnd",
"}",
"// We own the file, so we should be able to fix it",
"$",
"set_gid",
"=",
"false",
";",
"if",
"(",
"self",
"::",
"$",
"file_group",
"!==",
"null",
")",
"{",
"if",
"(",
"self",
"::",
"$",
"file_group",
"!==",
"$",
"group",
"[",
"'name'",
"]",
"&&",
"!",
"chgrp",
"(",
"$",
"path",
",",
"self",
"::",
"$",
"file_group",
")",
")",
"{",
"// @codeCoverageIgnoreStart",
"// This is not testable - a read only file system would be needed",
"throw",
"new",
"PermissionError",
"(",
"$",
"path",
",",
"\"Cannot change group\"",
")",
";",
"// @codeCoverageIgnoreEnd",
"}",
"$",
"set_gid",
"=",
"true",
";",
"}",
"// Owner and group are all right now, we should be able to modify the permissions",
"$",
"new_mode",
"=",
"$",
"perms",
"[",
"'mode'",
"]",
"|",
"self",
"::",
"OWNER_WRITE",
"|",
"(",
"$",
"set_gid",
"?",
"self",
"::",
"GROUP_WRITE",
":",
"0",
")",
";",
"if",
"(",
"is_dir",
"(",
"$",
"path",
")",
")",
"$",
"new_mode",
"|=",
"self",
"::",
"OWNER_EXECUTE",
"|",
"(",
"$",
"set_gid",
"?",
"self",
"::",
"GROUP_EXECUTE",
":",
"0",
")",
";",
"$",
"what",
"=",
"is_dir",
"(",
"$",
"path",
")",
"?",
"\"directory\"",
":",
"\"file\"",
";",
"self",
"::",
"getLogger",
"(",
")",
"->",
"notice",
"(",
"\"Changing permissions of {0} {1} to {2} (was: {3})\"",
",",
"[",
"$",
"what",
",",
"$",
"path",
",",
"$",
"new_mode",
",",
"$",
"perms",
"[",
"'mode'",
"]",
"]",
")",
";",
"try",
"{",
"@",
"chmod",
"(",
"$",
"path",
",",
"$",
"new_mode",
")",
";",
"}",
"// @codeCoverageIgnoreStart",
"// Basically untestable - we need a read-only file system for this",
"catch",
"(",
"Throwable",
"$",
"e",
")",
"{",
"throw",
"new",
"PermissionError",
"(",
"$",
"path",
",",
"\"Could not set permissions\"",
")",
";",
"}",
"// @codeCoverageIgnoreEnd",
"}"
] | Attempt to gain write access to the file. This will only work on files
that are owned but not writable - e.g. rarely. | [
"Attempt",
"to",
"gain",
"write",
"access",
"to",
"the",
"file",
".",
"This",
"will",
"only",
"work",
"on",
"files",
"that",
"are",
"owned",
"but",
"not",
"writable",
"-",
"e",
".",
"g",
".",
"rarely",
"."
] | train | https://github.com/Wedeto/IO/blob/4cfeaedd1bd9bda3097d18cb12233a4afecb2e85/src/Path.php#L210-L270 |
Wedeto/IO | src/Path.php | Path.getPermissions | public static function getPermissions($path)
{
try
{
$mode = @fileperms($path);
if ($mode === false)
throw new IOException();
}
catch (Throwable $e)
{
throw new IOException("Could not stat: " . $path);
}
$perms = array(
'owner' => array(
'read' => (bool)($mode & 0x0100),
'write' => (bool)($mode & 0x0080),
'execute' => (bool)($mode & 0x0040)
),
'group' => array(
'read' => (bool)($mode & 0x0020),
'write' => (bool)($mode & 0x0010),
'execute' => (bool)($mode & 0x0008)
),
'world' => array(
'read' => (bool)($mode & 0x0004),
'write' => (bool)($mode & 0x0002),
'execute' => (bool)($mode & 0x0001)
)
);
$perms['mode'] = self::compileMode($perms);
return $perms;
} | php | public static function getPermissions($path)
{
try
{
$mode = @fileperms($path);
if ($mode === false)
throw new IOException();
}
catch (Throwable $e)
{
throw new IOException("Could not stat: " . $path);
}
$perms = array(
'owner' => array(
'read' => (bool)($mode & 0x0100),
'write' => (bool)($mode & 0x0080),
'execute' => (bool)($mode & 0x0040)
),
'group' => array(
'read' => (bool)($mode & 0x0020),
'write' => (bool)($mode & 0x0010),
'execute' => (bool)($mode & 0x0008)
),
'world' => array(
'read' => (bool)($mode & 0x0004),
'write' => (bool)($mode & 0x0002),
'execute' => (bool)($mode & 0x0001)
)
);
$perms['mode'] = self::compileMode($perms);
return $perms;
} | [
"public",
"static",
"function",
"getPermissions",
"(",
"$",
"path",
")",
"{",
"try",
"{",
"$",
"mode",
"=",
"@",
"fileperms",
"(",
"$",
"path",
")",
";",
"if",
"(",
"$",
"mode",
"===",
"false",
")",
"throw",
"new",
"IOException",
"(",
")",
";",
"}",
"catch",
"(",
"Throwable",
"$",
"e",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Could not stat: \"",
".",
"$",
"path",
")",
";",
"}",
"$",
"perms",
"=",
"array",
"(",
"'owner'",
"=>",
"array",
"(",
"'read'",
"=>",
"(",
"bool",
")",
"(",
"$",
"mode",
"&",
"0x0100",
")",
",",
"'write'",
"=>",
"(",
"bool",
")",
"(",
"$",
"mode",
"&",
"0x0080",
")",
",",
"'execute'",
"=>",
"(",
"bool",
")",
"(",
"$",
"mode",
"&",
"0x0040",
")",
")",
",",
"'group'",
"=>",
"array",
"(",
"'read'",
"=>",
"(",
"bool",
")",
"(",
"$",
"mode",
"&",
"0x0020",
")",
",",
"'write'",
"=>",
"(",
"bool",
")",
"(",
"$",
"mode",
"&",
"0x0010",
")",
",",
"'execute'",
"=>",
"(",
"bool",
")",
"(",
"$",
"mode",
"&",
"0x0008",
")",
")",
",",
"'world'",
"=>",
"array",
"(",
"'read'",
"=>",
"(",
"bool",
")",
"(",
"$",
"mode",
"&",
"0x0004",
")",
",",
"'write'",
"=>",
"(",
"bool",
")",
"(",
"$",
"mode",
"&",
"0x0002",
")",
",",
"'execute'",
"=>",
"(",
"bool",
")",
"(",
"$",
"mode",
"&",
"0x0001",
")",
")",
")",
";",
"$",
"perms",
"[",
"'mode'",
"]",
"=",
"self",
"::",
"compileMode",
"(",
"$",
"perms",
")",
";",
"return",
"$",
"perms",
";",
"}"
] | Return the permissions set on the specified file.
@param string $path The path to examine
@return array An associative array containing 'owner', 'group' and 'world',
members, each containing 'read', 'write' and 'execute'
indicating their permissions. | [
"Return",
"the",
"permissions",
"set",
"on",
"the",
"specified",
"file",
"."
] | train | https://github.com/Wedeto/IO/blob/4cfeaedd1bd9bda3097d18cb12233a4afecb2e85/src/Path.php#L279-L312 |
Wedeto/IO | src/Path.php | Path.compileMode | public static function compileMode(array $perms)
{
$fmode = 0;
$fmode |= !empty($perms['owner']['read']) ? self::OWNER_READ : 0;
$fmode |= !empty($perms['owner']['write']) ? self::OWNER_WRITE : 0;
$fmode |= !empty($perms['owner']['execute']) ? self::OWNER_EXECUTE : 0;
$fmode |= !empty($perms['group']['read']) ? self::GROUP_READ : 0;
$fmode |= !empty($perms['group']['write']) ? self::GROUP_WRITE : 0;
$fmode |= !empty($perms['group']['execute']) ? self::GROUP_EXECUTE : 0;
$fmode |= !empty($perms['world']['read']) ? self::WORLD_READ : 0;
$fmode |= !empty($perms['world']['write']) ? self::WORLD_WRITE : 0;
$fmode |= !empty($perms['world']['execute']) ? self::WORLD_EXECUTE : 0;
return $fmode;
} | php | public static function compileMode(array $perms)
{
$fmode = 0;
$fmode |= !empty($perms['owner']['read']) ? self::OWNER_READ : 0;
$fmode |= !empty($perms['owner']['write']) ? self::OWNER_WRITE : 0;
$fmode |= !empty($perms['owner']['execute']) ? self::OWNER_EXECUTE : 0;
$fmode |= !empty($perms['group']['read']) ? self::GROUP_READ : 0;
$fmode |= !empty($perms['group']['write']) ? self::GROUP_WRITE : 0;
$fmode |= !empty($perms['group']['execute']) ? self::GROUP_EXECUTE : 0;
$fmode |= !empty($perms['world']['read']) ? self::WORLD_READ : 0;
$fmode |= !empty($perms['world']['write']) ? self::WORLD_WRITE : 0;
$fmode |= !empty($perms['world']['execute']) ? self::WORLD_EXECUTE : 0;
return $fmode;
} | [
"public",
"static",
"function",
"compileMode",
"(",
"array",
"$",
"perms",
")",
"{",
"$",
"fmode",
"=",
"0",
";",
"$",
"fmode",
"|=",
"!",
"empty",
"(",
"$",
"perms",
"[",
"'owner'",
"]",
"[",
"'read'",
"]",
")",
"?",
"self",
"::",
"OWNER_READ",
":",
"0",
";",
"$",
"fmode",
"|=",
"!",
"empty",
"(",
"$",
"perms",
"[",
"'owner'",
"]",
"[",
"'write'",
"]",
")",
"?",
"self",
"::",
"OWNER_WRITE",
":",
"0",
";",
"$",
"fmode",
"|=",
"!",
"empty",
"(",
"$",
"perms",
"[",
"'owner'",
"]",
"[",
"'execute'",
"]",
")",
"?",
"self",
"::",
"OWNER_EXECUTE",
":",
"0",
";",
"$",
"fmode",
"|=",
"!",
"empty",
"(",
"$",
"perms",
"[",
"'group'",
"]",
"[",
"'read'",
"]",
")",
"?",
"self",
"::",
"GROUP_READ",
":",
"0",
";",
"$",
"fmode",
"|=",
"!",
"empty",
"(",
"$",
"perms",
"[",
"'group'",
"]",
"[",
"'write'",
"]",
")",
"?",
"self",
"::",
"GROUP_WRITE",
":",
"0",
";",
"$",
"fmode",
"|=",
"!",
"empty",
"(",
"$",
"perms",
"[",
"'group'",
"]",
"[",
"'execute'",
"]",
")",
"?",
"self",
"::",
"GROUP_EXECUTE",
":",
"0",
";",
"$",
"fmode",
"|=",
"!",
"empty",
"(",
"$",
"perms",
"[",
"'world'",
"]",
"[",
"'read'",
"]",
")",
"?",
"self",
"::",
"WORLD_READ",
":",
"0",
";",
"$",
"fmode",
"|=",
"!",
"empty",
"(",
"$",
"perms",
"[",
"'world'",
"]",
"[",
"'write'",
"]",
")",
"?",
"self",
"::",
"WORLD_WRITE",
":",
"0",
";",
"$",
"fmode",
"|=",
"!",
"empty",
"(",
"$",
"perms",
"[",
"'world'",
"]",
"[",
"'execute'",
"]",
")",
"?",
"self",
"::",
"WORLD_EXECUTE",
":",
"0",
";",
"return",
"$",
"fmode",
";",
"}"
] | Create a file mode from an array containing permissions. The array
can have 'owner', 'group' and 'world' members, each which can have
'read', 'write', and 'execute' booleans that indicate whether that
permission is present or not. | [
"Create",
"a",
"file",
"mode",
"from",
"an",
"array",
"containing",
"permissions",
".",
"The",
"array",
"can",
"have",
"owner",
"group",
"and",
"world",
"members",
"each",
"which",
"can",
"have",
"read",
"write",
"and",
"execute",
"booleans",
"that",
"indicate",
"whether",
"that",
"permission",
"is",
"present",
"or",
"not",
"."
] | train | https://github.com/Wedeto/IO/blob/4cfeaedd1bd9bda3097d18cb12233a4afecb2e85/src/Path.php#L320-L336 |
Wedeto/IO | src/Path.php | Path.setPermissions | public static function setPermissions(string $path, int $mode = null)
{
$is_dir = is_dir($path);
$current_uid = posix_getuid();
$owner = @fileowner($path);
if ($current_uid !== $owner)
return;
if (self::$file_group)
{
$current_gid = filegroup($path);
$grpinfo = posix_getgrnam(self::$file_group);
$wanted_gid = $grpinfo['gid'];
if ($wanted_gid !== $current_gid)
{
try
{
!@chgrp($path, self::$file_group);
clearstatcache(true, $path);
}
// @codeCoverageIgnoreStart
// Impossible to test - this would require a RO file system
catch (Throwable $e)
{
throw new IOException(
"Could not set group on " . $path . " to " . self::$file_group
);
}
// @codeCoverageIgnoreEnd
}
}
if ($mode === null)
$mode = $is_dir ? self::$dir_mode : self::$file_mode;
if (!empty($mode))
{
$perms = self::getPermissions($path);
$current_mode = $perms['mode'];
if ($mode !== $current_mode)
{
try
{
@chmod($path, $mode);
clearstatcache(true, $path);
}
// @codeCoverageIgnoreStart
// Impossible to test - this would require a RO file system
catch (Throwable $e)
{
throw new IOException(
"Could not set mode on " . $path . " to " . $mode
);
}
// @codeCoverageIgnoreEnd
}
}
} | php | public static function setPermissions(string $path, int $mode = null)
{
$is_dir = is_dir($path);
$current_uid = posix_getuid();
$owner = @fileowner($path);
if ($current_uid !== $owner)
return;
if (self::$file_group)
{
$current_gid = filegroup($path);
$grpinfo = posix_getgrnam(self::$file_group);
$wanted_gid = $grpinfo['gid'];
if ($wanted_gid !== $current_gid)
{
try
{
!@chgrp($path, self::$file_group);
clearstatcache(true, $path);
}
// @codeCoverageIgnoreStart
// Impossible to test - this would require a RO file system
catch (Throwable $e)
{
throw new IOException(
"Could not set group on " . $path . " to " . self::$file_group
);
}
// @codeCoverageIgnoreEnd
}
}
if ($mode === null)
$mode = $is_dir ? self::$dir_mode : self::$file_mode;
if (!empty($mode))
{
$perms = self::getPermissions($path);
$current_mode = $perms['mode'];
if ($mode !== $current_mode)
{
try
{
@chmod($path, $mode);
clearstatcache(true, $path);
}
// @codeCoverageIgnoreStart
// Impossible to test - this would require a RO file system
catch (Throwable $e)
{
throw new IOException(
"Could not set mode on " . $path . " to " . $mode
);
}
// @codeCoverageIgnoreEnd
}
}
} | [
"public",
"static",
"function",
"setPermissions",
"(",
"string",
"$",
"path",
",",
"int",
"$",
"mode",
"=",
"null",
")",
"{",
"$",
"is_dir",
"=",
"is_dir",
"(",
"$",
"path",
")",
";",
"$",
"current_uid",
"=",
"posix_getuid",
"(",
")",
";",
"$",
"owner",
"=",
"@",
"fileowner",
"(",
"$",
"path",
")",
";",
"if",
"(",
"$",
"current_uid",
"!==",
"$",
"owner",
")",
"return",
";",
"if",
"(",
"self",
"::",
"$",
"file_group",
")",
"{",
"$",
"current_gid",
"=",
"filegroup",
"(",
"$",
"path",
")",
";",
"$",
"grpinfo",
"=",
"posix_getgrnam",
"(",
"self",
"::",
"$",
"file_group",
")",
";",
"$",
"wanted_gid",
"=",
"$",
"grpinfo",
"[",
"'gid'",
"]",
";",
"if",
"(",
"$",
"wanted_gid",
"!==",
"$",
"current_gid",
")",
"{",
"try",
"{",
"!",
"@",
"chgrp",
"(",
"$",
"path",
",",
"self",
"::",
"$",
"file_group",
")",
";",
"clearstatcache",
"(",
"true",
",",
"$",
"path",
")",
";",
"}",
"// @codeCoverageIgnoreStart",
"// Impossible to test - this would require a RO file system",
"catch",
"(",
"Throwable",
"$",
"e",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Could not set group on \"",
".",
"$",
"path",
".",
"\" to \"",
".",
"self",
"::",
"$",
"file_group",
")",
";",
"}",
"// @codeCoverageIgnoreEnd",
"}",
"}",
"if",
"(",
"$",
"mode",
"===",
"null",
")",
"$",
"mode",
"=",
"$",
"is_dir",
"?",
"self",
"::",
"$",
"dir_mode",
":",
"self",
"::",
"$",
"file_mode",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"mode",
")",
")",
"{",
"$",
"perms",
"=",
"self",
"::",
"getPermissions",
"(",
"$",
"path",
")",
";",
"$",
"current_mode",
"=",
"$",
"perms",
"[",
"'mode'",
"]",
";",
"if",
"(",
"$",
"mode",
"!==",
"$",
"current_mode",
")",
"{",
"try",
"{",
"@",
"chmod",
"(",
"$",
"path",
",",
"$",
"mode",
")",
";",
"clearstatcache",
"(",
"true",
",",
"$",
"path",
")",
";",
"}",
"// @codeCoverageIgnoreStart",
"// Impossible to test - this would require a RO file system",
"catch",
"(",
"Throwable",
"$",
"e",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Could not set mode on \"",
".",
"$",
"path",
".",
"\" to \"",
".",
"$",
"mode",
")",
";",
"}",
"// @codeCoverageIgnoreEnd",
"}",
"}",
"}"
] | Set / fix the permissions as specified in the configuration
@param string $path The path to update
@param int $mode The (octal) mode to set. When omitted, the default is
used. | [
"Set",
"/",
"fix",
"the",
"permissions",
"as",
"specified",
"in",
"the",
"configuration"
] | train | https://github.com/Wedeto/IO/blob/4cfeaedd1bd9bda3097d18cb12233a4afecb2e85/src/Path.php#L352-L411 |
eureka-framework/component-template | src/Template/Pattern/PatternMain.php | PatternMain.render | public function render()
{
$pattern = array(
'{{' => '<?php ', '{%' => '<?php', '}}' => '?>', '%}' => '?>', '{#' => '<?php /* ', '#}' => ' */ ?>',
);
return $this->templateContent = trim(str_replace(array_keys($pattern), $pattern, $this->templateContent));
} | php | public function render()
{
$pattern = array(
'{{' => '<?php ', '{%' => '<?php', '}}' => '?>', '%}' => '?>', '{#' => '<?php /* ', '#}' => ' */ ?>',
);
return $this->templateContent = trim(str_replace(array_keys($pattern), $pattern, $this->templateContent));
} | [
"public",
"function",
"render",
"(",
")",
"{",
"$",
"pattern",
"=",
"array",
"(",
"'{{'",
"=>",
"'<?php '",
",",
"'{%'",
"=>",
"'<?php'",
",",
"'}}'",
"=>",
"'?>'",
",",
"'%}'",
"=>",
"'?>'",
",",
"'{#'",
"=>",
"'<?php /* '",
",",
"'#}'",
"=>",
"' */ ?>'",
",",
")",
";",
"return",
"$",
"this",
"->",
"templateContent",
"=",
"trim",
"(",
"str_replace",
"(",
"array_keys",
"(",
"$",
"pattern",
")",
",",
"$",
"pattern",
",",
"$",
"this",
"->",
"templateContent",
")",
")",
";",
"}"
] | Search & replace current defined pattern for template.
Example of template:
<code>
# In Template:
<ul>
{# Comment in php tag #}
{{foreach($array as $index => $value):}}
<li>{{@$index;}}: {{@$value;}}</li>
{{endforeach;}}
</ul>
# In Compiled template:
<ul>
<?php /* Comment in php tag * / ?>
<?php foreach($array as $index => $value): ?>
<li><?=$index;?>: <?=$value;?></li>
<?php endforeach; ?>
</ul>
</code>
{{ & }} ARE DEPRECATED
@return string Compiled template | [
"Search",
"&",
"replace",
"current",
"defined",
"pattern",
"for",
"template",
".",
"Example",
"of",
"template",
":"
] | train | https://github.com/eureka-framework/component-template/blob/42e9b3954b79892ba340ba7ca909f03ee99c36fe/src/Template/Pattern/PatternMain.php#L48-L55 |
wb-crowdfusion/crowdfusion | system/core/classes/mvc/filters/CmsFilterer.php | CmsFilterer.menu | protected function menu()
{
$this->Benchmark->start('getMenu');
try {
$menu = $this->CMSNavItemService->getMenu();
} catch (Exception $e) {
return '';
}
$this->Benchmark->end('getMenu');
$this->Benchmark->start('buildMenu');
$dom_id = $this->getParameter('id');
$dom_class = $this->getParameter('class');
$this->matchedCurrentURI = false;
$root_options = array();
if (!empty($dom_id))
$root_options[] = "id='{$dom_id}'";
if (!empty($dom_class))
$root_options[] = "class='{$dom_class}'";
$family_tree = "<ul " . join(' ', $root_options). ">\n";
$this->requestURI = ltrim($this->Request->getAdjustedRequestURI(), '/');
foreach ( $menu as $parent ) {
$family_tree .= $this->_buildMenuTree($parent, "parent", "<span>%s</span>", true);
}
$family_tree .= "</ul>\n";
$this->Benchmark->end('buildMenu');
return $family_tree;
} | php | protected function menu()
{
$this->Benchmark->start('getMenu');
try {
$menu = $this->CMSNavItemService->getMenu();
} catch (Exception $e) {
return '';
}
$this->Benchmark->end('getMenu');
$this->Benchmark->start('buildMenu');
$dom_id = $this->getParameter('id');
$dom_class = $this->getParameter('class');
$this->matchedCurrentURI = false;
$root_options = array();
if (!empty($dom_id))
$root_options[] = "id='{$dom_id}'";
if (!empty($dom_class))
$root_options[] = "class='{$dom_class}'";
$family_tree = "<ul " . join(' ', $root_options). ">\n";
$this->requestURI = ltrim($this->Request->getAdjustedRequestURI(), '/');
foreach ( $menu as $parent ) {
$family_tree .= $this->_buildMenuTree($parent, "parent", "<span>%s</span>", true);
}
$family_tree .= "</ul>\n";
$this->Benchmark->end('buildMenu');
return $family_tree;
} | [
"protected",
"function",
"menu",
"(",
")",
"{",
"$",
"this",
"->",
"Benchmark",
"->",
"start",
"(",
"'getMenu'",
")",
";",
"try",
"{",
"$",
"menu",
"=",
"$",
"this",
"->",
"CMSNavItemService",
"->",
"getMenu",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"return",
"''",
";",
"}",
"$",
"this",
"->",
"Benchmark",
"->",
"end",
"(",
"'getMenu'",
")",
";",
"$",
"this",
"->",
"Benchmark",
"->",
"start",
"(",
"'buildMenu'",
")",
";",
"$",
"dom_id",
"=",
"$",
"this",
"->",
"getParameter",
"(",
"'id'",
")",
";",
"$",
"dom_class",
"=",
"$",
"this",
"->",
"getParameter",
"(",
"'class'",
")",
";",
"$",
"this",
"->",
"matchedCurrentURI",
"=",
"false",
";",
"$",
"root_options",
"=",
"array",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"dom_id",
")",
")",
"$",
"root_options",
"[",
"]",
"=",
"\"id='{$dom_id}'\"",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"dom_class",
")",
")",
"$",
"root_options",
"[",
"]",
"=",
"\"class='{$dom_class}'\"",
";",
"$",
"family_tree",
"=",
"\"<ul \"",
".",
"join",
"(",
"' '",
",",
"$",
"root_options",
")",
".",
"\">\\n\"",
";",
"$",
"this",
"->",
"requestURI",
"=",
"ltrim",
"(",
"$",
"this",
"->",
"Request",
"->",
"getAdjustedRequestURI",
"(",
")",
",",
"'/'",
")",
";",
"foreach",
"(",
"$",
"menu",
"as",
"$",
"parent",
")",
"{",
"$",
"family_tree",
".=",
"$",
"this",
"->",
"_buildMenuTree",
"(",
"$",
"parent",
",",
"\"parent\"",
",",
"\"<span>%s</span>\"",
",",
"true",
")",
";",
"}",
"$",
"family_tree",
".=",
"\"</ul>\\n\"",
";",
"$",
"this",
"->",
"Benchmark",
"->",
"end",
"(",
"'buildMenu'",
")",
";",
"return",
"$",
"family_tree",
";",
"}"
] | Returns a full HTML rendering of the CMS navigation menu
@return string | [
"Returns",
"a",
"full",
"HTML",
"rendering",
"of",
"the",
"CMS",
"navigation",
"menu"
] | train | https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/mvc/filters/CmsFilterer.php#L135-L170 |
wb-crowdfusion/crowdfusion | system/core/classes/mvc/filters/CmsFilterer.php | CmsFilterer._buildMenuTree | private function _buildMenuTree($parent, $classes = '', $format_string = '%s', $is_top_level = false)
{
// Permissions check
if (!empty($parent->Permissions)) {
$permissions = StringUtils::smartExplode($parent->Permissions);
foreach ( $permissions as $perm ) {
if (!$this->Permissions->checkPermission(trim($perm)))
return '';
}
}
if($parent->Enabled == false)
return '';
$contains_current_uri = false;
$content = '';
if (($this->requestURI == $parent->URI || stripos($this->requestURI, $parent->URI) === 0) && !$this->matchedCurrentURI) {
$contains_current_uri = true;
$this->matchedCurrentURI = true;
}
if (!empty($parent->DoAddLinksFor)) {
try {
// Look up all items
$add_links = array();
$add_menu_items = StringUtils::smartExplode($parent->DoAddLinksFor);
foreach ( $add_menu_items as $element_or_aspect )
$add_links = array_merge($add_links, $this->lookupElementsForNav(trim($element_or_aspect)));
$uri = $parent->URI;
if (substr($uri, -1) != '/')
$uri .= '/';
// Build a submenu with all items.
if (count($add_links) == 1) {
$content .= "\t<a href='{$uri}{$add_links[0]['URI']}/'>";
$content .= sprintf($format_string, 'Add '.$add_links[0]['Name']);
$content .= "</a>\n";
} elseif (count($add_links) > 1) {
$content .= "\t<a class='daddy'>{$parent->Label}</a>\n";
$content .= "<ul>\n";
foreach ( $add_links as $link ) {
$content .= "<li><a href='{$uri}{$link['URI']}/'>{$link['Name']}</a></li>\n";
}
$content .= "</ul>\n";
}
} catch(Exception $e) {
}
} else {
$content .= "\t<a href='{$parent->URI}'>";
$content .= sprintf($format_string, $parent->Label);
$content .= "</a>\n";
$ccontent = '';
if (count($parent->Children) > 0) {
foreach ( $parent->Children as $kid ) {
$res = $this->_buildMenuTree($kid);
if (!empty($res)) {
list($child_content, $child_has_uri) = $res;
if ($child_has_uri)
$contains_current_uri = true;
$ccontent .= $child_content;
}
}
}
if (!empty($ccontent)) {
$content .= "<ul>\n";
$content .= $ccontent;
$content .= "</ul>\n";
}
}
$item = "<li id='nav-{$parent->Slug}' class='{$classes}'>\n{$content}</li>\n";
if (!$is_top_level)
return array($item, $contains_current_uri);
else
return "<li id='nav-{$parent->Slug}' class='{$classes} ". (($contains_current_uri) ? "selected" : "") . "'>\n{$content}</li>\n";
} | php | private function _buildMenuTree($parent, $classes = '', $format_string = '%s', $is_top_level = false)
{
// Permissions check
if (!empty($parent->Permissions)) {
$permissions = StringUtils::smartExplode($parent->Permissions);
foreach ( $permissions as $perm ) {
if (!$this->Permissions->checkPermission(trim($perm)))
return '';
}
}
if($parent->Enabled == false)
return '';
$contains_current_uri = false;
$content = '';
if (($this->requestURI == $parent->URI || stripos($this->requestURI, $parent->URI) === 0) && !$this->matchedCurrentURI) {
$contains_current_uri = true;
$this->matchedCurrentURI = true;
}
if (!empty($parent->DoAddLinksFor)) {
try {
// Look up all items
$add_links = array();
$add_menu_items = StringUtils::smartExplode($parent->DoAddLinksFor);
foreach ( $add_menu_items as $element_or_aspect )
$add_links = array_merge($add_links, $this->lookupElementsForNav(trim($element_or_aspect)));
$uri = $parent->URI;
if (substr($uri, -1) != '/')
$uri .= '/';
// Build a submenu with all items.
if (count($add_links) == 1) {
$content .= "\t<a href='{$uri}{$add_links[0]['URI']}/'>";
$content .= sprintf($format_string, 'Add '.$add_links[0]['Name']);
$content .= "</a>\n";
} elseif (count($add_links) > 1) {
$content .= "\t<a class='daddy'>{$parent->Label}</a>\n";
$content .= "<ul>\n";
foreach ( $add_links as $link ) {
$content .= "<li><a href='{$uri}{$link['URI']}/'>{$link['Name']}</a></li>\n";
}
$content .= "</ul>\n";
}
} catch(Exception $e) {
}
} else {
$content .= "\t<a href='{$parent->URI}'>";
$content .= sprintf($format_string, $parent->Label);
$content .= "</a>\n";
$ccontent = '';
if (count($parent->Children) > 0) {
foreach ( $parent->Children as $kid ) {
$res = $this->_buildMenuTree($kid);
if (!empty($res)) {
list($child_content, $child_has_uri) = $res;
if ($child_has_uri)
$contains_current_uri = true;
$ccontent .= $child_content;
}
}
}
if (!empty($ccontent)) {
$content .= "<ul>\n";
$content .= $ccontent;
$content .= "</ul>\n";
}
}
$item = "<li id='nav-{$parent->Slug}' class='{$classes}'>\n{$content}</li>\n";
if (!$is_top_level)
return array($item, $contains_current_uri);
else
return "<li id='nav-{$parent->Slug}' class='{$classes} ". (($contains_current_uri) ? "selected" : "") . "'>\n{$content}</li>\n";
} | [
"private",
"function",
"_buildMenuTree",
"(",
"$",
"parent",
",",
"$",
"classes",
"=",
"''",
",",
"$",
"format_string",
"=",
"'%s'",
",",
"$",
"is_top_level",
"=",
"false",
")",
"{",
"// Permissions check",
"if",
"(",
"!",
"empty",
"(",
"$",
"parent",
"->",
"Permissions",
")",
")",
"{",
"$",
"permissions",
"=",
"StringUtils",
"::",
"smartExplode",
"(",
"$",
"parent",
"->",
"Permissions",
")",
";",
"foreach",
"(",
"$",
"permissions",
"as",
"$",
"perm",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"Permissions",
"->",
"checkPermission",
"(",
"trim",
"(",
"$",
"perm",
")",
")",
")",
"return",
"''",
";",
"}",
"}",
"if",
"(",
"$",
"parent",
"->",
"Enabled",
"==",
"false",
")",
"return",
"''",
";",
"$",
"contains_current_uri",
"=",
"false",
";",
"$",
"content",
"=",
"''",
";",
"if",
"(",
"(",
"$",
"this",
"->",
"requestURI",
"==",
"$",
"parent",
"->",
"URI",
"||",
"stripos",
"(",
"$",
"this",
"->",
"requestURI",
",",
"$",
"parent",
"->",
"URI",
")",
"===",
"0",
")",
"&&",
"!",
"$",
"this",
"->",
"matchedCurrentURI",
")",
"{",
"$",
"contains_current_uri",
"=",
"true",
";",
"$",
"this",
"->",
"matchedCurrentURI",
"=",
"true",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"parent",
"->",
"DoAddLinksFor",
")",
")",
"{",
"try",
"{",
"// Look up all items",
"$",
"add_links",
"=",
"array",
"(",
")",
";",
"$",
"add_menu_items",
"=",
"StringUtils",
"::",
"smartExplode",
"(",
"$",
"parent",
"->",
"DoAddLinksFor",
")",
";",
"foreach",
"(",
"$",
"add_menu_items",
"as",
"$",
"element_or_aspect",
")",
"$",
"add_links",
"=",
"array_merge",
"(",
"$",
"add_links",
",",
"$",
"this",
"->",
"lookupElementsForNav",
"(",
"trim",
"(",
"$",
"element_or_aspect",
")",
")",
")",
";",
"$",
"uri",
"=",
"$",
"parent",
"->",
"URI",
";",
"if",
"(",
"substr",
"(",
"$",
"uri",
",",
"-",
"1",
")",
"!=",
"'/'",
")",
"$",
"uri",
".=",
"'/'",
";",
"// Build a submenu with all items.",
"if",
"(",
"count",
"(",
"$",
"add_links",
")",
"==",
"1",
")",
"{",
"$",
"content",
".=",
"\"\\t<a href='{$uri}{$add_links[0]['URI']}/'>\"",
";",
"$",
"content",
".=",
"sprintf",
"(",
"$",
"format_string",
",",
"'Add '",
".",
"$",
"add_links",
"[",
"0",
"]",
"[",
"'Name'",
"]",
")",
";",
"$",
"content",
".=",
"\"</a>\\n\"",
";",
"}",
"elseif",
"(",
"count",
"(",
"$",
"add_links",
")",
">",
"1",
")",
"{",
"$",
"content",
".=",
"\"\\t<a class='daddy'>{$parent->Label}</a>\\n\"",
";",
"$",
"content",
".=",
"\"<ul>\\n\"",
";",
"foreach",
"(",
"$",
"add_links",
"as",
"$",
"link",
")",
"{",
"$",
"content",
".=",
"\"<li><a href='{$uri}{$link['URI']}/'>{$link['Name']}</a></li>\\n\"",
";",
"}",
"$",
"content",
".=",
"\"</ul>\\n\"",
";",
"}",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"}",
"}",
"else",
"{",
"$",
"content",
".=",
"\"\\t<a href='{$parent->URI}'>\"",
";",
"$",
"content",
".=",
"sprintf",
"(",
"$",
"format_string",
",",
"$",
"parent",
"->",
"Label",
")",
";",
"$",
"content",
".=",
"\"</a>\\n\"",
";",
"$",
"ccontent",
"=",
"''",
";",
"if",
"(",
"count",
"(",
"$",
"parent",
"->",
"Children",
")",
">",
"0",
")",
"{",
"foreach",
"(",
"$",
"parent",
"->",
"Children",
"as",
"$",
"kid",
")",
"{",
"$",
"res",
"=",
"$",
"this",
"->",
"_buildMenuTree",
"(",
"$",
"kid",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"res",
")",
")",
"{",
"list",
"(",
"$",
"child_content",
",",
"$",
"child_has_uri",
")",
"=",
"$",
"res",
";",
"if",
"(",
"$",
"child_has_uri",
")",
"$",
"contains_current_uri",
"=",
"true",
";",
"$",
"ccontent",
".=",
"$",
"child_content",
";",
"}",
"}",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"ccontent",
")",
")",
"{",
"$",
"content",
".=",
"\"<ul>\\n\"",
";",
"$",
"content",
".=",
"$",
"ccontent",
";",
"$",
"content",
".=",
"\"</ul>\\n\"",
";",
"}",
"}",
"$",
"item",
"=",
"\"<li id='nav-{$parent->Slug}' class='{$classes}'>\\n{$content}</li>\\n\"",
";",
"if",
"(",
"!",
"$",
"is_top_level",
")",
"return",
"array",
"(",
"$",
"item",
",",
"$",
"contains_current_uri",
")",
";",
"else",
"return",
"\"<li id='nav-{$parent->Slug}' class='{$classes} \"",
".",
"(",
"(",
"$",
"contains_current_uri",
")",
"?",
"\"selected\"",
":",
"\"\"",
")",
".",
"\"'>\\n{$content}</li>\\n\"",
";",
"}"
] | Recursive function that build the menu tree for each menu item.
@param CMSNavItem $parent The parent item
@param string $classes Any css classes that should be applied to the items generated
@param string $format_string A format string that determines how menu items will appear in the html
@param boolean $is_top_level If TRUE, we're processing the top level items
@return string | [
"Recursive",
"function",
"that",
"build",
"the",
"menu",
"tree",
"for",
"each",
"menu",
"item",
"."
] | train | https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/mvc/filters/CmsFilterer.php#L183-L266 |
wb-crowdfusion/crowdfusion | system/core/classes/mvc/filters/CmsFilterer.php | CmsFilterer.lookupElementsForNav | protected function lookupElementsForNav($element_or_aspect)
{
$results = array();
if (substr($element_or_aspect, 0, 1) == '@') {
$elements = $this->ElementService->findAllWithAspect(substr($element_or_aspect, 1));
foreach ( $elements as $element ) {
$results[] = array('Name' => $element->Name, 'URI' => $element->Slug);
}
} else {
// Assume it's an element slug
$element = $this->ElementService->getBySlug($element_or_aspect);
$results[] = array('Name' => $element->Name, 'URI' => $element->Slug);
}
return $results;
} | php | protected function lookupElementsForNav($element_or_aspect)
{
$results = array();
if (substr($element_or_aspect, 0, 1) == '@') {
$elements = $this->ElementService->findAllWithAspect(substr($element_or_aspect, 1));
foreach ( $elements as $element ) {
$results[] = array('Name' => $element->Name, 'URI' => $element->Slug);
}
} else {
// Assume it's an element slug
$element = $this->ElementService->getBySlug($element_or_aspect);
$results[] = array('Name' => $element->Name, 'URI' => $element->Slug);
}
return $results;
} | [
"protected",
"function",
"lookupElementsForNav",
"(",
"$",
"element_or_aspect",
")",
"{",
"$",
"results",
"=",
"array",
"(",
")",
";",
"if",
"(",
"substr",
"(",
"$",
"element_or_aspect",
",",
"0",
",",
"1",
")",
"==",
"'@'",
")",
"{",
"$",
"elements",
"=",
"$",
"this",
"->",
"ElementService",
"->",
"findAllWithAspect",
"(",
"substr",
"(",
"$",
"element_or_aspect",
",",
"1",
")",
")",
";",
"foreach",
"(",
"$",
"elements",
"as",
"$",
"element",
")",
"{",
"$",
"results",
"[",
"]",
"=",
"array",
"(",
"'Name'",
"=>",
"$",
"element",
"->",
"Name",
",",
"'URI'",
"=>",
"$",
"element",
"->",
"Slug",
")",
";",
"}",
"}",
"else",
"{",
"// Assume it's an element slug",
"$",
"element",
"=",
"$",
"this",
"->",
"ElementService",
"->",
"getBySlug",
"(",
"$",
"element_or_aspect",
")",
";",
"$",
"results",
"[",
"]",
"=",
"array",
"(",
"'Name'",
"=>",
"$",
"element",
"->",
"Name",
",",
"'URI'",
"=>",
"$",
"element",
"->",
"Slug",
")",
";",
"}",
"return",
"$",
"results",
";",
"}"
] | REturns all the elements for the specified element or aspect
@param string $element_or_aspect The element or aspect to lookup
@return array | [
"REturns",
"all",
"the",
"elements",
"for",
"the",
"specified",
"element",
"or",
"aspect"
] | train | https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/mvc/filters/CmsFilterer.php#L275-L291 |
wb-crowdfusion/crowdfusion | system/core/classes/mvc/filters/CmsFilterer.php | CmsFilterer.sortingLink | public function sortingLink()
{
$filterlist = '';
if ($this->getParameter('filter') != null) {
foreach ($this->getParameter('filter') as $get => $value) {
$filterlist .= 'filter['.$get.'][]='.$value.'&';
}
}
if ($this->getParameter('sort') != null) {
$sort = $this->getParameter('sort');
} else {
$sort = array();
}
if (!empty($sort[$this->getParameter('field')])) {
if ($sort[$this->getParameter('field')] == 'ASC') {
return $filterlist.'sort['.$this->getParameter('field').']=DESC';
} else {
return $filterlist.'sort['.$this->getParameter('field').']=ASC';
}
}
return $filterlist.'sort['.$this->getParameter('field').']='.$this->getParameter('order');
} | php | public function sortingLink()
{
$filterlist = '';
if ($this->getParameter('filter') != null) {
foreach ($this->getParameter('filter') as $get => $value) {
$filterlist .= 'filter['.$get.'][]='.$value.'&';
}
}
if ($this->getParameter('sort') != null) {
$sort = $this->getParameter('sort');
} else {
$sort = array();
}
if (!empty($sort[$this->getParameter('field')])) {
if ($sort[$this->getParameter('field')] == 'ASC') {
return $filterlist.'sort['.$this->getParameter('field').']=DESC';
} else {
return $filterlist.'sort['.$this->getParameter('field').']=ASC';
}
}
return $filterlist.'sort['.$this->getParameter('field').']='.$this->getParameter('order');
} | [
"public",
"function",
"sortingLink",
"(",
")",
"{",
"$",
"filterlist",
"=",
"''",
";",
"if",
"(",
"$",
"this",
"->",
"getParameter",
"(",
"'filter'",
")",
"!=",
"null",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getParameter",
"(",
"'filter'",
")",
"as",
"$",
"get",
"=>",
"$",
"value",
")",
"{",
"$",
"filterlist",
".=",
"'filter['",
".",
"$",
"get",
".",
"'][]='",
".",
"$",
"value",
".",
"'&'",
";",
"}",
"}",
"if",
"(",
"$",
"this",
"->",
"getParameter",
"(",
"'sort'",
")",
"!=",
"null",
")",
"{",
"$",
"sort",
"=",
"$",
"this",
"->",
"getParameter",
"(",
"'sort'",
")",
";",
"}",
"else",
"{",
"$",
"sort",
"=",
"array",
"(",
")",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"sort",
"[",
"$",
"this",
"->",
"getParameter",
"(",
"'field'",
")",
"]",
")",
")",
"{",
"if",
"(",
"$",
"sort",
"[",
"$",
"this",
"->",
"getParameter",
"(",
"'field'",
")",
"]",
"==",
"'ASC'",
")",
"{",
"return",
"$",
"filterlist",
".",
"'sort['",
".",
"$",
"this",
"->",
"getParameter",
"(",
"'field'",
")",
".",
"']=DESC'",
";",
"}",
"else",
"{",
"return",
"$",
"filterlist",
".",
"'sort['",
".",
"$",
"this",
"->",
"getParameter",
"(",
"'field'",
")",
".",
"']=ASC'",
";",
"}",
"}",
"return",
"$",
"filterlist",
".",
"'sort['",
".",
"$",
"this",
"->",
"getParameter",
"(",
"'field'",
")",
".",
"']='",
".",
"$",
"this",
"->",
"getParameter",
"(",
"'order'",
")",
";",
"}"
] | Returns a URL with sort parameters
Expected Params:
filter string the string to operate upon
sort integer (optional) the starting point for our substring, default 0
field integer (optional) the length of the substring. default 1
order integer (optional) the length of the substring. default 1
@return string | [
"Returns",
"a",
"URL",
"with",
"sort",
"parameters"
] | train | https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/mvc/filters/CmsFilterer.php#L304-L326 |
kdaviesnz/Functional | src/FunctionalModel.php | FunctionalModel.getCodeFromReflection | private function getCodeFromReflection(string $method_or_function_name, $reflection, string $className=""):array
{
if (is_bool($reflection->getFileName())) {
return array();
}
$file = new \SplFileObject($reflection->getFileName());
$file->seek($reflection->getStartLine());
$code = "";
do {
$code .= $file->current();
$file->next();
} while ($file->key() < $reflection->getEndLine());
return array(
"className" => $className,
"name" => $method_or_function_name,
"code" => $this->stripComments($code)
);
} | php | private function getCodeFromReflection(string $method_or_function_name, $reflection, string $className=""):array
{
if (is_bool($reflection->getFileName())) {
return array();
}
$file = new \SplFileObject($reflection->getFileName());
$file->seek($reflection->getStartLine());
$code = "";
do {
$code .= $file->current();
$file->next();
} while ($file->key() < $reflection->getEndLine());
return array(
"className" => $className,
"name" => $method_or_function_name,
"code" => $this->stripComments($code)
);
} | [
"private",
"function",
"getCodeFromReflection",
"(",
"string",
"$",
"method_or_function_name",
",",
"$",
"reflection",
",",
"string",
"$",
"className",
"=",
"\"\"",
")",
":",
"array",
"{",
"if",
"(",
"is_bool",
"(",
"$",
"reflection",
"->",
"getFileName",
"(",
")",
")",
")",
"{",
"return",
"array",
"(",
")",
";",
"}",
"$",
"file",
"=",
"new",
"\\",
"SplFileObject",
"(",
"$",
"reflection",
"->",
"getFileName",
"(",
")",
")",
";",
"$",
"file",
"->",
"seek",
"(",
"$",
"reflection",
"->",
"getStartLine",
"(",
")",
")",
";",
"$",
"code",
"=",
"\"\"",
";",
"do",
"{",
"$",
"code",
".=",
"$",
"file",
"->",
"current",
"(",
")",
";",
"$",
"file",
"->",
"next",
"(",
")",
";",
"}",
"while",
"(",
"$",
"file",
"->",
"key",
"(",
")",
"<",
"$",
"reflection",
"->",
"getEndLine",
"(",
")",
")",
";",
"return",
"array",
"(",
"\"className\"",
"=>",
"$",
"className",
",",
"\"name\"",
"=>",
"$",
"method_or_function_name",
",",
"\"code\"",
"=>",
"$",
"this",
"->",
"stripComments",
"(",
"$",
"code",
")",
")",
";",
"}"
] | @param string $method_or_function_name
@param $reflection
@return array | [
"@param",
"string",
"$method_or_function_name",
"@param",
"$reflection"
] | train | https://github.com/kdaviesnz/Functional/blob/475c2f6dbd8a64258715a25d131398aa10d6f3cf/src/FunctionalModel.php#L386-L405 |
kdaviesnz/Functional | src/FunctionalModel.php | FunctionalModel.addToken | private function addToken(array $tokenised_content, array $tokens, string $code): array
{
for ($i = 0; $i < count($tokens); $i ++) {
$token = $tokens[$i];
switch ($token[0]) {
case T_CLASS:
$class = "";
do {
$i ++;
if (!is_string($tokens[$i][0]) && !empty(trim($tokens[$i][1]))) {
$class .= $tokens[$i][1];
}
} while (!is_string($tokens[$i][0]));
// Check for "extends"
preg_match("/(.*?)extends/", $class, $matches);
if (!empty($matches)) {
$class = $matches[1];
}
// Check for "implements"
preg_match("/(.*?)implements/", $class, $matches);
if (!empty($matches)) {
$class = $matches[1];
}
if (!empty($tokenised_content)) {
$class = $tokenised_content["namespace"] . "\\" . $class;
}
$tokenised_content["class"] = $class;
$methods = get_class_methods($class);
// $methods will be null if the class hasn't been loaded.
if (empty($methods)) {
$methods_with_code = $this->parseClassCode($code, $class);
} else {
$methods_with_code = array_map(
function ( $method ) use ( $class ) {
return $this->getMethodCode( $class, $method );
},
$methods
);
}
$tokenised_content["methods"] = $methods_with_code;
break;
case T_NAMESPACE:
$namespace = "";
do {
$i ++;
if (!is_string($tokens[$i][0]) && !empty(trim($tokens[$i][1]))) {
$namespace .= $tokens[$i][1];
}
} while (!is_string($tokens[$i][0]));
$tokenised_content["namespace"] = $namespace;
break;
case T_FUNCTION:
$function_name = "\\";
do {
$i ++;
if (!is_string($tokens[$i][0]) && !empty(trim($tokens[$i][1]))) {
$function_name .= $tokens[$i][1];
}
} while (!is_string($tokens[$i][0]));
if (function_exists($function_name)) { //
$tokenised_content["functions"][] = $this->getFunctionCode($function_name);
} else {
$tokenised_content["functions"][] = $this->parseFunctionCode($function_name, $code);
}
}
}
return $tokenised_content;
} | php | private function addToken(array $tokenised_content, array $tokens, string $code): array
{
for ($i = 0; $i < count($tokens); $i ++) {
$token = $tokens[$i];
switch ($token[0]) {
case T_CLASS:
$class = "";
do {
$i ++;
if (!is_string($tokens[$i][0]) && !empty(trim($tokens[$i][1]))) {
$class .= $tokens[$i][1];
}
} while (!is_string($tokens[$i][0]));
// Check for "extends"
preg_match("/(.*?)extends/", $class, $matches);
if (!empty($matches)) {
$class = $matches[1];
}
// Check for "implements"
preg_match("/(.*?)implements/", $class, $matches);
if (!empty($matches)) {
$class = $matches[1];
}
if (!empty($tokenised_content)) {
$class = $tokenised_content["namespace"] . "\\" . $class;
}
$tokenised_content["class"] = $class;
$methods = get_class_methods($class);
// $methods will be null if the class hasn't been loaded.
if (empty($methods)) {
$methods_with_code = $this->parseClassCode($code, $class);
} else {
$methods_with_code = array_map(
function ( $method ) use ( $class ) {
return $this->getMethodCode( $class, $method );
},
$methods
);
}
$tokenised_content["methods"] = $methods_with_code;
break;
case T_NAMESPACE:
$namespace = "";
do {
$i ++;
if (!is_string($tokens[$i][0]) && !empty(trim($tokens[$i][1]))) {
$namespace .= $tokens[$i][1];
}
} while (!is_string($tokens[$i][0]));
$tokenised_content["namespace"] = $namespace;
break;
case T_FUNCTION:
$function_name = "\\";
do {
$i ++;
if (!is_string($tokens[$i][0]) && !empty(trim($tokens[$i][1]))) {
$function_name .= $tokens[$i][1];
}
} while (!is_string($tokens[$i][0]));
if (function_exists($function_name)) { //
$tokenised_content["functions"][] = $this->getFunctionCode($function_name);
} else {
$tokenised_content["functions"][] = $this->parseFunctionCode($function_name, $code);
}
}
}
return $tokenised_content;
} | [
"private",
"function",
"addToken",
"(",
"array",
"$",
"tokenised_content",
",",
"array",
"$",
"tokens",
",",
"string",
"$",
"code",
")",
":",
"array",
"{",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"count",
"(",
"$",
"tokens",
")",
";",
"$",
"i",
"++",
")",
"{",
"$",
"token",
"=",
"$",
"tokens",
"[",
"$",
"i",
"]",
";",
"switch",
"(",
"$",
"token",
"[",
"0",
"]",
")",
"{",
"case",
"T_CLASS",
":",
"$",
"class",
"=",
"\"\"",
";",
"do",
"{",
"$",
"i",
"++",
";",
"if",
"(",
"!",
"is_string",
"(",
"$",
"tokens",
"[",
"$",
"i",
"]",
"[",
"0",
"]",
")",
"&&",
"!",
"empty",
"(",
"trim",
"(",
"$",
"tokens",
"[",
"$",
"i",
"]",
"[",
"1",
"]",
")",
")",
")",
"{",
"$",
"class",
".=",
"$",
"tokens",
"[",
"$",
"i",
"]",
"[",
"1",
"]",
";",
"}",
"}",
"while",
"(",
"!",
"is_string",
"(",
"$",
"tokens",
"[",
"$",
"i",
"]",
"[",
"0",
"]",
")",
")",
";",
"// Check for \"extends\"",
"preg_match",
"(",
"\"/(.*?)extends/\"",
",",
"$",
"class",
",",
"$",
"matches",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"matches",
")",
")",
"{",
"$",
"class",
"=",
"$",
"matches",
"[",
"1",
"]",
";",
"}",
"// Check for \"implements\"",
"preg_match",
"(",
"\"/(.*?)implements/\"",
",",
"$",
"class",
",",
"$",
"matches",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"matches",
")",
")",
"{",
"$",
"class",
"=",
"$",
"matches",
"[",
"1",
"]",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"tokenised_content",
")",
")",
"{",
"$",
"class",
"=",
"$",
"tokenised_content",
"[",
"\"namespace\"",
"]",
".",
"\"\\\\\"",
".",
"$",
"class",
";",
"}",
"$",
"tokenised_content",
"[",
"\"class\"",
"]",
"=",
"$",
"class",
";",
"$",
"methods",
"=",
"get_class_methods",
"(",
"$",
"class",
")",
";",
"// $methods will be null if the class hasn't been loaded.",
"if",
"(",
"empty",
"(",
"$",
"methods",
")",
")",
"{",
"$",
"methods_with_code",
"=",
"$",
"this",
"->",
"parseClassCode",
"(",
"$",
"code",
",",
"$",
"class",
")",
";",
"}",
"else",
"{",
"$",
"methods_with_code",
"=",
"array_map",
"(",
"function",
"(",
"$",
"method",
")",
"use",
"(",
"$",
"class",
")",
"{",
"return",
"$",
"this",
"->",
"getMethodCode",
"(",
"$",
"class",
",",
"$",
"method",
")",
";",
"}",
",",
"$",
"methods",
")",
";",
"}",
"$",
"tokenised_content",
"[",
"\"methods\"",
"]",
"=",
"$",
"methods_with_code",
";",
"break",
";",
"case",
"T_NAMESPACE",
":",
"$",
"namespace",
"=",
"\"\"",
";",
"do",
"{",
"$",
"i",
"++",
";",
"if",
"(",
"!",
"is_string",
"(",
"$",
"tokens",
"[",
"$",
"i",
"]",
"[",
"0",
"]",
")",
"&&",
"!",
"empty",
"(",
"trim",
"(",
"$",
"tokens",
"[",
"$",
"i",
"]",
"[",
"1",
"]",
")",
")",
")",
"{",
"$",
"namespace",
".=",
"$",
"tokens",
"[",
"$",
"i",
"]",
"[",
"1",
"]",
";",
"}",
"}",
"while",
"(",
"!",
"is_string",
"(",
"$",
"tokens",
"[",
"$",
"i",
"]",
"[",
"0",
"]",
")",
")",
";",
"$",
"tokenised_content",
"[",
"\"namespace\"",
"]",
"=",
"$",
"namespace",
";",
"break",
";",
"case",
"T_FUNCTION",
":",
"$",
"function_name",
"=",
"\"\\\\\"",
";",
"do",
"{",
"$",
"i",
"++",
";",
"if",
"(",
"!",
"is_string",
"(",
"$",
"tokens",
"[",
"$",
"i",
"]",
"[",
"0",
"]",
")",
"&&",
"!",
"empty",
"(",
"trim",
"(",
"$",
"tokens",
"[",
"$",
"i",
"]",
"[",
"1",
"]",
")",
")",
")",
"{",
"$",
"function_name",
".=",
"$",
"tokens",
"[",
"$",
"i",
"]",
"[",
"1",
"]",
";",
"}",
"}",
"while",
"(",
"!",
"is_string",
"(",
"$",
"tokens",
"[",
"$",
"i",
"]",
"[",
"0",
"]",
")",
")",
";",
"if",
"(",
"function_exists",
"(",
"$",
"function_name",
")",
")",
"{",
"//",
"$",
"tokenised_content",
"[",
"\"functions\"",
"]",
"[",
"]",
"=",
"$",
"this",
"->",
"getFunctionCode",
"(",
"$",
"function_name",
")",
";",
"}",
"else",
"{",
"$",
"tokenised_content",
"[",
"\"functions\"",
"]",
"[",
"]",
"=",
"$",
"this",
"->",
"parseFunctionCode",
"(",
"$",
"function_name",
",",
"$",
"code",
")",
";",
"}",
"}",
"}",
"return",
"$",
"tokenised_content",
";",
"}"
] | @param array $tokenised_content
@param array $tokens
@return array | [
"@param",
"array",
"$tokenised_content",
"@param",
"array",
"$tokens"
] | train | https://github.com/kdaviesnz/Functional/blob/475c2f6dbd8a64258715a25d131398aa10d6f3cf/src/FunctionalModel.php#L413-L492 |
kdaviesnz/Functional | src/FunctionalModel.php | FunctionalModel.getTokenisedContent | private function getTokenisedContent(string $content)
{
$tokens = token_get_all($content);
$tokenised_content = array();
$tokenised_content = $this->addToken($tokenised_content, $tokens, $content);
return $tokenised_content;
} | php | private function getTokenisedContent(string $content)
{
$tokens = token_get_all($content);
$tokenised_content = array();
$tokenised_content = $this->addToken($tokenised_content, $tokens, $content);
return $tokenised_content;
} | [
"private",
"function",
"getTokenisedContent",
"(",
"string",
"$",
"content",
")",
"{",
"$",
"tokens",
"=",
"token_get_all",
"(",
"$",
"content",
")",
";",
"$",
"tokenised_content",
"=",
"array",
"(",
")",
";",
"$",
"tokenised_content",
"=",
"$",
"this",
"->",
"addToken",
"(",
"$",
"tokenised_content",
",",
"$",
"tokens",
",",
"$",
"content",
")",
";",
"return",
"$",
"tokenised_content",
";",
"}"
] | @param string $content
@return array | [
"@param",
"string",
"$content"
] | train | https://github.com/kdaviesnz/Functional/blob/475c2f6dbd8a64258715a25d131398aa10d6f3cf/src/FunctionalModel.php#L499-L510 |
kdaviesnz/Functional | src/FunctionalModel.php | FunctionalModel.getFunctions | public function getFunctions(string $content): array
{
$functions = array();
$tokenised_content = $this->getTokenisedContent($content);
// Check for $tokenised_content["methods"];
if (isset($tokenised_content["methods"])) {
$functions = $tokenised_content["methods"];
} elseif (isset($tokenised_content["functions"])) {
$functions = $tokenised_content["functions"];
}
return $functions;
} | php | public function getFunctions(string $content): array
{
$functions = array();
$tokenised_content = $this->getTokenisedContent($content);
// Check for $tokenised_content["methods"];
if (isset($tokenised_content["methods"])) {
$functions = $tokenised_content["methods"];
} elseif (isset($tokenised_content["functions"])) {
$functions = $tokenised_content["functions"];
}
return $functions;
} | [
"public",
"function",
"getFunctions",
"(",
"string",
"$",
"content",
")",
":",
"array",
"{",
"$",
"functions",
"=",
"array",
"(",
")",
";",
"$",
"tokenised_content",
"=",
"$",
"this",
"->",
"getTokenisedContent",
"(",
"$",
"content",
")",
";",
"// Check for $tokenised_content[\"methods\"];",
"if",
"(",
"isset",
"(",
"$",
"tokenised_content",
"[",
"\"methods\"",
"]",
")",
")",
"{",
"$",
"functions",
"=",
"$",
"tokenised_content",
"[",
"\"methods\"",
"]",
";",
"}",
"elseif",
"(",
"isset",
"(",
"$",
"tokenised_content",
"[",
"\"functions\"",
"]",
")",
")",
"{",
"$",
"functions",
"=",
"$",
"tokenised_content",
"[",
"\"functions\"",
"]",
";",
"}",
"return",
"$",
"functions",
";",
"}"
] | @param string $content
@return array | [
"@param",
"string",
"$content"
] | train | https://github.com/kdaviesnz/Functional/blob/475c2f6dbd8a64258715a25d131398aa10d6f3cf/src/FunctionalModel.php#L517-L533 |
kdaviesnz/Functional | src/FunctionalModel.php | FunctionalModel.isSimilar | private function isSimilar(string $comparisonFunctionContent, string $currentFunctionContent): bool
{
$numberOfcomparisonFunctionContentLines = array_filter(
explode("\n", $comparisonFunctionContent),
function($line){
return !empty(trim($line));
}
);
$currentFunctionContentLines = array_filter(
explode("\n", $currentFunctionContent),
function($line){
return !empty(trim($line));
}
);
if (count($numberOfcomparisonFunctionContentLines) <= 5 || count($currentFunctionContentLines) <= 5 ) {
return false;
}
similar_text($comparisonFunctionContent, $currentFunctionContent, $perc);
return $perc > 60;
} | php | private function isSimilar(string $comparisonFunctionContent, string $currentFunctionContent): bool
{
$numberOfcomparisonFunctionContentLines = array_filter(
explode("\n", $comparisonFunctionContent),
function($line){
return !empty(trim($line));
}
);
$currentFunctionContentLines = array_filter(
explode("\n", $currentFunctionContent),
function($line){
return !empty(trim($line));
}
);
if (count($numberOfcomparisonFunctionContentLines) <= 5 || count($currentFunctionContentLines) <= 5 ) {
return false;
}
similar_text($comparisonFunctionContent, $currentFunctionContent, $perc);
return $perc > 60;
} | [
"private",
"function",
"isSimilar",
"(",
"string",
"$",
"comparisonFunctionContent",
",",
"string",
"$",
"currentFunctionContent",
")",
":",
"bool",
"{",
"$",
"numberOfcomparisonFunctionContentLines",
"=",
"array_filter",
"(",
"explode",
"(",
"\"\\n\"",
",",
"$",
"comparisonFunctionContent",
")",
",",
"function",
"(",
"$",
"line",
")",
"{",
"return",
"!",
"empty",
"(",
"trim",
"(",
"$",
"line",
")",
")",
";",
"}",
")",
";",
"$",
"currentFunctionContentLines",
"=",
"array_filter",
"(",
"explode",
"(",
"\"\\n\"",
",",
"$",
"currentFunctionContent",
")",
",",
"function",
"(",
"$",
"line",
")",
"{",
"return",
"!",
"empty",
"(",
"trim",
"(",
"$",
"line",
")",
")",
";",
"}",
")",
";",
"if",
"(",
"count",
"(",
"$",
"numberOfcomparisonFunctionContentLines",
")",
"<=",
"5",
"||",
"count",
"(",
"$",
"currentFunctionContentLines",
")",
"<=",
"5",
")",
"{",
"return",
"false",
";",
"}",
"similar_text",
"(",
"$",
"comparisonFunctionContent",
",",
"$",
"currentFunctionContent",
",",
"$",
"perc",
")",
";",
"return",
"$",
"perc",
">",
"60",
";",
"}"
] | @param string $comparisonFunctionContent
@param string $currentFunctionContent
@return bool | [
"@param",
"string",
"$comparisonFunctionContent",
"@param",
"string",
"$currentFunctionContent"
] | train | https://github.com/kdaviesnz/Functional/blob/475c2f6dbd8a64258715a25d131398aa10d6f3cf/src/FunctionalModel.php#L541-L564 |
kdaviesnz/Functional | src/FunctionalModel.php | FunctionalModel.stripComments | private function stripComments(string $content): string
{
$tokens = token_get_all($content);
$content_sans_comments = array_reduce(
$tokens,
function ($carry, $token) {
if (is_string($token)) {
// simple 1-character token
return $carry . $token;
} else {
// token array
list($id, $text) = $token;
switch ($id) {
case T_COMMENT:
case T_DOC_COMMENT:
// no action on comments
break;
default:
// anything else -> output "as is"
return $carry . $text;
break;
}
}
return $carry;
},
""
);
return $content_sans_comments;
} | php | private function stripComments(string $content): string
{
$tokens = token_get_all($content);
$content_sans_comments = array_reduce(
$tokens,
function ($carry, $token) {
if (is_string($token)) {
// simple 1-character token
return $carry . $token;
} else {
// token array
list($id, $text) = $token;
switch ($id) {
case T_COMMENT:
case T_DOC_COMMENT:
// no action on comments
break;
default:
// anything else -> output "as is"
return $carry . $text;
break;
}
}
return $carry;
},
""
);
return $content_sans_comments;
} | [
"private",
"function",
"stripComments",
"(",
"string",
"$",
"content",
")",
":",
"string",
"{",
"$",
"tokens",
"=",
"token_get_all",
"(",
"$",
"content",
")",
";",
"$",
"content_sans_comments",
"=",
"array_reduce",
"(",
"$",
"tokens",
",",
"function",
"(",
"$",
"carry",
",",
"$",
"token",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"token",
")",
")",
"{",
"// simple 1-character token",
"return",
"$",
"carry",
".",
"$",
"token",
";",
"}",
"else",
"{",
"// token array",
"list",
"(",
"$",
"id",
",",
"$",
"text",
")",
"=",
"$",
"token",
";",
"switch",
"(",
"$",
"id",
")",
"{",
"case",
"T_COMMENT",
":",
"case",
"T_DOC_COMMENT",
":",
"// no action on comments",
"break",
";",
"default",
":",
"// anything else -> output \"as is\"",
"return",
"$",
"carry",
".",
"$",
"text",
";",
"break",
";",
"}",
"}",
"return",
"$",
"carry",
";",
"}",
",",
"\"\"",
")",
";",
"return",
"$",
"content_sans_comments",
";",
"}"
] | @param string $content
@return string | [
"@param",
"string",
"$content"
] | train | https://github.com/kdaviesnz/Functional/blob/475c2f6dbd8a64258715a25d131398aa10d6f3cf/src/FunctionalModel.php#L571-L601 |
kdaviesnz/Functional | src/FunctionalModel.php | FunctionalModel.parseClassCode | private function parseClassCode(string $code, string $className):array
{
$codeSansComments = $this->stripComments($code);
$lines = array_map("trim", explode("\n", $codeSansComments));
preg_match_all("/p[a-zA-Z]*\sfunction\s+([a-zA-Z\_]*)\(.*?\).*/ui", $code, $matches);
if (!empty($matches[0])) {
$functions = array_map(function ($item, $key) use ($lines, $matches, $className) {
$startLineNumber = array_search($item, $lines);
if ($startLineNumber) {
if (isset($matches[0][$key+1])) {
$endLineNumber = array_search($matches[0][$key+1], $lines);
}
if (isset($endLineNumber) && is_int($endLineNumber)) {
$code = trim(implode("\n", array_slice( $lines, $startLineNumber, $endLineNumber - $startLineNumber )));
} else {
$code = trim(implode("\n", array_slice( $lines, $startLineNumber )));
}
}
return array(
"className" => $className,
"name" => $matches[1][$key],
"code" => isset($code)?$code:""
);
}, $matches[0], array_keys($matches[0]));
return $functions;
}
return array();
} | php | private function parseClassCode(string $code, string $className):array
{
$codeSansComments = $this->stripComments($code);
$lines = array_map("trim", explode("\n", $codeSansComments));
preg_match_all("/p[a-zA-Z]*\sfunction\s+([a-zA-Z\_]*)\(.*?\).*/ui", $code, $matches);
if (!empty($matches[0])) {
$functions = array_map(function ($item, $key) use ($lines, $matches, $className) {
$startLineNumber = array_search($item, $lines);
if ($startLineNumber) {
if (isset($matches[0][$key+1])) {
$endLineNumber = array_search($matches[0][$key+1], $lines);
}
if (isset($endLineNumber) && is_int($endLineNumber)) {
$code = trim(implode("\n", array_slice( $lines, $startLineNumber, $endLineNumber - $startLineNumber )));
} else {
$code = trim(implode("\n", array_slice( $lines, $startLineNumber )));
}
}
return array(
"className" => $className,
"name" => $matches[1][$key],
"code" => isset($code)?$code:""
);
}, $matches[0], array_keys($matches[0]));
return $functions;
}
return array();
} | [
"private",
"function",
"parseClassCode",
"(",
"string",
"$",
"code",
",",
"string",
"$",
"className",
")",
":",
"array",
"{",
"$",
"codeSansComments",
"=",
"$",
"this",
"->",
"stripComments",
"(",
"$",
"code",
")",
";",
"$",
"lines",
"=",
"array_map",
"(",
"\"trim\"",
",",
"explode",
"(",
"\"\\n\"",
",",
"$",
"codeSansComments",
")",
")",
";",
"preg_match_all",
"(",
"\"/p[a-zA-Z]*\\sfunction\\s+([a-zA-Z\\_]*)\\(.*?\\).*/ui\"",
",",
"$",
"code",
",",
"$",
"matches",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"matches",
"[",
"0",
"]",
")",
")",
"{",
"$",
"functions",
"=",
"array_map",
"(",
"function",
"(",
"$",
"item",
",",
"$",
"key",
")",
"use",
"(",
"$",
"lines",
",",
"$",
"matches",
",",
"$",
"className",
")",
"{",
"$",
"startLineNumber",
"=",
"array_search",
"(",
"$",
"item",
",",
"$",
"lines",
")",
";",
"if",
"(",
"$",
"startLineNumber",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"matches",
"[",
"0",
"]",
"[",
"$",
"key",
"+",
"1",
"]",
")",
")",
"{",
"$",
"endLineNumber",
"=",
"array_search",
"(",
"$",
"matches",
"[",
"0",
"]",
"[",
"$",
"key",
"+",
"1",
"]",
",",
"$",
"lines",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"endLineNumber",
")",
"&&",
"is_int",
"(",
"$",
"endLineNumber",
")",
")",
"{",
"$",
"code",
"=",
"trim",
"(",
"implode",
"(",
"\"\\n\"",
",",
"array_slice",
"(",
"$",
"lines",
",",
"$",
"startLineNumber",
",",
"$",
"endLineNumber",
"-",
"$",
"startLineNumber",
")",
")",
")",
";",
"}",
"else",
"{",
"$",
"code",
"=",
"trim",
"(",
"implode",
"(",
"\"\\n\"",
",",
"array_slice",
"(",
"$",
"lines",
",",
"$",
"startLineNumber",
")",
")",
")",
";",
"}",
"}",
"return",
"array",
"(",
"\"className\"",
"=>",
"$",
"className",
",",
"\"name\"",
"=>",
"$",
"matches",
"[",
"1",
"]",
"[",
"$",
"key",
"]",
",",
"\"code\"",
"=>",
"isset",
"(",
"$",
"code",
")",
"?",
"$",
"code",
":",
"\"\"",
")",
";",
"}",
",",
"$",
"matches",
"[",
"0",
"]",
",",
"array_keys",
"(",
"$",
"matches",
"[",
"0",
"]",
")",
")",
";",
"return",
"$",
"functions",
";",
"}",
"return",
"array",
"(",
")",
";",
"}"
] | @param string $code
@return array | [
"@param",
"string",
"$code"
] | train | https://github.com/kdaviesnz/Functional/blob/475c2f6dbd8a64258715a25d131398aa10d6f3cf/src/FunctionalModel.php#L608-L644 |
Vectrex/vxPHP | src/Webpage/DefaultMenuAuthenticator.php | DefaultMenuAuthenticator.authenticateMenuEntries | private function authenticateMenuEntries(Menu $menu, array $userRoles) {
foreach($menu->getEntries() as $e) {
if(!$e->getAuth()) {
$e->setAttribute('display', NULL);
}
else {
$e->setAttribute('display', 'none');
foreach($userRoles as $role) {
if($e->isAuthenticatedByRole($role)) {
$e->setAttribute('display', NULL);
break;
}
}
}
}
} | php | private function authenticateMenuEntries(Menu $menu, array $userRoles) {
foreach($menu->getEntries() as $e) {
if(!$e->getAuth()) {
$e->setAttribute('display', NULL);
}
else {
$e->setAttribute('display', 'none');
foreach($userRoles as $role) {
if($e->isAuthenticatedByRole($role)) {
$e->setAttribute('display', NULL);
break;
}
}
}
}
} | [
"private",
"function",
"authenticateMenuEntries",
"(",
"Menu",
"$",
"menu",
",",
"array",
"$",
"userRoles",
")",
"{",
"foreach",
"(",
"$",
"menu",
"->",
"getEntries",
"(",
")",
"as",
"$",
"e",
")",
"{",
"if",
"(",
"!",
"$",
"e",
"->",
"getAuth",
"(",
")",
")",
"{",
"$",
"e",
"->",
"setAttribute",
"(",
"'display'",
",",
"NULL",
")",
";",
"}",
"else",
"{",
"$",
"e",
"->",
"setAttribute",
"(",
"'display'",
",",
"'none'",
")",
";",
"foreach",
"(",
"$",
"userRoles",
"as",
"$",
"role",
")",
"{",
"if",
"(",
"$",
"e",
"->",
"isAuthenticatedByRole",
"(",
"$",
"role",
")",
")",
"{",
"$",
"e",
"->",
"setAttribute",
"(",
"'display'",
",",
"NULL",
")",
";",
"break",
";",
"}",
"}",
"}",
"}",
"}"
] | authenticate menu entries by checking each one against the
user's roles if necessary
@param Menu $menu
@param Role[] $userRoles | [
"authenticate",
"menu",
"entries",
"by",
"checking",
"each",
"one",
"against",
"the",
"user",
"s",
"roles",
"if",
"necessary"
] | train | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Webpage/DefaultMenuAuthenticator.php#L115-L138 |
satori-php/middleware | src/Capsule.php | Capsule.offsetGet | public function offsetGet($key)
{
if (isset($this->granules[$key])) {
return $this->granules[$key];
}
throw new \OutOfBoundsException(sprintf('Granule "%s" is not defined.', $key));
} | php | public function offsetGet($key)
{
if (isset($this->granules[$key])) {
return $this->granules[$key];
}
throw new \OutOfBoundsException(sprintf('Granule "%s" is not defined.', $key));
} | [
"public",
"function",
"offsetGet",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"granules",
"[",
"$",
"key",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"granules",
"[",
"$",
"key",
"]",
";",
"}",
"throw",
"new",
"\\",
"OutOfBoundsException",
"(",
"sprintf",
"(",
"'Granule \"%s\" is not defined.'",
",",
"$",
"key",
")",
")",
";",
"}"
] | Returns a granule.
@param string $key The unique key of the granule.
@throws \OutOfBoundsException If the granule is not defined.
@return mixed | [
"Returns",
"a",
"granule",
"."
] | train | https://github.com/satori-php/middleware/blob/d43051baef9ccd2802e0a09e3b7aaaf72784dc7e/src/Capsule.php#L55-L62 |
goncalomb/asbestos | src/classes/Http/HeaderContainer.php | HeaderContainer.setHeader | public function setHeader($name, $value, $replace=true)
{
if ($replace) {
$this->removeHeader($name);
}
$this->_headers[] = [$name, $value];
} | php | public function setHeader($name, $value, $replace=true)
{
if ($replace) {
$this->removeHeader($name);
}
$this->_headers[] = [$name, $value];
} | [
"public",
"function",
"setHeader",
"(",
"$",
"name",
",",
"$",
"value",
",",
"$",
"replace",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"replace",
")",
"{",
"$",
"this",
"->",
"removeHeader",
"(",
"$",
"name",
")",
";",
"}",
"$",
"this",
"->",
"_headers",
"[",
"]",
"=",
"[",
"$",
"name",
",",
"$",
"value",
"]",
";",
"}"
] | Set header.
@param string $name The header name.
@param string $value The header value.
@param bool $replace Replace the current value or append. | [
"Set",
"header",
"."
] | train | https://github.com/goncalomb/asbestos/blob/14a875b6c125cfeefe4eb1c3c524500eb8a51d04/src/classes/Http/HeaderContainer.php#L35-L41 |
goncalomb/asbestos | src/classes/Http/HeaderContainer.php | HeaderContainer.getHeader | public function getHeader($name, $all=false)
{
$nameLower = strtolower($name);
if ($all) {
$values = [];
foreach ($this->_headers as &$h) {
if ($h && strtolower($h[0]) == $nameLower) {
$values[] = $h[1];
}
}
return $values;
} else {
foreach ($this->_headers as &$h) {
if ($h && strtolower($h[0]) == $nameLower) {
return $h[1];
}
}
}
return null;
} | php | public function getHeader($name, $all=false)
{
$nameLower = strtolower($name);
if ($all) {
$values = [];
foreach ($this->_headers as &$h) {
if ($h && strtolower($h[0]) == $nameLower) {
$values[] = $h[1];
}
}
return $values;
} else {
foreach ($this->_headers as &$h) {
if ($h && strtolower($h[0]) == $nameLower) {
return $h[1];
}
}
}
return null;
} | [
"public",
"function",
"getHeader",
"(",
"$",
"name",
",",
"$",
"all",
"=",
"false",
")",
"{",
"$",
"nameLower",
"=",
"strtolower",
"(",
"$",
"name",
")",
";",
"if",
"(",
"$",
"all",
")",
"{",
"$",
"values",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"_headers",
"as",
"&",
"$",
"h",
")",
"{",
"if",
"(",
"$",
"h",
"&&",
"strtolower",
"(",
"$",
"h",
"[",
"0",
"]",
")",
"==",
"$",
"nameLower",
")",
"{",
"$",
"values",
"[",
"]",
"=",
"$",
"h",
"[",
"1",
"]",
";",
"}",
"}",
"return",
"$",
"values",
";",
"}",
"else",
"{",
"foreach",
"(",
"$",
"this",
"->",
"_headers",
"as",
"&",
"$",
"h",
")",
"{",
"if",
"(",
"$",
"h",
"&&",
"strtolower",
"(",
"$",
"h",
"[",
"0",
"]",
")",
"==",
"$",
"nameLower",
")",
"{",
"return",
"$",
"h",
"[",
"1",
"]",
";",
"}",
"}",
"}",
"return",
"null",
";",
"}"
] | Get header.
@param string $name The header name.
@param bool $all Return all values or just the first.
@return string|array The header value. | [
"Get",
"header",
"."
] | train | https://github.com/goncalomb/asbestos/blob/14a875b6c125cfeefe4eb1c3c524500eb8a51d04/src/classes/Http/HeaderContainer.php#L50-L69 |
goncalomb/asbestos | src/classes/Http/HeaderContainer.php | HeaderContainer.removeHeader | public function removeHeader($name)
{
$nameLower = strtolower($name);
foreach ($this->_headers as &$h) {
if ($h && strtolower($h[0]) == $nameLower) {
$h = null;
}
}
} | php | public function removeHeader($name)
{
$nameLower = strtolower($name);
foreach ($this->_headers as &$h) {
if ($h && strtolower($h[0]) == $nameLower) {
$h = null;
}
}
} | [
"public",
"function",
"removeHeader",
"(",
"$",
"name",
")",
"{",
"$",
"nameLower",
"=",
"strtolower",
"(",
"$",
"name",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"_headers",
"as",
"&",
"$",
"h",
")",
"{",
"if",
"(",
"$",
"h",
"&&",
"strtolower",
"(",
"$",
"h",
"[",
"0",
"]",
")",
"==",
"$",
"nameLower",
")",
"{",
"$",
"h",
"=",
"null",
";",
"}",
"}",
"}"
] | Remove header.
@param $name The header name. | [
"Remove",
"header",
"."
] | train | https://github.com/goncalomb/asbestos/blob/14a875b6c125cfeefe4eb1c3c524500eb8a51d04/src/classes/Http/HeaderContainer.php#L76-L84 |
vainproject/vain-blog | src/Blog/Policies/CommentPolicy.php | CommentPolicy.create | public function create($user, $post)
{
return $this->postPolicy->create($user, $post)
&& $user->can('blog.comment.edit');
} | php | public function create($user, $post)
{
return $this->postPolicy->create($user, $post)
&& $user->can('blog.comment.edit');
} | [
"public",
"function",
"create",
"(",
"$",
"user",
",",
"$",
"post",
")",
"{",
"return",
"$",
"this",
"->",
"postPolicy",
"->",
"create",
"(",
"$",
"user",
",",
"$",
"post",
")",
"&&",
"$",
"user",
"->",
"can",
"(",
"'blog.comment.edit'",
")",
";",
"}"
] | @param User $user
@param Post $post
@return bool | [
"@param",
"User",
"$user",
"@param",
"Post",
"$post"
] | train | https://github.com/vainproject/vain-blog/blob/e6b7b590b2aa86f8de4e0e5a984a97c3a342b8c0/src/Blog/Policies/CommentPolicy.php#L26-L30 |
vainproject/vain-blog | src/Blog/Policies/CommentPolicy.php | CommentPolicy.edit | public function edit($user, $comment)
{
return $this->postPolicy->show($user, $comment->post)
|| $user->owns($comment)
|| $user->can('blog.comment.edit');
} | php | public function edit($user, $comment)
{
return $this->postPolicy->show($user, $comment->post)
|| $user->owns($comment)
|| $user->can('blog.comment.edit');
} | [
"public",
"function",
"edit",
"(",
"$",
"user",
",",
"$",
"comment",
")",
"{",
"return",
"$",
"this",
"->",
"postPolicy",
"->",
"show",
"(",
"$",
"user",
",",
"$",
"comment",
"->",
"post",
")",
"||",
"$",
"user",
"->",
"owns",
"(",
"$",
"comment",
")",
"||",
"$",
"user",
"->",
"can",
"(",
"'blog.comment.edit'",
")",
";",
"}"
] | @param User $user
@param Comment $comment
@return bool | [
"@param",
"User",
"$user",
"@param",
"Comment",
"$comment"
] | train | https://github.com/vainproject/vain-blog/blob/e6b7b590b2aa86f8de4e0e5a984a97c3a342b8c0/src/Blog/Policies/CommentPolicy.php#L38-L43 |
bytic/orm | src/Relations/HasAndBelongsToMany.php | HasAndBelongsToMany.getLinkQuery | public function getLinkQuery($specific = true)
{
$query = $this->getDB()->newSelect();
$query->from($this->getTable());
if ($specific) {
$query = $this->populateQuerySpecific($query);
}
return $query;
} | php | public function getLinkQuery($specific = true)
{
$query = $this->getDB()->newSelect();
$query->from($this->getTable());
if ($specific) {
$query = $this->populateQuerySpecific($query);
}
return $query;
} | [
"public",
"function",
"getLinkQuery",
"(",
"$",
"specific",
"=",
"true",
")",
"{",
"$",
"query",
"=",
"$",
"this",
"->",
"getDB",
"(",
")",
"->",
"newSelect",
"(",
")",
";",
"$",
"query",
"->",
"from",
"(",
"$",
"this",
"->",
"getTable",
"(",
")",
")",
";",
"if",
"(",
"$",
"specific",
")",
"{",
"$",
"query",
"=",
"$",
"this",
"->",
"populateQuerySpecific",
"(",
"$",
"query",
")",
";",
"}",
"return",
"$",
"query",
";",
"}"
] | Simple select query from the link table
@param bool $specific
@return SelectQuery | [
"Simple",
"select",
"query",
"from",
"the",
"link",
"table"
] | train | https://github.com/bytic/orm/blob/8d9a79b47761af0bfd9b8d1d28c83221dcac0de0/src/Relations/HasAndBelongsToMany.php#L116-L126 |
ARCANESOFT/SEO | src/Http/Controllers/Admin/SpammersController.php | SpammersController.index | public function index(Request $request)
{
$spammers = $this->paginate($this->blocker->all(), $request, $this->perPage);
$this->setTitle($title = trans('seo::spammers.titles.spammers-list'));
$this->addBreadcrumb($title);
return $this->view('admin.spammers.index', compact('spammers'));
} | php | public function index(Request $request)
{
$spammers = $this->paginate($this->blocker->all(), $request, $this->perPage);
$this->setTitle($title = trans('seo::spammers.titles.spammers-list'));
$this->addBreadcrumb($title);
return $this->view('admin.spammers.index', compact('spammers'));
} | [
"public",
"function",
"index",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"spammers",
"=",
"$",
"this",
"->",
"paginate",
"(",
"$",
"this",
"->",
"blocker",
"->",
"all",
"(",
")",
",",
"$",
"request",
",",
"$",
"this",
"->",
"perPage",
")",
";",
"$",
"this",
"->",
"setTitle",
"(",
"$",
"title",
"=",
"trans",
"(",
"'seo::spammers.titles.spammers-list'",
")",
")",
";",
"$",
"this",
"->",
"addBreadcrumb",
"(",
"$",
"title",
")",
";",
"return",
"$",
"this",
"->",
"view",
"(",
"'admin.spammers.index'",
",",
"compact",
"(",
"'spammers'",
")",
")",
";",
"}"
] | List all the spammers.
@param \Illuminate\Http\Request $request
@return \Illuminate\View\View | [
"List",
"all",
"the",
"spammers",
"."
] | train | https://github.com/ARCANESOFT/SEO/blob/ce6d6135d55e8b2fd43cf7923839b4791b7c7ad2/src/Http/Controllers/Admin/SpammersController.php#L67-L75 |
formapro/BadaBoom | src/BadaBoom/ChainNode/Decorator/SafeChainNodeDecorator.php | SafeChainNodeDecorator.handle | public function handle(\Exception $exception, DataHolderInterface $data)
{
try {
$this->chainNode->handle($exception, $data);
} catch (\Exception $internalException) {
$chainExceptions = $data->get('chain_exceptions', array());
$chainExceptions[] = array(
'chain' => get_class($this->chainNode),
'class' => get_class($internalException),
'message' => $internalException->getMessage(),
'code' => $internalException->getCode(),
'line' => $internalException->getLine(),
'file' => $internalException->getFile(),
'has_previous' => $internalException->getPrevious() instanceof \Exception,
);
$data->set('chain_exceptions', $chainExceptions);
}
} | php | public function handle(\Exception $exception, DataHolderInterface $data)
{
try {
$this->chainNode->handle($exception, $data);
} catch (\Exception $internalException) {
$chainExceptions = $data->get('chain_exceptions', array());
$chainExceptions[] = array(
'chain' => get_class($this->chainNode),
'class' => get_class($internalException),
'message' => $internalException->getMessage(),
'code' => $internalException->getCode(),
'line' => $internalException->getLine(),
'file' => $internalException->getFile(),
'has_previous' => $internalException->getPrevious() instanceof \Exception,
);
$data->set('chain_exceptions', $chainExceptions);
}
} | [
"public",
"function",
"handle",
"(",
"\\",
"Exception",
"$",
"exception",
",",
"DataHolderInterface",
"$",
"data",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"chainNode",
"->",
"handle",
"(",
"$",
"exception",
",",
"$",
"data",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"internalException",
")",
"{",
"$",
"chainExceptions",
"=",
"$",
"data",
"->",
"get",
"(",
"'chain_exceptions'",
",",
"array",
"(",
")",
")",
";",
"$",
"chainExceptions",
"[",
"]",
"=",
"array",
"(",
"'chain'",
"=>",
"get_class",
"(",
"$",
"this",
"->",
"chainNode",
")",
",",
"'class'",
"=>",
"get_class",
"(",
"$",
"internalException",
")",
",",
"'message'",
"=>",
"$",
"internalException",
"->",
"getMessage",
"(",
")",
",",
"'code'",
"=>",
"$",
"internalException",
"->",
"getCode",
"(",
")",
",",
"'line'",
"=>",
"$",
"internalException",
"->",
"getLine",
"(",
")",
",",
"'file'",
"=>",
"$",
"internalException",
"->",
"getFile",
"(",
")",
",",
"'has_previous'",
"=>",
"$",
"internalException",
"->",
"getPrevious",
"(",
")",
"instanceof",
"\\",
"Exception",
",",
")",
";",
"$",
"data",
"->",
"set",
"(",
"'chain_exceptions'",
",",
"$",
"chainExceptions",
")",
";",
"}",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/formapro/BadaBoom/blob/db42dbc4a43f7070586229c0e6075fe3a781e04e/src/BadaBoom/ChainNode/Decorator/SafeChainNodeDecorator.php#L26-L44 |
netbull/CoreBundle | Form/Type/MoneyType.php | MoneyType.buildForm | public function buildForm(FormBuilderInterface $builder, array $options)
{
$transformer = $options['localize'] ?
new MoneyToLocalizedStringTransformer(
$options['scale'],
$options['grouping'],
null,
$options['divisor']
) :
new MoneyToStringTransformer(
$options['thousands_separator'],
$options['decimal_separator'],
$options['scale'],
$options['grouping'],
null,
$options['divisor']
);
$builder->addViewTransformer($transformer);
} | php | public function buildForm(FormBuilderInterface $builder, array $options)
{
$transformer = $options['localize'] ?
new MoneyToLocalizedStringTransformer(
$options['scale'],
$options['grouping'],
null,
$options['divisor']
) :
new MoneyToStringTransformer(
$options['thousands_separator'],
$options['decimal_separator'],
$options['scale'],
$options['grouping'],
null,
$options['divisor']
);
$builder->addViewTransformer($transformer);
} | [
"public",
"function",
"buildForm",
"(",
"FormBuilderInterface",
"$",
"builder",
",",
"array",
"$",
"options",
")",
"{",
"$",
"transformer",
"=",
"$",
"options",
"[",
"'localize'",
"]",
"?",
"new",
"MoneyToLocalizedStringTransformer",
"(",
"$",
"options",
"[",
"'scale'",
"]",
",",
"$",
"options",
"[",
"'grouping'",
"]",
",",
"null",
",",
"$",
"options",
"[",
"'divisor'",
"]",
")",
":",
"new",
"MoneyToStringTransformer",
"(",
"$",
"options",
"[",
"'thousands_separator'",
"]",
",",
"$",
"options",
"[",
"'decimal_separator'",
"]",
",",
"$",
"options",
"[",
"'scale'",
"]",
",",
"$",
"options",
"[",
"'grouping'",
"]",
",",
"null",
",",
"$",
"options",
"[",
"'divisor'",
"]",
")",
";",
"$",
"builder",
"->",
"addViewTransformer",
"(",
"$",
"transformer",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/netbull/CoreBundle/blob/0bacc1d9e4733b6da613027400c48421e5a14645/Form/Type/MoneyType.php#L21-L40 |
AnonymPHP/Anonym-Database | Mode/Read.php | Read.select | public function select($select = null)
{
$this->string['select'] = $this->useBuilder('select')
->select($select, $this->cleanThis());
return $this;
} | php | public function select($select = null)
{
$this->string['select'] = $this->useBuilder('select')
->select($select, $this->cleanThis());
return $this;
} | [
"public",
"function",
"select",
"(",
"$",
"select",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"string",
"[",
"'select'",
"]",
"=",
"$",
"this",
"->",
"useBuilder",
"(",
"'select'",
")",
"->",
"select",
"(",
"$",
"select",
",",
"$",
"this",
"->",
"cleanThis",
"(",
")",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Select sorgusu olu�turur
@param string $select
@return $this | [
"Select",
"sorgusu",
"olu�turur"
] | train | https://github.com/AnonymPHP/Anonym-Database/blob/4d034219e0e3eb2833fa53204e9f52a74a9a7e4b/Mode/Read.php#L80-L87 |
AnonymPHP/Anonym-Database | Mode/Read.php | Read.order | public function order($order, $type = 'DESC')
{
$this->string['order'] .= $this->useBuilder('order')
->order($order, $type);
return $this;
} | php | public function order($order, $type = 'DESC')
{
$this->string['order'] .= $this->useBuilder('order')
->order($order, $type);
return $this;
} | [
"public",
"function",
"order",
"(",
"$",
"order",
",",
"$",
"type",
"=",
"'DESC'",
")",
"{",
"$",
"this",
"->",
"string",
"[",
"'order'",
"]",
".=",
"$",
"this",
"->",
"useBuilder",
"(",
"'order'",
")",
"->",
"order",
"(",
"$",
"order",
",",
"$",
"type",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Order Sorgusu oluşturur
@param string $order
@param string $type
@return \Anonym\Components\Database\Mode\Read | [
"Order",
"Sorgusu",
"oluşturur"
] | train | https://github.com/AnonymPHP/Anonym-Database/blob/4d034219e0e3eb2833fa53204e9f52a74a9a7e4b/Mode/Read.php#L107-L114 |
AnonymPHP/Anonym-Database | Mode/Read.php | Read.join | public function join($join = [])
{
$this->string['join'] = $this->useBuilder('join')->join($join, $this->getBase()->getTable());
return $this;
} | php | public function join($join = [])
{
$this->string['join'] = $this->useBuilder('join')->join($join, $this->getBase()->getTable());
return $this;
} | [
"public",
"function",
"join",
"(",
"$",
"join",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"string",
"[",
"'join'",
"]",
"=",
"$",
"this",
"->",
"useBuilder",
"(",
"'join'",
")",
"->",
"join",
"(",
"$",
"join",
",",
"$",
"this",
"->",
"getBase",
"(",
")",
"->",
"getTable",
"(",
")",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Join komutu ekler
@param array $join
@return $this | [
"Join",
"komutu",
"ekler"
] | train | https://github.com/AnonymPHP/Anonym-Database/blob/4d034219e0e3eb2833fa53204e9f52a74a9a7e4b/Mode/Read.php#L122-L126 |
FlexModel/FlexModelBundle | DataCollector/FlexModelDataCollector.php | FlexModelDataCollector.collect | public function collect(Request $request, Response $response, Exception $exception = null)
{
$objects = array();
$objectNames = $this->flexModel->getObjectNames();
foreach ($objectNames as $objectName) {
$fieldNames = $this->flexModel->getFieldNames($objectName);
$objects[] = array(
'objectName' => $objectName,
'fieldNames' => $fieldNames,
);
}
$this->data = array(
'objects' => $objects,
);
} | php | public function collect(Request $request, Response $response, Exception $exception = null)
{
$objects = array();
$objectNames = $this->flexModel->getObjectNames();
foreach ($objectNames as $objectName) {
$fieldNames = $this->flexModel->getFieldNames($objectName);
$objects[] = array(
'objectName' => $objectName,
'fieldNames' => $fieldNames,
);
}
$this->data = array(
'objects' => $objects,
);
} | [
"public",
"function",
"collect",
"(",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
",",
"Exception",
"$",
"exception",
"=",
"null",
")",
"{",
"$",
"objects",
"=",
"array",
"(",
")",
";",
"$",
"objectNames",
"=",
"$",
"this",
"->",
"flexModel",
"->",
"getObjectNames",
"(",
")",
";",
"foreach",
"(",
"$",
"objectNames",
"as",
"$",
"objectName",
")",
"{",
"$",
"fieldNames",
"=",
"$",
"this",
"->",
"flexModel",
"->",
"getFieldNames",
"(",
"$",
"objectName",
")",
";",
"$",
"objects",
"[",
"]",
"=",
"array",
"(",
"'objectName'",
"=>",
"$",
"objectName",
",",
"'fieldNames'",
"=>",
"$",
"fieldNames",
",",
")",
";",
"}",
"$",
"this",
"->",
"data",
"=",
"array",
"(",
"'objects'",
"=>",
"$",
"objects",
",",
")",
";",
"}"
] | Collect the specific FlexModel data for the Symfony Profiler.
@param Request $request
@param Response $response
@param Exception $exception | [
"Collect",
"the",
"specific",
"FlexModel",
"data",
"for",
"the",
"Symfony",
"Profiler",
"."
] | train | https://github.com/FlexModel/FlexModelBundle/blob/7b4720d25b0dc6baf29b1da8ad7c67dfb2686460/DataCollector/FlexModelDataCollector.php#L42-L58 |
PascalKleindienst/simple-api-client | src/Console/AbstractScaffoldingCommand.php | AbstractScaffoldingCommand.configure | protected function configure()
{
$this
->setName('create:' . $this->type)
->setDescription('Create a new ' . ucfirst($this->type))
->addArgument(
'namespace',
InputArgument::REQUIRED,
'Namespace in Dot-Notation e.g. Acme.Api'
)
->addArgument(
'name',
InputArgument::REQUIRED,
'Name of the ' . ucfirst($this->type)
)
;
} | php | protected function configure()
{
$this
->setName('create:' . $this->type)
->setDescription('Create a new ' . ucfirst($this->type))
->addArgument(
'namespace',
InputArgument::REQUIRED,
'Namespace in Dot-Notation e.g. Acme.Api'
)
->addArgument(
'name',
InputArgument::REQUIRED,
'Name of the ' . ucfirst($this->type)
)
;
} | [
"protected",
"function",
"configure",
"(",
")",
"{",
"$",
"this",
"->",
"setName",
"(",
"'create:'",
".",
"$",
"this",
"->",
"type",
")",
"->",
"setDescription",
"(",
"'Create a new '",
".",
"ucfirst",
"(",
"$",
"this",
"->",
"type",
")",
")",
"->",
"addArgument",
"(",
"'namespace'",
",",
"InputArgument",
"::",
"REQUIRED",
",",
"'Namespace in Dot-Notation e.g. Acme.Api'",
")",
"->",
"addArgument",
"(",
"'name'",
",",
"InputArgument",
"::",
"REQUIRED",
",",
"'Name of the '",
".",
"ucfirst",
"(",
"$",
"this",
"->",
"type",
")",
")",
";",
"}"
] | Command Config | [
"Command",
"Config"
] | train | https://github.com/PascalKleindienst/simple-api-client/blob/f4e20aa65bb9c340b8aff78acaede7dc62cd2105/src/Console/AbstractScaffoldingCommand.php#L23-L39 |
phata/widgetfy | src/Site/OnCc.php | OnCc.preprocess | public static function preprocess($url_parsed) {
$url = URL::build($url_parsed);
if (preg_match('/^[\w\/]*\/index.html$/', $url_parsed['path']) == 1) {
parse_str($url_parsed['query'], $args);
if (isset($args['s']) && isset($args['i'])) {
return array(
'url' => $url,
);
}
}
return FALSE;
} | php | public static function preprocess($url_parsed) {
$url = URL::build($url_parsed);
if (preg_match('/^[\w\/]*\/index.html$/', $url_parsed['path']) == 1) {
parse_str($url_parsed['query'], $args);
if (isset($args['s']) && isset($args['i'])) {
return array(
'url' => $url,
);
}
}
return FALSE;
} | [
"public",
"static",
"function",
"preprocess",
"(",
"$",
"url_parsed",
")",
"{",
"$",
"url",
"=",
"URL",
"::",
"build",
"(",
"$",
"url_parsed",
")",
";",
"if",
"(",
"preg_match",
"(",
"'/^[\\w\\/]*\\/index.html$/'",
",",
"$",
"url_parsed",
"[",
"'path'",
"]",
")",
"==",
"1",
")",
"{",
"parse_str",
"(",
"$",
"url_parsed",
"[",
"'query'",
"]",
",",
"$",
"args",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"args",
"[",
"'s'",
"]",
")",
"&&",
"isset",
"(",
"$",
"args",
"[",
"'i'",
"]",
")",
")",
"{",
"return",
"array",
"(",
"'url'",
"=>",
"$",
"url",
",",
")",
";",
"}",
"}",
"return",
"FALSE",
";",
"}"
] | Implements Phata\Widgetfy\Site\Common::translate
preprocess the URL
by this site adapter
@param string[] $url_parsed result of parse_url($url)
@return mixed array of preprocess result; boolean FALSE if not translatable | [
"Implements",
"Phata",
"\\",
"Widgetfy",
"\\",
"Site",
"\\",
"Common",
"::",
"translate"
] | train | https://github.com/phata/widgetfy/blob/00102c35ec5267b42c627f1e34b8e64a7dd3590c/src/Site/OnCc.php#L54-L65 |
phata/widgetfy | src/Site/OnCc.php | OnCc.translate | public static function translate($info, $options=array()) {
// default dimension is 680 x 383
$d = Dimension::fromOptions($options, array(
'factor' => 0.5632,
'default_width'=> 680,
'max_width' => 960,
));
return array(
'type' => 'iframe',
'html' => '<iframe src="'.$info['url'].'" '.
'allowtransparency="true" allowfullscreen="true" '.
'scrolling="no" border="0" frameborder="0" '.
$d->toAttr().' ></iframe>',
'dimension' => $d,
);
} | php | public static function translate($info, $options=array()) {
// default dimension is 680 x 383
$d = Dimension::fromOptions($options, array(
'factor' => 0.5632,
'default_width'=> 680,
'max_width' => 960,
));
return array(
'type' => 'iframe',
'html' => '<iframe src="'.$info['url'].'" '.
'allowtransparency="true" allowfullscreen="true" '.
'scrolling="no" border="0" frameborder="0" '.
$d->toAttr().' ></iframe>',
'dimension' => $d,
);
} | [
"public",
"static",
"function",
"translate",
"(",
"$",
"info",
",",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"// default dimension is 680 x 383",
"$",
"d",
"=",
"Dimension",
"::",
"fromOptions",
"(",
"$",
"options",
",",
"array",
"(",
"'factor'",
"=>",
"0.5632",
",",
"'default_width'",
"=>",
"680",
",",
"'max_width'",
"=>",
"960",
",",
")",
")",
";",
"return",
"array",
"(",
"'type'",
"=>",
"'iframe'",
",",
"'html'",
"=>",
"'<iframe src=\"'",
".",
"$",
"info",
"[",
"'url'",
"]",
".",
"'\" '",
".",
"'allowtransparency=\"true\" allowfullscreen=\"true\" '",
".",
"'scrolling=\"no\" border=\"0\" frameborder=\"0\" '",
".",
"$",
"d",
"->",
"toAttr",
"(",
")",
".",
"' ></iframe>'",
",",
"'dimension'",
"=>",
"$",
"d",
",",
")",
";",
"}"
] | Implements Phata\Widgetfy\Site\Common::translate
translate the provided URL into
HTML embed code of it
@param mixed[] $info array of preprocessed url information
@param mixed[] $options array of options
@return mixed[] array of embed information or NULL if not applicable | [
"Implements",
"Phata",
"\\",
"Widgetfy",
"\\",
"Site",
"\\",
"Common",
"::",
"translate"
] | train | https://github.com/phata/widgetfy/blob/00102c35ec5267b42c627f1e34b8e64a7dd3590c/src/Site/OnCc.php#L76-L91 |
Topolis/Filter | src/Types/EnumFilter.php | EnumFilter.filter | public function filter($value) {
$testvalue = $this->options["insensitive"] ? strtolower($value): $value;
// Value is not in enumeration
if (!in_array($testvalue, $this->enumeration, $this->options["strict"]))
return Filter::ERR_INVALID;
$found = array_search($value, $this->enumeration, $this->options["strict"]);
return $this->options["values"][$found];
} | php | public function filter($value) {
$testvalue = $this->options["insensitive"] ? strtolower($value): $value;
// Value is not in enumeration
if (!in_array($testvalue, $this->enumeration, $this->options["strict"]))
return Filter::ERR_INVALID;
$found = array_search($value, $this->enumeration, $this->options["strict"]);
return $this->options["values"][$found];
} | [
"public",
"function",
"filter",
"(",
"$",
"value",
")",
"{",
"$",
"testvalue",
"=",
"$",
"this",
"->",
"options",
"[",
"\"insensitive\"",
"]",
"?",
"strtolower",
"(",
"$",
"value",
")",
":",
"$",
"value",
";",
"// Value is not in enumeration",
"if",
"(",
"!",
"in_array",
"(",
"$",
"testvalue",
",",
"$",
"this",
"->",
"enumeration",
",",
"$",
"this",
"->",
"options",
"[",
"\"strict\"",
"]",
")",
")",
"return",
"Filter",
"::",
"ERR_INVALID",
";",
"$",
"found",
"=",
"array_search",
"(",
"$",
"value",
",",
"$",
"this",
"->",
"enumeration",
",",
"$",
"this",
"->",
"options",
"[",
"\"strict\"",
"]",
")",
";",
"return",
"$",
"this",
"->",
"options",
"[",
"\"values\"",
"]",
"[",
"$",
"found",
"]",
";",
"}"
] | execute the filter on a value
@param mixed $value
@return mixed | [
"execute",
"the",
"filter",
"on",
"a",
"value"
] | train | https://github.com/Topolis/Filter/blob/6208a6270490c39f028248dc99f21b3e816e388b/src/Types/EnumFilter.php#L53-L64 |
fxpio/fxp-doctrine-extra | Util/ManagerUtils.php | ManagerUtils.getManager | public static function getManager(ManagerRegistry $or, $class)
{
$manager = $or->getManagerForClass($class);
if (null === $manager) {
foreach ($or->getManagers() as $objectManager) {
if ($objectManager->getMetadataFactory()->hasMetadataFor($class)
&& self::isValidManager($objectManager, $class)) {
$manager = $objectManager;
break;
}
}
}
return $manager;
} | php | public static function getManager(ManagerRegistry $or, $class)
{
$manager = $or->getManagerForClass($class);
if (null === $manager) {
foreach ($or->getManagers() as $objectManager) {
if ($objectManager->getMetadataFactory()->hasMetadataFor($class)
&& self::isValidManager($objectManager, $class)) {
$manager = $objectManager;
break;
}
}
}
return $manager;
} | [
"public",
"static",
"function",
"getManager",
"(",
"ManagerRegistry",
"$",
"or",
",",
"$",
"class",
")",
"{",
"$",
"manager",
"=",
"$",
"or",
"->",
"getManagerForClass",
"(",
"$",
"class",
")",
";",
"if",
"(",
"null",
"===",
"$",
"manager",
")",
"{",
"foreach",
"(",
"$",
"or",
"->",
"getManagers",
"(",
")",
"as",
"$",
"objectManager",
")",
"{",
"if",
"(",
"$",
"objectManager",
"->",
"getMetadataFactory",
"(",
")",
"->",
"hasMetadataFor",
"(",
"$",
"class",
")",
"&&",
"self",
"::",
"isValidManager",
"(",
"$",
"objectManager",
",",
"$",
"class",
")",
")",
"{",
"$",
"manager",
"=",
"$",
"objectManager",
";",
"break",
";",
"}",
"}",
"}",
"return",
"$",
"manager",
";",
"}"
] | Get the doctrine object manager of the class.
@param ManagerRegistry $or The doctrine registry
@param string $class The class name or doctrine shortcut class name
@return null|ObjectManager | [
"Get",
"the",
"doctrine",
"object",
"manager",
"of",
"the",
"class",
"."
] | train | https://github.com/fxpio/fxp-doctrine-extra/blob/9c672acde7892717958efff0ee3bad723be4a70f/Util/ManagerUtils.php#L34-L50 |
fxpio/fxp-doctrine-extra | Util/ManagerUtils.php | ManagerUtils.isValidManager | private static function isValidManager(ObjectManager $manager, $class)
{
$meta = $manager->getClassMetadata($class);
return !$meta instanceof OrmClassMetadata || !$meta->isMappedSuperclass;
} | php | private static function isValidManager(ObjectManager $manager, $class)
{
$meta = $manager->getClassMetadata($class);
return !$meta instanceof OrmClassMetadata || !$meta->isMappedSuperclass;
} | [
"private",
"static",
"function",
"isValidManager",
"(",
"ObjectManager",
"$",
"manager",
",",
"$",
"class",
")",
"{",
"$",
"meta",
"=",
"$",
"manager",
"->",
"getClassMetadata",
"(",
"$",
"class",
")",
";",
"return",
"!",
"$",
"meta",
"instanceof",
"OrmClassMetadata",
"||",
"!",
"$",
"meta",
"->",
"isMappedSuperclass",
";",
"}"
] | Check if the object manager is valid.
@param ObjectManager $manager The object manager
@param string $class The class name
@return bool | [
"Check",
"if",
"the",
"object",
"manager",
"is",
"valid",
"."
] | train | https://github.com/fxpio/fxp-doctrine-extra/blob/9c672acde7892717958efff0ee3bad723be4a70f/Util/ManagerUtils.php#L81-L86 |
zodream/validate | src/Rules/RequiredRule.php | RequiredRule.validate | public function validate($input) {
if (is_null($input)) {
return false;
}
if (is_string($input)) {
return trim($input) !== '';
}
if (!is_array($input)) {
return true;
}
foreach ($input as $item) {
if ($this->validate($item)) {
return true;
}
}
return false;
} | php | public function validate($input) {
if (is_null($input)) {
return false;
}
if (is_string($input)) {
return trim($input) !== '';
}
if (!is_array($input)) {
return true;
}
foreach ($input as $item) {
if ($this->validate($item)) {
return true;
}
}
return false;
} | [
"public",
"function",
"validate",
"(",
"$",
"input",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"input",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"is_string",
"(",
"$",
"input",
")",
")",
"{",
"return",
"trim",
"(",
"$",
"input",
")",
"!==",
"''",
";",
"}",
"if",
"(",
"!",
"is_array",
"(",
"$",
"input",
")",
")",
"{",
"return",
"true",
";",
"}",
"foreach",
"(",
"$",
"input",
"as",
"$",
"item",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"validate",
"(",
"$",
"item",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | 验证信息
@param mixed $input
@return boolean | [
"验证信息"
] | train | https://github.com/zodream/validate/blob/17c878b5a643a78df96c3be623f779115096f17b/src/Rules/RequiredRule.php#L12-L28 |
WideFocus/Feed-Writer | src/ExtractFieldValuesTrait.php | ExtractFieldValuesTrait.extractFieldValues | protected function extractFieldValues(
ArrayAccess $item,
WriterFieldInterface ...$fields
): array {
return array_map(
function (WriterFieldInterface $field) use ($item) : string {
return $field->getValue($item);
},
$fields
);
} | php | protected function extractFieldValues(
ArrayAccess $item,
WriterFieldInterface ...$fields
): array {
return array_map(
function (WriterFieldInterface $field) use ($item) : string {
return $field->getValue($item);
},
$fields
);
} | [
"protected",
"function",
"extractFieldValues",
"(",
"ArrayAccess",
"$",
"item",
",",
"WriterFieldInterface",
"...",
"$",
"fields",
")",
":",
"array",
"{",
"return",
"array_map",
"(",
"function",
"(",
"WriterFieldInterface",
"$",
"field",
")",
"use",
"(",
"$",
"item",
")",
":",
"string",
"{",
"return",
"$",
"field",
"->",
"getValue",
"(",
"$",
"item",
")",
";",
"}",
",",
"$",
"fields",
")",
";",
"}"
] | Extract item values from fields.
@param ArrayAccess $item
@param WriterFieldInterface[] ...$fields
@return string[] | [
"Extract",
"item",
"values",
"from",
"fields",
"."
] | train | https://github.com/WideFocus/Feed-Writer/blob/c2698394645c75db06962e5e9d638f0cabe69fe3/src/ExtractFieldValuesTrait.php#L21-L31 |
wb-crowdfusion/crowdfusion | system/core/classes/nodedb/search/AbstractSearchIndex.php | AbstractSearchIndex.reindex | public function reindex(NodeRef $nodeRef)
{
if(!$nodeRef->isFullyQualified())
throw new Exception('Cannot reindex node without fully-qualified NodeRef');
if(substr($this->Elements, 0, 1) == '@') {
if(!$nodeRef->getElement()->hasAspect($this->Elements))
return;
} else if(!in_array($nodeRef->getElement()->getSlug(), StringUtils::smartExplode($this->Elements)))
return;
if(array_key_exists(''.$nodeRef, $this->markedForDeletion))
unset($this->markedForDeletion[''.$nodeRef]);
if(array_key_exists(''.$nodeRef, $this->markedForReindex))
return;
$this->markedForReindex[''.$nodeRef] = $nodeRef;
$this->bindReindex();
} | php | public function reindex(NodeRef $nodeRef)
{
if(!$nodeRef->isFullyQualified())
throw new Exception('Cannot reindex node without fully-qualified NodeRef');
if(substr($this->Elements, 0, 1) == '@') {
if(!$nodeRef->getElement()->hasAspect($this->Elements))
return;
} else if(!in_array($nodeRef->getElement()->getSlug(), StringUtils::smartExplode($this->Elements)))
return;
if(array_key_exists(''.$nodeRef, $this->markedForDeletion))
unset($this->markedForDeletion[''.$nodeRef]);
if(array_key_exists(''.$nodeRef, $this->markedForReindex))
return;
$this->markedForReindex[''.$nodeRef] = $nodeRef;
$this->bindReindex();
} | [
"public",
"function",
"reindex",
"(",
"NodeRef",
"$",
"nodeRef",
")",
"{",
"if",
"(",
"!",
"$",
"nodeRef",
"->",
"isFullyQualified",
"(",
")",
")",
"throw",
"new",
"Exception",
"(",
"'Cannot reindex node without fully-qualified NodeRef'",
")",
";",
"if",
"(",
"substr",
"(",
"$",
"this",
"->",
"Elements",
",",
"0",
",",
"1",
")",
"==",
"'@'",
")",
"{",
"if",
"(",
"!",
"$",
"nodeRef",
"->",
"getElement",
"(",
")",
"->",
"hasAspect",
"(",
"$",
"this",
"->",
"Elements",
")",
")",
"return",
";",
"}",
"else",
"if",
"(",
"!",
"in_array",
"(",
"$",
"nodeRef",
"->",
"getElement",
"(",
")",
"->",
"getSlug",
"(",
")",
",",
"StringUtils",
"::",
"smartExplode",
"(",
"$",
"this",
"->",
"Elements",
")",
")",
")",
"return",
";",
"if",
"(",
"array_key_exists",
"(",
"''",
".",
"$",
"nodeRef",
",",
"$",
"this",
"->",
"markedForDeletion",
")",
")",
"unset",
"(",
"$",
"this",
"->",
"markedForDeletion",
"[",
"''",
".",
"$",
"nodeRef",
"]",
")",
";",
"if",
"(",
"array_key_exists",
"(",
"''",
".",
"$",
"nodeRef",
",",
"$",
"this",
"->",
"markedForReindex",
")",
")",
"return",
";",
"$",
"this",
"->",
"markedForReindex",
"[",
"''",
".",
"$",
"nodeRef",
"]",
"=",
"$",
"nodeRef",
";",
"$",
"this",
"->",
"bindReindex",
"(",
")",
";",
"}"
] | reindex | [
"reindex"
] | train | https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/nodedb/search/AbstractSearchIndex.php#L67-L86 |
Elephant418/Iniliq | src/Pixel418/Iniliq/Stack/Util/IniParser.php | IniParser.parse | public function parse( $files, $initialize = array( ) ) {
\UArray::doConvertToArray( $files );
$result = array( );
if ( is_array( $initialize ) ) {
array_unshift( $files, $initialize );
}
foreach ( $files as $file ) {
$parsed = $this->parseIni( $file );
$this->mergeValues( $result, $parsed );
}
if ( $this->arrayObjectOption ) {
$options = array( $this->errorStrategy );
if ( ! $this->deepSelectorOption ) {
$options[ ] = \Pixel418\Iniliq::DISABLE_DEEP_SELECTORS;
}
$ArrayClass = \UObject::getNamespace( $this ) . '\\ArrayObject';
$result = new $ArrayClass( $result, $options );
}
return $result;
} | php | public function parse( $files, $initialize = array( ) ) {
\UArray::doConvertToArray( $files );
$result = array( );
if ( is_array( $initialize ) ) {
array_unshift( $files, $initialize );
}
foreach ( $files as $file ) {
$parsed = $this->parseIni( $file );
$this->mergeValues( $result, $parsed );
}
if ( $this->arrayObjectOption ) {
$options = array( $this->errorStrategy );
if ( ! $this->deepSelectorOption ) {
$options[ ] = \Pixel418\Iniliq::DISABLE_DEEP_SELECTORS;
}
$ArrayClass = \UObject::getNamespace( $this ) . '\\ArrayObject';
$result = new $ArrayClass( $result, $options );
}
return $result;
} | [
"public",
"function",
"parse",
"(",
"$",
"files",
",",
"$",
"initialize",
"=",
"array",
"(",
")",
")",
"{",
"\\",
"UArray",
"::",
"doConvertToArray",
"(",
"$",
"files",
")",
";",
"$",
"result",
"=",
"array",
"(",
")",
";",
"if",
"(",
"is_array",
"(",
"$",
"initialize",
")",
")",
"{",
"array_unshift",
"(",
"$",
"files",
",",
"$",
"initialize",
")",
";",
"}",
"foreach",
"(",
"$",
"files",
"as",
"$",
"file",
")",
"{",
"$",
"parsed",
"=",
"$",
"this",
"->",
"parseIni",
"(",
"$",
"file",
")",
";",
"$",
"this",
"->",
"mergeValues",
"(",
"$",
"result",
",",
"$",
"parsed",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"arrayObjectOption",
")",
"{",
"$",
"options",
"=",
"array",
"(",
"$",
"this",
"->",
"errorStrategy",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"deepSelectorOption",
")",
"{",
"$",
"options",
"[",
"]",
"=",
"\\",
"Pixel418",
"\\",
"Iniliq",
"::",
"DISABLE_DEEP_SELECTORS",
";",
"}",
"$",
"ArrayClass",
"=",
"\\",
"UObject",
"::",
"getNamespace",
"(",
"$",
"this",
")",
".",
"'\\\\ArrayObject'",
";",
"$",
"result",
"=",
"new",
"$",
"ArrayClass",
"(",
"$",
"result",
",",
"$",
"options",
")",
";",
"}",
"return",
"$",
"result",
";",
"}"
] | ***********************************************************************
PUBLIC METHODS
*********************************************************************** | [
"***********************************************************************",
"PUBLIC",
"METHODS",
"***********************************************************************"
] | train | https://github.com/Elephant418/Iniliq/blob/8f7d2cd23aff6f4a0723a3a06419bb9511f60b05/src/Pixel418/Iniliq/Stack/Util/IniParser.php#L25-L44 |
Elephant418/Iniliq | src/Pixel418/Iniliq/Stack/Util/IniParser.php | IniParser.parseIni | protected function parseIni( $file ) {
$parsed = array( );
if ( is_array( $file ) ) {
$parsed = $file;
} else if ( \UString::has( $file, PHP_EOL ) ) {
$parsed = @parse_ini_string( $file, TRUE );
if ( $parsed === FALSE ) {
$this->manageError( 'The ini string has a bad format.' );
}
} else {
if ( is_file( $file ) ) {
$parsed = @parse_ini_file( $file, TRUE );
if ( $parsed === FALSE ) {
$this->manageError( 'The ini file has a bad format: ' . $file );
}
} else {
$this->manageError( 'No such file or directory: ' . $file );
}
}
return $parsed;
} | php | protected function parseIni( $file ) {
$parsed = array( );
if ( is_array( $file ) ) {
$parsed = $file;
} else if ( \UString::has( $file, PHP_EOL ) ) {
$parsed = @parse_ini_string( $file, TRUE );
if ( $parsed === FALSE ) {
$this->manageError( 'The ini string has a bad format.' );
}
} else {
if ( is_file( $file ) ) {
$parsed = @parse_ini_file( $file, TRUE );
if ( $parsed === FALSE ) {
$this->manageError( 'The ini file has a bad format: ' . $file );
}
} else {
$this->manageError( 'No such file or directory: ' . $file );
}
}
return $parsed;
} | [
"protected",
"function",
"parseIni",
"(",
"$",
"file",
")",
"{",
"$",
"parsed",
"=",
"array",
"(",
")",
";",
"if",
"(",
"is_array",
"(",
"$",
"file",
")",
")",
"{",
"$",
"parsed",
"=",
"$",
"file",
";",
"}",
"else",
"if",
"(",
"\\",
"UString",
"::",
"has",
"(",
"$",
"file",
",",
"PHP_EOL",
")",
")",
"{",
"$",
"parsed",
"=",
"@",
"parse_ini_string",
"(",
"$",
"file",
",",
"TRUE",
")",
";",
"if",
"(",
"$",
"parsed",
"===",
"FALSE",
")",
"{",
"$",
"this",
"->",
"manageError",
"(",
"'The ini string has a bad format.'",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"is_file",
"(",
"$",
"file",
")",
")",
"{",
"$",
"parsed",
"=",
"@",
"parse_ini_file",
"(",
"$",
"file",
",",
"TRUE",
")",
";",
"if",
"(",
"$",
"parsed",
"===",
"FALSE",
")",
"{",
"$",
"this",
"->",
"manageError",
"(",
"'The ini file has a bad format: '",
".",
"$",
"file",
")",
";",
"}",
"}",
"else",
"{",
"$",
"this",
"->",
"manageError",
"(",
"'No such file or directory: '",
".",
"$",
"file",
")",
";",
"}",
"}",
"return",
"$",
"parsed",
";",
"}"
] | ***********************************************************************
PROTECTED METHODS
*********************************************************************** | [
"***********************************************************************",
"PROTECTED",
"METHODS",
"***********************************************************************"
] | train | https://github.com/Elephant418/Iniliq/blob/8f7d2cd23aff6f4a0723a3a06419bb9511f60b05/src/Pixel418/Iniliq/Stack/Util/IniParser.php#L89-L109 |
Talesoft/tale-framework | src/Tale/Event/EmitterTrait.php | EmitterTrait.getEvent | public function getEvent($name)
{
if (!isset($this->_events))
$this->_events = [];
if (!isset($this->_events[$name])) {
$className = $this->getEventClassName();
$this->_events[$name] = new $className($name);
}
return $this->_events[$name];
} | php | public function getEvent($name)
{
if (!isset($this->_events))
$this->_events = [];
if (!isset($this->_events[$name])) {
$className = $this->getEventClassName();
$this->_events[$name] = new $className($name);
}
return $this->_events[$name];
} | [
"public",
"function",
"getEvent",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"_events",
")",
")",
"$",
"this",
"->",
"_events",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"_events",
"[",
"$",
"name",
"]",
")",
")",
"{",
"$",
"className",
"=",
"$",
"this",
"->",
"getEventClassName",
"(",
")",
";",
"$",
"this",
"->",
"_events",
"[",
"$",
"name",
"]",
"=",
"new",
"$",
"className",
"(",
"$",
"name",
")",
";",
"}",
"return",
"$",
"this",
"->",
"_events",
"[",
"$",
"name",
"]",
";",
"}"
] | Returns an event by name.
If the event doesnt exist yet, it is created
@param $name The name of the event
@return \Tale\Event The unique event instance | [
"Returns",
"an",
"event",
"by",
"name",
".",
"If",
"the",
"event",
"doesnt",
"exist",
"yet",
"it",
"is",
"created"
] | train | https://github.com/Talesoft/tale-framework/blob/739a7011c6dad409a51c4bcfbcf4b4ffbc8cba49/src/Tale/Event/EmitterTrait.php#L38-L51 |
Talesoft/tale-framework | src/Tale/Event/EmitterTrait.php | EmitterTrait.emit | public function emit($name, Args $args = null, $reverse = false)
{
$args = $args ? $args : new Args();
$event = $this->getEvent($name);
return $event($args, $reverse);
} | php | public function emit($name, Args $args = null, $reverse = false)
{
$args = $args ? $args : new Args();
$event = $this->getEvent($name);
return $event($args, $reverse);
} | [
"public",
"function",
"emit",
"(",
"$",
"name",
",",
"Args",
"$",
"args",
"=",
"null",
",",
"$",
"reverse",
"=",
"false",
")",
"{",
"$",
"args",
"=",
"$",
"args",
"?",
"$",
"args",
":",
"new",
"Args",
"(",
")",
";",
"$",
"event",
"=",
"$",
"this",
"->",
"getEvent",
"(",
"$",
"name",
")",
";",
"return",
"$",
"event",
"(",
"$",
"args",
",",
"$",
"reverse",
")",
";",
"}"
] | Emits an event.
When an event is emitted, all bound callbacks are called.
$args is passed as the first argument to each callback
@param string $name The name of the event
@param \Tale\Event\Args|null $args The arguments to pass to the event
@param bool $reverse
@return bool The value of !$args->isDefaultPrevented() | [
"Emits",
"an",
"event",
"."
] | train | https://github.com/Talesoft/tale-framework/blob/739a7011c6dad409a51c4bcfbcf4b4ffbc8cba49/src/Tale/Event/EmitterTrait.php#L110-L117 |
Subscribo/omnipay-subscribo-shared | src/Shared/Widget/AbstractWidget.php | AbstractWidget.checkParameters | protected function checkParameters($parameters, $requirements = true)
{
if (is_array($parameters)) {
$parameters = array_replace($this->getParameters(), $parameters);
}
$obstacles = $this->collectRenderingObstacles($parameters, $requirements);
if ($obstacles) {
throw new WidgetInvalidRenderingParametersException(reset($obstacles));
}
return $parameters;
} | php | protected function checkParameters($parameters, $requirements = true)
{
if (is_array($parameters)) {
$parameters = array_replace($this->getParameters(), $parameters);
}
$obstacles = $this->collectRenderingObstacles($parameters, $requirements);
if ($obstacles) {
throw new WidgetInvalidRenderingParametersException(reset($obstacles));
}
return $parameters;
} | [
"protected",
"function",
"checkParameters",
"(",
"$",
"parameters",
",",
"$",
"requirements",
"=",
"true",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"parameters",
")",
")",
"{",
"$",
"parameters",
"=",
"array_replace",
"(",
"$",
"this",
"->",
"getParameters",
"(",
")",
",",
"$",
"parameters",
")",
";",
"}",
"$",
"obstacles",
"=",
"$",
"this",
"->",
"collectRenderingObstacles",
"(",
"$",
"parameters",
",",
"$",
"requirements",
")",
";",
"if",
"(",
"$",
"obstacles",
")",
"{",
"throw",
"new",
"WidgetInvalidRenderingParametersException",
"(",
"reset",
"(",
"$",
"obstacles",
")",
")",
";",
"}",
"return",
"$",
"parameters",
";",
"}"
] | Merges provided parameters with those from objects and checks them
@param array $parameters
@param bool|array $requirements - required parameter names or true for getting them from getRequiredParameters()
@return array
@throws \Subscribo\Omnipay\Shared\Exception\WidgetInvalidRenderingParametersException | [
"Merges",
"provided",
"parameters",
"with",
"those",
"from",
"objects",
"and",
"checks",
"them"
] | train | https://github.com/Subscribo/omnipay-subscribo-shared/blob/aa9fa115ef8324b50fe5c91d3593d5632f53b669/src/Shared/Widget/AbstractWidget.php#L40-L50 |
Subscribo/omnipay-subscribo-shared | src/Shared/Widget/AbstractWidget.php | AbstractWidget.collectRenderingObstacles | protected function collectRenderingObstacles($parameters, $requirements = true)
{
if ( ! is_array($parameters)) {
return ['Parameters should be an array'];
}
if (true === $requirements) {
$requirements = $this->getRequiredParameters();
}
$obstacles = [];
foreach ($requirements as $requiredParameterName) {
if (empty($parameters[$requiredParameterName])) {
$obstacles[] = "Parameter '".$requiredParameterName."' is required";
}
}
return $obstacles;
} | php | protected function collectRenderingObstacles($parameters, $requirements = true)
{
if ( ! is_array($parameters)) {
return ['Parameters should be an array'];
}
if (true === $requirements) {
$requirements = $this->getRequiredParameters();
}
$obstacles = [];
foreach ($requirements as $requiredParameterName) {
if (empty($parameters[$requiredParameterName])) {
$obstacles[] = "Parameter '".$requiredParameterName."' is required";
}
}
return $obstacles;
} | [
"protected",
"function",
"collectRenderingObstacles",
"(",
"$",
"parameters",
",",
"$",
"requirements",
"=",
"true",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"parameters",
")",
")",
"{",
"return",
"[",
"'Parameters should be an array'",
"]",
";",
"}",
"if",
"(",
"true",
"===",
"$",
"requirements",
")",
"{",
"$",
"requirements",
"=",
"$",
"this",
"->",
"getRequiredParameters",
"(",
")",
";",
"}",
"$",
"obstacles",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"requirements",
"as",
"$",
"requiredParameterName",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"parameters",
"[",
"$",
"requiredParameterName",
"]",
")",
")",
"{",
"$",
"obstacles",
"[",
"]",
"=",
"\"Parameter '\"",
".",
"$",
"requiredParameterName",
".",
"\"' is required\"",
";",
"}",
"}",
"return",
"$",
"obstacles",
";",
"}"
] | Returns an array of possible problems for rendering widget or of some widget rendering functionality
@param $parameters
@param bool|array $requirements - required parameter names or true for getting them from getRequiredParameters()
@return array | [
"Returns",
"an",
"array",
"of",
"possible",
"problems",
"for",
"rendering",
"widget",
"or",
"of",
"some",
"widget",
"rendering",
"functionality"
] | train | https://github.com/Subscribo/omnipay-subscribo-shared/blob/aa9fa115ef8324b50fe5c91d3593d5632f53b669/src/Shared/Widget/AbstractWidget.php#L59-L74 |
spryker/company-unit-address-data-import | src/Spryker/Zed/CompanyUnitAddressDataImport/Business/CompanyUnitAddressDataImportFacade.php | CompanyUnitAddressDataImportFacade.import | public function import(?DataImporterConfigurationTransfer $dataImporterConfigurationTransfer = null): DataImporterReportTransfer
{
return $this->getFactory()->createCompanyUnitAddressDataImport()->import($dataImporterConfigurationTransfer);
} | php | public function import(?DataImporterConfigurationTransfer $dataImporterConfigurationTransfer = null): DataImporterReportTransfer
{
return $this->getFactory()->createCompanyUnitAddressDataImport()->import($dataImporterConfigurationTransfer);
} | [
"public",
"function",
"import",
"(",
"?",
"DataImporterConfigurationTransfer",
"$",
"dataImporterConfigurationTransfer",
"=",
"null",
")",
":",
"DataImporterReportTransfer",
"{",
"return",
"$",
"this",
"->",
"getFactory",
"(",
")",
"->",
"createCompanyUnitAddressDataImport",
"(",
")",
"->",
"import",
"(",
"$",
"dataImporterConfigurationTransfer",
")",
";",
"}"
] | {@inheritdoc}
@api
@param \Generated\Shared\Transfer\DataImporterConfigurationTransfer|null $dataImporterConfigurationTransfer
@return \Generated\Shared\Transfer\DataImporterReportTransfer | [
"{",
"@inheritdoc",
"}"
] | train | https://github.com/spryker/company-unit-address-data-import/blob/d6cef0685784d0c4ba7bc22ed37ecf725d46dd58/src/Spryker/Zed/CompanyUnitAddressDataImport/Business/CompanyUnitAddressDataImportFacade.php#L28-L31 |
heiglandreas/DateFormatter | src/Formatter/Pdf.php | Pdf.format | public function format(\DateTimeInterface $date)
{
if ($date->getOffset() == 0) {
return $date->format('YmdHis\Z');
}
return str_replace(':', '\'', $date->format('YmdHisP')) . '\'';
} | php | public function format(\DateTimeInterface $date)
{
if ($date->getOffset() == 0) {
return $date->format('YmdHis\Z');
}
return str_replace(':', '\'', $date->format('YmdHisP')) . '\'';
} | [
"public",
"function",
"format",
"(",
"\\",
"DateTimeInterface",
"$",
"date",
")",
"{",
"if",
"(",
"$",
"date",
"->",
"getOffset",
"(",
")",
"==",
"0",
")",
"{",
"return",
"$",
"date",
"->",
"format",
"(",
"'YmdHis\\Z'",
")",
";",
"}",
"return",
"str_replace",
"(",
"':'",
",",
"'\\''",
",",
"$",
"date",
"->",
"format",
"(",
"'YmdHisP'",
")",
")",
".",
"'\\''",
";",
"}"
] | Formats the date according to the formatting string
@param \DateTimeInterface $date
@return string | [
"Formats",
"the",
"date",
"according",
"to",
"the",
"formatting",
"string"
] | train | https://github.com/heiglandreas/DateFormatter/blob/948737d329e72b74c118dac902d795d6c244a486/src/Formatter/Pdf.php#L43-L49 |
o100ja/Rug | lib/Rug/Message/Parser/AbstractParser.php | AbstractParser.handle | public function handle(Response $response, $method = null, $mime = null) {
if (empty($method) || !method_exists($this, $method)) {
return $this->_parse($response, $mime);
}
return $this->$method($response, $mime);
} | php | public function handle(Response $response, $method = null, $mime = null) {
if (empty($method) || !method_exists($this, $method)) {
return $this->_parse($response, $mime);
}
return $this->$method($response, $mime);
} | [
"public",
"function",
"handle",
"(",
"Response",
"$",
"response",
",",
"$",
"method",
"=",
"null",
",",
"$",
"mime",
"=",
"null",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"method",
")",
"||",
"!",
"method_exists",
"(",
"$",
"this",
",",
"$",
"method",
")",
")",
"{",
"return",
"$",
"this",
"->",
"_parse",
"(",
"$",
"response",
",",
"$",
"mime",
")",
";",
"}",
"return",
"$",
"this",
"->",
"$",
"method",
"(",
"$",
"response",
",",
"$",
"mime",
")",
";",
"}"
] | ***************************************************************************************************************** | [
"*****************************************************************************************************************"
] | train | https://github.com/o100ja/Rug/blob/5a6fe447b382efeb8000791d1dc89b44113b301e/lib/Rug/Message/Parser/AbstractParser.php#L24-L29 |
o100ja/Rug | lib/Rug/Message/Parser/AbstractParser.php | AbstractParser._parse | public function _parse(Response $response, $mime = null) {
$data = $this->decode($response->getContent(), $mime);
if (isset($data->error)) {
throw new RugException($data->error, $this->_error($data));
}
return $data;
} | php | public function _parse(Response $response, $mime = null) {
$data = $this->decode($response->getContent(), $mime);
if (isset($data->error)) {
throw new RugException($data->error, $this->_error($data));
}
return $data;
} | [
"public",
"function",
"_parse",
"(",
"Response",
"$",
"response",
",",
"$",
"mime",
"=",
"null",
")",
"{",
"$",
"data",
"=",
"$",
"this",
"->",
"decode",
"(",
"$",
"response",
"->",
"getContent",
"(",
")",
",",
"$",
"mime",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"data",
"->",
"error",
")",
")",
"{",
"throw",
"new",
"RugException",
"(",
"$",
"data",
"->",
"error",
",",
"$",
"this",
"->",
"_error",
"(",
"$",
"data",
")",
")",
";",
"}",
"return",
"$",
"data",
";",
"}"
] | ***************************************************************************************************************** | [
"*****************************************************************************************************************"
] | train | https://github.com/o100ja/Rug/blob/5a6fe447b382efeb8000791d1dc89b44113b301e/lib/Rug/Message/Parser/AbstractParser.php#L43-L49 |
capimichi/crawler | src/Crawler/Downloader/Downloader.php | Downloader.getDomXpath | public function getDomXpath($url)
{
$dom = $this->getDomDocument($url);
$xpath = new \DOMXPath($dom);
return $xpath;
} | php | public function getDomXpath($url)
{
$dom = $this->getDomDocument($url);
$xpath = new \DOMXPath($dom);
return $xpath;
} | [
"public",
"function",
"getDomXpath",
"(",
"$",
"url",
")",
"{",
"$",
"dom",
"=",
"$",
"this",
"->",
"getDomDocument",
"(",
"$",
"url",
")",
";",
"$",
"xpath",
"=",
"new",
"\\",
"DOMXPath",
"(",
"$",
"dom",
")",
";",
"return",
"$",
"xpath",
";",
"}"
] | Get the DOMXPath of the downloaded content
@param $url
@return \DOMXPath | [
"Get",
"the",
"DOMXPath",
"of",
"the",
"downloaded",
"content"
] | train | https://github.com/capimichi/crawler/blob/e1cd4ba00a9a1da994dc381ee396ba4a5038c986/src/Crawler/Downloader/Downloader.php#L94-L99 |
SysControllers/Admin | src/database/seeds/NoticiasTableSeeder.php | NoticiasTableSeeder.run | public function run()
{
factory(\App\Entities\Admin\Categoria::class, 6)->create();
factory(\App\Entities\Admin\Tag::class, 10)->create();
factory(\App\Entities\Admin\Noticia::class, 20)->create()->each(function ($n){{
$tags = \App\Entities\Admin\Tag::all()->random()->id;
$n->tags()->sync($tags);
}});
} | php | public function run()
{
factory(\App\Entities\Admin\Categoria::class, 6)->create();
factory(\App\Entities\Admin\Tag::class, 10)->create();
factory(\App\Entities\Admin\Noticia::class, 20)->create()->each(function ($n){{
$tags = \App\Entities\Admin\Tag::all()->random()->id;
$n->tags()->sync($tags);
}});
} | [
"public",
"function",
"run",
"(",
")",
"{",
"factory",
"(",
"\\",
"App",
"\\",
"Entities",
"\\",
"Admin",
"\\",
"Categoria",
"::",
"class",
",",
"6",
")",
"->",
"create",
"(",
")",
";",
"factory",
"(",
"\\",
"App",
"\\",
"Entities",
"\\",
"Admin",
"\\",
"Tag",
"::",
"class",
",",
"10",
")",
"->",
"create",
"(",
")",
";",
"factory",
"(",
"\\",
"App",
"\\",
"Entities",
"\\",
"Admin",
"\\",
"Noticia",
"::",
"class",
",",
"20",
")",
"->",
"create",
"(",
")",
"->",
"each",
"(",
"function",
"(",
"$",
"n",
")",
"{",
"{",
"$",
"tags",
"=",
"\\",
"App",
"\\",
"Entities",
"\\",
"Admin",
"\\",
"Tag",
"::",
"all",
"(",
")",
"->",
"random",
"(",
")",
"->",
"id",
";",
"$",
"n",
"->",
"tags",
"(",
")",
"->",
"sync",
"(",
"$",
"tags",
")",
";",
"}",
"}",
")",
";",
"}"
] | Run the database seeds.
@return void | [
"Run",
"the",
"database",
"seeds",
"."
] | train | https://github.com/SysControllers/Admin/blob/8f1df46aca422b87f2f522fbba610dcfa0c5f7f3/src/database/seeds/NoticiasTableSeeder.php#L12-L22 |
ARCANESOFT/Media | src/Http/Controllers/Admin/ApiController.php | ApiController.getAll | public function getAll(Request $request)
{
$this->authorize(MediasPolicy::PERMISSION_LIST);
return $this->jsonResponseSuccess([
'medias' => $this->media->all(
$request->get('location', '/')
),
]);
} | php | public function getAll(Request $request)
{
$this->authorize(MediasPolicy::PERMISSION_LIST);
return $this->jsonResponseSuccess([
'medias' => $this->media->all(
$request->get('location', '/')
),
]);
} | [
"public",
"function",
"getAll",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"this",
"->",
"authorize",
"(",
"MediasPolicy",
"::",
"PERMISSION_LIST",
")",
";",
"return",
"$",
"this",
"->",
"jsonResponseSuccess",
"(",
"[",
"'medias'",
"=>",
"$",
"this",
"->",
"media",
"->",
"all",
"(",
"$",
"request",
"->",
"get",
"(",
"'location'",
",",
"'/'",
")",
")",
",",
"]",
")",
";",
"}"
] | Get the the media files.
@param \Illuminate\Http\Request $request
@return \Illuminate\Http\JsonResponse | [
"Get",
"the",
"the",
"media",
"files",
"."
] | train | https://github.com/ARCANESOFT/Media/blob/e98aad52f94e6587fcbf79c56f7bf7072929bfc9/src/Http/Controllers/Admin/ApiController.php#L65-L74 |
ARCANESOFT/Media | src/Http/Controllers/Admin/ApiController.php | ApiController.uploadMedia | public function uploadMedia(Request $request)
{
$this->authorize(MediasPolicy::PERMISSION_CREATE);
// TODO: Refactor this with the Laravel 5.5 new Exception Handler & Form Request
$validator = validator($request->all(), [
'location' => ['required', 'string'],
'medias' => ['required', 'array'],
'medias.*' => ['required', 'file']
]);
if ($validator->fails()) {
return $this->jsonResponseError([
'messages' => $validator->messages(),
], 422);
}
$uploaded = $this->media->storeMany(
$request->get('location'), $request->file('medias')
);
return $this->jsonResponseSuccess([
'data' => compact('uploaded')
]);
} | php | public function uploadMedia(Request $request)
{
$this->authorize(MediasPolicy::PERMISSION_CREATE);
// TODO: Refactor this with the Laravel 5.5 new Exception Handler & Form Request
$validator = validator($request->all(), [
'location' => ['required', 'string'],
'medias' => ['required', 'array'],
'medias.*' => ['required', 'file']
]);
if ($validator->fails()) {
return $this->jsonResponseError([
'messages' => $validator->messages(),
], 422);
}
$uploaded = $this->media->storeMany(
$request->get('location'), $request->file('medias')
);
return $this->jsonResponseSuccess([
'data' => compact('uploaded')
]);
} | [
"public",
"function",
"uploadMedia",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"this",
"->",
"authorize",
"(",
"MediasPolicy",
"::",
"PERMISSION_CREATE",
")",
";",
"// TODO: Refactor this with the Laravel 5.5 new Exception Handler & Form Request",
"$",
"validator",
"=",
"validator",
"(",
"$",
"request",
"->",
"all",
"(",
")",
",",
"[",
"'location'",
"=>",
"[",
"'required'",
",",
"'string'",
"]",
",",
"'medias'",
"=>",
"[",
"'required'",
",",
"'array'",
"]",
",",
"'medias.*'",
"=>",
"[",
"'required'",
",",
"'file'",
"]",
"]",
")",
";",
"if",
"(",
"$",
"validator",
"->",
"fails",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"jsonResponseError",
"(",
"[",
"'messages'",
"=>",
"$",
"validator",
"->",
"messages",
"(",
")",
",",
"]",
",",
"422",
")",
";",
"}",
"$",
"uploaded",
"=",
"$",
"this",
"->",
"media",
"->",
"storeMany",
"(",
"$",
"request",
"->",
"get",
"(",
"'location'",
")",
",",
"$",
"request",
"->",
"file",
"(",
"'medias'",
")",
")",
";",
"return",
"$",
"this",
"->",
"jsonResponseSuccess",
"(",
"[",
"'data'",
"=>",
"compact",
"(",
"'uploaded'",
")",
"]",
")",
";",
"}"
] | Upload a media file.
@param \Illuminate\Http\Request $request
@return \Illuminate\Http\JsonResponse | [
"Upload",
"a",
"media",
"file",
"."
] | train | https://github.com/ARCANESOFT/Media/blob/e98aad52f94e6587fcbf79c56f7bf7072929bfc9/src/Http/Controllers/Admin/ApiController.php#L83-L107 |
ARCANESOFT/Media | src/Http/Controllers/Admin/ApiController.php | ApiController.createDirectory | public function createDirectory(Request $request)
{
$this->authorize(MediasPolicy::PERMISSION_CREATE);
// TODO: Refactor this with the Laravel 5.5 new Exception Handler & Form Request
$validator = validator($data = $request->all(), [
'name' => ['required', 'string'], // TODO: check if the folder does not exists
'location' => ['required', 'string'],
]);
if ($validator->fails()) {
return $this->jsonResponseError([
'messages' => $validator->messages(),
], 422);
}
$this->media->makeDirectory(
$path = trim($data['location'], '/').'/'.Str::slug($data['name'])
);
return $this->jsonResponseSuccess(['data' => compact('path')]);
} | php | public function createDirectory(Request $request)
{
$this->authorize(MediasPolicy::PERMISSION_CREATE);
// TODO: Refactor this with the Laravel 5.5 new Exception Handler & Form Request
$validator = validator($data = $request->all(), [
'name' => ['required', 'string'], // TODO: check if the folder does not exists
'location' => ['required', 'string'],
]);
if ($validator->fails()) {
return $this->jsonResponseError([
'messages' => $validator->messages(),
], 422);
}
$this->media->makeDirectory(
$path = trim($data['location'], '/').'/'.Str::slug($data['name'])
);
return $this->jsonResponseSuccess(['data' => compact('path')]);
} | [
"public",
"function",
"createDirectory",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"this",
"->",
"authorize",
"(",
"MediasPolicy",
"::",
"PERMISSION_CREATE",
")",
";",
"// TODO: Refactor this with the Laravel 5.5 new Exception Handler & Form Request",
"$",
"validator",
"=",
"validator",
"(",
"$",
"data",
"=",
"$",
"request",
"->",
"all",
"(",
")",
",",
"[",
"'name'",
"=>",
"[",
"'required'",
",",
"'string'",
"]",
",",
"// TODO: check if the folder does not exists",
"'location'",
"=>",
"[",
"'required'",
",",
"'string'",
"]",
",",
"]",
")",
";",
"if",
"(",
"$",
"validator",
"->",
"fails",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"jsonResponseError",
"(",
"[",
"'messages'",
"=>",
"$",
"validator",
"->",
"messages",
"(",
")",
",",
"]",
",",
"422",
")",
";",
"}",
"$",
"this",
"->",
"media",
"->",
"makeDirectory",
"(",
"$",
"path",
"=",
"trim",
"(",
"$",
"data",
"[",
"'location'",
"]",
",",
"'/'",
")",
".",
"'/'",
".",
"Str",
"::",
"slug",
"(",
"$",
"data",
"[",
"'name'",
"]",
")",
")",
";",
"return",
"$",
"this",
"->",
"jsonResponseSuccess",
"(",
"[",
"'data'",
"=>",
"compact",
"(",
"'path'",
")",
"]",
")",
";",
"}"
] | Create a directory.
@param \Illuminate\Http\Request $request
@return \Illuminate\Http\JsonResponse | [
"Create",
"a",
"directory",
"."
] | train | https://github.com/ARCANESOFT/Media/blob/e98aad52f94e6587fcbf79c56f7bf7072929bfc9/src/Http/Controllers/Admin/ApiController.php#L116-L137 |
ARCANESOFT/Media | src/Http/Controllers/Admin/ApiController.php | ApiController.getDestinations | private function getDestinations($name, $location)
{
$selected = ($isHome = $location === '/') ? $name : "{$location}/{$name}";
$destinations = $this->media->directories($location)
->pluck('path')
->reject(function ($path) use ($selected) {
return $path === $selected;
})
->values();
if ( ! $isHome)
$destinations->prepend('..');
return $destinations;
} | php | private function getDestinations($name, $location)
{
$selected = ($isHome = $location === '/') ? $name : "{$location}/{$name}";
$destinations = $this->media->directories($location)
->pluck('path')
->reject(function ($path) use ($selected) {
return $path === $selected;
})
->values();
if ( ! $isHome)
$destinations->prepend('..');
return $destinations;
} | [
"private",
"function",
"getDestinations",
"(",
"$",
"name",
",",
"$",
"location",
")",
"{",
"$",
"selected",
"=",
"(",
"$",
"isHome",
"=",
"$",
"location",
"===",
"'/'",
")",
"?",
"$",
"name",
":",
"\"{$location}/{$name}\"",
";",
"$",
"destinations",
"=",
"$",
"this",
"->",
"media",
"->",
"directories",
"(",
"$",
"location",
")",
"->",
"pluck",
"(",
"'path'",
")",
"->",
"reject",
"(",
"function",
"(",
"$",
"path",
")",
"use",
"(",
"$",
"selected",
")",
"{",
"return",
"$",
"path",
"===",
"$",
"selected",
";",
"}",
")",
"->",
"values",
"(",
")",
";",
"if",
"(",
"!",
"$",
"isHome",
")",
"$",
"destinations",
"->",
"prepend",
"(",
"'..'",
")",
";",
"return",
"$",
"destinations",
";",
"}"
] | Get the destinations paths.
@param string $name
@param string $location
@return \Arcanesoft\Media\Entities\DirectoryCollection | [
"Get",
"the",
"destinations",
"paths",
"."
] | train | https://github.com/ARCANESOFT/Media/blob/e98aad52f94e6587fcbf79c56f7bf7072929bfc9/src/Http/Controllers/Admin/ApiController.php#L245-L259 |
ARCANESOFT/Media | src/Http/Controllers/Admin/ApiController.php | ApiController.performMoveMedia | private function performMoveMedia($type, $location, $oldName, $newName)
{
$from = "{$location}/{$oldName}";
switch (Str::lower($type)) {
case Media::MEDIA_TYPE_FILE:
return $this->moveFile($from, $location, $newName);
case Media::MEDIA_TYPE_DIRECTORY:
return $this->moveDirectory($from, $location, $newName);
default:
return false;
}
} | php | private function performMoveMedia($type, $location, $oldName, $newName)
{
$from = "{$location}/{$oldName}";
switch (Str::lower($type)) {
case Media::MEDIA_TYPE_FILE:
return $this->moveFile($from, $location, $newName);
case Media::MEDIA_TYPE_DIRECTORY:
return $this->moveDirectory($from, $location, $newName);
default:
return false;
}
} | [
"private",
"function",
"performMoveMedia",
"(",
"$",
"type",
",",
"$",
"location",
",",
"$",
"oldName",
",",
"$",
"newName",
")",
"{",
"$",
"from",
"=",
"\"{$location}/{$oldName}\"",
";",
"switch",
"(",
"Str",
"::",
"lower",
"(",
"$",
"type",
")",
")",
"{",
"case",
"Media",
"::",
"MEDIA_TYPE_FILE",
":",
"return",
"$",
"this",
"->",
"moveFile",
"(",
"$",
"from",
",",
"$",
"location",
",",
"$",
"newName",
")",
";",
"case",
"Media",
"::",
"MEDIA_TYPE_DIRECTORY",
":",
"return",
"$",
"this",
"->",
"moveDirectory",
"(",
"$",
"from",
",",
"$",
"location",
",",
"$",
"newName",
")",
";",
"default",
":",
"return",
"false",
";",
"}",
"}"
] | Perform the media movement.
@param string $type
@param string $location
@param string $oldName
@param string $newName
@return bool|string | [
"Perform",
"the",
"media",
"movement",
"."
] | train | https://github.com/ARCANESOFT/Media/blob/e98aad52f94e6587fcbf79c56f7bf7072929bfc9/src/Http/Controllers/Admin/ApiController.php#L271-L285 |
ARCANESOFT/Media | src/Http/Controllers/Admin/ApiController.php | ApiController.moveFile | private function moveFile($from, $location, $newName)
{
$filename = Str::slug(pathinfo($newName, PATHINFO_FILENAME));
$extension = pathinfo($newName, PATHINFO_EXTENSION);
$this->media->move($from, $to = "{$location}/{$filename}.{$extension}");
return $to;
} | php | private function moveFile($from, $location, $newName)
{
$filename = Str::slug(pathinfo($newName, PATHINFO_FILENAME));
$extension = pathinfo($newName, PATHINFO_EXTENSION);
$this->media->move($from, $to = "{$location}/{$filename}.{$extension}");
return $to;
} | [
"private",
"function",
"moveFile",
"(",
"$",
"from",
",",
"$",
"location",
",",
"$",
"newName",
")",
"{",
"$",
"filename",
"=",
"Str",
"::",
"slug",
"(",
"pathinfo",
"(",
"$",
"newName",
",",
"PATHINFO_FILENAME",
")",
")",
";",
"$",
"extension",
"=",
"pathinfo",
"(",
"$",
"newName",
",",
"PATHINFO_EXTENSION",
")",
";",
"$",
"this",
"->",
"media",
"->",
"move",
"(",
"$",
"from",
",",
"$",
"to",
"=",
"\"{$location}/{$filename}.{$extension}\"",
")",
";",
"return",
"$",
"to",
";",
"}"
] | Move file.
@param string $location
@param string $location
@param string $from
@param string $newName
@return string | [
"Move",
"file",
"."
] | train | https://github.com/ARCANESOFT/Media/blob/e98aad52f94e6587fcbf79c56f7bf7072929bfc9/src/Http/Controllers/Admin/ApiController.php#L297-L305 |
ARCANESOFT/Media | src/Http/Controllers/Admin/ApiController.php | ApiController.moveDirectory | private function moveDirectory($from, $location, $newName)
{
$newName = Str::slug($newName);
return tap("{$location}/{$newName}", function ($to) use ($from) {
$this->media->move($from, $to);
});
} | php | private function moveDirectory($from, $location, $newName)
{
$newName = Str::slug($newName);
return tap("{$location}/{$newName}", function ($to) use ($from) {
$this->media->move($from, $to);
});
} | [
"private",
"function",
"moveDirectory",
"(",
"$",
"from",
",",
"$",
"location",
",",
"$",
"newName",
")",
"{",
"$",
"newName",
"=",
"Str",
"::",
"slug",
"(",
"$",
"newName",
")",
";",
"return",
"tap",
"(",
"\"{$location}/{$newName}\"",
",",
"function",
"(",
"$",
"to",
")",
"use",
"(",
"$",
"from",
")",
"{",
"$",
"this",
"->",
"media",
"->",
"move",
"(",
"$",
"from",
",",
"$",
"to",
")",
";",
"}",
")",
";",
"}"
] | Move directory.
@param string $from
@param string $location
@param string $newName
@return string | [
"Move",
"directory",
"."
] | train | https://github.com/ARCANESOFT/Media/blob/e98aad52f94e6587fcbf79c56f7bf7072929bfc9/src/Http/Controllers/Admin/ApiController.php#L316-L323 |
ARCANESOFT/Media | src/Http/Controllers/Admin/ApiController.php | ApiController.performDeleteMedia | private function performDeleteMedia($type, $path)
{
switch (Str::lower($type)) {
case Media::MEDIA_TYPE_FILE:
return $this->media->deleteFile($path);
case Media::MEDIA_TYPE_DIRECTORY:
return $this->media->deleteDirectory(trim($path, '/'));
default:
return false;
}
} | php | private function performDeleteMedia($type, $path)
{
switch (Str::lower($type)) {
case Media::MEDIA_TYPE_FILE:
return $this->media->deleteFile($path);
case Media::MEDIA_TYPE_DIRECTORY:
return $this->media->deleteDirectory(trim($path, '/'));
default:
return false;
}
} | [
"private",
"function",
"performDeleteMedia",
"(",
"$",
"type",
",",
"$",
"path",
")",
"{",
"switch",
"(",
"Str",
"::",
"lower",
"(",
"$",
"type",
")",
")",
"{",
"case",
"Media",
"::",
"MEDIA_TYPE_FILE",
":",
"return",
"$",
"this",
"->",
"media",
"->",
"deleteFile",
"(",
"$",
"path",
")",
";",
"case",
"Media",
"::",
"MEDIA_TYPE_DIRECTORY",
":",
"return",
"$",
"this",
"->",
"media",
"->",
"deleteDirectory",
"(",
"trim",
"(",
"$",
"path",
",",
"'/'",
")",
")",
";",
"default",
":",
"return",
"false",
";",
"}",
"}"
] | Perform the media deletion.
@param string $type
@param string $path
@return bool | [
"Perform",
"the",
"media",
"deletion",
"."
] | train | https://github.com/ARCANESOFT/Media/blob/e98aad52f94e6587fcbf79c56f7bf7072929bfc9/src/Http/Controllers/Admin/ApiController.php#L333-L345 |
SlaxWeb/Bootstrap | src/Service/LoggerProvider.php | LoggerProvider.register | public function register(App $app)
{
$app["logger.service"] = $app->protect(
function (string $loggerName = "") use ($app) {
$cacheName = "logger.service-{$loggerName}";
if (isset($app[$cacheName])) {
return $app[$cacheName];
}
/*
* Check the config service has been defined and provides correct
* object
*/
if (isset($app["config.service"]) === false
|| get_class($app["config.service"]) !== "SlaxWeb\\Config\\Container") {
throw new \SlaxWeb\Bootstrap\Exception\LoggerConfigException(
"Config component provider must be registered before you can use the Logger component."
);
}
$config = $app["config.service"];
if ($loggerName === "") {
$loggerName = $config["logger.defaultLogger"];
}
$logger = new MLogger($loggerName);
foreach ($config["logger.loggerSettings"][$loggerName] as $type => $settings) {
// load propper handler and instantiate the Monolog\Logger
$handler = null;
switch ($type) {
case Helper::L_TYPE_FILE:
$app["temp.logger.settings"] = $settings;
$handler = $app["logger.{$type}.service"];
unset($app["temp.logger.settings"]);
break;
default:
throw new \SlaxWeb\Bootstrap\Exception\UnknownLoggerHandlerException(
"The handler you are tring to use is not known or not supported."
);
}
$logger->pushHandler($handler);
}
return $app[$cacheName] = $logger;
}
);
$app["logger.StreamHandler.service"] = $app->factory(
function (App $cont) {
$settings = $cont["temp.logger.settings"];
// if the log file name does not begin with a dir separator, treat
// it as relative path and prepend 'logFilePath'
if ($settings[0][0] !== DIRECTORY_SEPARATOR) {
$settings[0] = ($cont["config.service"]["logger.logFilePath"] ?? "")
. $settings[0];
}
return new \Monolog\Handler\StreamHandler(...$settings);
}
);
} | php | public function register(App $app)
{
$app["logger.service"] = $app->protect(
function (string $loggerName = "") use ($app) {
$cacheName = "logger.service-{$loggerName}";
if (isset($app[$cacheName])) {
return $app[$cacheName];
}
/*
* Check the config service has been defined and provides correct
* object
*/
if (isset($app["config.service"]) === false
|| get_class($app["config.service"]) !== "SlaxWeb\\Config\\Container") {
throw new \SlaxWeb\Bootstrap\Exception\LoggerConfigException(
"Config component provider must be registered before you can use the Logger component."
);
}
$config = $app["config.service"];
if ($loggerName === "") {
$loggerName = $config["logger.defaultLogger"];
}
$logger = new MLogger($loggerName);
foreach ($config["logger.loggerSettings"][$loggerName] as $type => $settings) {
// load propper handler and instantiate the Monolog\Logger
$handler = null;
switch ($type) {
case Helper::L_TYPE_FILE:
$app["temp.logger.settings"] = $settings;
$handler = $app["logger.{$type}.service"];
unset($app["temp.logger.settings"]);
break;
default:
throw new \SlaxWeb\Bootstrap\Exception\UnknownLoggerHandlerException(
"The handler you are tring to use is not known or not supported."
);
}
$logger->pushHandler($handler);
}
return $app[$cacheName] = $logger;
}
);
$app["logger.StreamHandler.service"] = $app->factory(
function (App $cont) {
$settings = $cont["temp.logger.settings"];
// if the log file name does not begin with a dir separator, treat
// it as relative path and prepend 'logFilePath'
if ($settings[0][0] !== DIRECTORY_SEPARATOR) {
$settings[0] = ($cont["config.service"]["logger.logFilePath"] ?? "")
. $settings[0];
}
return new \Monolog\Handler\StreamHandler(...$settings);
}
);
} | [
"public",
"function",
"register",
"(",
"App",
"$",
"app",
")",
"{",
"$",
"app",
"[",
"\"logger.service\"",
"]",
"=",
"$",
"app",
"->",
"protect",
"(",
"function",
"(",
"string",
"$",
"loggerName",
"=",
"\"\"",
")",
"use",
"(",
"$",
"app",
")",
"{",
"$",
"cacheName",
"=",
"\"logger.service-{$loggerName}\"",
";",
"if",
"(",
"isset",
"(",
"$",
"app",
"[",
"$",
"cacheName",
"]",
")",
")",
"{",
"return",
"$",
"app",
"[",
"$",
"cacheName",
"]",
";",
"}",
"/*\n * Check the config service has been defined and provides correct\n * object\n */",
"if",
"(",
"isset",
"(",
"$",
"app",
"[",
"\"config.service\"",
"]",
")",
"===",
"false",
"||",
"get_class",
"(",
"$",
"app",
"[",
"\"config.service\"",
"]",
")",
"!==",
"\"SlaxWeb\\\\Config\\\\Container\"",
")",
"{",
"throw",
"new",
"\\",
"SlaxWeb",
"\\",
"Bootstrap",
"\\",
"Exception",
"\\",
"LoggerConfigException",
"(",
"\"Config component provider must be registered before you can use the Logger component.\"",
")",
";",
"}",
"$",
"config",
"=",
"$",
"app",
"[",
"\"config.service\"",
"]",
";",
"if",
"(",
"$",
"loggerName",
"===",
"\"\"",
")",
"{",
"$",
"loggerName",
"=",
"$",
"config",
"[",
"\"logger.defaultLogger\"",
"]",
";",
"}",
"$",
"logger",
"=",
"new",
"MLogger",
"(",
"$",
"loggerName",
")",
";",
"foreach",
"(",
"$",
"config",
"[",
"\"logger.loggerSettings\"",
"]",
"[",
"$",
"loggerName",
"]",
"as",
"$",
"type",
"=>",
"$",
"settings",
")",
"{",
"// load propper handler and instantiate the Monolog\\Logger",
"$",
"handler",
"=",
"null",
";",
"switch",
"(",
"$",
"type",
")",
"{",
"case",
"Helper",
"::",
"L_TYPE_FILE",
":",
"$",
"app",
"[",
"\"temp.logger.settings\"",
"]",
"=",
"$",
"settings",
";",
"$",
"handler",
"=",
"$",
"app",
"[",
"\"logger.{$type}.service\"",
"]",
";",
"unset",
"(",
"$",
"app",
"[",
"\"temp.logger.settings\"",
"]",
")",
";",
"break",
";",
"default",
":",
"throw",
"new",
"\\",
"SlaxWeb",
"\\",
"Bootstrap",
"\\",
"Exception",
"\\",
"UnknownLoggerHandlerException",
"(",
"\"The handler you are tring to use is not known or not supported.\"",
")",
";",
"}",
"$",
"logger",
"->",
"pushHandler",
"(",
"$",
"handler",
")",
";",
"}",
"return",
"$",
"app",
"[",
"$",
"cacheName",
"]",
"=",
"$",
"logger",
";",
"}",
")",
";",
"$",
"app",
"[",
"\"logger.StreamHandler.service\"",
"]",
"=",
"$",
"app",
"->",
"factory",
"(",
"function",
"(",
"App",
"$",
"cont",
")",
"{",
"$",
"settings",
"=",
"$",
"cont",
"[",
"\"temp.logger.settings\"",
"]",
";",
"// if the log file name does not begin with a dir separator, treat",
"// it as relative path and prepend 'logFilePath'",
"if",
"(",
"$",
"settings",
"[",
"0",
"]",
"[",
"0",
"]",
"!==",
"DIRECTORY_SEPARATOR",
")",
"{",
"$",
"settings",
"[",
"0",
"]",
"=",
"(",
"$",
"cont",
"[",
"\"config.service\"",
"]",
"[",
"\"logger.logFilePath\"",
"]",
"??",
"\"\"",
")",
".",
"$",
"settings",
"[",
"0",
"]",
";",
"}",
"return",
"new",
"\\",
"Monolog",
"\\",
"Handler",
"\\",
"StreamHandler",
"(",
"...",
"$",
"settings",
")",
";",
"}",
")",
";",
"}"
] | Register Logger Service Provider
Method used by the DIC to register a new service provider. This Service
Provider defines only the Logger service.
@param \Pimple\Container $app Pimple Dependency Injection Container
@return void | [
"Register",
"Logger",
"Service",
"Provider"
] | train | https://github.com/SlaxWeb/Bootstrap/blob/5ec8ef40f357f2c75afa0ad99090a9d2f7021557/src/Service/LoggerProvider.php#L32-L91 |
Wedeto/HTTP | src/Forms/FormField.php | FormField.setName | public function setName(string $name)
{
$this->name = $name;
while (preg_match('/^(.*)\[([^\]]*)\]$/', $name, $matches) === 1)
{
if (empty($matches[2]))
{
if ($this->name_depth > 1)
throw new \InvalidArgumentException("Invalid name: {$this->name}");
$this->is_array = true;
}
else
array_unshift($this->name_parts, $matches[2]);
$name = $matches[1];
++$this->name_depth;
}
array_unshift($this->name_parts, $name);
return $this;
} | php | public function setName(string $name)
{
$this->name = $name;
while (preg_match('/^(.*)\[([^\]]*)\]$/', $name, $matches) === 1)
{
if (empty($matches[2]))
{
if ($this->name_depth > 1)
throw new \InvalidArgumentException("Invalid name: {$this->name}");
$this->is_array = true;
}
else
array_unshift($this->name_parts, $matches[2]);
$name = $matches[1];
++$this->name_depth;
}
array_unshift($this->name_parts, $name);
return $this;
} | [
"public",
"function",
"setName",
"(",
"string",
"$",
"name",
")",
"{",
"$",
"this",
"->",
"name",
"=",
"$",
"name",
";",
"while",
"(",
"preg_match",
"(",
"'/^(.*)\\[([^\\]]*)\\]$/'",
",",
"$",
"name",
",",
"$",
"matches",
")",
"===",
"1",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"matches",
"[",
"2",
"]",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"name_depth",
">",
"1",
")",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"Invalid name: {$this->name}\"",
")",
";",
"$",
"this",
"->",
"is_array",
"=",
"true",
";",
"}",
"else",
"array_unshift",
"(",
"$",
"this",
"->",
"name_parts",
",",
"$",
"matches",
"[",
"2",
"]",
")",
";",
"$",
"name",
"=",
"$",
"matches",
"[",
"1",
"]",
";",
"++",
"$",
"this",
"->",
"name_depth",
";",
"}",
"array_unshift",
"(",
"$",
"this",
"->",
"name_parts",
",",
"$",
"name",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Change the name of the field.
@param string $name The name to set. If the name contains [] pairs,
the field type will be set to array.
@return FormField Provides fluent interface
@throws InvalidArgumentException When an invalid names as used. An invalid name
is a name with more than one empty array pair,
like foo[][] | [
"Change",
"the",
"name",
"of",
"the",
"field",
"."
] | train | https://github.com/Wedeto/HTTP/blob/7318eff1b81a3c103c4263466d09b7f3593b70b9/src/Forms/FormField.php#L99-L119 |
Wedeto/HTTP | src/Forms/FormField.php | FormField.addValidator | public function addValidator($validator)
{
if ($validator === FormField::TYPE_FILE)
{
$this->is_file = true;
$validator = Type::RESOURCE;
}
if (!$validator instanceof Validator)
{
$validator = new Validator($validator, ['unstrict' => true]);
}
$this->validators[] = $validator;
return $this;
} | php | public function addValidator($validator)
{
if ($validator === FormField::TYPE_FILE)
{
$this->is_file = true;
$validator = Type::RESOURCE;
}
if (!$validator instanceof Validator)
{
$validator = new Validator($validator, ['unstrict' => true]);
}
$this->validators[] = $validator;
return $this;
} | [
"public",
"function",
"addValidator",
"(",
"$",
"validator",
")",
"{",
"if",
"(",
"$",
"validator",
"===",
"FormField",
"::",
"TYPE_FILE",
")",
"{",
"$",
"this",
"->",
"is_file",
"=",
"true",
";",
"$",
"validator",
"=",
"Type",
"::",
"RESOURCE",
";",
"}",
"if",
"(",
"!",
"$",
"validator",
"instanceof",
"Validator",
")",
"{",
"$",
"validator",
"=",
"new",
"Validator",
"(",
"$",
"validator",
",",
"[",
"'unstrict'",
"=>",
"true",
"]",
")",
";",
"}",
"$",
"this",
"->",
"validators",
"[",
"]",
"=",
"$",
"validator",
";",
"return",
"$",
"this",
";",
"}"
] | Change the type of the field
@param Validator $validator The validator to add. Provide either
one of the constants in Type, or a instantiated
Validator. FormField::TYPE_FILE will be transparently
converted to a file upload form field.
@return FormField Provides fluent interface | [
"Change",
"the",
"type",
"of",
"the",
"field"
] | train | https://github.com/Wedeto/HTTP/blob/7318eff1b81a3c103c4263466d09b7f3593b70b9/src/Forms/FormField.php#L129-L144 |
Wedeto/HTTP | src/Forms/FormField.php | FormField.removeValidator | public function removeValidator(int $index)
{
$validators = $this->validators;
unset($validators[$index]);
$this->validators = array_values($validators);
return $this;
} | php | public function removeValidator(int $index)
{
$validators = $this->validators;
unset($validators[$index]);
$this->validators = array_values($validators);
return $this;
} | [
"public",
"function",
"removeValidator",
"(",
"int",
"$",
"index",
")",
"{",
"$",
"validators",
"=",
"$",
"this",
"->",
"validators",
";",
"unset",
"(",
"$",
"validators",
"[",
"$",
"index",
"]",
")",
";",
"$",
"this",
"->",
"validators",
"=",
"array_values",
"(",
"$",
"validators",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Remove a validator with a specific index
@param int $index The index to remove
@return FormField Provides fluent interface | [
"Remove",
"a",
"validator",
"with",
"a",
"specific",
"index"
] | train | https://github.com/Wedeto/HTTP/blob/7318eff1b81a3c103c4263466d09b7f3593b70b9/src/Forms/FormField.php#L151-L157 |
Wedeto/HTTP | src/Forms/FormField.php | FormField.validate | public function validate(Dictionary $arguments, Dictionary $files)
{
$source = $this->isFile() ? $files : $arguments;
$value = $this->extractValue($source);
$this->setValue($value, true);
$value = $this->value;
$this->errors = [];
if ($this->is_array)
{
$name = $this->getName(true);
$value = $this->isFile() ? $files[$name] : $arguments[$name];
$this->setValue($value);
// Validate arrays element by element
if (WF::is_array_like($value) && !($value instanceof Dictionary))
$value = new Dictionary($value);
if (!$value instanceof Dictionary)
{
$this->errors[''][] = [
'msg' => 'Invalid value for {name}: {value}',
'context' => ['name' => $this->name, 'value' => (string)$value]
];
return false;
}
// Value should be a shallow array
if (!$value->isShallow())
{
$this->errors[''][] = [
'msg' => 'Field {name} should not nest',
'context' => ['name' => $this->name]
];
}
// Empty depends on the value of nullable
if (count($value) === 0)
{
$nullable = true;
foreach ($this->validators as $validator)
$nullable = $nullable && $validator->isNullable();
if (!$nullable)
{
$this->errors[''][] = [
'msg' => 'Required field: {name}',
'context' => ['name' => $this->name]
];
}
}
// Validate each value of the array
foreach ($value as $key => $v)
{
foreach ($this->validators as $validator)
{
if (!$validator->validate($v))
{
$this->errors[$key][] = $validator->getErrorMessage($v);
}
}
}
// Check if any errors were produced
return count($this->errors) === 0;
}
foreach ($this->validators as $validator)
{
$result = $validator->validate($this->value, $value);
if (!$result)
{
$this->errors[] = $validator->getErrorMessage($value);
}
else
{
$this->value = $value;
}
}
return count($this->errors) === 0;
} | php | public function validate(Dictionary $arguments, Dictionary $files)
{
$source = $this->isFile() ? $files : $arguments;
$value = $this->extractValue($source);
$this->setValue($value, true);
$value = $this->value;
$this->errors = [];
if ($this->is_array)
{
$name = $this->getName(true);
$value = $this->isFile() ? $files[$name] : $arguments[$name];
$this->setValue($value);
// Validate arrays element by element
if (WF::is_array_like($value) && !($value instanceof Dictionary))
$value = new Dictionary($value);
if (!$value instanceof Dictionary)
{
$this->errors[''][] = [
'msg' => 'Invalid value for {name}: {value}',
'context' => ['name' => $this->name, 'value' => (string)$value]
];
return false;
}
// Value should be a shallow array
if (!$value->isShallow())
{
$this->errors[''][] = [
'msg' => 'Field {name} should not nest',
'context' => ['name' => $this->name]
];
}
// Empty depends on the value of nullable
if (count($value) === 0)
{
$nullable = true;
foreach ($this->validators as $validator)
$nullable = $nullable && $validator->isNullable();
if (!$nullable)
{
$this->errors[''][] = [
'msg' => 'Required field: {name}',
'context' => ['name' => $this->name]
];
}
}
// Validate each value of the array
foreach ($value as $key => $v)
{
foreach ($this->validators as $validator)
{
if (!$validator->validate($v))
{
$this->errors[$key][] = $validator->getErrorMessage($v);
}
}
}
// Check if any errors were produced
return count($this->errors) === 0;
}
foreach ($this->validators as $validator)
{
$result = $validator->validate($this->value, $value);
if (!$result)
{
$this->errors[] = $validator->getErrorMessage($value);
}
else
{
$this->value = $value;
}
}
return count($this->errors) === 0;
} | [
"public",
"function",
"validate",
"(",
"Dictionary",
"$",
"arguments",
",",
"Dictionary",
"$",
"files",
")",
"{",
"$",
"source",
"=",
"$",
"this",
"->",
"isFile",
"(",
")",
"?",
"$",
"files",
":",
"$",
"arguments",
";",
"$",
"value",
"=",
"$",
"this",
"->",
"extractValue",
"(",
"$",
"source",
")",
";",
"$",
"this",
"->",
"setValue",
"(",
"$",
"value",
",",
"true",
")",
";",
"$",
"value",
"=",
"$",
"this",
"->",
"value",
";",
"$",
"this",
"->",
"errors",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"is_array",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"getName",
"(",
"true",
")",
";",
"$",
"value",
"=",
"$",
"this",
"->",
"isFile",
"(",
")",
"?",
"$",
"files",
"[",
"$",
"name",
"]",
":",
"$",
"arguments",
"[",
"$",
"name",
"]",
";",
"$",
"this",
"->",
"setValue",
"(",
"$",
"value",
")",
";",
"// Validate arrays element by element",
"if",
"(",
"WF",
"::",
"is_array_like",
"(",
"$",
"value",
")",
"&&",
"!",
"(",
"$",
"value",
"instanceof",
"Dictionary",
")",
")",
"$",
"value",
"=",
"new",
"Dictionary",
"(",
"$",
"value",
")",
";",
"if",
"(",
"!",
"$",
"value",
"instanceof",
"Dictionary",
")",
"{",
"$",
"this",
"->",
"errors",
"[",
"''",
"]",
"[",
"]",
"=",
"[",
"'msg'",
"=>",
"'Invalid value for {name}: {value}'",
",",
"'context'",
"=>",
"[",
"'name'",
"=>",
"$",
"this",
"->",
"name",
",",
"'value'",
"=>",
"(",
"string",
")",
"$",
"value",
"]",
"]",
";",
"return",
"false",
";",
"}",
"// Value should be a shallow array",
"if",
"(",
"!",
"$",
"value",
"->",
"isShallow",
"(",
")",
")",
"{",
"$",
"this",
"->",
"errors",
"[",
"''",
"]",
"[",
"]",
"=",
"[",
"'msg'",
"=>",
"'Field {name} should not nest'",
",",
"'context'",
"=>",
"[",
"'name'",
"=>",
"$",
"this",
"->",
"name",
"]",
"]",
";",
"}",
"// Empty depends on the value of nullable",
"if",
"(",
"count",
"(",
"$",
"value",
")",
"===",
"0",
")",
"{",
"$",
"nullable",
"=",
"true",
";",
"foreach",
"(",
"$",
"this",
"->",
"validators",
"as",
"$",
"validator",
")",
"$",
"nullable",
"=",
"$",
"nullable",
"&&",
"$",
"validator",
"->",
"isNullable",
"(",
")",
";",
"if",
"(",
"!",
"$",
"nullable",
")",
"{",
"$",
"this",
"->",
"errors",
"[",
"''",
"]",
"[",
"]",
"=",
"[",
"'msg'",
"=>",
"'Required field: {name}'",
",",
"'context'",
"=>",
"[",
"'name'",
"=>",
"$",
"this",
"->",
"name",
"]",
"]",
";",
"}",
"}",
"// Validate each value of the array",
"foreach",
"(",
"$",
"value",
"as",
"$",
"key",
"=>",
"$",
"v",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"validators",
"as",
"$",
"validator",
")",
"{",
"if",
"(",
"!",
"$",
"validator",
"->",
"validate",
"(",
"$",
"v",
")",
")",
"{",
"$",
"this",
"->",
"errors",
"[",
"$",
"key",
"]",
"[",
"]",
"=",
"$",
"validator",
"->",
"getErrorMessage",
"(",
"$",
"v",
")",
";",
"}",
"}",
"}",
"// Check if any errors were produced",
"return",
"count",
"(",
"$",
"this",
"->",
"errors",
")",
"===",
"0",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"validators",
"as",
"$",
"validator",
")",
"{",
"$",
"result",
"=",
"$",
"validator",
"->",
"validate",
"(",
"$",
"this",
"->",
"value",
",",
"$",
"value",
")",
";",
"if",
"(",
"!",
"$",
"result",
")",
"{",
"$",
"this",
"->",
"errors",
"[",
"]",
"=",
"$",
"validator",
"->",
"getErrorMessage",
"(",
"$",
"value",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"value",
"=",
"$",
"value",
";",
"}",
"}",
"return",
"count",
"(",
"$",
"this",
"->",
"errors",
")",
"===",
"0",
";",
"}"
] | Validate the value
@param mixed $request The HTTP request containing the post data
@return bool True when the value validates, false if it does not | [
"Validate",
"the",
"value"
] | train | https://github.com/Wedeto/HTTP/blob/7318eff1b81a3c103c4263466d09b7f3593b70b9/src/Forms/FormField.php#L189-L270 |
Wedeto/HTTP | src/Forms/FormField.php | FormField.getErrors | public function getErrors()
{
if (!empty($this->fixed_error))
return count($this->errors) ? [$this->fixed_error] : [];
return $this->errors;
} | php | public function getErrors()
{
if (!empty($this->fixed_error))
return count($this->errors) ? [$this->fixed_error] : [];
return $this->errors;
} | [
"public",
"function",
"getErrors",
"(",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"fixed_error",
")",
")",
"return",
"count",
"(",
"$",
"this",
"->",
"errors",
")",
"?",
"[",
"$",
"this",
"->",
"fixed_error",
"]",
":",
"[",
"]",
";",
"return",
"$",
"this",
"->",
"errors",
";",
"}"
] | Return the error messages produced during validation. Should be called
after validation failed, otherwise an non-relevant or empty array will be
returned.
@return array List of errors. Empty when validation succeeded. | [
"Return",
"the",
"error",
"messages",
"produced",
"during",
"validation",
".",
"Should",
"be",
"called",
"after",
"validation",
"failed",
"otherwise",
"an",
"non",
"-",
"relevant",
"or",
"empty",
"array",
"will",
"be",
"returned",
"."
] | train | https://github.com/Wedeto/HTTP/blob/7318eff1b81a3c103c4263466d09b7f3593b70b9/src/Forms/FormField.php#L279-L285 |
Wedeto/HTTP | src/Forms/FormField.php | FormField.setError | public function setError(array $msg)
{
if (!isset($msg['msg']))
throw new InvalidArgumentException("Error message does not contain msg key");
$this->errors = [$msg];
$this->fixed_error = $msg;
return $this;
} | php | public function setError(array $msg)
{
if (!isset($msg['msg']))
throw new InvalidArgumentException("Error message does not contain msg key");
$this->errors = [$msg];
$this->fixed_error = $msg;
return $this;
} | [
"public",
"function",
"setError",
"(",
"array",
"$",
"msg",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"msg",
"[",
"'msg'",
"]",
")",
")",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Error message does not contain msg key\"",
")",
";",
"$",
"this",
"->",
"errors",
"=",
"[",
"$",
"msg",
"]",
";",
"$",
"this",
"->",
"fixed_error",
"=",
"$",
"msg",
";",
"return",
"$",
"this",
";",
"}"
] | Set the form field with an error state. This will override the
fixed error.
@param array $msg The error message. Must contain a 'msg' key.
@return FormField provides fluent interface | [
"Set",
"the",
"form",
"field",
"with",
"an",
"error",
"state",
".",
"This",
"will",
"override",
"the",
"fixed",
"error",
"."
] | train | https://github.com/Wedeto/HTTP/blob/7318eff1b81a3c103c4263466d09b7f3593b70b9/src/Forms/FormField.php#L318-L326 |
Wedeto/HTTP | src/Forms/FormField.php | FormField.getValue | public function getValue(bool $transform = false)
{
if ($transform && $this->transformer !== null)
return $this->transformer->serialize($this->value);
return $this->value;
} | php | public function getValue(bool $transform = false)
{
if ($transform && $this->transformer !== null)
return $this->transformer->serialize($this->value);
return $this->value;
} | [
"public",
"function",
"getValue",
"(",
"bool",
"$",
"transform",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"transform",
"&&",
"$",
"this",
"->",
"transformer",
"!==",
"null",
")",
"return",
"$",
"this",
"->",
"transformer",
"->",
"serialize",
"(",
"$",
"this",
"->",
"value",
")",
";",
"return",
"$",
"this",
"->",
"value",
";",
"}"
] | Returns the value, optionally HTML escaped
@param bool $transform Set to true to run the transformer on the value, false
to return the raw value.
@return mixed The value for the item | [
"Returns",
"the",
"value",
"optionally",
"HTML",
"escaped"
] | train | https://github.com/Wedeto/HTTP/blob/7318eff1b81a3c103c4263466d09b7f3593b70b9/src/Forms/FormField.php#L424-L429 |
Wedeto/HTTP | src/Forms/FormField.php | FormField.setValue | public function setValue($value, bool $transform = false)
{
if (null === $value)
$this->value = null;
elseif ($transform && $this->transformer !== null)
$this->value = $this->transformer->deserialize($value);
else
$this->value = $value;
return $this;
} | php | public function setValue($value, bool $transform = false)
{
if (null === $value)
$this->value = null;
elseif ($transform && $this->transformer !== null)
$this->value = $this->transformer->deserialize($value);
else
$this->value = $value;
return $this;
} | [
"public",
"function",
"setValue",
"(",
"$",
"value",
",",
"bool",
"$",
"transform",
"=",
"false",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"value",
")",
"$",
"this",
"->",
"value",
"=",
"null",
";",
"elseif",
"(",
"$",
"transform",
"&&",
"$",
"this",
"->",
"transformer",
"!==",
"null",
")",
"$",
"this",
"->",
"value",
"=",
"$",
"this",
"->",
"transformer",
"->",
"deserialize",
"(",
"$",
"value",
")",
";",
"else",
"$",
"this",
"->",
"value",
"=",
"$",
"value",
";",
"return",
"$",
"this",
";",
"}"
] | Change the value for this field. The value is not validated, this is
just to be referred to later, for example for showing to the visitor
@param mixed $value The value to set
@param bool $transform Whether to run the transformer on it before setting
@return FormField Provides fluent interface | [
"Change",
"the",
"value",
"for",
"this",
"field",
".",
"The",
"value",
"is",
"not",
"validated",
"this",
"is",
"just",
"to",
"be",
"referred",
"to",
"later",
"for",
"example",
"for",
"showing",
"to",
"the",
"visitor"
] | train | https://github.com/Wedeto/HTTP/blob/7318eff1b81a3c103c4263466d09b7f3593b70b9/src/Forms/FormField.php#L439-L449 |
Wedeto/HTTP | src/Forms/FormField.php | FormField.extractValue | public function extractValue(Dictionary $dict)
{
$parts = $this->name_parts;
$value = null;
$depth = 1;
while (count($parts) > 1)
{
$key = array_shift($parts);
if (!$dict->has($key, Type::ARRAY))
return null;
$dict = $dict->get($key);
++$depth;
}
$key = array_shift($parts);
$value = $dict->get($key);
// No values submitted
if (null === $value || ($value instanceof \Countable && count($value) === 0))
return null;
if ($depth < $this->name_depth)
{
// Depth is one less than the amount of array levels,
// because the last one was without a key. This
// means that $value should not be a shallow array
// containing no sub-arrays.
if (!$value instanceof Dictionary || !$value->isShallow())
return null;
}
// Result matches expected depth
return $value;
} | php | public function extractValue(Dictionary $dict)
{
$parts = $this->name_parts;
$value = null;
$depth = 1;
while (count($parts) > 1)
{
$key = array_shift($parts);
if (!$dict->has($key, Type::ARRAY))
return null;
$dict = $dict->get($key);
++$depth;
}
$key = array_shift($parts);
$value = $dict->get($key);
// No values submitted
if (null === $value || ($value instanceof \Countable && count($value) === 0))
return null;
if ($depth < $this->name_depth)
{
// Depth is one less than the amount of array levels,
// because the last one was without a key. This
// means that $value should not be a shallow array
// containing no sub-arrays.
if (!$value instanceof Dictionary || !$value->isShallow())
return null;
}
// Result matches expected depth
return $value;
} | [
"public",
"function",
"extractValue",
"(",
"Dictionary",
"$",
"dict",
")",
"{",
"$",
"parts",
"=",
"$",
"this",
"->",
"name_parts",
";",
"$",
"value",
"=",
"null",
";",
"$",
"depth",
"=",
"1",
";",
"while",
"(",
"count",
"(",
"$",
"parts",
")",
">",
"1",
")",
"{",
"$",
"key",
"=",
"array_shift",
"(",
"$",
"parts",
")",
";",
"if",
"(",
"!",
"$",
"dict",
"->",
"has",
"(",
"$",
"key",
",",
"Type",
"::",
"ARRAY",
")",
")",
"return",
"null",
";",
"$",
"dict",
"=",
"$",
"dict",
"->",
"get",
"(",
"$",
"key",
")",
";",
"++",
"$",
"depth",
";",
"}",
"$",
"key",
"=",
"array_shift",
"(",
"$",
"parts",
")",
";",
"$",
"value",
"=",
"$",
"dict",
"->",
"get",
"(",
"$",
"key",
")",
";",
"// No values submitted",
"if",
"(",
"null",
"===",
"$",
"value",
"||",
"(",
"$",
"value",
"instanceof",
"\\",
"Countable",
"&&",
"count",
"(",
"$",
"value",
")",
"===",
"0",
")",
")",
"return",
"null",
";",
"if",
"(",
"$",
"depth",
"<",
"$",
"this",
"->",
"name_depth",
")",
"{",
"// Depth is one less than the amount of array levels,",
"// because the last one was without a key. This",
"// means that $value should not be a shallow array",
"// containing no sub-arrays.",
"if",
"(",
"!",
"$",
"value",
"instanceof",
"Dictionary",
"||",
"!",
"$",
"value",
"->",
"isShallow",
"(",
")",
")",
"return",
"null",
";",
"}",
"// Result matches expected depth",
"return",
"$",
"value",
";",
"}"
] | Extract the value submitted from the provided dictionary
@param Dictionary $dict Where to get the value from
@return mixed The value from the dictionary, null if it doesn't exist | [
"Extract",
"the",
"value",
"submitted",
"from",
"the",
"provided",
"dictionary",
"@param",
"Dictionary",
"$dict",
"Where",
"to",
"get",
"the",
"value",
"from"
] | train | https://github.com/Wedeto/HTTP/blob/7318eff1b81a3c103c4263466d09b7f3593b70b9/src/Forms/FormField.php#L457-L492 |
Subsets and Splits