repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1 value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
paypayue/paypay-soap | src/PayPayWebservice.php | PayPayWebservice.getEntityPayments | public function getEntityPayments($startDate, $endDate)
{
$requestInterval = new Structure\RequestInterval($startDate, $endDate);
$this->response = parent::getEntityPayments($this->entity, $requestInterval);
/**
* Checks the state of the platform integration.
*/
if (Exception\IntegrationState::check($this->response->integrationState)) {
throw new Exception\IntegrationState($this->response->integrationState);
}
return $this->response;
} | php | public function getEntityPayments($startDate, $endDate)
{
$requestInterval = new Structure\RequestInterval($startDate, $endDate);
$this->response = parent::getEntityPayments($this->entity, $requestInterval);
/**
* Checks the state of the platform integration.
*/
if (Exception\IntegrationState::check($this->response->integrationState)) {
throw new Exception\IntegrationState($this->response->integrationState);
}
return $this->response;
} | [
"public",
"function",
"getEntityPayments",
"(",
"$",
"startDate",
",",
"$",
"endDate",
")",
"{",
"$",
"requestInterval",
"=",
"new",
"Structure",
"\\",
"RequestInterval",
"(",
"$",
"startDate",
",",
"$",
"endDate",
")",
";",
"$",
"this",
"->",
"response",
... | Calls the PayPay Webservice to obtain a list of payments whose state was updated in the given interval.
@param string $startDate
@param string $endDate
@return ResponseEntityPayments | [
"Calls",
"the",
"PayPay",
"Webservice",
"to",
"obtain",
"a",
"list",
"of",
"payments",
"whose",
"state",
"was",
"updated",
"in",
"the",
"given",
"interval",
"."
] | ab01d5c041bbf1032fa5725abef5a6b19af746e4 | https://github.com/paypayue/paypay-soap/blob/ab01d5c041bbf1032fa5725abef5a6b19af746e4/src/PayPayWebservice.php#L323-L337 | train |
paypayue/paypay-soap | src/PayPayWebservice.php | PayPayWebservice.checkEntityPayments | public function checkEntityPayments($payments = array())
{
$requestReferenceDetails = new Structure\RequestEntityPayments();
if ($payments) {
foreach ($payments as $key => $value) {
$requestPayment = new Structure\RequestReferenceDetails($value);
$requestReferenceDetails->addPayment($requestPayment);
}
}
$this->response = parent::checkEntityPayments($this->entity, $requestReferenceDetails);
/**
* Checks the state of the platform integration.
*/
if (Exception\IntegrationState::check($this->response->state)) {
throw new Exception\IntegrationState($this->response->state);
}
if ($this->response->state->state == 0) {
throw new Exception\IntegrationResponse($this->response->state->message, $this->response->state->code);
}
return $this->response;
} | php | public function checkEntityPayments($payments = array())
{
$requestReferenceDetails = new Structure\RequestEntityPayments();
if ($payments) {
foreach ($payments as $key => $value) {
$requestPayment = new Structure\RequestReferenceDetails($value);
$requestReferenceDetails->addPayment($requestPayment);
}
}
$this->response = parent::checkEntityPayments($this->entity, $requestReferenceDetails);
/**
* Checks the state of the platform integration.
*/
if (Exception\IntegrationState::check($this->response->state)) {
throw new Exception\IntegrationState($this->response->state);
}
if ($this->response->state->state == 0) {
throw new Exception\IntegrationResponse($this->response->state->message, $this->response->state->code);
}
return $this->response;
} | [
"public",
"function",
"checkEntityPayments",
"(",
"$",
"payments",
"=",
"array",
"(",
")",
")",
"{",
"$",
"requestReferenceDetails",
"=",
"new",
"Structure",
"\\",
"RequestEntityPayments",
"(",
")",
";",
"if",
"(",
"$",
"payments",
")",
"{",
"foreach",
"(",
... | Calls the PayPay Webservice to check the state of multiple payments.
@param array $payments [description]
@return ResponseEntityPaymentsDetails Webservice Response | [
"Calls",
"the",
"PayPay",
"Webservice",
"to",
"check",
"the",
"state",
"of",
"multiple",
"payments",
"."
] | ab01d5c041bbf1032fa5725abef5a6b19af746e4 | https://github.com/paypayue/paypay-soap/blob/ab01d5c041bbf1032fa5725abef5a6b19af746e4/src/PayPayWebservice.php#L353-L377 | train |
fezfez/codeGenerator | src/CrudGenerator/EnvironnementResolver/ZendFramework2Environnement.php | ZendFramework2Environnement.getDependence | public static function getDependence(FileManager $fileManager)
{
if (null === self::$serviceManager) {
$config = self::findConfigFile($fileManager);
try {
self::$serviceManager = Application::init(
$fileManager->includeFile($config)
)->getServiceManager();
} catch(RuntimeException $e) {
throw new EnvironnementResolverException($e->getMessage());
} catch (ExceptionInterface $e) {
throw new EnvironnementResolverException(
sprintf(
'%s. Config loaded %s',
$e->getMessage(),
$config
)
);
}
}
return self::$serviceManager;
} | php | public static function getDependence(FileManager $fileManager)
{
if (null === self::$serviceManager) {
$config = self::findConfigFile($fileManager);
try {
self::$serviceManager = Application::init(
$fileManager->includeFile($config)
)->getServiceManager();
} catch(RuntimeException $e) {
throw new EnvironnementResolverException($e->getMessage());
} catch (ExceptionInterface $e) {
throw new EnvironnementResolverException(
sprintf(
'%s. Config loaded %s',
$e->getMessage(),
$config
)
);
}
}
return self::$serviceManager;
} | [
"public",
"static",
"function",
"getDependence",
"(",
"FileManager",
"$",
"fileManager",
")",
"{",
"if",
"(",
"null",
"===",
"self",
"::",
"$",
"serviceManager",
")",
"{",
"$",
"config",
"=",
"self",
"::",
"findConfigFile",
"(",
"$",
"fileManager",
")",
";... | Check if we are in zf2 env
@param FileManager $fileManager
@throws RuntimeException
@throws EnvironnementResolverException
@return \Zend\ServiceManager\ServiceManager | [
"Check",
"if",
"we",
"are",
"in",
"zf2",
"env"
] | 559f22bcc525c3157ecb17fe96818dd7b7ee58c2 | https://github.com/fezfez/codeGenerator/blob/559f22bcc525c3157ecb17fe96818dd7b7ee58c2/src/CrudGenerator/EnvironnementResolver/ZendFramework2Environnement.php#L37-L60 | train |
pscheit/jparser | PLUG/parsing/LR/LRStation.php | LRStation.collect_non_deterministic | function collect_non_deterministic( Grammar $Grammar, $k ){
// avoid recursion by testing if already collected
if ( isset($this->etransitions) ){
return;
}
$this->etransitions = array();
// get all rules with our non-terminal as left had side
foreach( $Grammar->get_rules($this->nt) as $r => $rule ){
// create single Item for new state with pointer at start of rule
$Item = LRItem::make( $r, $rule, 0 );
if( isset($this->la) && $k === 1 ){
$Item->lookahead( $this->la );
}
// create e-transition to state with single item
$State = LRState::make( $Item );
$State->collect_non_deterministic( $Grammar, $k );
$this->etransitions[] = $State;
}
} | php | function collect_non_deterministic( Grammar $Grammar, $k ){
// avoid recursion by testing if already collected
if ( isset($this->etransitions) ){
return;
}
$this->etransitions = array();
// get all rules with our non-terminal as left had side
foreach( $Grammar->get_rules($this->nt) as $r => $rule ){
// create single Item for new state with pointer at start of rule
$Item = LRItem::make( $r, $rule, 0 );
if( isset($this->la) && $k === 1 ){
$Item->lookahead( $this->la );
}
// create e-transition to state with single item
$State = LRState::make( $Item );
$State->collect_non_deterministic( $Grammar, $k );
$this->etransitions[] = $State;
}
} | [
"function",
"collect_non_deterministic",
"(",
"Grammar",
"$",
"Grammar",
",",
"$",
"k",
")",
"{",
"// avoid recursion by testing if already collected",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"etransitions",
")",
")",
"{",
"return",
";",
"}",
"$",
"this",
... | Start recursive collection of e-transtions to states
@param Grammar
@param int number of symbols to look ahead, currently only 0 or 1
@return void | [
"Start",
"recursive",
"collection",
"of",
"e",
"-",
"transtions",
"to",
"states"
] | f9de77171c0d37d237e0e9a918ed7bff19e12095 | https://github.com/pscheit/jparser/blob/f9de77171c0d37d237e0e9a918ed7bff19e12095/PLUG/parsing/LR/LRStation.php#L100-L120 | train |
pscheit/jparser | PLUG/parsing/LR/LRStation.php | LRStation.collect_states | function collect_states( Grammar $Grammar ){
$states = array();
// start recursion
$this->collect_states_recursive( $states, $Grammar, array(), ++self::$threadInc );
return $states;
} | php | function collect_states( Grammar $Grammar ){
$states = array();
// start recursion
$this->collect_states_recursive( $states, $Grammar, array(), ++self::$threadInc );
return $states;
} | [
"function",
"collect_states",
"(",
"Grammar",
"$",
"Grammar",
")",
"{",
"$",
"states",
"=",
"array",
"(",
")",
";",
"// start recursion",
"$",
"this",
"->",
"collect_states_recursive",
"(",
"$",
"states",
",",
"$",
"Grammar",
",",
"array",
"(",
")",
",",
... | Collect all child states passing through any e-transitions to further stations
@return array | [
"Collect",
"all",
"child",
"states",
"passing",
"through",
"any",
"e",
"-",
"transitions",
"to",
"further",
"stations"
] | f9de77171c0d37d237e0e9a918ed7bff19e12095 | https://github.com/pscheit/jparser/blob/f9de77171c0d37d237e0e9a918ed7bff19e12095/PLUG/parsing/LR/LRStation.php#L128-L133 | train |
pscheit/jparser | PLUG/parsing/LR/LRStation.php | LRStation.make | static function make( $nt, $la = null ){
if( isset(self::$uindex[$nt][$la]) ){
return self::$uindex[$nt][$la];
}
return new LRStation( $nt, $la );
} | php | static function make( $nt, $la = null ){
if( isset(self::$uindex[$nt][$la]) ){
return self::$uindex[$nt][$la];
}
return new LRStation( $nt, $la );
} | [
"static",
"function",
"make",
"(",
"$",
"nt",
",",
"$",
"la",
"=",
"null",
")",
"{",
"if",
"(",
"isset",
"(",
"self",
"::",
"$",
"uindex",
"[",
"$",
"nt",
"]",
"[",
"$",
"la",
"]",
")",
")",
"{",
"return",
"self",
"::",
"$",
"uindex",
"[",
... | Factory method to ensure unique object instances globally
And stored in global index in an accessible way
@param int non-terminal symbol
@param int|string optional lookahead symbol
@return LRStation | [
"Factory",
"method",
"to",
"ensure",
"unique",
"object",
"instances",
"globally",
"And",
"stored",
"in",
"global",
"index",
"in",
"an",
"accessible",
"way"
] | f9de77171c0d37d237e0e9a918ed7bff19e12095 | https://github.com/pscheit/jparser/blob/f9de77171c0d37d237e0e9a918ed7bff19e12095/PLUG/parsing/LR/LRStation.php#L212-L217 | train |
pscheit/jparser | PLUG/parsing/LR/LRStation.php | LRStation.get | static function get( $nt, $la = null ){
if( isset(self::$uindex[$nt][$la]) ){
return self::$uindex[$nt][$la];
}
return null;
} | php | static function get( $nt, $la = null ){
if( isset(self::$uindex[$nt][$la]) ){
return self::$uindex[$nt][$la];
}
return null;
} | [
"static",
"function",
"get",
"(",
"$",
"nt",
",",
"$",
"la",
"=",
"null",
")",
"{",
"if",
"(",
"isset",
"(",
"self",
"::",
"$",
"uindex",
"[",
"$",
"nt",
"]",
"[",
"$",
"la",
"]",
")",
")",
"{",
"return",
"self",
"::",
"$",
"uindex",
"[",
"... | Getter method that consults global index
@param int non-terminal symbol
@param int|string optional lookahead symbol
@return LRStation | [
"Getter",
"method",
"that",
"consults",
"global",
"index"
] | f9de77171c0d37d237e0e9a918ed7bff19e12095 | https://github.com/pscheit/jparser/blob/f9de77171c0d37d237e0e9a918ed7bff19e12095/PLUG/parsing/LR/LRStation.php#L227-L232 | train |
pscheit/jparser | PLUG/compiler/miniparsers/Inc/IncStatementNode.php | IncStatementNode.get_args | function get_args( array $consts, array $vars ){
$args = array();
// limit depth of search to avoid collecting nested func calls
$argnodes = $this->get_nodes_by_symbol( NT_ARG, 3 );
foreach( $argnodes as $i => $arg ){
$args[] = $arg->compile_string( $consts, $vars );
}
return $args;
} | php | function get_args( array $consts, array $vars ){
$args = array();
// limit depth of search to avoid collecting nested func calls
$argnodes = $this->get_nodes_by_symbol( NT_ARG, 3 );
foreach( $argnodes as $i => $arg ){
$args[] = $arg->compile_string( $consts, $vars );
}
return $args;
} | [
"function",
"get_args",
"(",
"array",
"$",
"consts",
",",
"array",
"$",
"vars",
")",
"{",
"$",
"args",
"=",
"array",
"(",
")",
";",
"// limit depth of search to avoid collecting nested func calls",
"$",
"argnodes",
"=",
"$",
"this",
"->",
"get_nodes_by_symbol",
... | Fetch full resolved arguments.
@param array registry of contants values to override those currently defined in script
@param array registry of variables, e.g. <code>array ( 'argv' => array('path/info'), '_SERVER' => array( ... ), ... );</code>
@return array one or more string arguments | [
"Fetch",
"full",
"resolved",
"arguments",
"."
] | f9de77171c0d37d237e0e9a918ed7bff19e12095 | https://github.com/pscheit/jparser/blob/f9de77171c0d37d237e0e9a918ed7bff19e12095/PLUG/compiler/miniparsers/Inc/IncStatementNode.php#L30-L38 | train |
fezfez/codeGenerator | src/CrudGenerator/History/HistoryFactory.php | HistoryFactory.getInstance | public static function getInstance(ContextInterface $context)
{
$fileManager = new FileManager();
$historyHydrator = HistoryHydratorFactory::getInstance($context);
return new HistoryManager($fileManager, $historyHydrator);
} | php | public static function getInstance(ContextInterface $context)
{
$fileManager = new FileManager();
$historyHydrator = HistoryHydratorFactory::getInstance($context);
return new HistoryManager($fileManager, $historyHydrator);
} | [
"public",
"static",
"function",
"getInstance",
"(",
"ContextInterface",
"$",
"context",
")",
"{",
"$",
"fileManager",
"=",
"new",
"FileManager",
"(",
")",
";",
"$",
"historyHydrator",
"=",
"HistoryHydratorFactory",
"::",
"getInstance",
"(",
"$",
"context",
")",
... | Create HistoryManager instance
@return \CrudGenerator\History\HistoryManager | [
"Create",
"HistoryManager",
"instance"
] | 559f22bcc525c3157ecb17fe96818dd7b7ee58c2 | https://github.com/fezfez/codeGenerator/blob/559f22bcc525c3157ecb17fe96818dd7b7ee58c2/src/CrudGenerator/History/HistoryFactory.php#L27-L33 | train |
pscheit/jparser | PLUG/parsing/GrammarBuilder.php | GrammarBuilder.make | static function make( array $grammar, $class = __CLASS__ ){
$Me = new $class;
foreach( $grammar as $nt => $rhss ){
foreach( $rhss as $rhs ){
$Me->make_rule( $nt, $rhs );
}
}
return $Me;
} | php | static function make( array $grammar, $class = __CLASS__ ){
$Me = new $class;
foreach( $grammar as $nt => $rhss ){
foreach( $rhss as $rhs ){
$Me->make_rule( $nt, $rhs );
}
}
return $Me;
} | [
"static",
"function",
"make",
"(",
"array",
"$",
"grammar",
",",
"$",
"class",
"=",
"__CLASS__",
")",
"{",
"$",
"Me",
"=",
"new",
"$",
"class",
";",
"foreach",
"(",
"$",
"grammar",
"as",
"$",
"nt",
"=>",
"$",
"rhss",
")",
"{",
"foreach",
"(",
"$"... | Convert a hard-coded grammar into a Grammar instance
@param array grammar in form [ A => [ [abc],[def] ], B => ...
@param string optionally allow instantiation of a Grammar subclass
@return Grammar | [
"Convert",
"a",
"hard",
"-",
"coded",
"grammar",
"into",
"a",
"Grammar",
"instance"
] | f9de77171c0d37d237e0e9a918ed7bff19e12095 | https://github.com/pscheit/jparser/blob/f9de77171c0d37d237e0e9a918ed7bff19e12095/PLUG/parsing/GrammarBuilder.php#L29-L37 | train |
pscheit/jparser | PLUG/parsing/GrammarBuilder.php | GrammarBuilder.rule_signature | private static function rule_signature( $lhs, array $rhs ){
$a[] = $lhs;
foreach( $rhs as $t ){
$a[] = $t;
}
return implode( '.', $a );
} | php | private static function rule_signature( $lhs, array $rhs ){
$a[] = $lhs;
foreach( $rhs as $t ){
$a[] = $t;
}
return implode( '.', $a );
} | [
"private",
"static",
"function",
"rule_signature",
"(",
"$",
"lhs",
",",
"array",
"$",
"rhs",
")",
"{",
"$",
"a",
"[",
"]",
"=",
"$",
"lhs",
";",
"foreach",
"(",
"$",
"rhs",
"as",
"$",
"t",
")",
"{",
"$",
"a",
"[",
"]",
"=",
"$",
"t",
";",
... | Create a signature to identify a rule uniquely
@param mixed scalar non-terminal symbol
@param array list of symbols in right hand side
@return string | [
"Create",
"a",
"signature",
"to",
"identify",
"a",
"rule",
"uniquely"
] | f9de77171c0d37d237e0e9a918ed7bff19e12095 | https://github.com/pscheit/jparser/blob/f9de77171c0d37d237e0e9a918ed7bff19e12095/PLUG/parsing/GrammarBuilder.php#L94-L100 | train |
pscheit/jparser | PLUG/parsing/GrammarBuilder.php | GrammarBuilder.make_rule | function make_rule( $nt, array $rhs ){
if( ! isset($this->uindex) || ! isset($this->ntindex) ){
$this->rebuild_index();
}
// explicit goal rule ??
if( end($rhs) === P_EOF ){
// trigger_error("Do not specify P_EOF explicitly in grammar", E_USER_WARNING );
$this->goal = $nt;
$this->rules[ -2 ] = array( P_GOAL, array( $nt ) );
$this->rebuild_index();
}
// guess start symbol as first in grammar
else if( is_null( $this->start_symbol() ) ){
$this->start_symbol( $nt );
}
reset( $rhs );
$sig = self::rule_signature( $nt, $rhs );
// return existing if possible
if( isset($this->uindex[$sig]) ){
return $this->rules[ $this->uindex[$sig] ];
}
// else create new rule
$rule = array( $nt, $rhs );
// register globally
$this->rules[ $this->i ] = $rule;
$this->uindex[$sig] = $this->i;
$this->ntindex[$nt][] = $this->i;
$this->i += 2;
// register symbols
if( isset($this->ts[$nt] ) ){
// not terminal after all
unset( $this->ts[$nt] );
}
$this->nts[ $nt ] = $nt;
// assume rhs all terminals until identified as not
foreach( $rhs as $s ){
is_array( $s ) and $s = $s[0];
if( !isset($this->nts[$s]) ){
$this->ts[ $s ] = $s;
}
}
return $rule;
} | php | function make_rule( $nt, array $rhs ){
if( ! isset($this->uindex) || ! isset($this->ntindex) ){
$this->rebuild_index();
}
// explicit goal rule ??
if( end($rhs) === P_EOF ){
// trigger_error("Do not specify P_EOF explicitly in grammar", E_USER_WARNING );
$this->goal = $nt;
$this->rules[ -2 ] = array( P_GOAL, array( $nt ) );
$this->rebuild_index();
}
// guess start symbol as first in grammar
else if( is_null( $this->start_symbol() ) ){
$this->start_symbol( $nt );
}
reset( $rhs );
$sig = self::rule_signature( $nt, $rhs );
// return existing if possible
if( isset($this->uindex[$sig]) ){
return $this->rules[ $this->uindex[$sig] ];
}
// else create new rule
$rule = array( $nt, $rhs );
// register globally
$this->rules[ $this->i ] = $rule;
$this->uindex[$sig] = $this->i;
$this->ntindex[$nt][] = $this->i;
$this->i += 2;
// register symbols
if( isset($this->ts[$nt] ) ){
// not terminal after all
unset( $this->ts[$nt] );
}
$this->nts[ $nt ] = $nt;
// assume rhs all terminals until identified as not
foreach( $rhs as $s ){
is_array( $s ) and $s = $s[0];
if( !isset($this->nts[$s]) ){
$this->ts[ $s ] = $s;
}
}
return $rule;
} | [
"function",
"make_rule",
"(",
"$",
"nt",
",",
"array",
"$",
"rhs",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"uindex",
")",
"||",
"!",
"isset",
"(",
"$",
"this",
"->",
"ntindex",
")",
")",
"{",
"$",
"this",
"->",
"rebuild_index",... | Factory method, ensures unique rules
@param mixed scalar non-terminal symbol
@param array list of symbols in right hand side
@return array | [
"Factory",
"method",
"ensures",
"unique",
"rules"
] | f9de77171c0d37d237e0e9a918ed7bff19e12095 | https://github.com/pscheit/jparser/blob/f9de77171c0d37d237e0e9a918ed7bff19e12095/PLUG/parsing/GrammarBuilder.php#L111-L159 | train |
pscheit/jparser | PLUG/parsing/GrammarBuilder.php | GrammarBuilder.remove_rules | function remove_rules( $nt ){
if( ! isset($this->ntindex) ){
$this->rebuild_index();
}
// remove this non-terminal's rules
if( isset($this->ntindex[$nt]) ){
foreach( $this->ntindex[$nt] as $i ){
$sig = self::rule_signature( $nt, $this->rules[$i][1] );
unset( $this->rules[$i] );
unset( $this->uindex[$sig] );
}
}
// remove non terminal
unset (
$this->nts[$nt],
$this->ntindex[$nt]
);
} | php | function remove_rules( $nt ){
if( ! isset($this->ntindex) ){
$this->rebuild_index();
}
// remove this non-terminal's rules
if( isset($this->ntindex[$nt]) ){
foreach( $this->ntindex[$nt] as $i ){
$sig = self::rule_signature( $nt, $this->rules[$i][1] );
unset( $this->rules[$i] );
unset( $this->uindex[$sig] );
}
}
// remove non terminal
unset (
$this->nts[$nt],
$this->ntindex[$nt]
);
} | [
"function",
"remove_rules",
"(",
"$",
"nt",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"ntindex",
")",
")",
"{",
"$",
"this",
"->",
"rebuild_index",
"(",
")",
";",
"}",
"// remove this non-terminal's rules",
"if",
"(",
"isset",
"(",
"$"... | Remove a non-terminal symbol and delete all of its rules.
@param int
@return void | [
"Remove",
"a",
"non",
"-",
"terminal",
"symbol",
"and",
"delete",
"all",
"of",
"its",
"rules",
"."
] | f9de77171c0d37d237e0e9a918ed7bff19e12095 | https://github.com/pscheit/jparser/blob/f9de77171c0d37d237e0e9a918ed7bff19e12095/PLUG/parsing/GrammarBuilder.php#L168-L185 | train |
pscheit/jparser | PLUG/parsing/GrammarBuilder.php | GrammarBuilder.build_first_sets | private function build_first_sets(){
$firsts = array();
do {
$changes = 0;
foreach( $this->rules as $rule ){
list( $nt, $rhs ) = $rule;
$s = reset( $rhs );
// get any special rule processing for this non-terminal
//$excludela = isset($this->excludela[$nt]) ? $this->excludela[$nt] : null;
do {
// add terminal to first set of $nt
if( $this->is_terminal( $s ) ){
if( ! isset($firsts[$nt][$s]) ){
$firsts[$nt][$s] = $s;
$changes++;
}
continue 2;
}
// else inherit from first set of this non-terminal
if( ! isset($firsts[$s]) ){
// throw new Exception( sprintf("FIRST(%s) not defined", $s) );
$changes++;
continue 2;
}
// collect all terminal symbols in this non-terminal's set
// except the empty string which we do not inherit.
$derives_e = isset( $firsts[$s][P_EPSILON] );
foreach( $firsts[$s] as $t ){
// Omit any lookahead symbols denied by special rule
//if( $excludela && in_array( $t, $excludela,true ) ){
// // ignored
//}
//else
if( $t !== P_EPSILON && ! isset( $firsts[$nt][$t] ) ){
$firsts[$nt][$t] = $t;
$changes++;
}
}
// we move to next in sequence if non-terminal can derive empty
}
while( $derives_e && $s = next($rhs) );
}
}
while( $changes > 0 );
return $firsts;
} | php | private function build_first_sets(){
$firsts = array();
do {
$changes = 0;
foreach( $this->rules as $rule ){
list( $nt, $rhs ) = $rule;
$s = reset( $rhs );
// get any special rule processing for this non-terminal
//$excludela = isset($this->excludela[$nt]) ? $this->excludela[$nt] : null;
do {
// add terminal to first set of $nt
if( $this->is_terminal( $s ) ){
if( ! isset($firsts[$nt][$s]) ){
$firsts[$nt][$s] = $s;
$changes++;
}
continue 2;
}
// else inherit from first set of this non-terminal
if( ! isset($firsts[$s]) ){
// throw new Exception( sprintf("FIRST(%s) not defined", $s) );
$changes++;
continue 2;
}
// collect all terminal symbols in this non-terminal's set
// except the empty string which we do not inherit.
$derives_e = isset( $firsts[$s][P_EPSILON] );
foreach( $firsts[$s] as $t ){
// Omit any lookahead symbols denied by special rule
//if( $excludela && in_array( $t, $excludela,true ) ){
// // ignored
//}
//else
if( $t !== P_EPSILON && ! isset( $firsts[$nt][$t] ) ){
$firsts[$nt][$t] = $t;
$changes++;
}
}
// we move to next in sequence if non-terminal can derive empty
}
while( $derives_e && $s = next($rhs) );
}
}
while( $changes > 0 );
return $firsts;
} | [
"private",
"function",
"build_first_sets",
"(",
")",
"{",
"$",
"firsts",
"=",
"array",
"(",
")",
";",
"do",
"{",
"$",
"changes",
"=",
"0",
";",
"foreach",
"(",
"$",
"this",
"->",
"rules",
"as",
"$",
"rule",
")",
"{",
"list",
"(",
"$",
"nt",
",",
... | Generate FIRST sets for each non-terminal.
@return array | [
"Generate",
"FIRST",
"sets",
"for",
"each",
"non",
"-",
"terminal",
"."
] | f9de77171c0d37d237e0e9a918ed7bff19e12095 | https://github.com/pscheit/jparser/blob/f9de77171c0d37d237e0e9a918ed7bff19e12095/PLUG/parsing/GrammarBuilder.php#L205-L250 | train |
pscheit/jparser | PLUG/parsing/GrammarBuilder.php | GrammarBuilder.build_follow_sets | private function build_follow_sets(){
if( ! isset($this->firsts) ){
$this->firsts = $this->build_first_sets();
}
// remember inhritance for error checking
//$inherits = array();
// create default/dummy sets with special symbols
$follows = array(
P_GOAL => array(),
P_EOF => array()
);
do {
$changes = 0;
foreach( $this->rules as $rule ){
list( $s, $rhs ) = $rule;
//echo "----\n";
//echo "$s -> ", implode(',', $rhs), "\n";
while( $a = current($rhs) ){
if( $a === P_EPSILON ){
next($rhs);
continue;
}
//echo "\na = $a\n";
if( false === next($rhs) ){
// end of rule, inherit from LHS
if( !isset($follows[$s]) ){
//echo "FOLLOW($s) not set, required by $a \n";
//$inherits[$s] = true;
continue 2;
}
foreach( $follows[$s] as $t ){
if( !isset($follows[$a][$t]) ){
//echo "FOLLOW($a) []= $t \n";
$follows[$a][$t] = $t;
$changes++;
}
}
// next rule.
continue 2;
}
$r = array_slice( $rhs, key($rhs) );
while( $b = current($r) ){
//echo "b = $b\n";
// merge first(b) into follow(a),
// if it derives the empty string, continue to next in rhs
$fs = $this->is_terminal($b) ? array($b) : $this->firsts[$b];
//echo "FOLLOW($a) []= FIRST($b) = ",implode(',', $fs),"\n";
foreach( $fs as $t ){
if( ! isset($follows[$a][$t]) && $t !== P_EPSILON ){
$follows[$a][$t] = $t;
//echo "FOLLOW($a) []= $t \n";
$changes++;
}
}
// if derives empty, skip to next or inherit lhs
if( ! isset($fs[P_EPSILON]) ){
break;
}
if( false === next($r) ){
//echo "FOLLOW($a) []= FOLLOW($s)\n";
if( !isset($follows[$s]) ){
//echo "FOLLOW($s) not set, required by $a \n";
//$inherits[$s] = true;
continue 3;
}
foreach( $follows[$s] as $t ){
if( !isset($follows[$a][$t]) ){
//echo "FOLLOW($a) []= $t \n";
$follows[$a][$t] = $t;
$changes++;
}
}
}
}
}
}
}
while( $changes );
// check inheritance problems, uncomment to debug
/*
foreach( $inherits as $s => $bool ){
if( ! isset($follows[$s]) ){
trigger_error("FOLLOW($s) was never created", E_USER_NOTICE );
}
}
//*/
return $follows;
} | php | private function build_follow_sets(){
if( ! isset($this->firsts) ){
$this->firsts = $this->build_first_sets();
}
// remember inhritance for error checking
//$inherits = array();
// create default/dummy sets with special symbols
$follows = array(
P_GOAL => array(),
P_EOF => array()
);
do {
$changes = 0;
foreach( $this->rules as $rule ){
list( $s, $rhs ) = $rule;
//echo "----\n";
//echo "$s -> ", implode(',', $rhs), "\n";
while( $a = current($rhs) ){
if( $a === P_EPSILON ){
next($rhs);
continue;
}
//echo "\na = $a\n";
if( false === next($rhs) ){
// end of rule, inherit from LHS
if( !isset($follows[$s]) ){
//echo "FOLLOW($s) not set, required by $a \n";
//$inherits[$s] = true;
continue 2;
}
foreach( $follows[$s] as $t ){
if( !isset($follows[$a][$t]) ){
//echo "FOLLOW($a) []= $t \n";
$follows[$a][$t] = $t;
$changes++;
}
}
// next rule.
continue 2;
}
$r = array_slice( $rhs, key($rhs) );
while( $b = current($r) ){
//echo "b = $b\n";
// merge first(b) into follow(a),
// if it derives the empty string, continue to next in rhs
$fs = $this->is_terminal($b) ? array($b) : $this->firsts[$b];
//echo "FOLLOW($a) []= FIRST($b) = ",implode(',', $fs),"\n";
foreach( $fs as $t ){
if( ! isset($follows[$a][$t]) && $t !== P_EPSILON ){
$follows[$a][$t] = $t;
//echo "FOLLOW($a) []= $t \n";
$changes++;
}
}
// if derives empty, skip to next or inherit lhs
if( ! isset($fs[P_EPSILON]) ){
break;
}
if( false === next($r) ){
//echo "FOLLOW($a) []= FOLLOW($s)\n";
if( !isset($follows[$s]) ){
//echo "FOLLOW($s) not set, required by $a \n";
//$inherits[$s] = true;
continue 3;
}
foreach( $follows[$s] as $t ){
if( !isset($follows[$a][$t]) ){
//echo "FOLLOW($a) []= $t \n";
$follows[$a][$t] = $t;
$changes++;
}
}
}
}
}
}
}
while( $changes );
// check inheritance problems, uncomment to debug
/*
foreach( $inherits as $s => $bool ){
if( ! isset($follows[$s]) ){
trigger_error("FOLLOW($s) was never created", E_USER_NOTICE );
}
}
//*/
return $follows;
} | [
"private",
"function",
"build_follow_sets",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"firsts",
")",
")",
"{",
"$",
"this",
"->",
"firsts",
"=",
"$",
"this",
"->",
"build_first_sets",
"(",
")",
";",
"}",
"// remember inhritance for ... | Generate FOLLOW sets for each non-terminal.
@todo fix inheritance problem
@return array | [
"Generate",
"FOLLOW",
"sets",
"for",
"each",
"non",
"-",
"terminal",
"."
] | f9de77171c0d37d237e0e9a918ed7bff19e12095 | https://github.com/pscheit/jparser/blob/f9de77171c0d37d237e0e9a918ed7bff19e12095/PLUG/parsing/GrammarBuilder.php#L273-L361 | train |
stanislav-web/Searcher | src/Searcher/Hydrators/JsonHydrator.php | JsonHydrator.extract | public function extract(callable $callback = null)
{
$this->response = Di::getDefault()->get('response');
if ($callback === null) {
$this->response->setContent(json_encode($this->result->toArray()));
}
else {
$this->response->setContent($callback(
json_encode($this->result->toArray())
));
}
$this->response->send();
} | php | public function extract(callable $callback = null)
{
$this->response = Di::getDefault()->get('response');
if ($callback === null) {
$this->response->setContent(json_encode($this->result->toArray()));
}
else {
$this->response->setContent($callback(
json_encode($this->result->toArray())
));
}
$this->response->send();
} | [
"public",
"function",
"extract",
"(",
"callable",
"$",
"callback",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"response",
"=",
"Di",
"::",
"getDefault",
"(",
")",
"->",
"get",
"(",
"'response'",
")",
";",
"if",
"(",
"$",
"callback",
"===",
"null",
")"... | Extract result data to json
@param callback|null $callback function to data
@return mixed | [
"Extract",
"result",
"data",
"to",
"json"
] | bf01156d1a2416ceddef0d238469563b74087d44 | https://github.com/stanislav-web/Searcher/blob/bf01156d1a2416ceddef0d238469563b74087d44/src/Searcher/Hydrators/JsonHydrator.php#L77-L93 | train |
webfactory/symfony-application-tests | src/Webfactory/Constraint/IsEventSubscriberConstraint.php | IsEventSubscriberConstraint.matches | protected function matches($other): bool
{
$this->resetProblems();
if (!($other instanceof EventSubscriberInterface)) {
$this->addProblem('Subscriber must implement \Symfony\Component\EventDispatcher\EventSubscriberInterface.');
return false;
}
$subscribedEvents = call_user_func(array(get_class($other), 'getSubscribedEvents'));
if (!is_array($subscribedEvents)) {
$this->addProblem('getSubscribedEvents() must return an array.');
return false;
}
foreach ($subscribedEvents as $event => $subscription) {
/* @var $event string */
/* @var $subscription mixed|string|array */
$this->checkListener($other, $event, $subscription);
}
return !$this->hasProblems();
} | php | protected function matches($other): bool
{
$this->resetProblems();
if (!($other instanceof EventSubscriberInterface)) {
$this->addProblem('Subscriber must implement \Symfony\Component\EventDispatcher\EventSubscriberInterface.');
return false;
}
$subscribedEvents = call_user_func(array(get_class($other), 'getSubscribedEvents'));
if (!is_array($subscribedEvents)) {
$this->addProblem('getSubscribedEvents() must return an array.');
return false;
}
foreach ($subscribedEvents as $event => $subscription) {
/* @var $event string */
/* @var $subscription mixed|string|array */
$this->checkListener($other, $event, $subscription);
}
return !$this->hasProblems();
} | [
"protected",
"function",
"matches",
"(",
"$",
"other",
")",
":",
"bool",
"{",
"$",
"this",
"->",
"resetProblems",
"(",
")",
";",
"if",
"(",
"!",
"(",
"$",
"other",
"instanceof",
"EventSubscriberInterface",
")",
")",
"{",
"$",
"this",
"->",
"addProblem",
... | Checks if the given object is an event subscriber.
@param mixed $other
@return boolean | [
"Checks",
"if",
"the",
"given",
"object",
"is",
"an",
"event",
"subscriber",
"."
] | 971c0d45c46dc20323535940fc0d1cc7eafaf553 | https://github.com/webfactory/symfony-application-tests/blob/971c0d45c46dc20323535940fc0d1cc7eafaf553/src/Webfactory/Constraint/IsEventSubscriberConstraint.php#L26-L44 | train |
webfactory/symfony-application-tests | src/Webfactory/Constraint/IsEventSubscriberConstraint.php | IsEventSubscriberConstraint.checkListener | protected function checkListener(EventSubscriberInterface $subscriber, $event, $listener)
{
if (is_string($listener)) {
// Add the default priority and use the default validation.
$listener = array($listener, 0);
}
if (!is_array($listener)) {
$this->addProblem(sprintf('Listener definition for event "%s" must be an array or a string.', $event));
return;
}
if ($this->containsSeveralSubscriptions($listener)) {
foreach ($listener as $subListener) {
$this->checkListener($subscriber, $event, $subListener);
}
return;
}
if (count($listener) === 1) {
// Method without priority.
$listener[] = 0;
}
if (count($listener) !== 2) {
$message = 'Listener definition for event "%s" must consist of a method and a priority, but received: %s';
$this->addProblem(sprintf($message, $event, $this->exporter->export($listener)));
return;
}
list($method, $priority) = $listener;
$this->checkMethod($subscriber, $event, $method);
$this->checkPriority($event, $priority);
} | php | protected function checkListener(EventSubscriberInterface $subscriber, $event, $listener)
{
if (is_string($listener)) {
// Add the default priority and use the default validation.
$listener = array($listener, 0);
}
if (!is_array($listener)) {
$this->addProblem(sprintf('Listener definition for event "%s" must be an array or a string.', $event));
return;
}
if ($this->containsSeveralSubscriptions($listener)) {
foreach ($listener as $subListener) {
$this->checkListener($subscriber, $event, $subListener);
}
return;
}
if (count($listener) === 1) {
// Method without priority.
$listener[] = 0;
}
if (count($listener) !== 2) {
$message = 'Listener definition for event "%s" must consist of a method and a priority, but received: %s';
$this->addProblem(sprintf($message, $event, $this->exporter->export($listener)));
return;
}
list($method, $priority) = $listener;
$this->checkMethod($subscriber, $event, $method);
$this->checkPriority($event, $priority);
} | [
"protected",
"function",
"checkListener",
"(",
"EventSubscriberInterface",
"$",
"subscriber",
",",
"$",
"event",
",",
"$",
"listener",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"listener",
")",
")",
"{",
"// Add the default priority and use the default validation.",... | Checks if the listener definition for the given event is valid.
@param EventSubscriberInterface $subscriber
@param string $event
@param mixed $listener | [
"Checks",
"if",
"the",
"listener",
"definition",
"for",
"the",
"given",
"event",
"is",
"valid",
"."
] | 971c0d45c46dc20323535940fc0d1cc7eafaf553 | https://github.com/webfactory/symfony-application-tests/blob/971c0d45c46dc20323535940fc0d1cc7eafaf553/src/Webfactory/Constraint/IsEventSubscriberConstraint.php#L63-L92 | train |
webfactory/symfony-application-tests | src/Webfactory/Constraint/IsEventSubscriberConstraint.php | IsEventSubscriberConstraint.checkMethod | protected function checkMethod($subscriber, $event, $method)
{
if (!is_string($method)) {
$message = 'Listener definition for event "%s" contains an invalid method reference: %s';
$this->addProblem(sprintf($message, $event, $this->exporter->export($method)));
return;
}
if (!method_exists($subscriber, $method)) {
$message = 'Listener definition for event "%s" references method "%s", '
. 'but the method does not exist on subscriber.';
$this->addProblem(sprintf($message, $event, $method));
return;
}
if (!is_callable(array($subscriber, $method))) {
$message = 'Listener definition for event "%s" references method "%s", '
. 'but the method is not publicly accessible.';
$this->addProblem(sprintf($message, $event, $method));
return;
}
} | php | protected function checkMethod($subscriber, $event, $method)
{
if (!is_string($method)) {
$message = 'Listener definition for event "%s" contains an invalid method reference: %s';
$this->addProblem(sprintf($message, $event, $this->exporter->export($method)));
return;
}
if (!method_exists($subscriber, $method)) {
$message = 'Listener definition for event "%s" references method "%s", '
. 'but the method does not exist on subscriber.';
$this->addProblem(sprintf($message, $event, $method));
return;
}
if (!is_callable(array($subscriber, $method))) {
$message = 'Listener definition for event "%s" references method "%s", '
. 'but the method is not publicly accessible.';
$this->addProblem(sprintf($message, $event, $method));
return;
}
} | [
"protected",
"function",
"checkMethod",
"(",
"$",
"subscriber",
",",
"$",
"event",
",",
"$",
"method",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"method",
")",
")",
"{",
"$",
"message",
"=",
"'Listener definition for event \"%s\" contains an invalid metho... | Checks the given subscriber method.
@param EventSubscriberInterface $subscriber
@param string $event
@param string|mixed $method | [
"Checks",
"the",
"given",
"subscriber",
"method",
"."
] | 971c0d45c46dc20323535940fc0d1cc7eafaf553 | https://github.com/webfactory/symfony-application-tests/blob/971c0d45c46dc20323535940fc0d1cc7eafaf553/src/Webfactory/Constraint/IsEventSubscriberConstraint.php#L101-L120 | train |
webfactory/symfony-application-tests | src/Webfactory/Constraint/IsEventSubscriberConstraint.php | IsEventSubscriberConstraint.checkPriority | protected function checkPriority($event, $priority)
{
if (!is_int($priority)) {
$message = 'Priority for event "%s" must be an integer, but received: %s';
$this->addProblem(sprintf($message, $event, $this->exporter->export($priority)));
return;
}
} | php | protected function checkPriority($event, $priority)
{
if (!is_int($priority)) {
$message = 'Priority for event "%s" must be an integer, but received: %s';
$this->addProblem(sprintf($message, $event, $this->exporter->export($priority)));
return;
}
} | [
"protected",
"function",
"checkPriority",
"(",
"$",
"event",
",",
"$",
"priority",
")",
"{",
"if",
"(",
"!",
"is_int",
"(",
"$",
"priority",
")",
")",
"{",
"$",
"message",
"=",
"'Priority for event \"%s\" must be an integer, but received: %s'",
";",
"$",
"this",... | Checks the given priority.
@param string $event
@param integer|mixed $priority | [
"Checks",
"the",
"given",
"priority",
"."
] | 971c0d45c46dc20323535940fc0d1cc7eafaf553 | https://github.com/webfactory/symfony-application-tests/blob/971c0d45c46dc20323535940fc0d1cc7eafaf553/src/Webfactory/Constraint/IsEventSubscriberConstraint.php#L128-L135 | train |
silverstripe/silverstripe-controllerpolicy | src/ControllerPolicyMiddleware.php | ControllerPolicyMiddleware.isIgnoredDomain | public function isIgnoredDomain($domain)
{
if ($ignoreRegexes = $this->config()->get('ignore_domain_regexes')) {
foreach ($ignoreRegexes as $ignore) {
if (preg_match($ignore, $domain) > 0) {
return true;
}
}
}
return false;
} | php | public function isIgnoredDomain($domain)
{
if ($ignoreRegexes = $this->config()->get('ignore_domain_regexes')) {
foreach ($ignoreRegexes as $ignore) {
if (preg_match($ignore, $domain) > 0) {
return true;
}
}
}
return false;
} | [
"public",
"function",
"isIgnoredDomain",
"(",
"$",
"domain",
")",
"{",
"if",
"(",
"$",
"ignoreRegexes",
"=",
"$",
"this",
"->",
"config",
"(",
")",
"->",
"get",
"(",
"'ignore_domain_regexes'",
")",
")",
"{",
"foreach",
"(",
"$",
"ignoreRegexes",
"as",
"$... | Check if the given domain is on the list of ignored domains.
@param string $domain
@return boolean | [
"Check",
"if",
"the",
"given",
"domain",
"is",
"on",
"the",
"list",
"of",
"ignored",
"domains",
"."
] | 1b6d73c81b863d11dcbfb1fbdfb8bc860dac5de9 | https://github.com/silverstripe/silverstripe-controllerpolicy/blob/1b6d73c81b863d11dcbfb1fbdfb8bc860dac5de9/src/ControllerPolicyMiddleware.php#L41-L52 | train |
silverstripe/silverstripe-controllerpolicy | src/ControllerPolicyMiddleware.php | ControllerPolicyMiddleware.process | public function process(HTTPRequest $request, callable $delegate)
{
/** @var HTTPResponse $response */
$response = $delegate($request);
// Ignore by regexes.
if ($this->shouldCheckHttpHost() && $this->isIgnoredDomain($_SERVER['HTTP_HOST'])) {
return $response;
}
foreach ($this->requestedPolicies as $requestedPolicy) {
/** @var ControllerPolicy $policyInstance */
$policyInstance = $requestedPolicy['policy'];
$policyInstance->applyToResponse(
$requestedPolicy['originator'],
$request,
$response
);
}
return $response;
} | php | public function process(HTTPRequest $request, callable $delegate)
{
/** @var HTTPResponse $response */
$response = $delegate($request);
// Ignore by regexes.
if ($this->shouldCheckHttpHost() && $this->isIgnoredDomain($_SERVER['HTTP_HOST'])) {
return $response;
}
foreach ($this->requestedPolicies as $requestedPolicy) {
/** @var ControllerPolicy $policyInstance */
$policyInstance = $requestedPolicy['policy'];
$policyInstance->applyToResponse(
$requestedPolicy['originator'],
$request,
$response
);
}
return $response;
} | [
"public",
"function",
"process",
"(",
"HTTPRequest",
"$",
"request",
",",
"callable",
"$",
"delegate",
")",
"{",
"/** @var HTTPResponse $response */",
"$",
"response",
"=",
"$",
"delegate",
"(",
"$",
"request",
")",
";",
"// Ignore by regexes.",
"if",
"(",
"$",
... | Apply all the requested policies.
@param HTTPRequest $request
@param callable $delegate
@return HTTPResponse | [
"Apply",
"all",
"the",
"requested",
"policies",
"."
] | 1b6d73c81b863d11dcbfb1fbdfb8bc860dac5de9 | https://github.com/silverstripe/silverstripe-controllerpolicy/blob/1b6d73c81b863d11dcbfb1fbdfb8bc860dac5de9/src/ControllerPolicyMiddleware.php#L77-L99 | train |
manaphp/framework | View/Flash/Adapter/Direct.php | Direct._message | public function _message($type, $message)
{
$context = $this->_context;
$cssClasses = isset($this->_cssClasses[$type]) ? $this->_cssClasses[$type] : '';
$context->messages[] = '<div class="' . $cssClasses . '">' . $message . '</div>' . PHP_EOL;
} | php | public function _message($type, $message)
{
$context = $this->_context;
$cssClasses = isset($this->_cssClasses[$type]) ? $this->_cssClasses[$type] : '';
$context->messages[] = '<div class="' . $cssClasses . '">' . $message . '</div>' . PHP_EOL;
} | [
"public",
"function",
"_message",
"(",
"$",
"type",
",",
"$",
"message",
")",
"{",
"$",
"context",
"=",
"$",
"this",
"->",
"_context",
";",
"$",
"cssClasses",
"=",
"isset",
"(",
"$",
"this",
"->",
"_cssClasses",
"[",
"$",
"type",
"]",
")",
"?",
"$"... | Outputs a message
@param string $type
@param string $message
@return void | [
"Outputs",
"a",
"message"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/View/Flash/Adapter/Direct.php#L22-L29 | train |
milejko/mmi-cms | src/CmsAdmin/Model/CategoryAclModel.php | CategoryAclModel._updateAcl | protected function _updateAcl(\Cms\Orm\CmsCategoryAclRecord $aclRecord)
{
//iteracja po identyfikatorach kategorii
foreach ($this->_getChildrenCategoryIds($aclRecord->cmsCategoryId) as $categoryId) {
//dozwalanie lub zabranianie w ACL
$aclRecord->access == 'allow' ?
$this->_acl->allow($aclRecord->getJoined('cms_role')->name, $categoryId) :
$this->_acl->deny($aclRecord->getJoined('cms_role')->name, $categoryId);
}
} | php | protected function _updateAcl(\Cms\Orm\CmsCategoryAclRecord $aclRecord)
{
//iteracja po identyfikatorach kategorii
foreach ($this->_getChildrenCategoryIds($aclRecord->cmsCategoryId) as $categoryId) {
//dozwalanie lub zabranianie w ACL
$aclRecord->access == 'allow' ?
$this->_acl->allow($aclRecord->getJoined('cms_role')->name, $categoryId) :
$this->_acl->deny($aclRecord->getJoined('cms_role')->name, $categoryId);
}
} | [
"protected",
"function",
"_updateAcl",
"(",
"\\",
"Cms",
"\\",
"Orm",
"\\",
"CmsCategoryAclRecord",
"$",
"aclRecord",
")",
"{",
"//iteracja po identyfikatorach kategorii",
"foreach",
"(",
"$",
"this",
"->",
"_getChildrenCategoryIds",
"(",
"$",
"aclRecord",
"->",
"cm... | Aktualizuje ustawienie ACL
@param \Cms\Orm\CmsCategoryAclRecord $aclRecord | [
"Aktualizuje",
"ustawienie",
"ACL"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/CmsAdmin/Model/CategoryAclModel.php#L52-L61 | train |
pscheit/jparser | PLUG/core/PLUGTool.php | PLUGTool.import_php | static function import_php( $package, $silent = false ){
$type = current( explode('.', $package) );
$paths = self::collect_package( $package, 'php', $silent, 'conf' );
if( !$silent && empty($paths) ){
trigger_error("Bad import `$package'", E_USER_ERROR );
}
foreach( $paths as $cname => $path ){
// leniant inclusion if silent
if( $silent ){
include_once $path;
continue;
}
// path should already be validated by collect_package
require_once $path;
// Run checks according to type of import
switch( $type ){
case 'conf':
break;
default:
// Class or function import must define an entity with the same name as the file
// testing function first to avoid call to __autoload
if( ! function_exists($cname) && ! class_exists($cname) ){
trigger_error( "Class, or function '$cname' not defined in file `$path'", E_USER_ERROR );
}
}
}
} | php | static function import_php( $package, $silent = false ){
$type = current( explode('.', $package) );
$paths = self::collect_package( $package, 'php', $silent, 'conf' );
if( !$silent && empty($paths) ){
trigger_error("Bad import `$package'", E_USER_ERROR );
}
foreach( $paths as $cname => $path ){
// leniant inclusion if silent
if( $silent ){
include_once $path;
continue;
}
// path should already be validated by collect_package
require_once $path;
// Run checks according to type of import
switch( $type ){
case 'conf':
break;
default:
// Class or function import must define an entity with the same name as the file
// testing function first to avoid call to __autoload
if( ! function_exists($cname) && ! class_exists($cname) ){
trigger_error( "Class, or function '$cname' not defined in file `$path'", E_USER_ERROR );
}
}
}
} | [
"static",
"function",
"import_php",
"(",
"$",
"package",
",",
"$",
"silent",
"=",
"false",
")",
"{",
"$",
"type",
"=",
"current",
"(",
"explode",
"(",
"'.'",
",",
"$",
"package",
")",
")",
";",
"$",
"paths",
"=",
"self",
"::",
"collect_package",
"(",... | Import PHP classes and functions into the runtime environment
@param string
@param bool whether to allow silent failure
@return Void | [
"Import",
"PHP",
"classes",
"and",
"functions",
"into",
"the",
"runtime",
"environment"
] | f9de77171c0d37d237e0e9a918ed7bff19e12095 | https://github.com/pscheit/jparser/blob/f9de77171c0d37d237e0e9a918ed7bff19e12095/PLUG/core/PLUGTool.php#L36-L65 | train |
pscheit/jparser | PLUG/core/PLUGTool.php | PLUGTool.collect_package | static function collect_package( $package, $ext, $silent, $confname ){
// get from cache for speed
$cachekey = $package.'.'.$ext;
if( isset(self::$dircache[$cachekey]) ){
return self::$dircache[$cachekey];
}
$apath = explode( '.', $package );
$type = $apath[0]; // e.g. "PLUG"
$cname = array_pop( $apath ); // e.g. "PLUGSession"
// force special extensions, in certain cases
switch( $type ){
case 'conf':
$ext = 'conf.php';
break;
}
// special rules for types of import
switch( $ext ){
case 'js':
// Javascript under document root
$dpath = PLUG_VIRTUAL_DIR.'/plug/js/'.implode( '/', $apath );
break;
case 'conf.php':
// replace with target conf dir
$apath[0] = $confname;
// fall through ....
default:
// regular PHP import from outside document root
$dpath = PLUG_HOST_DIR .'/'. implode( '/', $apath );
}
$incs = array();
switch( $cname ){
case '':
case '*':
// import all files under directory
if( !$silent && !self::check_dir( $dpath ) ){
break;
}
$dhandle = opendir( $dpath );
while( $f = readdir($dhandle) ){
// skip dot files
if( $f{0} === '.' ){
continue;
}
$i = strpos( $f, ".$ext" );
if( $i ){
// file has correct extension
if( substr($f,0,2) === '__' ){
// skip file name starting "__"
continue;
}
$cname = substr_replace( $f, '', $i );
$incs[$cname] = "$dpath/$f";
}
}
closedir($dhandle);
break;
default:
// assume single file exists with expected extension
$path = "$dpath/$cname.$ext";
if( !$silent && !self::check_file($path) ){
break;
}
$incs[$cname] = $path;
}
// cache for next time
self::$dircache[$cachekey] = $incs;
return $incs;
} | php | static function collect_package( $package, $ext, $silent, $confname ){
// get from cache for speed
$cachekey = $package.'.'.$ext;
if( isset(self::$dircache[$cachekey]) ){
return self::$dircache[$cachekey];
}
$apath = explode( '.', $package );
$type = $apath[0]; // e.g. "PLUG"
$cname = array_pop( $apath ); // e.g. "PLUGSession"
// force special extensions, in certain cases
switch( $type ){
case 'conf':
$ext = 'conf.php';
break;
}
// special rules for types of import
switch( $ext ){
case 'js':
// Javascript under document root
$dpath = PLUG_VIRTUAL_DIR.'/plug/js/'.implode( '/', $apath );
break;
case 'conf.php':
// replace with target conf dir
$apath[0] = $confname;
// fall through ....
default:
// regular PHP import from outside document root
$dpath = PLUG_HOST_DIR .'/'. implode( '/', $apath );
}
$incs = array();
switch( $cname ){
case '':
case '*':
// import all files under directory
if( !$silent && !self::check_dir( $dpath ) ){
break;
}
$dhandle = opendir( $dpath );
while( $f = readdir($dhandle) ){
// skip dot files
if( $f{0} === '.' ){
continue;
}
$i = strpos( $f, ".$ext" );
if( $i ){
// file has correct extension
if( substr($f,0,2) === '__' ){
// skip file name starting "__"
continue;
}
$cname = substr_replace( $f, '', $i );
$incs[$cname] = "$dpath/$f";
}
}
closedir($dhandle);
break;
default:
// assume single file exists with expected extension
$path = "$dpath/$cname.$ext";
if( !$silent && !self::check_file($path) ){
break;
}
$incs[$cname] = $path;
}
// cache for next time
self::$dircache[$cachekey] = $incs;
return $incs;
} | [
"static",
"function",
"collect_package",
"(",
"$",
"package",
",",
"$",
"ext",
",",
"$",
"silent",
",",
"$",
"confname",
")",
"{",
"// get from cache for speed",
"$",
"cachekey",
"=",
"$",
"package",
".",
"'.'",
".",
"$",
"ext",
";",
"if",
"(",
"isset",
... | Collect files from import argument
@param string package identifier, e.g. `PLUG.core.*'
@param string file extension to match
@param bool whether to allow silent failure
@param string alternative config directory
@return array | [
"Collect",
"files",
"from",
"import",
"argument"
] | f9de77171c0d37d237e0e9a918ed7bff19e12095 | https://github.com/pscheit/jparser/blob/f9de77171c0d37d237e0e9a918ed7bff19e12095/PLUG/core/PLUGTool.php#L78-L154 | train |
pscheit/jparser | PLUG/core/PLUGTool.php | PLUGTool.collect_files | static function collect_files( $dpath, $r = false, $match = null, $ignore = null ){
$paths = array();
$dhandle = opendir( $dpath );
while( $f = readdir($dhandle) ){
if( $f === '.' || $f === '..' ){
continue;
}
// pattern tested only on file name
// ignore pattern applies to directories as well as files
if( isset($ignore) && preg_match($ignore, $f) ){
continue;
}
$path = $dpath.'/'.$f;
if( is_dir($path) ){
if( $r ){
$paths = array_merge( $paths, self::collect_files($path, true, $match, $ignore) );
}
}
// test match requirement on files only
else if( isset($match) && ! preg_match($match, $f) ){
continue;
}
// else file ok to collect
else {
$paths[] = $path;
}
}
closedir($dhandle);
return $paths;
} | php | static function collect_files( $dpath, $r = false, $match = null, $ignore = null ){
$paths = array();
$dhandle = opendir( $dpath );
while( $f = readdir($dhandle) ){
if( $f === '.' || $f === '..' ){
continue;
}
// pattern tested only on file name
// ignore pattern applies to directories as well as files
if( isset($ignore) && preg_match($ignore, $f) ){
continue;
}
$path = $dpath.'/'.$f;
if( is_dir($path) ){
if( $r ){
$paths = array_merge( $paths, self::collect_files($path, true, $match, $ignore) );
}
}
// test match requirement on files only
else if( isset($match) && ! preg_match($match, $f) ){
continue;
}
// else file ok to collect
else {
$paths[] = $path;
}
}
closedir($dhandle);
return $paths;
} | [
"static",
"function",
"collect_files",
"(",
"$",
"dpath",
",",
"$",
"r",
"=",
"false",
",",
"$",
"match",
"=",
"null",
",",
"$",
"ignore",
"=",
"null",
")",
"{",
"$",
"paths",
"=",
"array",
"(",
")",
";",
"$",
"dhandle",
"=",
"opendir",
"(",
"$",... | Collect files from a directory
@param string directory path
@param bool whether to recurse into directories
@param string optional match pattern
@param string optional ignore pattern (match overrides)
@return array absolute paths collected | [
"Collect",
"files",
"from",
"a",
"directory"
] | f9de77171c0d37d237e0e9a918ed7bff19e12095 | https://github.com/pscheit/jparser/blob/f9de77171c0d37d237e0e9a918ed7bff19e12095/PLUG/core/PLUGTool.php#L166-L195 | train |
pscheit/jparser | PLUG/core/PLUGTool.php | PLUGTool.check_file | static function check_file( $path, $w = false, $isdir = false ){
$strtype = $isdir ? 'Directory' : 'File';
if( !file_exists($path) ){
trigger_error("$strtype not found; `$path'", E_USER_NOTICE );
return false;
}
if( $isdir && !is_dir($path) ){
trigger_error("Not a directory; `$path'", E_USER_NOTICE );
return false;
}
if( !$isdir && !is_file($path) ){
trigger_error("Not a file; `$path'", E_USER_NOTICE );
return false;
}
if( !is_readable($path) ){
trigger_error("$strtype not readable by `".trim(`whoami`)."'; `$path'", E_USER_NOTICE );
return false;
}
if( $w && !is_writeable($path) ){
trigger_error("$strtype not writeable by `".trim(`whoami`)."'; `$path'", E_USER_NOTICE );
return false;
}
return true;
} | php | static function check_file( $path, $w = false, $isdir = false ){
$strtype = $isdir ? 'Directory' : 'File';
if( !file_exists($path) ){
trigger_error("$strtype not found; `$path'", E_USER_NOTICE );
return false;
}
if( $isdir && !is_dir($path) ){
trigger_error("Not a directory; `$path'", E_USER_NOTICE );
return false;
}
if( !$isdir && !is_file($path) ){
trigger_error("Not a file; `$path'", E_USER_NOTICE );
return false;
}
if( !is_readable($path) ){
trigger_error("$strtype not readable by `".trim(`whoami`)."'; `$path'", E_USER_NOTICE );
return false;
}
if( $w && !is_writeable($path) ){
trigger_error("$strtype not writeable by `".trim(`whoami`)."'; `$path'", E_USER_NOTICE );
return false;
}
return true;
} | [
"static",
"function",
"check_file",
"(",
"$",
"path",
",",
"$",
"w",
"=",
"false",
",",
"$",
"isdir",
"=",
"false",
")",
"{",
"$",
"strtype",
"=",
"$",
"isdir",
"?",
"'Directory'",
":",
"'File'",
";",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"path"... | Utility function to check resource can be read.
- Include paths will not be evaluated.
- E_USER_NOTICE raised on failure.
@param string Full path to file
@param bool whether directory write permission to be checked
@param bool Whether file is expected to be a directory
@return bool False if file cannot be read or does not exist | [
"Utility",
"function",
"to",
"check",
"resource",
"can",
"be",
"read",
".",
"-",
"Include",
"paths",
"will",
"not",
"be",
"evaluated",
".",
"-",
"E_USER_NOTICE",
"raised",
"on",
"failure",
"."
] | f9de77171c0d37d237e0e9a918ed7bff19e12095 | https://github.com/pscheit/jparser/blob/f9de77171c0d37d237e0e9a918ed7bff19e12095/PLUG/core/PLUGTool.php#L209-L232 | train |
pscheit/jparser | PLUG/core/PLUGTool.php | PLUGTool.map_deployment_virtual | static function map_deployment_virtual( $path ){
// if path is outside document root move to special plug include dir
if( strpos( $path, PLUG_VIRTUAL_DIR ) !== 0 ){
if( strpos( $path, PLUG_HOST_DIR ) === 0 ){
// is under host root
$len = strlen(PLUG_HOST_DIR) + 1;
$subpath = substr_replace( $path, '', 0, $len );
}
else{
// else could be anywhere in filesystem
$subpath = md5( dirname($path) ).'/'.basename($path);
}
return '/plug/inc/'.$subpath;
}
// else just remove document root
return str_replace( PLUG_VIRTUAL_DIR, '', $path );
} | php | static function map_deployment_virtual( $path ){
// if path is outside document root move to special plug include dir
if( strpos( $path, PLUG_VIRTUAL_DIR ) !== 0 ){
if( strpos( $path, PLUG_HOST_DIR ) === 0 ){
// is under host root
$len = strlen(PLUG_HOST_DIR) + 1;
$subpath = substr_replace( $path, '', 0, $len );
}
else{
// else could be anywhere in filesystem
$subpath = md5( dirname($path) ).'/'.basename($path);
}
return '/plug/inc/'.$subpath;
}
// else just remove document root
return str_replace( PLUG_VIRTUAL_DIR, '', $path );
} | [
"static",
"function",
"map_deployment_virtual",
"(",
"$",
"path",
")",
"{",
"// if path is outside document root move to special plug include dir",
"if",
"(",
"strpos",
"(",
"$",
"path",
",",
"PLUG_VIRTUAL_DIR",
")",
"!==",
"0",
")",
"{",
"if",
"(",
"strpos",
"(",
... | Map source file location to a virtual path under document root.
@param string absolute path to development file
@return string virtual path | [
"Map",
"source",
"file",
"location",
"to",
"a",
"virtual",
"path",
"under",
"document",
"root",
"."
] | f9de77171c0d37d237e0e9a918ed7bff19e12095 | https://github.com/pscheit/jparser/blob/f9de77171c0d37d237e0e9a918ed7bff19e12095/PLUG/core/PLUGTool.php#L255-L271 | train |
milejko/mmi-cms | src/Cms/Model/AttributeValueRelationModel.php | AttributeValueRelationModel.getRelationFiles | public function getRelationFiles()
{
$filesByObject = new \Mmi\Orm\RecordCollection;
//wyszukiwanie wartości
foreach ($this->getAttributeValues() as $record) {
//pobieranie klucza atrybutu (w celu zgrupowania)
if ($record->getJoined('cms_attribute_type')->uploader) {
//dołączanie plików
foreach (\Cms\Orm\CmsFileQuery::byObject($record->value, $this->_objectId)->find() as $file) {
$filesByObject->append($file);
}
}
}
return $filesByObject;
} | php | public function getRelationFiles()
{
$filesByObject = new \Mmi\Orm\RecordCollection;
//wyszukiwanie wartości
foreach ($this->getAttributeValues() as $record) {
//pobieranie klucza atrybutu (w celu zgrupowania)
if ($record->getJoined('cms_attribute_type')->uploader) {
//dołączanie plików
foreach (\Cms\Orm\CmsFileQuery::byObject($record->value, $this->_objectId)->find() as $file) {
$filesByObject->append($file);
}
}
}
return $filesByObject;
} | [
"public",
"function",
"getRelationFiles",
"(",
")",
"{",
"$",
"filesByObject",
"=",
"new",
"\\",
"Mmi",
"\\",
"Orm",
"\\",
"RecordCollection",
";",
"//wyszukiwanie wartości",
"foreach",
"(",
"$",
"this",
"->",
"getAttributeValues",
"(",
")",
"as",
"$",
"record... | Pobiera wszystkie rekordy plikowe
@return \Mmi\DataObject | [
"Pobiera",
"wszystkie",
"rekordy",
"plikowe"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/Cms/Model/AttributeValueRelationModel.php#L239-L253 | train |
mapbender/fom | src/FOM/CoreBundle/Component/ExportResponse.php | ExportResponse.setCsv | public function setCsv(array &$data, $detectHead = true)
{
$handle = self::createMemoryHandle();
if($detectHead && count($data)> 0){
fputcsv($handle, array_keys($data[0]), $this->delimiter, $this->enclosure);
}
foreach ($data as $row) {
fputcsv($handle, $row, $this->delimiter, $this->enclosure);
}
rewind($handle);
$output = chr(255) . chr(254
) . mb_convert_encoding('sep=' . $this->delimiter . "\n" . stream_get_contents($handle),
self::UTF_16_LE,
$this->encodingFrom
);
$this->setData($output);
fclose($handle);
} | php | public function setCsv(array &$data, $detectHead = true)
{
$handle = self::createMemoryHandle();
if($detectHead && count($data)> 0){
fputcsv($handle, array_keys($data[0]), $this->delimiter, $this->enclosure);
}
foreach ($data as $row) {
fputcsv($handle, $row, $this->delimiter, $this->enclosure);
}
rewind($handle);
$output = chr(255) . chr(254
) . mb_convert_encoding('sep=' . $this->delimiter . "\n" . stream_get_contents($handle),
self::UTF_16_LE,
$this->encodingFrom
);
$this->setData($output);
fclose($handle);
} | [
"public",
"function",
"setCsv",
"(",
"array",
"&",
"$",
"data",
",",
"$",
"detectHead",
"=",
"true",
")",
"{",
"$",
"handle",
"=",
"self",
"::",
"createMemoryHandle",
"(",
")",
";",
"if",
"(",
"$",
"detectHead",
"&&",
"count",
"(",
"$",
"data",
")",
... | Generate CSV list
@param array $data
@param bool $detectHead
@internal param bool $xls | [
"Generate",
"CSV",
"list"
] | 6dea943121f3c3f9b1b4b14dc2a8e8640a120675 | https://github.com/mapbender/fom/blob/6dea943121f3c3f9b1b4b14dc2a8e8640a120675/src/FOM/CoreBundle/Component/ExportResponse.php#L123-L140 | train |
mapbender/fom | src/FOM/CoreBundle/Component/ExportResponse.php | ExportResponse.setType | public function setType($type)
{
switch ($type) {
case self::TYPE_CSV:
$this->headers->add(array('Content-Type' => 'text/csv;charset=' . self::UTF_16_LE));
break;
case self::TYPE_XLS:
$this->headers->add(array("Content-Type" => "application/vnd.ms-excel"));
break;
}
$this->type = $type;
} | php | public function setType($type)
{
switch ($type) {
case self::TYPE_CSV:
$this->headers->add(array('Content-Type' => 'text/csv;charset=' . self::UTF_16_LE));
break;
case self::TYPE_XLS:
$this->headers->add(array("Content-Type" => "application/vnd.ms-excel"));
break;
}
$this->type = $type;
} | [
"public",
"function",
"setType",
"(",
"$",
"type",
")",
"{",
"switch",
"(",
"$",
"type",
")",
"{",
"case",
"self",
"::",
"TYPE_CSV",
":",
"$",
"this",
"->",
"headers",
"->",
"add",
"(",
"array",
"(",
"'Content-Type'",
"=>",
"'text/csv;charset='",
".",
... | Set export type
@param string $type | [
"Set",
"export",
"type"
] | 6dea943121f3c3f9b1b4b14dc2a8e8640a120675 | https://github.com/mapbender/fom/blob/6dea943121f3c3f9b1b4b14dc2a8e8640a120675/src/FOM/CoreBundle/Component/ExportResponse.php#L157-L168 | train |
mapbender/fom | src/FOM/CoreBundle/Component/ExportResponse.php | ExportResponse.setFileName | public function setFileName($fileName)
{
$this->fileName = $fileName;
$this->headers->add(array('Content-Disposition' => 'attachment; filename="' . $this->fileName . '"'));
return $this;
} | php | public function setFileName($fileName)
{
$this->fileName = $fileName;
$this->headers->add(array('Content-Disposition' => 'attachment; filename="' . $this->fileName . '"'));
return $this;
} | [
"public",
"function",
"setFileName",
"(",
"$",
"fileName",
")",
"{",
"$",
"this",
"->",
"fileName",
"=",
"$",
"fileName",
";",
"$",
"this",
"->",
"headers",
"->",
"add",
"(",
"array",
"(",
"'Content-Disposition'",
"=>",
"'attachment; filename=\"'",
".",
"$",... | Set export file name
@param string $fileName
@return $this | [
"Set",
"export",
"file",
"name"
] | 6dea943121f3c3f9b1b4b14dc2a8e8640a120675 | https://github.com/mapbender/fom/blob/6dea943121f3c3f9b1b4b14dc2a8e8640a120675/src/FOM/CoreBundle/Component/ExportResponse.php#L212-L217 | train |
pscheit/jparser | PLUG/parsing/bnf/BNFRulesNode.php | BNFRulesNode.collect_symbols | function collect_symbols(){
if( ! $this->length ){
return null;
}
$Rule = $this->reset();
do {
if( $Rule->length !== 6 ){
// empty rule most likely
continue;
}
// collect rule name - guaranteed to be nontermainal
$Name = $Rule->get_child( 1 );
$n = $Name->evaluate();
$nts[ $n ] = $n;
// assume first nt is start symbol
if( is_null( $this->startsymbol ) ){
$this->startsymbol = $n;
}
$Expr = $Rule->get_child( 4 );
// lists in Expression
$List = $Expr->reset();
do {
// terms in list - may be terminal or nonterminal
$Term = $List->reset();
do {
$s = $Term->evaluate();
switch( $Term->length ){
case 1:
// "terminal" or terminal
if( $s === P_EPSILON || $s === P_EOF ){
// mandatory symbols already known
break;
}
$ts[ $s ] = (string) $Term;
break;
case 3:
// angle-bracketed <nonterminal>
$nts[ $s ] = (string) $Term;
break;
}
}
while(
$Term = $List->next()
);
}
while(
$Expr->next() && $List = $Expr->next()
);
}
while(
$Rule = $this->next()
);
return array( $ts, $nts );
} | php | function collect_symbols(){
if( ! $this->length ){
return null;
}
$Rule = $this->reset();
do {
if( $Rule->length !== 6 ){
// empty rule most likely
continue;
}
// collect rule name - guaranteed to be nontermainal
$Name = $Rule->get_child( 1 );
$n = $Name->evaluate();
$nts[ $n ] = $n;
// assume first nt is start symbol
if( is_null( $this->startsymbol ) ){
$this->startsymbol = $n;
}
$Expr = $Rule->get_child( 4 );
// lists in Expression
$List = $Expr->reset();
do {
// terms in list - may be terminal or nonterminal
$Term = $List->reset();
do {
$s = $Term->evaluate();
switch( $Term->length ){
case 1:
// "terminal" or terminal
if( $s === P_EPSILON || $s === P_EOF ){
// mandatory symbols already known
break;
}
$ts[ $s ] = (string) $Term;
break;
case 3:
// angle-bracketed <nonterminal>
$nts[ $s ] = (string) $Term;
break;
}
}
while(
$Term = $List->next()
);
}
while(
$Expr->next() && $List = $Expr->next()
);
}
while(
$Rule = $this->next()
);
return array( $ts, $nts );
} | [
"function",
"collect_symbols",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"length",
")",
"{",
"return",
"null",
";",
"}",
"$",
"Rule",
"=",
"$",
"this",
"->",
"reset",
"(",
")",
";",
"do",
"{",
"if",
"(",
"$",
"Rule",
"->",
"length",
"!=... | Recursively collect terminal and nonterminal strings from Term nodes.
@todo could take this opportunity to test for redundant or unreachable non-terminals
@return array [ [terminala,terminalb,..], [nonterminalX,nonterminalY,..] ] | [
"Recursively",
"collect",
"terminal",
"and",
"nonterminal",
"strings",
"from",
"Term",
"nodes",
"."
] | f9de77171c0d37d237e0e9a918ed7bff19e12095 | https://github.com/pscheit/jparser/blob/f9de77171c0d37d237e0e9a918ed7bff19e12095/PLUG/parsing/bnf/BNFRulesNode.php#L82-L139 | train |
pscheit/jparser | PLUG/parsing/bnf/BNFRulesNode.php | BNFRulesNode.make_lex | function make_lex( $i = 0 ){
$Lex = new LexBuilder( $i );
foreach( $this->collect_symbols() as $symbols ){
foreach( $symbols as $t => $s ){
if( preg_match('/^\W/', $s, $r ) ){
$Lex->define_literal( (string) $t );
}
else if( $Lex->defined($s) ){
}
else if( defined($s) ){
$Lex->redefine( $s );
}
else {
$Lex->define( $t );
}
}
}
return $Lex;
} | php | function make_lex( $i = 0 ){
$Lex = new LexBuilder( $i );
foreach( $this->collect_symbols() as $symbols ){
foreach( $symbols as $t => $s ){
if( preg_match('/^\W/', $s, $r ) ){
$Lex->define_literal( (string) $t );
}
else if( $Lex->defined($s) ){
}
else if( defined($s) ){
$Lex->redefine( $s );
}
else {
$Lex->define( $t );
}
}
}
return $Lex;
} | [
"function",
"make_lex",
"(",
"$",
"i",
"=",
"0",
")",
"{",
"$",
"Lex",
"=",
"new",
"LexBuilder",
"(",
"$",
"i",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"collect_symbols",
"(",
")",
"as",
"$",
"symbols",
")",
"{",
"foreach",
"(",
"$",
"symbol... | Create a Lex instance fro symbols
@param int Lowest value for new token constant definitions, defaults to 0 | [
"Create",
"a",
"Lex",
"instance",
"fro",
"symbols"
] | f9de77171c0d37d237e0e9a918ed7bff19e12095 | https://github.com/pscheit/jparser/blob/f9de77171c0d37d237e0e9a918ed7bff19e12095/PLUG/parsing/bnf/BNFRulesNode.php#L148-L166 | train |
manaphp/framework | View.php | View.setVar | public function setVar($name, $value)
{
$context = $this->_context;
$context->vars[$name] = $value;
return $this;
} | php | public function setVar($name, $value)
{
$context = $this->_context;
$context->vars[$name] = $value;
return $this;
} | [
"public",
"function",
"setVar",
"(",
"$",
"name",
",",
"$",
"value",
")",
"{",
"$",
"context",
"=",
"$",
"this",
"->",
"_context",
";",
"$",
"context",
"->",
"vars",
"[",
"$",
"name",
"]",
"=",
"$",
"value",
";",
"return",
"$",
"this",
";",
"}"
] | Set a single view parameter
@param string $name
@param mixed $value
@return static | [
"Set",
"a",
"single",
"view",
"parameter"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/View.php#L64-L71 | train |
manaphp/framework | View.php | View.setVars | public function setVars($vars)
{
$context = $this->_context;
$context->vars = array_merge($context->vars, $vars);
return $this;
} | php | public function setVars($vars)
{
$context = $this->_context;
$context->vars = array_merge($context->vars, $vars);
return $this;
} | [
"public",
"function",
"setVars",
"(",
"$",
"vars",
")",
"{",
"$",
"context",
"=",
"$",
"this",
"->",
"_context",
";",
"$",
"context",
"->",
"vars",
"=",
"array_merge",
"(",
"$",
"context",
"->",
"vars",
",",
"$",
"vars",
")",
";",
"return",
"$",
"t... | Adds parameters to view
@param array $vars
@return static | [
"Adds",
"parameters",
"to",
"view"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/View.php#L80-L87 | train |
manaphp/framework | View.php | View.getVar | public function getVar($name = null)
{
$context = $this->_context;
if ($name === null) {
return $context->vars;
} else {
return isset($context->vars[$name]) ? $context->vars[$name] : null;
}
} | php | public function getVar($name = null)
{
$context = $this->_context;
if ($name === null) {
return $context->vars;
} else {
return isset($context->vars[$name]) ? $context->vars[$name] : null;
}
} | [
"public",
"function",
"getVar",
"(",
"$",
"name",
"=",
"null",
")",
"{",
"$",
"context",
"=",
"$",
"this",
"->",
"_context",
";",
"if",
"(",
"$",
"name",
"===",
"null",
")",
"{",
"return",
"$",
"context",
"->",
"vars",
";",
"}",
"else",
"{",
"ret... | Returns a parameter previously set in the view
@param string $name
@return mixed | [
"Returns",
"a",
"parameter",
"previously",
"set",
"in",
"the",
"view"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/View.php#L96-L105 | train |
manaphp/framework | View.php | View.render | public function render($template = null, $vars = null)
{
$context = $this->_context;
if ($vars !== null) {
$context->vars = $vars;
}
if (!$template) {
$area = $this->dispatcher->getArea();
$controller = $this->dispatcher->getController();
if ($area) {
$dir = "@app/Areas/$area/Views/$controller";
} else {
$dir = "@views/$controller";
}
if (!isset($this->_dirs[$dir])) {
$this->_dirs[$dir] = $this->filesystem->dirExists($dir);
}
if ($this->_dirs[$dir]) {
$template = $dir . '/' . ucfirst($this->dispatcher->getAction());
} else {
$template = $dir;
}
}
$this->eventsManager->fireEvent('view:beforeRender', $this);
$context->content = $this->_render($template, $context->vars, false);
if ($context->layout !== false) {
$layout = $this->_findLayout();
$context->content = $this->_render($layout, $context->vars, false);
}
$this->eventsManager->fireEvent('view:afterRender', $this);
return $context->content;
} | php | public function render($template = null, $vars = null)
{
$context = $this->_context;
if ($vars !== null) {
$context->vars = $vars;
}
if (!$template) {
$area = $this->dispatcher->getArea();
$controller = $this->dispatcher->getController();
if ($area) {
$dir = "@app/Areas/$area/Views/$controller";
} else {
$dir = "@views/$controller";
}
if (!isset($this->_dirs[$dir])) {
$this->_dirs[$dir] = $this->filesystem->dirExists($dir);
}
if ($this->_dirs[$dir]) {
$template = $dir . '/' . ucfirst($this->dispatcher->getAction());
} else {
$template = $dir;
}
}
$this->eventsManager->fireEvent('view:beforeRender', $this);
$context->content = $this->_render($template, $context->vars, false);
if ($context->layout !== false) {
$layout = $this->_findLayout();
$context->content = $this->_render($layout, $context->vars, false);
}
$this->eventsManager->fireEvent('view:afterRender', $this);
return $context->content;
} | [
"public",
"function",
"render",
"(",
"$",
"template",
"=",
"null",
",",
"$",
"vars",
"=",
"null",
")",
"{",
"$",
"context",
"=",
"$",
"this",
"->",
"_context",
";",
"if",
"(",
"$",
"vars",
"!==",
"null",
")",
"{",
"$",
"context",
"->",
"vars",
"=... | Executes render process from dispatching data
@param string $template
@param array $vars
@return string | [
"Executes",
"render",
"process",
"from",
"dispatching",
"data"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/View.php#L186-L227 | train |
jbouzekri/ConfigKnpMenuBundle | DependencyInjection/JbConfigKnpMenuExtension.php | JbConfigKnpMenuExtension.parseFile | public function parseFile($file)
{
$bundleConfig = Yaml::parse(file_get_contents(realpath($file)));
if (!is_array($bundleConfig)) {
return array();
}
return $bundleConfig;
} | php | public function parseFile($file)
{
$bundleConfig = Yaml::parse(file_get_contents(realpath($file)));
if (!is_array($bundleConfig)) {
return array();
}
return $bundleConfig;
} | [
"public",
"function",
"parseFile",
"(",
"$",
"file",
")",
"{",
"$",
"bundleConfig",
"=",
"Yaml",
"::",
"parse",
"(",
"file_get_contents",
"(",
"realpath",
"(",
"$",
"file",
")",
")",
")",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"bundleConfig",
")",
... | Parse a navigation.yml file
@param string $file
@return array | [
"Parse",
"a",
"navigation",
".",
"yml",
"file"
] | d5a6154de04f3f7342f68496cad02a1b4a3846b9 | https://github.com/jbouzekri/ConfigKnpMenuBundle/blob/d5a6154de04f3f7342f68496cad02a1b4a3846b9/DependencyInjection/JbConfigKnpMenuExtension.php#L78-L87 | train |
fezfez/codeGenerator | src/CrudGenerator/Generators/Finder/GeneratorFinderFactory.php | GeneratorFinderFactory.getInstance | public static function getInstance()
{
return new GeneratorFinderCache(
new GeneratorFinder(
TranstyperFactory::getInstance(),
GeneratorValidatorFactory::getInstance(),
new FileManager()
),
Installer::getDirectories(),
new FileManager()
);
} | php | public static function getInstance()
{
return new GeneratorFinderCache(
new GeneratorFinder(
TranstyperFactory::getInstance(),
GeneratorValidatorFactory::getInstance(),
new FileManager()
),
Installer::getDirectories(),
new FileManager()
);
} | [
"public",
"static",
"function",
"getInstance",
"(",
")",
"{",
"return",
"new",
"GeneratorFinderCache",
"(",
"new",
"GeneratorFinder",
"(",
"TranstyperFactory",
"::",
"getInstance",
"(",
")",
",",
"GeneratorValidatorFactory",
"::",
"getInstance",
"(",
")",
",",
"ne... | Create GeneratorFinder instance
@return GeneratorFinderCache | [
"Create",
"GeneratorFinder",
"instance"
] | 559f22bcc525c3157ecb17fe96818dd7b7ee58c2 | https://github.com/fezfez/codeGenerator/blob/559f22bcc525c3157ecb17fe96818dd7b7ee58c2/src/CrudGenerator/Generators/Finder/GeneratorFinderFactory.php#L29-L40 | train |
manaphp/framework | Router/Route.php | Route._compilePattern | protected function _compilePattern($pattern)
{
if (strpos($pattern, '{') !== false) {
$tr = [
'{area}' => '{area:[a-z]\w*}',
'{controller}' => '{controller:[a-z]\w*}',
'{action}' => '{action:[a-z]\w*}',
'{params}' => '{params:.*}',
'{id}' => '{id:[^/]+}',
':int' => ':\d+',
];
$pattern = strtr($pattern, $tr);
}
if (strpos($pattern, '{') !== false) {
$need_restore_token = false;
if (preg_match('#{\d#', $pattern) === 1) {
$need_restore_token = true;
$pattern = (string)preg_replace('#{([\d,]+)}#', '@\1@', $pattern);
}
$matches = [];
if (preg_match_all('#{([A-Z].*)}#Ui', $pattern, $matches, PREG_SET_ORDER) > 0) {
foreach ($matches as $match) {
$parts = explode(':', $match[1], 2);
$to = '(?<' . $parts[0] . '>' . (isset($parts[1]) ? $parts[1] : '[\w-]+') . ')';
$pattern = (string)str_replace($match[0], $to, $pattern);
}
}
if ($need_restore_token) {
$pattern = (string)preg_replace('#@([\d,]+)@#', '{\1}', $pattern);
}
return '#^' . $pattern . '$#i';
} else {
return $pattern;
}
} | php | protected function _compilePattern($pattern)
{
if (strpos($pattern, '{') !== false) {
$tr = [
'{area}' => '{area:[a-z]\w*}',
'{controller}' => '{controller:[a-z]\w*}',
'{action}' => '{action:[a-z]\w*}',
'{params}' => '{params:.*}',
'{id}' => '{id:[^/]+}',
':int' => ':\d+',
];
$pattern = strtr($pattern, $tr);
}
if (strpos($pattern, '{') !== false) {
$need_restore_token = false;
if (preg_match('#{\d#', $pattern) === 1) {
$need_restore_token = true;
$pattern = (string)preg_replace('#{([\d,]+)}#', '@\1@', $pattern);
}
$matches = [];
if (preg_match_all('#{([A-Z].*)}#Ui', $pattern, $matches, PREG_SET_ORDER) > 0) {
foreach ($matches as $match) {
$parts = explode(':', $match[1], 2);
$to = '(?<' . $parts[0] . '>' . (isset($parts[1]) ? $parts[1] : '[\w-]+') . ')';
$pattern = (string)str_replace($match[0], $to, $pattern);
}
}
if ($need_restore_token) {
$pattern = (string)preg_replace('#@([\d,]+)@#', '{\1}', $pattern);
}
return '#^' . $pattern . '$#i';
} else {
return $pattern;
}
} | [
"protected",
"function",
"_compilePattern",
"(",
"$",
"pattern",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"pattern",
",",
"'{'",
")",
"!==",
"false",
")",
"{",
"$",
"tr",
"=",
"[",
"'{area}'",
"=>",
"'{area:[a-z]\\w*}'",
",",
"'{controller}'",
"=>",
"'{c... | Replaces placeholders from pattern returning a valid PCRE regular expression
@param string $pattern
@return string | [
"Replaces",
"placeholders",
"from",
"pattern",
"returning",
"a",
"valid",
"PCRE",
"regular",
"expression"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Router/Route.php#L56-L95 | train |
Ma27/Ma27ApiKeyAuthenticationBundle | CacheWarmer/ClassMetadataPropertiesCacheWarmer.php | ClassMetadataPropertiesCacheWarmer.buildCacheData | private function buildCacheData()
{
$metadata = $this->driver->getMetadataForUser();
return serialize(
array_map(function (\ReflectionProperty $property) {
return $property->getName();
}, $metadata)
);
} | php | private function buildCacheData()
{
$metadata = $this->driver->getMetadataForUser();
return serialize(
array_map(function (\ReflectionProperty $property) {
return $property->getName();
}, $metadata)
);
} | [
"private",
"function",
"buildCacheData",
"(",
")",
"{",
"$",
"metadata",
"=",
"$",
"this",
"->",
"driver",
"->",
"getMetadataForUser",
"(",
")",
";",
"return",
"serialize",
"(",
"array_map",
"(",
"function",
"(",
"\\",
"ReflectionProperty",
"$",
"property",
... | Builds the cache data.
@return string | [
"Builds",
"the",
"cache",
"data",
"."
] | 3f1e2ea6eacefac0db41b2ad964c8ef262f0e408 | https://github.com/Ma27/Ma27ApiKeyAuthenticationBundle/blob/3f1e2ea6eacefac0db41b2ad964c8ef262f0e408/CacheWarmer/ClassMetadataPropertiesCacheWarmer.php#L64-L73 | train |
cedriclombardot/TwigGenerator | src/TwigGenerator/Builder/Generator.php | Generator.addBuilder | public function addBuilder(BuilderInterface $builder)
{
$builder->setGenerator($this);
$builder->setTemplateDirs($this->templateDirectories);
$builder->setMustOverwriteIfExists($this->mustOverwriteIfExists);
$builder->setVariables(array_merge($this->variables, $builder->getVariables()));
$this->builders[] = $builder;
return $builder;
} | php | public function addBuilder(BuilderInterface $builder)
{
$builder->setGenerator($this);
$builder->setTemplateDirs($this->templateDirectories);
$builder->setMustOverwriteIfExists($this->mustOverwriteIfExists);
$builder->setVariables(array_merge($this->variables, $builder->getVariables()));
$this->builders[] = $builder;
return $builder;
} | [
"public",
"function",
"addBuilder",
"(",
"BuilderInterface",
"$",
"builder",
")",
"{",
"$",
"builder",
"->",
"setGenerator",
"(",
"$",
"this",
")",
";",
"$",
"builder",
"->",
"setTemplateDirs",
"(",
"$",
"this",
"->",
"templateDirectories",
")",
";",
"$",
... | Add a builder.
@param \TwigGenerator\Builder\BuilderInterface $builder A builder.
@return \TwigGenerator\Builder\BuilderInterface The builder | [
"Add",
"a",
"builder",
"."
] | 54c5ce3b83f5469865546c58ecf1fd32e552b6b2 | https://github.com/cedriclombardot/TwigGenerator/blob/54c5ce3b83f5469865546c58ecf1fd32e552b6b2/src/TwigGenerator/Builder/Generator.php#L126-L136 | train |
wikimedia/wikimedia-textcat | src/TextCat.php | TextCat.createLM | public function createLM( $text, $maxNgrams ) {
$ngram = [];
foreach ( preg_split( "/[{$this->wordSeparator}]+/u", $text ) as $word ) {
if ( empty( $word ) ) {
continue;
}
$word = "_" . $word . "_";
$len = mb_strlen( $word, "UTF-8" );
for ( $i = 0; $i < $len; $i++ ) {
$rlen = $len - $i;
if ( $rlen > 4 ) {
@$ngram[mb_substr( $word, $i, 5, "UTF-8" )]++;
}
if ( $rlen > 3 ) {
@$ngram[mb_substr( $word, $i, 4, "UTF-8" )]++;
}
if ( $rlen > 2 ) {
@$ngram[mb_substr( $word, $i, 3, "UTF-8" )]++;
}
if ( $rlen > 1 ) {
@$ngram[mb_substr( $word, $i, 2, "UTF-8" )]++;
}
@$ngram[mb_substr( $word, $i, 1, "UTF-8" )]++;
}
}
if ( $this->minFreq ) {
$min = $this->minFreq;
$ngram = array_filter( $ngram, function ( $v ) use ( $min ) {
return $v > $min;
} );
}
uksort( $ngram, function ( $k1, $k2 ) use ( $ngram ) {
if ( $ngram[$k1] == $ngram[$k2] ) {
return strcmp( $k1, $k2 );
}
return $ngram[$k2] - $ngram[$k1];
} );
if ( count( $ngram ) > $maxNgrams ) {
array_splice( $ngram, $maxNgrams );
}
return $ngram;
} | php | public function createLM( $text, $maxNgrams ) {
$ngram = [];
foreach ( preg_split( "/[{$this->wordSeparator}]+/u", $text ) as $word ) {
if ( empty( $word ) ) {
continue;
}
$word = "_" . $word . "_";
$len = mb_strlen( $word, "UTF-8" );
for ( $i = 0; $i < $len; $i++ ) {
$rlen = $len - $i;
if ( $rlen > 4 ) {
@$ngram[mb_substr( $word, $i, 5, "UTF-8" )]++;
}
if ( $rlen > 3 ) {
@$ngram[mb_substr( $word, $i, 4, "UTF-8" )]++;
}
if ( $rlen > 2 ) {
@$ngram[mb_substr( $word, $i, 3, "UTF-8" )]++;
}
if ( $rlen > 1 ) {
@$ngram[mb_substr( $word, $i, 2, "UTF-8" )]++;
}
@$ngram[mb_substr( $word, $i, 1, "UTF-8" )]++;
}
}
if ( $this->minFreq ) {
$min = $this->minFreq;
$ngram = array_filter( $ngram, function ( $v ) use ( $min ) {
return $v > $min;
} );
}
uksort( $ngram, function ( $k1, $k2 ) use ( $ngram ) {
if ( $ngram[$k1] == $ngram[$k2] ) {
return strcmp( $k1, $k2 );
}
return $ngram[$k2] - $ngram[$k1];
} );
if ( count( $ngram ) > $maxNgrams ) {
array_splice( $ngram, $maxNgrams );
}
return $ngram;
} | [
"public",
"function",
"createLM",
"(",
"$",
"text",
",",
"$",
"maxNgrams",
")",
"{",
"$",
"ngram",
"=",
"[",
"]",
";",
"foreach",
"(",
"preg_split",
"(",
"\"/[{$this->wordSeparator}]+/u\"",
",",
"$",
"text",
")",
"as",
"$",
"word",
")",
"{",
"if",
"(",... | Create ngrams list for text.
@param string $text
@param int $maxNgrams How many ngrams to use.
@return int[] | [
"Create",
"ngrams",
"list",
"for",
"text",
"."
] | 4f13aed2b32382c9d2fe9dc8b3e3fbb26ea4a2a9 | https://github.com/wikimedia/wikimedia-textcat/blob/4f13aed2b32382c9d2fe9dc8b3e3fbb26ea4a2a9/src/TextCat.php#L192-L233 | train |
wikimedia/wikimedia-textcat | src/TextCat.php | TextCat.writeLanguageFile | public function writeLanguageFile( $ngrams, $outfile ) {
$out = fopen( $outfile, "w" );
// write original array as "$ngrams"
fwrite( $out, '<?php $ngrams = ' . var_export( $ngrams, true ) . ";\n" );
// write reduced array as "$ranks"
$rank = 1;
$ranks = array_map( function ( $x ) use ( &$rank ) {
return $rank++;
}, $ngrams );
fwrite( $out, '$ranks = ' . var_export( $ranks, true ) . ";\n" );
fclose( $out );
} | php | public function writeLanguageFile( $ngrams, $outfile ) {
$out = fopen( $outfile, "w" );
// write original array as "$ngrams"
fwrite( $out, '<?php $ngrams = ' . var_export( $ngrams, true ) . ";\n" );
// write reduced array as "$ranks"
$rank = 1;
$ranks = array_map( function ( $x ) use ( &$rank ) {
return $rank++;
}, $ngrams );
fwrite( $out, '$ranks = ' . var_export( $ranks, true ) . ";\n" );
fclose( $out );
} | [
"public",
"function",
"writeLanguageFile",
"(",
"$",
"ngrams",
",",
"$",
"outfile",
")",
"{",
"$",
"out",
"=",
"fopen",
"(",
"$",
"outfile",
",",
"\"w\"",
")",
";",
"// write original array as \"$ngrams\"",
"fwrite",
"(",
"$",
"out",
",",
"'<?php $ngrams = '",... | Write ngrams to file in PHP format
@param int[] $ngrams
@param string $outfile Output filename | [
"Write",
"ngrams",
"to",
"file",
"in",
"PHP",
"format"
] | 4f13aed2b32382c9d2fe9dc8b3e3fbb26ea4a2a9 | https://github.com/wikimedia/wikimedia-textcat/blob/4f13aed2b32382c9d2fe9dc8b3e3fbb26ea4a2a9/src/TextCat.php#L251-L262 | train |
wikimedia/wikimedia-textcat | src/TextCat.php | TextCat.classify | public function classify( $text, $candidates = null ) {
$results = [];
$this->resultStatus = '';
// strip non-word characters before checking for min length, don't assess empty strings
$wordLength = mb_strlen( preg_replace( "/[{$this->wordSeparator}]+/", "", $text ) );
if ( $wordLength < $this->minInputLength || $wordLength == 0 ) {
$this->resultStatus = self::STATUSTOOSHORT;
return $results;
}
$inputgrams = array_keys( $this->createLM( $text, $this->maxNgrams ) );
if ( $candidates ) {
// flip for more efficient lookups
$candidates = array_flip( $candidates );
}
foreach ( $this->langFiles as $language => $langFile ) {
if ( $candidates && !isset( $candidates[$language] ) ) {
continue;
}
$ngrams = $this->loadLanguageFile( $langFile );
$p = 0;
foreach ( $inputgrams as $i => $ingram ) {
if ( !empty( $ngrams[$ingram] ) ) {
$p += abs( $ngrams[$ingram] - $i );
} else {
$p += $this->maxNgrams;
}
}
if ( isset( $this->boostedLangs[$language] ) ) {
$p = round( $p * ( 1 - $this->langBoostScore ) );
}
$results[$language] = $p;
}
asort( $results );
// ignore any item that scores higher than best * resultsRatio
$max = reset( $results ) * $this->resultsRatio;
$results = array_filter( $results, function ( $res ) use ( $max ) {
return $res <= $max;
} );
// if more than maxReturnedLanguages remain, the result is too ambiguous, so bail
if ( count( $results ) > $this->maxReturnedLanguages ) {
$this->resultStatus = self::STATUSAMBIGUOUS;
return [];
}
// filter max proportion of max score after ambiguity check; reuse $max variable
$max = count( $inputgrams ) * $this->maxNgrams * $this->maxProportion;
$results = array_filter( $results, function ( $res ) use ( $max ) {
return $res <= $max;
} );
if ( count( $results ) == 0 ) {
$this->resultStatus = self::STATUSNOMATCH;
return $results;
}
return $results;
} | php | public function classify( $text, $candidates = null ) {
$results = [];
$this->resultStatus = '';
// strip non-word characters before checking for min length, don't assess empty strings
$wordLength = mb_strlen( preg_replace( "/[{$this->wordSeparator}]+/", "", $text ) );
if ( $wordLength < $this->minInputLength || $wordLength == 0 ) {
$this->resultStatus = self::STATUSTOOSHORT;
return $results;
}
$inputgrams = array_keys( $this->createLM( $text, $this->maxNgrams ) );
if ( $candidates ) {
// flip for more efficient lookups
$candidates = array_flip( $candidates );
}
foreach ( $this->langFiles as $language => $langFile ) {
if ( $candidates && !isset( $candidates[$language] ) ) {
continue;
}
$ngrams = $this->loadLanguageFile( $langFile );
$p = 0;
foreach ( $inputgrams as $i => $ingram ) {
if ( !empty( $ngrams[$ingram] ) ) {
$p += abs( $ngrams[$ingram] - $i );
} else {
$p += $this->maxNgrams;
}
}
if ( isset( $this->boostedLangs[$language] ) ) {
$p = round( $p * ( 1 - $this->langBoostScore ) );
}
$results[$language] = $p;
}
asort( $results );
// ignore any item that scores higher than best * resultsRatio
$max = reset( $results ) * $this->resultsRatio;
$results = array_filter( $results, function ( $res ) use ( $max ) {
return $res <= $max;
} );
// if more than maxReturnedLanguages remain, the result is too ambiguous, so bail
if ( count( $results ) > $this->maxReturnedLanguages ) {
$this->resultStatus = self::STATUSAMBIGUOUS;
return [];
}
// filter max proportion of max score after ambiguity check; reuse $max variable
$max = count( $inputgrams ) * $this->maxNgrams * $this->maxProportion;
$results = array_filter( $results, function ( $res ) use ( $max ) {
return $res <= $max;
} );
if ( count( $results ) == 0 ) {
$this->resultStatus = self::STATUSNOMATCH;
return $results;
}
return $results;
} | [
"public",
"function",
"classify",
"(",
"$",
"text",
",",
"$",
"candidates",
"=",
"null",
")",
"{",
"$",
"results",
"=",
"[",
"]",
";",
"$",
"this",
"->",
"resultStatus",
"=",
"''",
";",
"// strip non-word characters before checking for min length, don't assess emp... | Classify text.
@param string $text
@param string[]|null $candidates List of candidate languages.
@return int[] Array with keys of language names and values of score.
Sorted by ascending score, with first result being the best. | [
"Classify",
"text",
"."
] | 4f13aed2b32382c9d2fe9dc8b3e3fbb26ea4a2a9 | https://github.com/wikimedia/wikimedia-textcat/blob/4f13aed2b32382c9d2fe9dc8b3e3fbb26ea4a2a9/src/TextCat.php#L271-L332 | train |
API-Skeletons/zf-oauth2-doctrine-identity | src/AuthenticationPostListener.php | AuthenticationPostListener.findAccessToken | private function findAccessToken(array $identity)
{
$config = $this->container->get('config');
foreach ($config['zf-oauth2-doctrine'] as $oauth2Config) {
if (array_key_exists('object_manager', $oauth2Config)) {
$objectManager = $this->container->get($oauth2Config['object_manager']);
$accessTokenRepository = $objectManager
->getRepository($oauth2Config['mapping']['AccessToken']['entity']);
$accessToken = $accessTokenRepository->findOneBy([
$oauth2Config['mapping']['AccessToken']['mapping']['access_token']['name']
=> array_key_exists('access_token', $identity) ? $identity['access_token'] : $identity['id'],
]);
if ($accessToken) {
if ($accessToken->getClient()->getClientId() == $identity['client_id']) {
// Match found
return $accessToken;
}
}
}
}
} | php | private function findAccessToken(array $identity)
{
$config = $this->container->get('config');
foreach ($config['zf-oauth2-doctrine'] as $oauth2Config) {
if (array_key_exists('object_manager', $oauth2Config)) {
$objectManager = $this->container->get($oauth2Config['object_manager']);
$accessTokenRepository = $objectManager
->getRepository($oauth2Config['mapping']['AccessToken']['entity']);
$accessToken = $accessTokenRepository->findOneBy([
$oauth2Config['mapping']['AccessToken']['mapping']['access_token']['name']
=> array_key_exists('access_token', $identity) ? $identity['access_token'] : $identity['id'],
]);
if ($accessToken) {
if ($accessToken->getClient()->getClientId() == $identity['client_id']) {
// Match found
return $accessToken;
}
}
}
}
} | [
"private",
"function",
"findAccessToken",
"(",
"array",
"$",
"identity",
")",
"{",
"$",
"config",
"=",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'config'",
")",
";",
"foreach",
"(",
"$",
"config",
"[",
"'zf-oauth2-doctrine'",
"]",
"as",
"$",
"oa... | Search each OAuth2 configuration for a matching clientId and access_token | [
"Search",
"each",
"OAuth2",
"configuration",
"for",
"a",
"matching",
"clientId",
"and",
"access_token"
] | fa176519932c0080ad07a63b3d7a983a2dc3f2ce | https://github.com/API-Skeletons/zf-oauth2-doctrine-identity/blob/fa176519932c0080ad07a63b3d7a983a2dc3f2ce/src/AuthenticationPostListener.php#L47-L70 | train |
silvershop/silvershop-comparison | src/Extension/ProductControllerFeaturesExtension.php | ProductControllerFeaturesExtension.GroupedFeatures | public function GroupedFeatures($showungrouped = false)
{
$features = $this->owner->Features()
->innerJoin("Feature","Feature.ID = ProductFeatureValue.FeatureID");
//figure out feature groups
$groupids = FeatureGroup::get()
->innerJoin("Feature","Feature.GroupID = FeatureGroup.ID")
->innerJoin("ProductFeatureValue","Feature.ID = ProductFeatureValue.FeatureID")
->filter("ProductID",$this->owner->ID)
->getIDList();
//pack existin features into seperate lists
$result = new ArrayList();
foreach($groupids as $groupid) {
$group = FeatureGroup::get()->byID($groupid);
$result->push(new ArrayData(array(
'Group' => $group,
'Children' => $features->filter("GroupID", $groupid)
)));
}
$ungrouped = $features->filter("GroupID:not", $groupids);
if ($ungrouped->exists() && $showungrouped) {
$result->push(new ArrayData(array(
'Children' => $ungrouped
)));
}
return $result;
} | php | public function GroupedFeatures($showungrouped = false)
{
$features = $this->owner->Features()
->innerJoin("Feature","Feature.ID = ProductFeatureValue.FeatureID");
//figure out feature groups
$groupids = FeatureGroup::get()
->innerJoin("Feature","Feature.GroupID = FeatureGroup.ID")
->innerJoin("ProductFeatureValue","Feature.ID = ProductFeatureValue.FeatureID")
->filter("ProductID",$this->owner->ID)
->getIDList();
//pack existin features into seperate lists
$result = new ArrayList();
foreach($groupids as $groupid) {
$group = FeatureGroup::get()->byID($groupid);
$result->push(new ArrayData(array(
'Group' => $group,
'Children' => $features->filter("GroupID", $groupid)
)));
}
$ungrouped = $features->filter("GroupID:not", $groupids);
if ($ungrouped->exists() && $showungrouped) {
$result->push(new ArrayData(array(
'Children' => $ungrouped
)));
}
return $result;
} | [
"public",
"function",
"GroupedFeatures",
"(",
"$",
"showungrouped",
"=",
"false",
")",
"{",
"$",
"features",
"=",
"$",
"this",
"->",
"owner",
"->",
"Features",
"(",
")",
"->",
"innerJoin",
"(",
"\"Feature\"",
",",
"\"Feature.ID = ProductFeatureValue.FeatureID\"",
... | Override features list with grouping. | [
"Override",
"features",
"list",
"with",
"grouping",
"."
] | 5ef095e65d5fa22714d1071ff78a43b2ce917db0 | https://github.com/silvershop/silvershop-comparison/blob/5ef095e65d5fa22714d1071ff78a43b2ce917db0/src/Extension/ProductControllerFeaturesExtension.php#L16-L47 | train |
pscheit/jparser | PLUG/parsing/bnf/BNFParser.php | BNFParser.parse_string | static function parse_string( $s ){
if( $s == '' ){
throw new Exception('Cannot parse empty string');
}
// instantiate self
$Parser = new BNFParser;
// perform external tokenizing on string input
$tokens = bnf_tokenize( $s );
return $Parser->parse( $tokens );
} | php | static function parse_string( $s ){
if( $s == '' ){
throw new Exception('Cannot parse empty string');
}
// instantiate self
$Parser = new BNFParser;
// perform external tokenizing on string input
$tokens = bnf_tokenize( $s );
return $Parser->parse( $tokens );
} | [
"static",
"function",
"parse_string",
"(",
"$",
"s",
")",
"{",
"if",
"(",
"$",
"s",
"==",
"''",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Cannot parse empty string'",
")",
";",
"}",
"// instantiate self",
"$",
"Parser",
"=",
"new",
"BNFParser",
";",
... | parse input string
@param string input source
@return ParseNode | [
"parse",
"input",
"string"
] | f9de77171c0d37d237e0e9a918ed7bff19e12095 | https://github.com/pscheit/jparser/blob/f9de77171c0d37d237e0e9a918ed7bff19e12095/PLUG/parsing/bnf/BNFParser.php#L58-L67 | train |
pscheit/jparser | PLUG/parsing/bnf/BNFParser.php | BNFParser.parse_file | static function parse_file( $f ){
$src = file_get_contents( $f, true );
if( $src === false ){
throw new Exception("Cannot read file $f");
}
return self::parse_string( $src );
} | php | static function parse_file( $f ){
$src = file_get_contents( $f, true );
if( $src === false ){
throw new Exception("Cannot read file $f");
}
return self::parse_string( $src );
} | [
"static",
"function",
"parse_file",
"(",
"$",
"f",
")",
"{",
"$",
"src",
"=",
"file_get_contents",
"(",
"$",
"f",
",",
"true",
")",
";",
"if",
"(",
"$",
"src",
"===",
"false",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"Cannot read file $f\"",
")",
... | Parse input from file
@param string file path
@return ParseNode | [
"Parse",
"input",
"from",
"file"
] | f9de77171c0d37d237e0e9a918ed7bff19e12095 | https://github.com/pscheit/jparser/blob/f9de77171c0d37d237e0e9a918ed7bff19e12095/PLUG/parsing/bnf/BNFParser.php#L76-L82 | train |
manaphp/framework | Db.php | Db.fetchOne | public function fetchOne($sql, $bind = [], $fetchMode = \PDO::FETCH_ASSOC, $useMaster = false)
{
return ($rs = $this->fetchAll($sql, $bind, $fetchMode, $useMaster)) ? $rs[0] : false;
} | php | public function fetchOne($sql, $bind = [], $fetchMode = \PDO::FETCH_ASSOC, $useMaster = false)
{
return ($rs = $this->fetchAll($sql, $bind, $fetchMode, $useMaster)) ? $rs[0] : false;
} | [
"public",
"function",
"fetchOne",
"(",
"$",
"sql",
",",
"$",
"bind",
"=",
"[",
"]",
",",
"$",
"fetchMode",
"=",
"\\",
"PDO",
"::",
"FETCH_ASSOC",
",",
"$",
"useMaster",
"=",
"false",
")",
"{",
"return",
"(",
"$",
"rs",
"=",
"$",
"this",
"->",
"fe... | Returns the first row in a SQL query result
@param string $sql
@param array $bind
@param int $fetchMode
@param bool $useMaster
@return array|false | [
"Returns",
"the",
"first",
"row",
"in",
"a",
"SQL",
"query",
"result"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Db.php#L200-L203 | train |
manaphp/framework | Db.php | Db.fetchAll | public function fetchAll($sql, $bind = [], $fetchMode = \PDO::FETCH_ASSOC, $useMaster = false)
{
$context = $this->_context;
$context->sql = $sql;
$context->bind = $bind;
$context->affected_rows = 0;
$this->eventsManager->fireEvent('db:beforeQuery', $this);
if ($context->connection) {
$type = null;
$connection = $context->connection;
} else {
$type = $this->_has_slave ? 'slave' : 'default';
$connection = $this->poolManager->pop($this, $this->_timeout, $type);
}
try {
$start_time = microtime(true);
$result = $connection->query($sql, $bind, $fetchMode, $useMaster);
$elapsed = round(microtime(true) - $start_time, 3);
} finally {
if ($type) {
$this->poolManager->push($this, $connection, $type);
}
}
$count = $context->affected_rows = count($result);
$event_data = compact('elapsed', 'count', 'sql', 'bind', 'result');
$this->logger->debug($event_data, 'db.query');
$this->eventsManager->fireEvent('db:afterQuery', $this, $event_data);
return $result;
} | php | public function fetchAll($sql, $bind = [], $fetchMode = \PDO::FETCH_ASSOC, $useMaster = false)
{
$context = $this->_context;
$context->sql = $sql;
$context->bind = $bind;
$context->affected_rows = 0;
$this->eventsManager->fireEvent('db:beforeQuery', $this);
if ($context->connection) {
$type = null;
$connection = $context->connection;
} else {
$type = $this->_has_slave ? 'slave' : 'default';
$connection = $this->poolManager->pop($this, $this->_timeout, $type);
}
try {
$start_time = microtime(true);
$result = $connection->query($sql, $bind, $fetchMode, $useMaster);
$elapsed = round(microtime(true) - $start_time, 3);
} finally {
if ($type) {
$this->poolManager->push($this, $connection, $type);
}
}
$count = $context->affected_rows = count($result);
$event_data = compact('elapsed', 'count', 'sql', 'bind', 'result');
$this->logger->debug($event_data, 'db.query');
$this->eventsManager->fireEvent('db:afterQuery', $this, $event_data);
return $result;
} | [
"public",
"function",
"fetchAll",
"(",
"$",
"sql",
",",
"$",
"bind",
"=",
"[",
"]",
",",
"$",
"fetchMode",
"=",
"\\",
"PDO",
"::",
"FETCH_ASSOC",
",",
"$",
"useMaster",
"=",
"false",
")",
"{",
"$",
"context",
"=",
"$",
"this",
"->",
"_context",
";"... | Dumps the complete result of a query into an array
@param string $sql
@param array $bind
@param int $fetchMode
@param bool $useMaster
@return array | [
"Dumps",
"the",
"complete",
"result",
"of",
"a",
"query",
"into",
"an",
"array"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Db.php#L215-L252 | train |
manaphp/framework | Db.php | Db.delete | public function delete($table, $conditions, $bind = [])
{
if (is_string($conditions)) {
$conditions = [$conditions];
}
$wheres = [];
/** @noinspection ForeachSourceInspection */
foreach ($conditions as $k => $v) {
if (is_int($k)) {
$wheres[] = stripos($v, ' or ') ? "($v)" : $v;
} else {
$wheres[] = "[$k]=:$k";
$bind[$k] = $v;
}
}
$sql = 'DELETE' . ' FROM ' . $this->_escapeIdentifier($table) . ' WHERE ' . implode(' AND ', $wheres);
return $this->_execute('delete', $sql, $bind);
} | php | public function delete($table, $conditions, $bind = [])
{
if (is_string($conditions)) {
$conditions = [$conditions];
}
$wheres = [];
/** @noinspection ForeachSourceInspection */
foreach ($conditions as $k => $v) {
if (is_int($k)) {
$wheres[] = stripos($v, ' or ') ? "($v)" : $v;
} else {
$wheres[] = "[$k]=:$k";
$bind[$k] = $v;
}
}
$sql = 'DELETE' . ' FROM ' . $this->_escapeIdentifier($table) . ' WHERE ' . implode(' AND ', $wheres);
return $this->_execute('delete', $sql, $bind);
} | [
"public",
"function",
"delete",
"(",
"$",
"table",
",",
"$",
"conditions",
",",
"$",
"bind",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"conditions",
")",
")",
"{",
"$",
"conditions",
"=",
"[",
"$",
"conditions",
"]",
";",
"}",
"$... | Deletes data from a table using custom SQL syntax
@param string $table
@param string|array $conditions
@param array $bind
@return int
@throws \ManaPHP\Db\Exception | [
"Deletes",
"data",
"from",
"a",
"table",
"using",
"custom",
"SQL",
"syntax"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Db.php#L443-L462 | train |
manaphp/framework | Db.php | Db.getEmulatedSQL | public function getEmulatedSQL($preservedStrLength = -1)
{
$context = $this->_context;
if (!$context->bind) {
return (string)$context->sql;
}
$bind = $context->bind;
if (isset($bind[0])) {
return (string)$context->sql;
} else {
$replaces = [];
foreach ($bind as $key => $value) {
$replaces[':' . $key] = $this->_parseBindValue($value, $preservedStrLength);
}
return strtr($context->sql, $replaces);
}
} | php | public function getEmulatedSQL($preservedStrLength = -1)
{
$context = $this->_context;
if (!$context->bind) {
return (string)$context->sql;
}
$bind = $context->bind;
if (isset($bind[0])) {
return (string)$context->sql;
} else {
$replaces = [];
foreach ($bind as $key => $value) {
$replaces[':' . $key] = $this->_parseBindValue($value, $preservedStrLength);
}
return strtr($context->sql, $replaces);
}
} | [
"public",
"function",
"getEmulatedSQL",
"(",
"$",
"preservedStrLength",
"=",
"-",
"1",
")",
"{",
"$",
"context",
"=",
"$",
"this",
"->",
"_context",
";",
"if",
"(",
"!",
"$",
"context",
"->",
"bind",
")",
"{",
"return",
"(",
"string",
")",
"$",
"cont... | Active SQL statement in the object with replace the bind with value
@param int $preservedStrLength
@return string | [
"Active",
"SQL",
"statement",
"in",
"the",
"object",
"with",
"replace",
"the",
"bind",
"with",
"value"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Db.php#L530-L549 | train |
manaphp/framework | Db.php | Db.begin | public function begin()
{
$context = $this->_context;
$this->logger->info('transaction begin', 'db.transaction.begin');
if ($context->transaction_level === 0) {
$this->eventsManager->fireEvent('db:beginTransaction', $this);
try {
$connection = $this->poolManager->pop($this, $this->_timeout);
if (!$connection->beginTransaction()) {
throw new DbException('beginTransaction failed.');
}
$context->connection = $connection;
} catch (\PDOException $exception) {
throw new DbException('beginTransaction failed: ' . $exception->getMessage(), $exception->getCode(), $exception);
} finally {
if (!$context->connection) {
$this->poolManager->push($this, $context);
}
}
}
$context->transaction_level++;
} | php | public function begin()
{
$context = $this->_context;
$this->logger->info('transaction begin', 'db.transaction.begin');
if ($context->transaction_level === 0) {
$this->eventsManager->fireEvent('db:beginTransaction', $this);
try {
$connection = $this->poolManager->pop($this, $this->_timeout);
if (!$connection->beginTransaction()) {
throw new DbException('beginTransaction failed.');
}
$context->connection = $connection;
} catch (\PDOException $exception) {
throw new DbException('beginTransaction failed: ' . $exception->getMessage(), $exception->getCode(), $exception);
} finally {
if (!$context->connection) {
$this->poolManager->push($this, $context);
}
}
}
$context->transaction_level++;
} | [
"public",
"function",
"begin",
"(",
")",
"{",
"$",
"context",
"=",
"$",
"this",
"->",
"_context",
";",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"'transaction begin'",
",",
"'db.transaction.begin'",
")",
";",
"if",
"(",
"$",
"context",
"->",
"trans... | Starts a transaction in the connection
@return void
@throws \ManaPHP\Db\Exception | [
"Starts",
"a",
"transaction",
"in",
"the",
"connection"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Db.php#L567-L593 | train |
manaphp/framework | Db.php | Db.rollback | public function rollback()
{
$context = $this->_context;
if ($context->transaction_level > 0) {
$this->logger->info('transaction rollback', 'db.transaction.rollback');
$context->transaction_level--;
if ($context->transaction_level === 0) {
$this->eventsManager->fireEvent('db:rollbackTransaction', $this);
try {
if (!$context->connection->rollBack()) {
throw new DbException('rollBack failed.');
}
} catch (\PDOException $exception) {
throw new DbException('rollBack failed: ' . $exception->getMessage(), $exception->getCode(), $exception);
} finally {
$this->poolManager->push($this, $context->connection);
$context->connection = null;
}
}
}
} | php | public function rollback()
{
$context = $this->_context;
if ($context->transaction_level > 0) {
$this->logger->info('transaction rollback', 'db.transaction.rollback');
$context->transaction_level--;
if ($context->transaction_level === 0) {
$this->eventsManager->fireEvent('db:rollbackTransaction', $this);
try {
if (!$context->connection->rollBack()) {
throw new DbException('rollBack failed.');
}
} catch (\PDOException $exception) {
throw new DbException('rollBack failed: ' . $exception->getMessage(), $exception->getCode(), $exception);
} finally {
$this->poolManager->push($this, $context->connection);
$context->connection = null;
}
}
}
} | [
"public",
"function",
"rollback",
"(",
")",
"{",
"$",
"context",
"=",
"$",
"this",
"->",
"_context",
";",
"if",
"(",
"$",
"context",
"->",
"transaction_level",
">",
"0",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"'transaction rollback'",
... | Rollbacks the active transaction in the connection
@return void
@throws \ManaPHP\Db\Exception | [
"Rollbacks",
"the",
"active",
"transaction",
"in",
"the",
"connection"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Db.php#L613-L636 | train |
milejko/mmi-cms | src/Cms/Model/CategoryModel.php | CategoryModel.getCategoryTree | public function getCategoryTree($parentCategoryId = null)
{
//brak zdefiniowanej kategorii
if ($parentCategoryId === null) {
return $this->_categoryTree;
}
//wyszukiwanie kategorii
return $this->_searchChildren($this->_categoryTree, $parentCategoryId);
} | php | public function getCategoryTree($parentCategoryId = null)
{
//brak zdefiniowanej kategorii
if ($parentCategoryId === null) {
return $this->_categoryTree;
}
//wyszukiwanie kategorii
return $this->_searchChildren($this->_categoryTree, $parentCategoryId);
} | [
"public",
"function",
"getCategoryTree",
"(",
"$",
"parentCategoryId",
"=",
"null",
")",
"{",
"//brak zdefiniowanej kategorii",
"if",
"(",
"$",
"parentCategoryId",
"===",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"_categoryTree",
";",
"}",
"//wyszukiwanie kat... | Zwraca drzewo kategorii
@param integer $parentCategoryId identyfikator kategorii rodzica (opcjonalny)
@return array | [
"Zwraca",
"drzewo",
"kategorii"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/Cms/Model/CategoryModel.php#L55-L63 | train |
milejko/mmi-cms | src/Cms/Model/CategoryModel.php | CategoryModel._buildTree | private function _buildTree(array &$tree, array $parents, array $orderedCategories, CmsCategoryRecord $parentCategory = null)
{
//uzupełnienie rodziców
if ($parentCategory !== null) {
$parents[$parentCategory->id] = $parentCategory;
} else {
$parentCategory = new CmsCategoryRecord;
$parentCategory->id = null;
}
/* @var $categoryRecord CmsCategoryRecord */
foreach ($orderedCategories as $key => $categoryRecord) {
//niezgodny rodzic
if ($categoryRecord->parentId != $parentCategory->id) {
continue;
}
//dodawanie do płaskiej listy
$this->_flatCategories[$categoryRecord->id] = $categoryRecord;
//usuwanie wykorzystanego rekordu kategorii
unset($orderedCategories[$key]);
//zapis do drzewa
$tree[$categoryRecord->id] = [];
$tree[$categoryRecord->id]['record'] = $categoryRecord->setOption('parents', $parents);
$tree[$categoryRecord->id]['children'] = [];
//zejście rekurencyjne do dzieci
$this->_buildTree($tree[$categoryRecord->id]['children'], $parents, $orderedCategories, $categoryRecord);
}
} | php | private function _buildTree(array &$tree, array $parents, array $orderedCategories, CmsCategoryRecord $parentCategory = null)
{
//uzupełnienie rodziców
if ($parentCategory !== null) {
$parents[$parentCategory->id] = $parentCategory;
} else {
$parentCategory = new CmsCategoryRecord;
$parentCategory->id = null;
}
/* @var $categoryRecord CmsCategoryRecord */
foreach ($orderedCategories as $key => $categoryRecord) {
//niezgodny rodzic
if ($categoryRecord->parentId != $parentCategory->id) {
continue;
}
//dodawanie do płaskiej listy
$this->_flatCategories[$categoryRecord->id] = $categoryRecord;
//usuwanie wykorzystanego rekordu kategorii
unset($orderedCategories[$key]);
//zapis do drzewa
$tree[$categoryRecord->id] = [];
$tree[$categoryRecord->id]['record'] = $categoryRecord->setOption('parents', $parents);
$tree[$categoryRecord->id]['children'] = [];
//zejście rekurencyjne do dzieci
$this->_buildTree($tree[$categoryRecord->id]['children'], $parents, $orderedCategories, $categoryRecord);
}
} | [
"private",
"function",
"_buildTree",
"(",
"array",
"&",
"$",
"tree",
",",
"array",
"$",
"parents",
",",
"array",
"$",
"orderedCategories",
",",
"CmsCategoryRecord",
"$",
"parentCategory",
"=",
"null",
")",
"{",
"//uzupełnienie rodziców",
"if",
"(",
"$",
"paren... | Buduje drzewo rekurencyjnie
@param array $tree
@param array $parents
@param array $orderedCategories
@param CmsCategoryRecord|null $parentCategory | [
"Buduje",
"drzewo",
"rekurencyjnie"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/Cms/Model/CategoryModel.php#L137-L163 | train |
mapbender/fom | src/FOM/UserBundle/Entity/User.php | User.getRoles | public function getRoles()
{
$roles = array();
foreach ($this->groups as $group) {
$roles[] = $group->getAsRole();
}
$roles[] = 'ROLE_USER';
return $roles;
} | php | public function getRoles()
{
$roles = array();
foreach ($this->groups as $group) {
$roles[] = $group->getAsRole();
}
$roles[] = 'ROLE_USER';
return $roles;
} | [
"public",
"function",
"getRoles",
"(",
")",
"{",
"$",
"roles",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"groups",
"as",
"$",
"group",
")",
"{",
"$",
"roles",
"[",
"]",
"=",
"$",
"group",
"->",
"getAsRole",
"(",
")",
";",
... | Get role objects
@return array | [
"Get",
"role",
"objects"
] | 6dea943121f3c3f9b1b4b14dc2a8e8640a120675 | https://github.com/mapbender/fom/blob/6dea943121f3c3f9b1b4b14dc2a8e8640a120675/src/FOM/UserBundle/Entity/User.php#L320-L328 | train |
milejko/mmi-cms | src/Cms/Orm/CmsFileRecord.php | CmsFileRecord.getHashName | public function getHashName()
{
//brak pliku
if ($this->id === null) {
return;
}
return substr(md5($this->name . \App\Registry::$config->salt), 0, 8);
} | php | public function getHashName()
{
//brak pliku
if ($this->id === null) {
return;
}
return substr(md5($this->name . \App\Registry::$config->salt), 0, 8);
} | [
"public",
"function",
"getHashName",
"(",
")",
"{",
"//brak pliku",
"if",
"(",
"$",
"this",
"->",
"id",
"===",
"null",
")",
"{",
"return",
";",
"}",
"return",
"substr",
"(",
"md5",
"(",
"$",
"this",
"->",
"name",
".",
"\\",
"App",
"\\",
"Registry",
... | Pobiera hash dla danej nazwy pliku
@param string $name nazwa pliku
@return string | [
"Pobiera",
"hash",
"dla",
"danej",
"nazwy",
"pliku"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/Cms/Orm/CmsFileRecord.php#L92-L99 | train |
milejko/mmi-cms | src/Cms/Orm/CmsFileRecord.php | CmsFileRecord.getPosterUrl | public function getPosterUrl($scaleType = 'default', $scale = null, $https = null)
{
//brak pliku
if (null === $this->id || !$this->data->posterFileName) {
return;
}
//ścieżka CDN
$cdnPath = rtrim(\Mmi\App\FrontController::getInstance()->getView()->cdn ? \Mmi\App\FrontController::getInstance()->getView()->cdn : \Mmi\App\FrontController::getInstance()->getView()->url([], true, $https), '/');
//pobranie ścieżki z systemu plików
return $cdnPath . (new \Cms\Model\FileSystemModel($this->data->posterFileName))->getPublicPath($scaleType, $scale);
} | php | public function getPosterUrl($scaleType = 'default', $scale = null, $https = null)
{
//brak pliku
if (null === $this->id || !$this->data->posterFileName) {
return;
}
//ścieżka CDN
$cdnPath = rtrim(\Mmi\App\FrontController::getInstance()->getView()->cdn ? \Mmi\App\FrontController::getInstance()->getView()->cdn : \Mmi\App\FrontController::getInstance()->getView()->url([], true, $https), '/');
//pobranie ścieżki z systemu plików
return $cdnPath . (new \Cms\Model\FileSystemModel($this->data->posterFileName))->getPublicPath($scaleType, $scale);
} | [
"public",
"function",
"getPosterUrl",
"(",
"$",
"scaleType",
"=",
"'default'",
",",
"$",
"scale",
"=",
"null",
",",
"$",
"https",
"=",
"null",
")",
"{",
"//brak pliku",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"id",
"||",
"!",
"$",
"this",
"->",
... | Pobiera adres postera pliku
@param string $scaleType scale, scalex, scaley, scalecrop
@param int|string $scale 320, 320x240
@param boolean $https null - bez zmian, true - tak, false - nie
@return string adres publiczny postera pliku | [
"Pobiera",
"adres",
"postera",
"pliku"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/Cms/Orm/CmsFileRecord.php#L148-L158 | train |
milejko/mmi-cms | src/Cms/Orm/CmsFileRecord.php | CmsFileRecord.delete | public function delete()
{
//usuwanie meta
if (!parent::delete()) {
return false;
}
//plik jest ciągle potrzebny (ma linki)
if (0 != (new CmsFileQuery)->whereName()->equals($this->name)->count()) {
return true;
}
//kasowanie z systemu plików
(new \Cms\Model\FileSystemModel($this->name))->unlink();
//usuwanie rekordu
return true;
} | php | public function delete()
{
//usuwanie meta
if (!parent::delete()) {
return false;
}
//plik jest ciągle potrzebny (ma linki)
if (0 != (new CmsFileQuery)->whereName()->equals($this->name)->count()) {
return true;
}
//kasowanie z systemu plików
(new \Cms\Model\FileSystemModel($this->name))->unlink();
//usuwanie rekordu
return true;
} | [
"public",
"function",
"delete",
"(",
")",
"{",
"//usuwanie meta",
"if",
"(",
"!",
"parent",
"::",
"delete",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"//plik jest ciągle potrzebny (ma linki)",
"if",
"(",
"0",
"!=",
"(",
"new",
"CmsFileQuery",
")",
"... | Usuwa plik, fizycznie i z bazy danych
@return boolean | [
"Usuwa",
"plik",
"fizycznie",
"i",
"z",
"bazy",
"danych"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/Cms/Orm/CmsFileRecord.php#L274-L288 | train |
manaphp/framework | Query.php | Query.limit | public function limit($limit, $offset = null)
{
$this->_limit = $limit > 0 ? (int)$limit : null;
$this->_offset = $offset > 0 ? (int)$offset : null;
return $this;
} | php | public function limit($limit, $offset = null)
{
$this->_limit = $limit > 0 ? (int)$limit : null;
$this->_offset = $offset > 0 ? (int)$offset : null;
return $this;
} | [
"public",
"function",
"limit",
"(",
"$",
"limit",
",",
"$",
"offset",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"_limit",
"=",
"$",
"limit",
">",
"0",
"?",
"(",
"int",
")",
"$",
"limit",
":",
"null",
";",
"$",
"this",
"->",
"_offset",
"=",
"$",... | Sets a LIMIT clause, optionally a offset clause
@param int $limit
@param int $offset
@return static | [
"Sets",
"a",
"LIMIT",
"clause",
"optionally",
"a",
"offset",
"clause"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Query.php#L175-L181 | train |
milejko/mmi-cms | src/CmsAdmin/Grid/GridRequestHandler.php | GridRequestHandler._retrievePostFilter | protected function _retrievePostFilter(\Mmi\Http\RequestPost $post)
{
//brak filtracji dla tego grida
if (false === strpos($post->filter, $this->_grid->getClass())) {
return;
}
$columnName = substr($post->filter, strpos($post->filter, '[') + 1, -1);
$tableName = null;
$fieldName = $columnName;
//obsługa joinowanych
if (strpos($columnName, '.')) {
$fieldTable = explode('.', $columnName);
$tableName = $fieldTable[0];
$fieldName = $fieldTable[1];
}
//paginator
if ($fieldName == '_paginator_') {
//ustawianie filtra
return (new GridStateFilter())
->setField($fieldName)
->setValue($post->value);
}
//iteracja po kolumnach
foreach ($this->_grid->getColumns() as $column) {
if ($column->getName() != $columnName) {
continue;
}
//ustawianie filtra
return (new GridStateFilter())
->setField($fieldName)
->setTableName($tableName)
->setMethod($column->getMethod())
->setValue($post->value);
}
} | php | protected function _retrievePostFilter(\Mmi\Http\RequestPost $post)
{
//brak filtracji dla tego grida
if (false === strpos($post->filter, $this->_grid->getClass())) {
return;
}
$columnName = substr($post->filter, strpos($post->filter, '[') + 1, -1);
$tableName = null;
$fieldName = $columnName;
//obsługa joinowanych
if (strpos($columnName, '.')) {
$fieldTable = explode('.', $columnName);
$tableName = $fieldTable[0];
$fieldName = $fieldTable[1];
}
//paginator
if ($fieldName == '_paginator_') {
//ustawianie filtra
return (new GridStateFilter())
->setField($fieldName)
->setValue($post->value);
}
//iteracja po kolumnach
foreach ($this->_grid->getColumns() as $column) {
if ($column->getName() != $columnName) {
continue;
}
//ustawianie filtra
return (new GridStateFilter())
->setField($fieldName)
->setTableName($tableName)
->setMethod($column->getMethod())
->setValue($post->value);
}
} | [
"protected",
"function",
"_retrievePostFilter",
"(",
"\\",
"Mmi",
"\\",
"Http",
"\\",
"RequestPost",
"$",
"post",
")",
"{",
"//brak filtracji dla tego grida",
"if",
"(",
"false",
"===",
"strpos",
"(",
"$",
"post",
"->",
"filter",
",",
"$",
"this",
"->",
"_gr... | Zwraca obiekt filtra na podstawie post
@param \Mmi\Http\RequestPost $post
@return GridStateFilter | [
"Zwraca",
"obiekt",
"filtra",
"na",
"podstawie",
"post"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/CmsAdmin/Grid/GridRequestHandler.php#L81-L115 | train |
vtalbot/repository-generator | src/RepositoryCreator.php | RepositoryCreator.create | public function create(
ReflectionClass $modelReflection,
$classFileName,
$shortClassName,
$classNamespace,
$contractFileName,
$shortContractName,
$contractNamespace,
array $methods
) {
$createdFiles = [$this->createRepository(
$modelReflection,
$classFileName,
$shortClassName,
$classNamespace,
$shortContractName,
$contractNamespace,
$methods
)];
if ($shortContractName) {
$createdFiles[] = $this->createContract(
$modelReflection,
$contractFileName,
$shortContractName,
$contractNamespace,
$methods
);
}
return $createdFiles;
} | php | public function create(
ReflectionClass $modelReflection,
$classFileName,
$shortClassName,
$classNamespace,
$contractFileName,
$shortContractName,
$contractNamespace,
array $methods
) {
$createdFiles = [$this->createRepository(
$modelReflection,
$classFileName,
$shortClassName,
$classNamespace,
$shortContractName,
$contractNamespace,
$methods
)];
if ($shortContractName) {
$createdFiles[] = $this->createContract(
$modelReflection,
$contractFileName,
$shortContractName,
$contractNamespace,
$methods
);
}
return $createdFiles;
} | [
"public",
"function",
"create",
"(",
"ReflectionClass",
"$",
"modelReflection",
",",
"$",
"classFileName",
",",
"$",
"shortClassName",
",",
"$",
"classNamespace",
",",
"$",
"contractFileName",
",",
"$",
"shortContractName",
",",
"$",
"contractNamespace",
",",
"arr... | Create the repository and contract.
@param ReflectionClass $modelReflection
@param string $classFileName
@param string $shortClassName
@param string $classNamespace
@param string $contractFileName
@param string|bool $shortContractName
@param string|bool $contractNamespace
@param array $methods
@return array | [
"Create",
"the",
"repository",
"and",
"contract",
"."
] | e74924552bd322c3b6f93087a049896d960843e3 | https://github.com/vtalbot/repository-generator/blob/e74924552bd322c3b6f93087a049896d960843e3/src/RepositoryCreator.php#L48-L79 | train |
vtalbot/repository-generator | src/RepositoryCreator.php | RepositoryCreator.createRepository | protected function createRepository(
ReflectionClass $model,
$fileName,
$shortName,
$namespace,
$contractName,
$contractNamespace,
array $methods
) {
$path = app_path($fileName);
$stub = $this->compileStub('repository.stub', [
'namespace' => $namespace,
'class' => $shortName,
'model.fullname' => $model->getName(),
'model' => $model->getShortName(),
'implementation' => $this->getImplementationClass($contractName),
'implementation.use' => $this->getImplementationUse($contractNamespace, $contractName),
]);
$stub = $this->compileMethods($stub, $methods);
$this->files->makeDirectory(dirname($path), 0755, true, true);
$this->files->put($path, $stub);
return $namespace . '\\' . $shortName;
} | php | protected function createRepository(
ReflectionClass $model,
$fileName,
$shortName,
$namespace,
$contractName,
$contractNamespace,
array $methods
) {
$path = app_path($fileName);
$stub = $this->compileStub('repository.stub', [
'namespace' => $namespace,
'class' => $shortName,
'model.fullname' => $model->getName(),
'model' => $model->getShortName(),
'implementation' => $this->getImplementationClass($contractName),
'implementation.use' => $this->getImplementationUse($contractNamespace, $contractName),
]);
$stub = $this->compileMethods($stub, $methods);
$this->files->makeDirectory(dirname($path), 0755, true, true);
$this->files->put($path, $stub);
return $namespace . '\\' . $shortName;
} | [
"protected",
"function",
"createRepository",
"(",
"ReflectionClass",
"$",
"model",
",",
"$",
"fileName",
",",
"$",
"shortName",
",",
"$",
"namespace",
",",
"$",
"contractName",
",",
"$",
"contractNamespace",
",",
"array",
"$",
"methods",
")",
"{",
"$",
"path... | Create the repository.
@param ReflectionClass $model
@param string $fileName
@param string $shortName
@param string $namespace
@param string|bool $contractName
@param string|bool $contractNamespace
@param array $methods
@return string | [
"Create",
"the",
"repository",
"."
] | e74924552bd322c3b6f93087a049896d960843e3 | https://github.com/vtalbot/repository-generator/blob/e74924552bd322c3b6f93087a049896d960843e3/src/RepositoryCreator.php#L104-L131 | train |
vtalbot/repository-generator | src/RepositoryCreator.php | RepositoryCreator.createContract | protected function createContract(ReflectionClass $model, $fileName, $shortName, $namespace, array $methods)
{
$path = app_path($fileName);
$stub = $this->compileStub('contract.stub', [
'namespace' => $namespace,
'class' => $shortName,
'model.fullname' => $model->getName(),
'model' => $model->getShortName(),
]);
$stub = $this->compileMethods($stub, $methods);
$this->files->makeDirectory(dirname($path), 0755, true, true);
$this->files->put($path, $stub);
return $namespace . '\\' . $shortName;
} | php | protected function createContract(ReflectionClass $model, $fileName, $shortName, $namespace, array $methods)
{
$path = app_path($fileName);
$stub = $this->compileStub('contract.stub', [
'namespace' => $namespace,
'class' => $shortName,
'model.fullname' => $model->getName(),
'model' => $model->getShortName(),
]);
$stub = $this->compileMethods($stub, $methods);
$this->files->makeDirectory(dirname($path), 0755, true, true);
$this->files->put($path, $stub);
return $namespace . '\\' . $shortName;
} | [
"protected",
"function",
"createContract",
"(",
"ReflectionClass",
"$",
"model",
",",
"$",
"fileName",
",",
"$",
"shortName",
",",
"$",
"namespace",
",",
"array",
"$",
"methods",
")",
"{",
"$",
"path",
"=",
"app_path",
"(",
"$",
"fileName",
")",
";",
"$"... | Create the contract for the repository.
@param ReflectionClass $model
@param string $fileName
@param string $shortName
@param string $namespace
@param array $methods
@return string | [
"Create",
"the",
"contract",
"for",
"the",
"repository",
"."
] | e74924552bd322c3b6f93087a049896d960843e3 | https://github.com/vtalbot/repository-generator/blob/e74924552bd322c3b6f93087a049896d960843e3/src/RepositoryCreator.php#L143-L161 | train |
vtalbot/repository-generator | src/RepositoryCreator.php | RepositoryCreator.compileMethods | protected function compileMethods($stub, array $methods)
{
foreach ($methods as $method) {
$stub = str_replace(['{{' . $method . '}}', '{{/' . $method . '}}'], '', $stub);
}
foreach ($this->methods as $method) {
$stub = preg_replace('/{{' . $method . '}}(.*){{\/' . $method . '}}(\r\n)?/s', '', $stub);
}
return $stub;
} | php | protected function compileMethods($stub, array $methods)
{
foreach ($methods as $method) {
$stub = str_replace(['{{' . $method . '}}', '{{/' . $method . '}}'], '', $stub);
}
foreach ($this->methods as $method) {
$stub = preg_replace('/{{' . $method . '}}(.*){{\/' . $method . '}}(\r\n)?/s', '', $stub);
}
return $stub;
} | [
"protected",
"function",
"compileMethods",
"(",
"$",
"stub",
",",
"array",
"$",
"methods",
")",
"{",
"foreach",
"(",
"$",
"methods",
"as",
"$",
"method",
")",
"{",
"$",
"stub",
"=",
"str_replace",
"(",
"[",
"'{{'",
".",
"$",
"method",
".",
"'}}'",
",... | Compile the stub with the given methods to keep.
@param string $stub
@param array $methods
@return string | [
"Compile",
"the",
"stub",
"with",
"the",
"given",
"methods",
"to",
"keep",
"."
] | e74924552bd322c3b6f93087a049896d960843e3 | https://github.com/vtalbot/repository-generator/blob/e74924552bd322c3b6f93087a049896d960843e3/src/RepositoryCreator.php#L170-L181 | train |
vtalbot/repository-generator | src/RepositoryCreator.php | RepositoryCreator.compileStub | protected function compileStub($stub, array $data)
{
$stub = $this->files->get(__DIR__ . '/../stub/' . $stub);
foreach ($data as $key => $value) {
$stub = str_replace('{{' . $key . '}}', $value, $stub);
}
return $stub;
} | php | protected function compileStub($stub, array $data)
{
$stub = $this->files->get(__DIR__ . '/../stub/' . $stub);
foreach ($data as $key => $value) {
$stub = str_replace('{{' . $key . '}}', $value, $stub);
}
return $stub;
} | [
"protected",
"function",
"compileStub",
"(",
"$",
"stub",
",",
"array",
"$",
"data",
")",
"{",
"$",
"stub",
"=",
"$",
"this",
"->",
"files",
"->",
"get",
"(",
"__DIR__",
".",
"'/../stub/'",
".",
"$",
"stub",
")",
";",
"foreach",
"(",
"$",
"data",
"... | Compile the stub with the given data.
@param string $stub
@param array $data
@return string
@throws \Illuminate\Contracts\Filesystem\FileNotFoundException | [
"Compile",
"the",
"stub",
"with",
"the",
"given",
"data",
"."
] | e74924552bd322c3b6f93087a049896d960843e3 | https://github.com/vtalbot/repository-generator/blob/e74924552bd322c3b6f93087a049896d960843e3/src/RepositoryCreator.php#L191-L200 | train |
jbouzekri/ConfigKnpMenuBundle | Config/Definition/Builder/MenuNodeDefinition.php | MenuNodeDefinition.menuNodeHierarchy | public function menuNodeHierarchy($depth = 10)
{
if ($depth == 0) {
return $this;
}
return $this
->prototype('array')
->children()
->scalarNode('route')->end()
->arrayNode('routeParameters')
->prototype('variable')
->end()
->end()
->scalarNode('uri')->end()
->scalarNode('label')->end()
->booleanNode('display')->defaultTrue()->end()
->booleanNode('displayChildren')->defaultTrue()->end()
->integerNode('order')->end()
->arrayNode('attributes')
->prototype('variable')
->end()
->end()
->arrayNode('linkAttributes')
->prototype('variable')
->end()
->end()
->arrayNode('childrenAttributes')
->prototype('variable')
->end()
->end()
->arrayNode('labelAttributes')
->prototype('variable')
->end()
->end()
->arrayNode('roles')
->prototype('scalar')
->end()
->end()
->arrayNode('extras')
->prototype('scalar')
->end()
->end()
->menuNode('children')->menuNodeHierarchy($depth - 1)
->end()
->end();
} | php | public function menuNodeHierarchy($depth = 10)
{
if ($depth == 0) {
return $this;
}
return $this
->prototype('array')
->children()
->scalarNode('route')->end()
->arrayNode('routeParameters')
->prototype('variable')
->end()
->end()
->scalarNode('uri')->end()
->scalarNode('label')->end()
->booleanNode('display')->defaultTrue()->end()
->booleanNode('displayChildren')->defaultTrue()->end()
->integerNode('order')->end()
->arrayNode('attributes')
->prototype('variable')
->end()
->end()
->arrayNode('linkAttributes')
->prototype('variable')
->end()
->end()
->arrayNode('childrenAttributes')
->prototype('variable')
->end()
->end()
->arrayNode('labelAttributes')
->prototype('variable')
->end()
->end()
->arrayNode('roles')
->prototype('scalar')
->end()
->end()
->arrayNode('extras')
->prototype('scalar')
->end()
->end()
->menuNode('children')->menuNodeHierarchy($depth - 1)
->end()
->end();
} | [
"public",
"function",
"menuNodeHierarchy",
"(",
"$",
"depth",
"=",
"10",
")",
"{",
"if",
"(",
"$",
"depth",
"==",
"0",
")",
"{",
"return",
"$",
"this",
";",
"}",
"return",
"$",
"this",
"->",
"prototype",
"(",
"'array'",
")",
"->",
"children",
"(",
... | Make menu hierarchy
@param int $depth
@return MenuNodeDefinition | [
"Make",
"menu",
"hierarchy"
] | d5a6154de04f3f7342f68496cad02a1b4a3846b9 | https://github.com/jbouzekri/ConfigKnpMenuBundle/blob/d5a6154de04f3f7342f68496cad02a1b4a3846b9/Config/Definition/Builder/MenuNodeDefinition.php#L30-L76 | train |
milejko/mmi-cms | src/CmsAdmin/AclController.php | AclController.deleteRoleAction | public function deleteRoleAction()
{
//wyszukiwanie i usuwanie roli
if ((null !== $role = (new \Cms\Orm\CmsRoleQuery)->findPk($this->id))) {
$this->getMessenger()->addMessage(($deleteResult = (bool) $role->delete()) ? 'messenger.acl.role.deleted' : 'messenger.acl.role.delete.error', $deleteResult);
}
//redirect
$this->getResponse()->redirect('cmsAdmin', 'acl', 'index', ['roleId' => $this->id]);
} | php | public function deleteRoleAction()
{
//wyszukiwanie i usuwanie roli
if ((null !== $role = (new \Cms\Orm\CmsRoleQuery)->findPk($this->id))) {
$this->getMessenger()->addMessage(($deleteResult = (bool) $role->delete()) ? 'messenger.acl.role.deleted' : 'messenger.acl.role.delete.error', $deleteResult);
}
//redirect
$this->getResponse()->redirect('cmsAdmin', 'acl', 'index', ['roleId' => $this->id]);
} | [
"public",
"function",
"deleteRoleAction",
"(",
")",
"{",
"//wyszukiwanie i usuwanie roli",
"if",
"(",
"(",
"null",
"!==",
"$",
"role",
"=",
"(",
"new",
"\\",
"Cms",
"\\",
"Orm",
"\\",
"CmsRoleQuery",
")",
"->",
"findPk",
"(",
"$",
"this",
"->",
"id",
")"... | Akcja usuwania roli | [
"Akcja",
"usuwania",
"roli"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/CmsAdmin/AclController.php#L49-L57 | train |
milejko/mmi-cms | src/CmsAdmin/UploadController.php | UploadController.pluploadAction | public function pluploadAction()
{
set_time_limit(5 * 60);
//obiekt handlera plupload
$pluploadHandler = new Model\PluploadHandler();
//jeśli wystąpił błąd
if (!$pluploadHandler->handle()) {
return $this->_jsonError($pluploadHandler->getErrorCode(), $pluploadHandler->getErrorMessage());
}
//jeśli wykonać operację po przesłaniu całego pliku i zapisaniu rekordu
if ($this->getPost()->afterUpload && null !== $record = $pluploadHandler->getSavedCmsFileRecord()) {
$this->_operationAfter($this->getPost()->afterUpload, $record);
}
return json_encode(['result' => 'OK', 'cmsFileId' => $pluploadHandler->getSavedCmsFileId()]);
} | php | public function pluploadAction()
{
set_time_limit(5 * 60);
//obiekt handlera plupload
$pluploadHandler = new Model\PluploadHandler();
//jeśli wystąpił błąd
if (!$pluploadHandler->handle()) {
return $this->_jsonError($pluploadHandler->getErrorCode(), $pluploadHandler->getErrorMessage());
}
//jeśli wykonać operację po przesłaniu całego pliku i zapisaniu rekordu
if ($this->getPost()->afterUpload && null !== $record = $pluploadHandler->getSavedCmsFileRecord()) {
$this->_operationAfter($this->getPost()->afterUpload, $record);
}
return json_encode(['result' => 'OK', 'cmsFileId' => $pluploadHandler->getSavedCmsFileId()]);
} | [
"public",
"function",
"pluploadAction",
"(",
")",
"{",
"set_time_limit",
"(",
"5",
"*",
"60",
")",
";",
"//obiekt handlera plupload",
"$",
"pluploadHandler",
"=",
"new",
"Model",
"\\",
"PluploadHandler",
"(",
")",
";",
"//jeśli wystąpił błąd",
"if",
"(",
"!",
... | Odbieranie danych z plugina Plupload | [
"Odbieranie",
"danych",
"z",
"plugina",
"Plupload"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/CmsAdmin/UploadController.php#L34-L48 | train |
milejko/mmi-cms | src/CmsAdmin/UploadController.php | UploadController.deleteAction | public function deleteAction()
{
//szukamy rekordu pliku
if (!$this->getPost()->cmsFileId || null === $record = (new CmsFileQuery)->findPk($this->getPost()->cmsFileId)) {
return $this->_jsonError(178);
}
//sprawdzenie zgodności z obiektem formularza
if ($record->object === $this->getPost()->object && $record->objectId == $this->getPost()->objectId) {
//usuwanie
if ($record->delete()) {
//jeśli wykonać operację po usunięciu
if ($this->getPost()->afterDelete) {
$this->_operationAfter($this->getPost()->afterDelete, $record);
}
return json_encode(['result' => 'OK']);
}
}
return $this->_jsonError(178);
} | php | public function deleteAction()
{
//szukamy rekordu pliku
if (!$this->getPost()->cmsFileId || null === $record = (new CmsFileQuery)->findPk($this->getPost()->cmsFileId)) {
return $this->_jsonError(178);
}
//sprawdzenie zgodności z obiektem formularza
if ($record->object === $this->getPost()->object && $record->objectId == $this->getPost()->objectId) {
//usuwanie
if ($record->delete()) {
//jeśli wykonać operację po usunięciu
if ($this->getPost()->afterDelete) {
$this->_operationAfter($this->getPost()->afterDelete, $record);
}
return json_encode(['result' => 'OK']);
}
}
return $this->_jsonError(178);
} | [
"public",
"function",
"deleteAction",
"(",
")",
"{",
"//szukamy rekordu pliku",
"if",
"(",
"!",
"$",
"this",
"->",
"getPost",
"(",
")",
"->",
"cmsFileId",
"||",
"null",
"===",
"$",
"record",
"=",
"(",
"new",
"CmsFileQuery",
")",
"->",
"findPk",
"(",
"$",... | Usuwa wybrany rekord pliku | [
"Usuwa",
"wybrany",
"rekord",
"pliku"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/CmsAdmin/UploadController.php#L85-L103 | train |
milejko/mmi-cms | src/CmsAdmin/UploadController.php | UploadController.downloadAction | public function downloadAction()
{
if (null === $file = (new CmsFileQuery)->byObject($this->object, $this->objectId)
->findPk($this->id)) {
return '';
}
$this->getResponse()->redirectToUrl($file->getUrl());
} | php | public function downloadAction()
{
if (null === $file = (new CmsFileQuery)->byObject($this->object, $this->objectId)
->findPk($this->id)) {
return '';
}
$this->getResponse()->redirectToUrl($file->getUrl());
} | [
"public",
"function",
"downloadAction",
"(",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"file",
"=",
"(",
"new",
"CmsFileQuery",
")",
"->",
"byObject",
"(",
"$",
"this",
"->",
"object",
",",
"$",
"this",
"->",
"objectId",
")",
"->",
"findPk",
"(",
"$",... | Przekierowanie na plik
@return string | [
"Przekierowanie",
"na",
"plik"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/CmsAdmin/UploadController.php#L232-L239 | train |
milejko/mmi-cms | src/CmsAdmin/UploadController.php | UploadController._savePoster | protected function _savePoster($blob, \Cms\Orm\CmsFileRecord $file)
{
//brak danych
if (!\preg_match('/^data:(image\/[a-z]+);base64,(.*)/i', $blob, $match)) {
return;
}
//nazwa postera
$posterFileName = substr($file->name, 0, strpos($file->name, '.')) . '-' . $file->id . '.' . \Mmi\Http\ResponseTypes::getExtensionByType($match[1]);
//próba utworzenia katalogu
try {
//tworzenie katalogu
mkdir(dirname($file->getRealPath()), 0777, true);
} catch (\Exception $e) {
//nic
}
//zapis
file_put_contents(str_replace($file->name, $posterFileName, $file->getRealPath()), base64_decode($match[2]));
//zapis do rekordu
$file->data->posterFileName = $posterFileName;
return $posterFileName;
} | php | protected function _savePoster($blob, \Cms\Orm\CmsFileRecord $file)
{
//brak danych
if (!\preg_match('/^data:(image\/[a-z]+);base64,(.*)/i', $blob, $match)) {
return;
}
//nazwa postera
$posterFileName = substr($file->name, 0, strpos($file->name, '.')) . '-' . $file->id . '.' . \Mmi\Http\ResponseTypes::getExtensionByType($match[1]);
//próba utworzenia katalogu
try {
//tworzenie katalogu
mkdir(dirname($file->getRealPath()), 0777, true);
} catch (\Exception $e) {
//nic
}
//zapis
file_put_contents(str_replace($file->name, $posterFileName, $file->getRealPath()), base64_decode($match[2]));
//zapis do rekordu
$file->data->posterFileName = $posterFileName;
return $posterFileName;
} | [
"protected",
"function",
"_savePoster",
"(",
"$",
"blob",
",",
"\\",
"Cms",
"\\",
"Orm",
"\\",
"CmsFileRecord",
"$",
"file",
")",
"{",
"//brak danych",
"if",
"(",
"!",
"\\",
"preg_match",
"(",
"'/^data:(image\\/[a-z]+);base64,(.*)/i'",
",",
"$",
"blob",
",",
... | Zapisanie postera dla video
@param string $blob
@param \Cms\Orm\CmsFileRecord $file
@return string | [
"Zapisanie",
"postera",
"dla",
"video"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/CmsAdmin/UploadController.php#L292-L312 | train |
fezfez/codeGenerator | src/CrudGenerator/Generators/Finder/GeneratorFinderCache.php | GeneratorFinderCache.getAllClasses | public function getAllClasses(MetaDataInterface $metadata = null)
{
$cacheFilename = $this->directories['Cache'] . DIRECTORY_SEPARATOR;
$cacheFilename .= md5('genrator_getAllClasses' . ($metadata !== null) ? get_class($metadata) : '');
if ($this->fileManager->isFile($cacheFilename) === true && $this->noCache === false) {
$data = unserialize($this->fileManager->fileGetContent($cacheFilename));
} else {
$data = $this->generatorFinder->getAllClasses($metadata);
$this->fileManager->filePutsContent($cacheFilename, serialize($data));
}
return $data;
} | php | public function getAllClasses(MetaDataInterface $metadata = null)
{
$cacheFilename = $this->directories['Cache'] . DIRECTORY_SEPARATOR;
$cacheFilename .= md5('genrator_getAllClasses' . ($metadata !== null) ? get_class($metadata) : '');
if ($this->fileManager->isFile($cacheFilename) === true && $this->noCache === false) {
$data = unserialize($this->fileManager->fileGetContent($cacheFilename));
} else {
$data = $this->generatorFinder->getAllClasses($metadata);
$this->fileManager->filePutsContent($cacheFilename, serialize($data));
}
return $data;
} | [
"public",
"function",
"getAllClasses",
"(",
"MetaDataInterface",
"$",
"metadata",
"=",
"null",
")",
"{",
"$",
"cacheFilename",
"=",
"$",
"this",
"->",
"directories",
"[",
"'Cache'",
"]",
".",
"DIRECTORY_SEPARATOR",
";",
"$",
"cacheFilename",
".=",
"md5",
"(",
... | Find all adapters allow in project
@return array | [
"Find",
"all",
"adapters",
"allow",
"in",
"project"
] | 559f22bcc525c3157ecb17fe96818dd7b7ee58c2 | https://github.com/fezfez/codeGenerator/blob/559f22bcc525c3157ecb17fe96818dd7b7ee58c2/src/CrudGenerator/Generators/Finder/GeneratorFinderCache.php#L63-L76 | train |
manaphp/framework | Event/Manager.php | Manager.fireEvent | public function fireEvent($event, $source, $data = [])
{
if ($this->_listeners) {
list($p1, $p2) = explode(':', $event, 2);
if (isset($this->_listeners[$p1])) {
foreach ($this->_listeners[$p1] as $k => $v) {
/**@var \ManaPHP\Event\Listener $listener */
if (is_int($v)) {
$this->_listeners[$p1][$k] = $listener = $this->_di->getShared($k);
} else {
$listener = $v;
}
$listener->process($p2, $source, $data);
}
}
}
foreach ($this->_peekers as $handler) {
if ($handler instanceof \Closure) {
$handler($event, $source, $data);
} else {
$handler[0]->{$handler[1]}($event, $source, $data);
}
}
if (!isset($this->_events[$event])) {
return;
}
foreach ($this->_events[$event] as $handler) {
if ($handler instanceof \Closure) {
$handler($source, $data, $event);
} else {
$handler[0]->{$handler[1]}($source, $data, $event);
}
}
} | php | public function fireEvent($event, $source, $data = [])
{
if ($this->_listeners) {
list($p1, $p2) = explode(':', $event, 2);
if (isset($this->_listeners[$p1])) {
foreach ($this->_listeners[$p1] as $k => $v) {
/**@var \ManaPHP\Event\Listener $listener */
if (is_int($v)) {
$this->_listeners[$p1][$k] = $listener = $this->_di->getShared($k);
} else {
$listener = $v;
}
$listener->process($p2, $source, $data);
}
}
}
foreach ($this->_peekers as $handler) {
if ($handler instanceof \Closure) {
$handler($event, $source, $data);
} else {
$handler[0]->{$handler[1]}($event, $source, $data);
}
}
if (!isset($this->_events[$event])) {
return;
}
foreach ($this->_events[$event] as $handler) {
if ($handler instanceof \Closure) {
$handler($source, $data, $event);
} else {
$handler[0]->{$handler[1]}($source, $data, $event);
}
}
} | [
"public",
"function",
"fireEvent",
"(",
"$",
"event",
",",
"$",
"source",
",",
"$",
"data",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_listeners",
")",
"{",
"list",
"(",
"$",
"p1",
",",
"$",
"p2",
")",
"=",
"explode",
"(",
"':'",
... | Fires an event in the events manager causing that active listeners be notified about it
@param string $event
@param mixed $source
@param array $data
@return void | [
"Fires",
"an",
"event",
"in",
"the",
"events",
"manager",
"causing",
"that",
"active",
"listeners",
"be",
"notified",
"about",
"it"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Event/Manager.php#L77-L114 | train |
mapbender/fom | src/FOM/UserBundle/Form/Type/ACLType.php | ACLType.getStandardPermissions | protected function getStandardPermissions(array $options, $master, $owner)
{
switch ($options['permissions']) {
case 'standard::object':
$disable = array ();
// if not owner or master, disable all permissions
if (!$master && !$owner) {
$disable = array (1, 3, 4, 6, 7, 8);
}
// if not master, disable
// 5 -> undelete is not used
return array (
'show' => array (
1 => 'View',
3 => 'Edit',
4 => 'Delete',
6 => 'Operator',
7 => 'Master',
8 => 'Owner'
),
'disable' => $disable);
break;
case 'standard::class':
return array (
'show' => array (
1 => 'View',
2 => 'Create',
3 => 'Edit',
4 => 'Delete',
6 => 'Operator',
7 => 'Master',
8 => 'Owner'
));
break;
default:
throw new \RuntimeException('"' . $options['permissions'] .
'" is not a valid standard permission set identifier');
}
} | php | protected function getStandardPermissions(array $options, $master, $owner)
{
switch ($options['permissions']) {
case 'standard::object':
$disable = array ();
// if not owner or master, disable all permissions
if (!$master && !$owner) {
$disable = array (1, 3, 4, 6, 7, 8);
}
// if not master, disable
// 5 -> undelete is not used
return array (
'show' => array (
1 => 'View',
3 => 'Edit',
4 => 'Delete',
6 => 'Operator',
7 => 'Master',
8 => 'Owner'
),
'disable' => $disable);
break;
case 'standard::class':
return array (
'show' => array (
1 => 'View',
2 => 'Create',
3 => 'Edit',
4 => 'Delete',
6 => 'Operator',
7 => 'Master',
8 => 'Owner'
));
break;
default:
throw new \RuntimeException('"' . $options['permissions'] .
'" is not a valid standard permission set identifier');
}
} | [
"protected",
"function",
"getStandardPermissions",
"(",
"array",
"$",
"options",
",",
"$",
"master",
",",
"$",
"owner",
")",
"{",
"switch",
"(",
"$",
"options",
"[",
"'permissions'",
"]",
")",
"{",
"case",
"'standard::object'",
":",
"$",
"disable",
"=",
"a... | Get standard permission sets for provided string identifier.
Returns an array with an array of permissions to show (['show']) and an
array with permissions which should be disabled (that means, still shown,
but uneditable) (['disable']).
@param array $options Form options
@param [type] $master is master permission assumed?
@param [type] $owner is owner permission assumed?
@return [type] Array with permissions to show and disable | [
"Get",
"standard",
"permission",
"sets",
"for",
"provided",
"string",
"identifier",
"."
] | 6dea943121f3c3f9b1b4b14dc2a8e8640a120675 | https://github.com/mapbender/fom/blob/6dea943121f3c3f9b1b4b14dc2a8e8640a120675/src/FOM/UserBundle/Form/Type/ACLType.php#L170-L208 | train |
manaphp/framework | Cli/Controllers/PharController.php | PharController.manacliCommand | public function manacliCommand()
{
$this->alias->set('@phar', '@data/manacli_phar');
$pharFile = $this->alias->resolve('@root/manacli.phar');
$this->console->writeLn(['cleaning `:dir` dir', 'dir' => $this->alias->resolve('@phar')]);
$this->filesystem->dirReCreate('@phar');
$this->console->writeLn('copying manaphp framework files.');
$this->filesystem->dirCopy('@root/ManaPHP', '@phar/ManaPHP');
//$di->filesystem->dirCopy('@root/Application', '@phar/Application');
$this->filesystem->fileCopy('@root/manacli.php', '@phar/manacli.php');
$phar = new \Phar($pharFile, \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::KEY_AS_FILENAME, basename($pharFile));
$phar->buildFromDirectory($this->alias->resolve('@phar'));
$phar->setStub($phar::createDefaultStub('manacli.php'));
$this->console->writeLn('compressing files');
$phar->compressFiles(\Phar::BZ2);
$this->console->writeLn(['`:phar` created successfully', 'phar' => $this->alias->resolve($pharFile)]);
} | php | public function manacliCommand()
{
$this->alias->set('@phar', '@data/manacli_phar');
$pharFile = $this->alias->resolve('@root/manacli.phar');
$this->console->writeLn(['cleaning `:dir` dir', 'dir' => $this->alias->resolve('@phar')]);
$this->filesystem->dirReCreate('@phar');
$this->console->writeLn('copying manaphp framework files.');
$this->filesystem->dirCopy('@root/ManaPHP', '@phar/ManaPHP');
//$di->filesystem->dirCopy('@root/Application', '@phar/Application');
$this->filesystem->fileCopy('@root/manacli.php', '@phar/manacli.php');
$phar = new \Phar($pharFile, \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::KEY_AS_FILENAME, basename($pharFile));
$phar->buildFromDirectory($this->alias->resolve('@phar'));
$phar->setStub($phar::createDefaultStub('manacli.php'));
$this->console->writeLn('compressing files');
$phar->compressFiles(\Phar::BZ2);
$this->console->writeLn(['`:phar` created successfully', 'phar' => $this->alias->resolve($pharFile)]);
} | [
"public",
"function",
"manacliCommand",
"(",
")",
"{",
"$",
"this",
"->",
"alias",
"->",
"set",
"(",
"'@phar'",
",",
"'@data/manacli_phar'",
")",
";",
"$",
"pharFile",
"=",
"$",
"this",
"->",
"alias",
"->",
"resolve",
"(",
"'@root/manacli.phar'",
")",
";",... | create manacli.phar file | [
"create",
"manacli",
".",
"phar",
"file"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Cli/Controllers/PharController.php#L11-L31 | train |
fezfez/codeGenerator | src/CrudGenerator/FileConflict/FileConflictManager.php | FileConflictManager.handle | public function handle($filePath, $results)
{
$responseCollection = new PredefinedResponseCollection();
$responseCollection->append(
new PredefinedResponse('postpone', 'postpone', self::POSTPONE)
);
$responseCollection->append(
new PredefinedResponse('show diff', 'show diff', self::SHOW_DIFF)
);
$responseCollection->append(
new PredefinedResponse('erase', 'erase', self::ERASE)
);
$responseCollection->append(
new PredefinedResponse('cancel', 'cancel', self::CANCEL)
);
$question = new QuestionWithPredefinedResponse(
sprintf('File "%s" already exist, erase it with the new', $filePath),
'conflict' . $filePath,
$responseCollection
);
$question->setShutdownWithoutResponse(true, sprintf('Conflict with file "%s" not resolved', $filePath));
while (($response = $this->context->askCollection($question)) !== null) {
$response = intval($response);
if ($response === self::SHOW_DIFF) {
// write to output the diff
$this->context->log(
'<info>' . $this->diffPHP->diff($results, $this->fileManager->fileGetContent($filePath)) . '</info>'
);
} else {
break;
}
}
if ($response === self::POSTPONE) {
//Generate the diff file
$this->fileManager->filePutsContent(
$filePath . '.diff',
$this->diffPHP->diff(
$results,
$this->fileManager->fileGetContent($filePath)
)
);
$this->context->log('--> Generate diff and new file ' . $filePath . '.diff', 'generationLog');
} elseif ($response === self::ERASE) {
$this->fileManager->filePutsContent($filePath, $results);
$this->context->log('--> Replace file ' . $filePath, 'generationLog');
}
} | php | public function handle($filePath, $results)
{
$responseCollection = new PredefinedResponseCollection();
$responseCollection->append(
new PredefinedResponse('postpone', 'postpone', self::POSTPONE)
);
$responseCollection->append(
new PredefinedResponse('show diff', 'show diff', self::SHOW_DIFF)
);
$responseCollection->append(
new PredefinedResponse('erase', 'erase', self::ERASE)
);
$responseCollection->append(
new PredefinedResponse('cancel', 'cancel', self::CANCEL)
);
$question = new QuestionWithPredefinedResponse(
sprintf('File "%s" already exist, erase it with the new', $filePath),
'conflict' . $filePath,
$responseCollection
);
$question->setShutdownWithoutResponse(true, sprintf('Conflict with file "%s" not resolved', $filePath));
while (($response = $this->context->askCollection($question)) !== null) {
$response = intval($response);
if ($response === self::SHOW_DIFF) {
// write to output the diff
$this->context->log(
'<info>' . $this->diffPHP->diff($results, $this->fileManager->fileGetContent($filePath)) . '</info>'
);
} else {
break;
}
}
if ($response === self::POSTPONE) {
//Generate the diff file
$this->fileManager->filePutsContent(
$filePath . '.diff',
$this->diffPHP->diff(
$results,
$this->fileManager->fileGetContent($filePath)
)
);
$this->context->log('--> Generate diff and new file ' . $filePath . '.diff', 'generationLog');
} elseif ($response === self::ERASE) {
$this->fileManager->filePutsContent($filePath, $results);
$this->context->log('--> Replace file ' . $filePath, 'generationLog');
}
} | [
"public",
"function",
"handle",
"(",
"$",
"filePath",
",",
"$",
"results",
")",
"{",
"$",
"responseCollection",
"=",
"new",
"PredefinedResponseCollection",
"(",
")",
";",
"$",
"responseCollection",
"->",
"append",
"(",
"new",
"PredefinedResponse",
"(",
"'postpon... | Handle the file conflict
@param string $filePath
@param string $results
@throws ResponseExpectedException | [
"Handle",
"the",
"file",
"conflict"
] | 559f22bcc525c3157ecb17fe96818dd7b7ee58c2 | https://github.com/fezfez/codeGenerator/blob/559f22bcc525c3157ecb17fe96818dd7b7ee58c2/src/CrudGenerator/FileConflict/FileConflictManager.php#L85-L136 | train |
fezfez/codeGenerator | src/CrudGenerator/Generators/Parser/GeneratorParser.php | GeneratorParser.analyzeDependencies | private function analyzeDependencies(array $process, PhpStringParser $phpParser, GeneratorDataObject $generator)
{
$generator = clone $generator;
if (isset($process['dependencies']) === true && is_array($process['dependencies']) === true) {
foreach ($process['dependencies'] as $dependencieName) {
$generator->addDependency(
$this->analyze($dependencieName, $phpParser, $generator, $generator->getDto()->getMetadata())
);
}
$generator = $this->addDependenciesVariablesToMainGenerator($generator);
}
return $generator;
} | php | private function analyzeDependencies(array $process, PhpStringParser $phpParser, GeneratorDataObject $generator)
{
$generator = clone $generator;
if (isset($process['dependencies']) === true && is_array($process['dependencies']) === true) {
foreach ($process['dependencies'] as $dependencieName) {
$generator->addDependency(
$this->analyze($dependencieName, $phpParser, $generator, $generator->getDto()->getMetadata())
);
}
$generator = $this->addDependenciesVariablesToMainGenerator($generator);
}
return $generator;
} | [
"private",
"function",
"analyzeDependencies",
"(",
"array",
"$",
"process",
",",
"PhpStringParser",
"$",
"phpParser",
",",
"GeneratorDataObject",
"$",
"generator",
")",
"{",
"$",
"generator",
"=",
"clone",
"$",
"generator",
";",
"if",
"(",
"isset",
"(",
"$",
... | Analyze the dependencies generator
@param array $process
@param PhpStringParser $phpParser
@param GeneratorDataObject $generator
@return \CrudGenerator\Generators\GeneratorDataObject | [
"Analyze",
"the",
"dependencies",
"generator"
] | 559f22bcc525c3157ecb17fe96818dd7b7ee58c2 | https://github.com/fezfez/codeGenerator/blob/559f22bcc525c3157ecb17fe96818dd7b7ee58c2/src/CrudGenerator/Generators/Parser/GeneratorParser.php#L130-L144 | train |
fezfez/codeGenerator | src/CrudGenerator/Generators/Parser/GeneratorParser.php | GeneratorParser.analyzePreParser | private function analyzePreParser(
array $process,
PhpStringParser $phpParser,
GeneratorDataObject $generator,
$firstIteration
) {
$generator = clone $generator;
if ($this->parserCollection->getPreParse()->count() > 0) {
foreach ($this->parserCollection->getPreParse() as $parser) {
$generator = $parser->evaluate($process, $phpParser, $generator, $firstIteration);
}
}
return $generator;
} | php | private function analyzePreParser(
array $process,
PhpStringParser $phpParser,
GeneratorDataObject $generator,
$firstIteration
) {
$generator = clone $generator;
if ($this->parserCollection->getPreParse()->count() > 0) {
foreach ($this->parserCollection->getPreParse() as $parser) {
$generator = $parser->evaluate($process, $phpParser, $generator, $firstIteration);
}
}
return $generator;
} | [
"private",
"function",
"analyzePreParser",
"(",
"array",
"$",
"process",
",",
"PhpStringParser",
"$",
"phpParser",
",",
"GeneratorDataObject",
"$",
"generator",
",",
"$",
"firstIteration",
")",
"{",
"$",
"generator",
"=",
"clone",
"$",
"generator",
";",
"if",
... | Analyze pre parser
@param array $process
@param PhpStringParser $phpParser
@param GeneratorDataObject $generator
@param boolean $firstIteration
@return \CrudGenerator\Generators\GeneratorDataObject | [
"Analyze",
"pre",
"parser"
] | 559f22bcc525c3157ecb17fe96818dd7b7ee58c2 | https://github.com/fezfez/codeGenerator/blob/559f22bcc525c3157ecb17fe96818dd7b7ee58c2/src/CrudGenerator/Generators/Parser/GeneratorParser.php#L176-L191 | train |
fezfez/codeGenerator | src/CrudGenerator/Generators/Parser/GeneratorParser.php | GeneratorParser.analyzePostParser | private function analyzePostParser(
array $process,
PhpStringParser $phpParser,
GeneratorDataObject $generator,
$firstIteration
) {
$generator = clone $generator;
if ($this->parserCollection->getPostParse()->count() > 0) {
foreach ($this->parserCollection->getPostParse() as $parser) {
$generator = $parser->evaluate($process, $phpParser, $generator, $firstIteration);
}
}
return $generator;
} | php | private function analyzePostParser(
array $process,
PhpStringParser $phpParser,
GeneratorDataObject $generator,
$firstIteration
) {
$generator = clone $generator;
if ($this->parserCollection->getPostParse()->count() > 0) {
foreach ($this->parserCollection->getPostParse() as $parser) {
$generator = $parser->evaluate($process, $phpParser, $generator, $firstIteration);
}
}
return $generator;
} | [
"private",
"function",
"analyzePostParser",
"(",
"array",
"$",
"process",
",",
"PhpStringParser",
"$",
"phpParser",
",",
"GeneratorDataObject",
"$",
"generator",
",",
"$",
"firstIteration",
")",
"{",
"$",
"generator",
"=",
"clone",
"$",
"generator",
";",
"if",
... | Analyze post parser
@param array $process
@param PhpStringParser $phpParser
@param GeneratorDataObject $generator
@param boolean $firstIteration
@return \CrudGenerator\Generators\GeneratorDataObject | [
"Analyze",
"post",
"parser"
] | 559f22bcc525c3157ecb17fe96818dd7b7ee58c2 | https://github.com/fezfez/codeGenerator/blob/559f22bcc525c3157ecb17fe96818dd7b7ee58c2/src/CrudGenerator/Generators/Parser/GeneratorParser.php#L202-L217 | train |
mapbender/fom | src/FOM/UserBundle/Controller/PasswordController.php | PasswordController.setContainer | public function setContainer(ContainerInterface $container = null)
{
parent::setContainer($container);
if (!$this->container->getParameter('fom_user.reset_password')) {
throw new AccessDeniedHttpException();
}
} | php | public function setContainer(ContainerInterface $container = null)
{
parent::setContainer($container);
if (!$this->container->getParameter('fom_user.reset_password')) {
throw new AccessDeniedHttpException();
}
} | [
"public",
"function",
"setContainer",
"(",
"ContainerInterface",
"$",
"container",
"=",
"null",
")",
"{",
"parent",
"::",
"setContainer",
"(",
"$",
"container",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"container",
"->",
"getParameter",
"(",
"'fom_user.r... | Check if password reset is allowed.
setContainer is called after controller creation is used to deny access to controller if password reset has
been disabled. | [
"Check",
"if",
"password",
"reset",
"is",
"allowed",
"."
] | 6dea943121f3c3f9b1b4b14dc2a8e8640a120675 | https://github.com/mapbender/fom/blob/6dea943121f3c3f9b1b4b14dc2a8e8640a120675/src/FOM/UserBundle/Controller/PasswordController.php#L52-L59 | train |
fezfez/codeGenerator | src/CrudGenerator/Metadata/Config/MetaDataConfigDAO.php | MetaDataConfigDAO.retrieveAll | public function retrieveAll()
{
$adapterCollection = new MetaDataSourceCollection();
foreach ($this->fileManager->glob(Installer::BASE_PATH . self::SOURCE_PATH . '*' . self::EXTENSION) as $file) {
// Decode
$config = $this->transtyper->decode($this->fileManager->fileGetContent($file));
// Validate
try {
$this->arrayValidator->isValid('CrudGenerator\Metadata\MetaDataSource', $config);
} catch (ValidationException $e) {
continue; // Do nothing
}
// Hydrate
$adapter = $this->metaDataSourceHydrator->adapterNameToMetaDataSource(
$config[MetaDataSource::METADATA_DAO_FACTORY]
);
$adapter->setMetadataDaoFactory($config[MetaDataSource::METADATA_DAO_FACTORY]);
$adapter->setMetadataDao($config[MetaDataSource::METADATA_DAO]);
// Test if have a config
if (isset($config[MetaDataSource::CONFIG]) === true) {
$adapter->setConfig($this->driverHydrator->arrayToDto($config[MetaDataSource::CONFIG]));
}
$adapterCollection->append($adapter);
}
return $adapterCollection;
} | php | public function retrieveAll()
{
$adapterCollection = new MetaDataSourceCollection();
foreach ($this->fileManager->glob(Installer::BASE_PATH . self::SOURCE_PATH . '*' . self::EXTENSION) as $file) {
// Decode
$config = $this->transtyper->decode($this->fileManager->fileGetContent($file));
// Validate
try {
$this->arrayValidator->isValid('CrudGenerator\Metadata\MetaDataSource', $config);
} catch (ValidationException $e) {
continue; // Do nothing
}
// Hydrate
$adapter = $this->metaDataSourceHydrator->adapterNameToMetaDataSource(
$config[MetaDataSource::METADATA_DAO_FACTORY]
);
$adapter->setMetadataDaoFactory($config[MetaDataSource::METADATA_DAO_FACTORY]);
$adapter->setMetadataDao($config[MetaDataSource::METADATA_DAO]);
// Test if have a config
if (isset($config[MetaDataSource::CONFIG]) === true) {
$adapter->setConfig($this->driverHydrator->arrayToDto($config[MetaDataSource::CONFIG]));
}
$adapterCollection->append($adapter);
}
return $adapterCollection;
} | [
"public",
"function",
"retrieveAll",
"(",
")",
"{",
"$",
"adapterCollection",
"=",
"new",
"MetaDataSourceCollection",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"fileManager",
"->",
"glob",
"(",
"Installer",
"::",
"BASE_PATH",
".",
"self",
"::",
"SOUR... | Retrieve all config
@return \CrudGenerator\Metadata\MetaDataSourceCollection | [
"Retrieve",
"all",
"config"
] | 559f22bcc525c3157ecb17fe96818dd7b7ee58c2 | https://github.com/fezfez/codeGenerator/blob/559f22bcc525c3157ecb17fe96818dd7b7ee58c2/src/CrudGenerator/Metadata/Config/MetaDataConfigDAO.php#L93-L124 | train |
fezfez/codeGenerator | src/CrudGenerator/Metadata/Sources/MySQL/MySQLMetaDataDAOFactory.php | MySQLMetaDataDAOFactory.getInstance | public static function getInstance(DriverConfig $config)
{
$pdoDriver = PdoDriverFactory::getInstance();
return new MySQLMetaDataDAO(
$pdoDriver->getConnection($config),
$config
);
} | php | public static function getInstance(DriverConfig $config)
{
$pdoDriver = PdoDriverFactory::getInstance();
return new MySQLMetaDataDAO(
$pdoDriver->getConnection($config),
$config
);
} | [
"public",
"static",
"function",
"getInstance",
"(",
"DriverConfig",
"$",
"config",
")",
"{",
"$",
"pdoDriver",
"=",
"PdoDriverFactory",
"::",
"getInstance",
"(",
")",
";",
"return",
"new",
"MySQLMetaDataDAO",
"(",
"$",
"pdoDriver",
"->",
"getConnection",
"(",
... | Create MySQL Metadata DAO instance
@return MySQLMetaDataDAO | [
"Create",
"MySQL",
"Metadata",
"DAO",
"instance"
] | 559f22bcc525c3157ecb17fe96818dd7b7ee58c2 | https://github.com/fezfez/codeGenerator/blob/559f22bcc525c3157ecb17fe96818dd7b7ee58c2/src/CrudGenerator/Metadata/Sources/MySQL/MySQLMetaDataDAOFactory.php#L29-L37 | train |
milejko/mmi-cms | src/CmsAdmin/CategoryWidgetController.php | CategoryWidgetController.deleteAttributeRelationAction | public function deleteAttributeRelationAction()
{
//usuwanie relacji
(new AttributeController($this->getRequest(), $this->view))->deleteAttributeRelationAction();
$this->getResponse()->redirect('cmsAdmin', 'categoryWidget', 'edit', ['id' => $this->id]);
} | php | public function deleteAttributeRelationAction()
{
//usuwanie relacji
(new AttributeController($this->getRequest(), $this->view))->deleteAttributeRelationAction();
$this->getResponse()->redirect('cmsAdmin', 'categoryWidget', 'edit', ['id' => $this->id]);
} | [
"public",
"function",
"deleteAttributeRelationAction",
"(",
")",
"{",
"//usuwanie relacji",
"(",
"new",
"AttributeController",
"(",
"$",
"this",
"->",
"getRequest",
"(",
")",
",",
"$",
"this",
"->",
"view",
")",
")",
"->",
"deleteAttributeRelationAction",
"(",
"... | Usuwanie relacji widget atrybut | [
"Usuwanie",
"relacji",
"widget",
"atrybut"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/CmsAdmin/CategoryWidgetController.php#L73-L78 | train |
fezfez/codeGenerator | src/CrudGenerator/Metadata/Sources/PostgreSQL/PostgreSQLMetaDataDAOFactory.php | PostgreSQLMetaDataDAOFactory.getInstance | public static function getInstance(DriverConfig $config)
{
$pdoDriver = PdoDriverFactory::getInstance();
return new PostgreSQLMetaDataDAO(
$pdoDriver->getConnection($config),
$config,
new SqlManager()
);
} | php | public static function getInstance(DriverConfig $config)
{
$pdoDriver = PdoDriverFactory::getInstance();
return new PostgreSQLMetaDataDAO(
$pdoDriver->getConnection($config),
$config,
new SqlManager()
);
} | [
"public",
"static",
"function",
"getInstance",
"(",
"DriverConfig",
"$",
"config",
")",
"{",
"$",
"pdoDriver",
"=",
"PdoDriverFactory",
"::",
"getInstance",
"(",
")",
";",
"return",
"new",
"PostgreSQLMetaDataDAO",
"(",
"$",
"pdoDriver",
"->",
"getConnection",
"(... | Create PostgreSQL Metadata DAO instance
@return PostgreSQLMetaDataDAO | [
"Create",
"PostgreSQL",
"Metadata",
"DAO",
"instance"
] | 559f22bcc525c3157ecb17fe96818dd7b7ee58c2 | https://github.com/fezfez/codeGenerator/blob/559f22bcc525c3157ecb17fe96818dd7b7ee58c2/src/CrudGenerator/Metadata/Sources/PostgreSQL/PostgreSQLMetaDataDAOFactory.php#L29-L38 | train |
beleneglorion/php-bugherd-api | lib/Bugherd/Api/Project.php | Project.addGuest | public function addGuest($id,$guest) {
if(is_string($guest)) {
$params = array('email'=>$guest);
} elseif(is_numeric($guest)) {
$params = array('user_id'=>$guest);
}else {
throw new \Exception('Invalid parameter');
}
return $this->post('/projects/'.$id.'/add_guest.json', $params);
} | php | public function addGuest($id,$guest) {
if(is_string($guest)) {
$params = array('email'=>$guest);
} elseif(is_numeric($guest)) {
$params = array('user_id'=>$guest);
}else {
throw new \Exception('Invalid parameter');
}
return $this->post('/projects/'.$id.'/add_guest.json', $params);
} | [
"public",
"function",
"addGuest",
"(",
"$",
"id",
",",
"$",
"guest",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"guest",
")",
")",
"{",
"$",
"params",
"=",
"array",
"(",
"'email'",
"=>",
"$",
"guest",
")",
";",
"}",
"elseif",
"(",
"is_numeric",
... | Add a member to a project
@link https://www.bugherd.com/api_v2#api_proj_add_guest
@param int $id
@param mixed $guest
@return boolean | [
"Add",
"a",
"member",
"to",
"a",
"project"
] | f0fce97042bd05bc5560fbf37051cd74f802cea1 | https://github.com/beleneglorion/php-bugherd-api/blob/f0fce97042bd05bc5560fbf37051cd74f802cea1/lib/Bugherd/Api/Project.php#L199-L210 | train |
milejko/mmi-cms | src/CmsAdmin/Form/Category.php | Category.afterSave | public function afterSave()
{
//jeśli czegoś nie uddało się zapisać wcześniej
if (!parent::afterSave()) {
return false;
}
//jeśli nie udało się zapisać powiązań z rolami
if (!$this->_saveRoles()) {
return false;
}
//commit wersji
if ($this->getElement('commit')->getValue()) {
$this->getRecord()->commitVersion();
}
//usunięcie locka
return (new CategoryLockModel($this->getRecord()->cmsCategoryOriginalId))->releaseLock();
} | php | public function afterSave()
{
//jeśli czegoś nie uddało się zapisać wcześniej
if (!parent::afterSave()) {
return false;
}
//jeśli nie udało się zapisać powiązań z rolami
if (!$this->_saveRoles()) {
return false;
}
//commit wersji
if ($this->getElement('commit')->getValue()) {
$this->getRecord()->commitVersion();
}
//usunięcie locka
return (new CategoryLockModel($this->getRecord()->cmsCategoryOriginalId))->releaseLock();
} | [
"public",
"function",
"afterSave",
"(",
")",
"{",
"//jeśli czegoś nie uddało się zapisać wcześniej",
"if",
"(",
"!",
"parent",
"::",
"afterSave",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"//jeśli nie udało się zapisać powiązań z rolami",
"if",
"(",
"!",
"$",... | Zapisuje dodatkowe dane, m.in. role
@return bool | [
"Zapisuje",
"dodatkowe",
"dane",
"m",
".",
"in",
".",
"role"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/CmsAdmin/Form/Category.php#L160-L176 | train |
brightnucleus/boilerplate | _scripts/Task/ReplacePlaceholdersInTemplateFiles.php | ReplacePlaceholdersInTemplateFiles.getPlaceholderArray | protected function getPlaceholderArray()
{
$placeholderArray = [];
foreach ($this->getConfigKey('Placeholders') as $key => $data) {
$placeholderArray[$key] = $data['value'];
}
return $placeholderArray;
} | php | protected function getPlaceholderArray()
{
$placeholderArray = [];
foreach ($this->getConfigKey('Placeholders') as $key => $data) {
$placeholderArray[$key] = $data['value'];
}
return $placeholderArray;
} | [
"protected",
"function",
"getPlaceholderArray",
"(",
")",
"{",
"$",
"placeholderArray",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getConfigKey",
"(",
"'Placeholders'",
")",
"as",
"$",
"key",
"=>",
"$",
"data",
")",
"{",
"$",
"placeholderArray... | Get an array of placeholder => value combinations to be used by Mustache.
@since 0.1.0
@return array Array of placeholder => value combinations. | [
"Get",
"an",
"array",
"of",
"placeholder",
"=",
">",
"value",
"combinations",
"to",
"be",
"used",
"by",
"Mustache",
"."
] | 27092790349481e1bece8f79eaccaa15cc35d845 | https://github.com/brightnucleus/boilerplate/blob/27092790349481e1bece8f79eaccaa15cc35d845/_scripts/Task/ReplacePlaceholdersInTemplateFiles.php#L55-L63 | train |
milejko/mmi-cms | src/CmsAdmin/Form/TagRelation.php | TagRelation.beforeSave | public function beforeSave()
{
$tag = $this->getElement('tag')->getValue();
//wyszukanie tagu
if (null === $tagRecord = (new \Cms\Orm\CmsTagQuery)
->whereTag()->equals($tag)
->findFirst()) {
//utworzenie tagu
$tagRecord = new \Cms\Orm\CmsTagRecord;
$tagRecord->tag = $tag;
$tagRecord->save();
}
//przypisanie id tagu
$this->getRecord()->cmsTagId = $tagRecord->id;
return true;
} | php | public function beforeSave()
{
$tag = $this->getElement('tag')->getValue();
//wyszukanie tagu
if (null === $tagRecord = (new \Cms\Orm\CmsTagQuery)
->whereTag()->equals($tag)
->findFirst()) {
//utworzenie tagu
$tagRecord = new \Cms\Orm\CmsTagRecord;
$tagRecord->tag = $tag;
$tagRecord->save();
}
//przypisanie id tagu
$this->getRecord()->cmsTagId = $tagRecord->id;
return true;
} | [
"public",
"function",
"beforeSave",
"(",
")",
"{",
"$",
"tag",
"=",
"$",
"this",
"->",
"getElement",
"(",
"'tag'",
")",
"->",
"getValue",
"(",
")",
";",
"//wyszukanie tagu",
"if",
"(",
"null",
"===",
"$",
"tagRecord",
"=",
"(",
"new",
"\\",
"Cms",
"\... | Przed zapisem odnalezienie identyfikatora wprowadzonego tagu
@return boolean | [
"Przed",
"zapisem",
"odnalezienie",
"identyfikatora",
"wprowadzonego",
"tagu"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/CmsAdmin/Form/TagRelation.php#L60-L75 | train |
manaphp/framework | Di.php | Di.set | public function set($name, $definition)
{
if (is_string($definition)) {
if (strpos($definition, '/') !== false || preg_match('#^[\w\\\\]+$#', $definition) !== 1) {
$definition = ['class' => $this->_interClassName($name), $definition, 'shared' => false];
} else {
if (strpos($definition, '\\') === false) {
$definition = $this->_completeClassName($name, $definition);
}
$definition = ['class' => $definition, 'shared' => false];
}
} elseif (is_array($definition)) {
if (isset($definition['class'])) {
if (strpos($definition['class'], '\\') === false) {
$definition['class'] = $this->_completeClassName($name, $definition['class']);
}
} elseif (isset($definition[0]) && count($definition) !== 1) {
if (strpos($definition[0], '\\') === false) {
$definition[0] = $this->_completeClassName($name, $definition[0]);
}
} else {
$definition['class'] = $this->_interClassName($name);
}
$definition['shared'] = false;
} elseif (is_object($definition)) {
$definition = ['class' => $definition, 'shared' => !$definition instanceof \Closure];
} else {
throw new UnexpectedValueException(['`:definition` definition is unknown', 'definition' => $name]);
}
$this->_definitions[$name] = $definition;
return $this;
} | php | public function set($name, $definition)
{
if (is_string($definition)) {
if (strpos($definition, '/') !== false || preg_match('#^[\w\\\\]+$#', $definition) !== 1) {
$definition = ['class' => $this->_interClassName($name), $definition, 'shared' => false];
} else {
if (strpos($definition, '\\') === false) {
$definition = $this->_completeClassName($name, $definition);
}
$definition = ['class' => $definition, 'shared' => false];
}
} elseif (is_array($definition)) {
if (isset($definition['class'])) {
if (strpos($definition['class'], '\\') === false) {
$definition['class'] = $this->_completeClassName($name, $definition['class']);
}
} elseif (isset($definition[0]) && count($definition) !== 1) {
if (strpos($definition[0], '\\') === false) {
$definition[0] = $this->_completeClassName($name, $definition[0]);
}
} else {
$definition['class'] = $this->_interClassName($name);
}
$definition['shared'] = false;
} elseif (is_object($definition)) {
$definition = ['class' => $definition, 'shared' => !$definition instanceof \Closure];
} else {
throw new UnexpectedValueException(['`:definition` definition is unknown', 'definition' => $name]);
}
$this->_definitions[$name] = $definition;
return $this;
} | [
"public",
"function",
"set",
"(",
"$",
"name",
",",
"$",
"definition",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"definition",
")",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"definition",
",",
"'/'",
")",
"!==",
"false",
"||",
"preg_match",
"(",
"... | Registers a component in the components container
@param string $name
@param mixed $definition
@return static | [
"Registers",
"a",
"component",
"in",
"the",
"components",
"container"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Di.php#L178-L212 | train |
manaphp/framework | Di.php | Di.setShared | public function setShared($name, $definition)
{
if (isset($this->_instances[$name])) {
throw new MisuseException(['it\'s too late to setShared(): `:name` instance has been created', 'name' => $name]);
}
if (is_string($definition)) {
if (strpos($definition, '/') !== false || preg_match('#^[\w\\\\]+$#', $definition) !== 1) {
$definition = ['class' => $this->_interClassName($name), $definition];
} elseif (strpos($definition, '\\') === false) {
$definition = $this->_completeClassName($name, $definition);
}
} elseif (is_array($definition)) {
if (isset($definition['class'])) {
if (strpos($definition['class'], '\\') === false) {
$definition['class'] = $this->_completeClassName($name, $definition['class']);
}
} elseif (isset($definition[0]) && count($definition) !== 1) {
if (strpos($definition[0], '\\') === false) {
$definition[0] = $this->_completeClassName($name, $definition[0]);
}
} else {
$definition['class'] = $this->_interClassName($name);
}
} elseif (is_object($definition)) {
$definition = ['class' => $definition];
} else {
throw new UnexpectedValueException(['`:definition` definition is unknown', 'definition' => $name]);
}
$this->_definitions[$name] = $definition;
return $this;
} | php | public function setShared($name, $definition)
{
if (isset($this->_instances[$name])) {
throw new MisuseException(['it\'s too late to setShared(): `:name` instance has been created', 'name' => $name]);
}
if (is_string($definition)) {
if (strpos($definition, '/') !== false || preg_match('#^[\w\\\\]+$#', $definition) !== 1) {
$definition = ['class' => $this->_interClassName($name), $definition];
} elseif (strpos($definition, '\\') === false) {
$definition = $this->_completeClassName($name, $definition);
}
} elseif (is_array($definition)) {
if (isset($definition['class'])) {
if (strpos($definition['class'], '\\') === false) {
$definition['class'] = $this->_completeClassName($name, $definition['class']);
}
} elseif (isset($definition[0]) && count($definition) !== 1) {
if (strpos($definition[0], '\\') === false) {
$definition[0] = $this->_completeClassName($name, $definition[0]);
}
} else {
$definition['class'] = $this->_interClassName($name);
}
} elseif (is_object($definition)) {
$definition = ['class' => $definition];
} else {
throw new UnexpectedValueException(['`:definition` definition is unknown', 'definition' => $name]);
}
$this->_definitions[$name] = $definition;
return $this;
} | [
"public",
"function",
"setShared",
"(",
"$",
"name",
",",
"$",
"definition",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"_instances",
"[",
"$",
"name",
"]",
")",
")",
"{",
"throw",
"new",
"MisuseException",
"(",
"[",
"'it\\'s too late to setSh... | Registers an "always shared" component in the components container
@param string $name
@param mixed $definition
@return static | [
"Registers",
"an",
"always",
"shared",
"component",
"in",
"the",
"components",
"container"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Di.php#L222-L255 | train |
manaphp/framework | Di.php | Di.remove | public function remove($name)
{
unset($this->_definitions[$name], $this->_instances[$name], $this->{$name});
return $this;
} | php | public function remove($name)
{
unset($this->_definitions[$name], $this->_instances[$name], $this->{$name});
return $this;
} | [
"public",
"function",
"remove",
"(",
"$",
"name",
")",
"{",
"unset",
"(",
"$",
"this",
"->",
"_definitions",
"[",
"$",
"name",
"]",
",",
"$",
"this",
"->",
"_instances",
"[",
"$",
"name",
"]",
",",
"$",
"this",
"->",
"{",
"$",
"name",
"}",
")",
... | Removes a component in the components container
@param string $name
@return static | [
"Removes",
"a",
"component",
"in",
"the",
"components",
"container"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Di.php#L277-L282 | train |
manaphp/framework | Di.php | Di.get | public function get($name, $parameters = null)
{
if (isset($this->_instances[$name])) {
return $this->_instances[$name];
}
if (isset($this->_definitions[$name])) {
$definition = $this->_definitions[$name];
} else {
return $this->getInstance($name, $parameters, $name);
}
$instance = $this->getInstance($definition, $parameters, $name);
if (is_string($definition) || !isset($definition['shared']) || $definition['shared'] === true) {
$this->_instances[$name] = $instance;
}
return $instance;
} | php | public function get($name, $parameters = null)
{
if (isset($this->_instances[$name])) {
return $this->_instances[$name];
}
if (isset($this->_definitions[$name])) {
$definition = $this->_definitions[$name];
} else {
return $this->getInstance($name, $parameters, $name);
}
$instance = $this->getInstance($definition, $parameters, $name);
if (is_string($definition) || !isset($definition['shared']) || $definition['shared'] === true) {
$this->_instances[$name] = $instance;
}
return $instance;
} | [
"public",
"function",
"get",
"(",
"$",
"name",
",",
"$",
"parameters",
"=",
"null",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"_instances",
"[",
"$",
"name",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"_instances",
"[",
"$",
"na... | Resolves the component based on its configuration
@param string $name
@param array $parameters
@return mixed | [
"Resolves",
"the",
"component",
"based",
"on",
"its",
"configuration"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Di.php#L364-L383 | train |
manaphp/framework | Di.php | Di.getShared | public function getShared($name)
{
if (isset($this->_instances[$name])) {
return $this->_instances[$name];
}
if (isset($this->_definitions[$name])) {
return $this->_instances[$name] = $this->getInstance($this->_definitions[$name], null, $name);
} elseif (strpos($name, '\\') !== false) {
return $this->_instances[$name] = $this->getInstance($name, null, $name);
} else {
$className = $this->_getPatterned($name);
if ($className === null) {
throw new InvalidValueException(['`:component` component is not exists', 'component' => $name]);
}
return $this->_instances[$name] = $this->getInstance($className, null, $name);
}
} | php | public function getShared($name)
{
if (isset($this->_instances[$name])) {
return $this->_instances[$name];
}
if (isset($this->_definitions[$name])) {
return $this->_instances[$name] = $this->getInstance($this->_definitions[$name], null, $name);
} elseif (strpos($name, '\\') !== false) {
return $this->_instances[$name] = $this->getInstance($name, null, $name);
} else {
$className = $this->_getPatterned($name);
if ($className === null) {
throw new InvalidValueException(['`:component` component is not exists', 'component' => $name]);
}
return $this->_instances[$name] = $this->getInstance($className, null, $name);
}
} | [
"public",
"function",
"getShared",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"_instances",
"[",
"$",
"name",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"_instances",
"[",
"$",
"name",
"]",
";",
"}",
"if",
"(",
... | Resolves a component, the resolved component is stored in the DI, subsequent requests for this component will return the same instance
@param string $name
@return mixed | [
"Resolves",
"a",
"component",
"the",
"resolved",
"component",
"is",
"stored",
"in",
"the",
"DI",
"subsequent",
"requests",
"for",
"this",
"component",
"will",
"return",
"the",
"same",
"instance"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Di.php#L418-L435 | train |
pscheit/jparser | PLUG/time/Timer.php | Timer.reset | function reset(){
$tmp = $this->milliseconds();
$this->started = microtime( false );
$this->stopped = null;
return $tmp;
} | php | function reset(){
$tmp = $this->milliseconds();
$this->started = microtime( false );
$this->stopped = null;
return $tmp;
} | [
"function",
"reset",
"(",
")",
"{",
"$",
"tmp",
"=",
"$",
"this",
"->",
"milliseconds",
"(",
")",
";",
"$",
"this",
"->",
"started",
"=",
"microtime",
"(",
"false",
")",
";",
"$",
"this",
"->",
"stopped",
"=",
"null",
";",
"return",
"$",
"tmp",
"... | Reset timer.
@return int milliseconds timer was last stopped or 0. | [
"Reset",
"timer",
"."
] | f9de77171c0d37d237e0e9a918ed7bff19e12095 | https://github.com/pscheit/jparser/blob/f9de77171c0d37d237e0e9a918ed7bff19e12095/PLUG/time/Timer.php#L55-L60 | train |
pscheit/jparser | PLUG/time/Timer.php | Timer.stop | function stop(){
if( $this->is_running() ){
$this->stopped = microtime( false );
return $this->milliseconds();
}
else{
trigger_error("Timer already stopped", E_USER_NOTICE);
return false;
}
} | php | function stop(){
if( $this->is_running() ){
$this->stopped = microtime( false );
return $this->milliseconds();
}
else{
trigger_error("Timer already stopped", E_USER_NOTICE);
return false;
}
} | [
"function",
"stop",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"is_running",
"(",
")",
")",
"{",
"$",
"this",
"->",
"stopped",
"=",
"microtime",
"(",
"false",
")",
";",
"return",
"$",
"this",
"->",
"milliseconds",
"(",
")",
";",
"}",
"else",
"{... | Stop timer.
Use this when you want to evaluate a value without the clock continuing.
@return int milliseconds or False if timer already has been stopped. | [
"Stop",
"timer",
".",
"Use",
"this",
"when",
"you",
"want",
"to",
"evaluate",
"a",
"value",
"without",
"the",
"clock",
"continuing",
"."
] | f9de77171c0d37d237e0e9a918ed7bff19e12095 | https://github.com/pscheit/jparser/blob/f9de77171c0d37d237e0e9a918ed7bff19e12095/PLUG/time/Timer.php#L70-L79 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.